Search Results

Search found 384 results on 16 pages for 'composition'.

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

  • Getter/Setter (composition, Java, HW)

    - by Crystal
    I have one class called Person that basically looks like: public class Person { String firstName; String lastName; String telephone; String email; public Person() { firstName = ""; lastName = ""; telephone = ""; email = ""; } public Person(String firstName, String lastName, String telephone, String email) { this.firstName = firstName; this.lastName = lastName; this.telephone = telephone; this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } .... Using that class, I setup an abstract class called Loan that looks like: public abstract class Loan { public void setClient(Person client) { this.client = client; } public Person getClient() { return client; } public void setLoanId(int nextId) { loanId = nextId; nextId++; } public int getLoanId() { return loanId; } public void setInterestRate(double interestRate) { this.interestRate = interestRate; } public double getInterestRate() { return interestRate; } public void setLoanLength(int loanLength) { this.loanLength = loanLength; } public int getLoanLength() { return loanLength; } public void setLoanAmount(double loanAmount) { this.loanAmount = loanAmount; } public double getLoanAmount(double loanAmount) { return loanAmount; } private Person client; private int loanId; private double interestRate; private int loanLength; private double loanAmount; private static int nextId = 1; } I have to extend the Loan class with CarLoan and it looks like: public class CarLoan extends Loan { public CarLoan(Person client, double vehiclePrice, double downPayment, double salesTax, double interestRate, CAR_LOAN_TERMS length) { super.setClient(client); super.setInterestRate(interestRate); this.client = client; this.vehiclePrice = vehiclePrice; this.downPayment = downPayment; this.salesTax = salesTax; this.length = length; } public void setVehiclePrice(double vehiclePrice) { this.vehiclePrice = vehiclePrice; } public double getVehiclePrice() { return vehiclePrice; } public void setDownPayment(double downPayment) { this.downPayment = downPayment; } public double getDownPayment() { return downPayment; } public void setSalesTax(double salesTax) { this.salesTax = salesTax; } public double getSalesTax() { return salesTax; } public String toString() { return getClass().getName() + "[vehiclePrice = " + vehiclePrice + '\n' + "downPayment = " + downPayment + '\n' + "salesTax = " + salesTax + "]"; } public enum CAR_LOAN_TERMS {TWO_YEAR, THREE_YEAR, SIX_YEAR}; private double vehiclePrice; private double downPayment; private double salesTax; Few questions. (a) Is what I did in the Loan class to setClient correct given what I have in the Person class? (e.g.this.client = client) (b) Can I call super twice in a method? I have to set two attributes from the Loan class from the constructor in the CarLoan class and I thought that would be a way to do it. (c) Do you have to set attributes for enumeration types differently in a constructor or getter/setter methods? I get an error for (this.length = length) in my CarLoan class and I was unsure of how enumeration values should be set. Thanks!

    Read the article

  • PNG composition using GD and PHP

    - by Dominic
    I am trying to take a rectangular png and add depth using GD by duplicating the background and moving it down 1 pixel and right 1 pixel. I am trying to preserve a transparent background as well. I am having a bunch of trouble with preserving the transparency. Any help would be greatly appreciated. Thanks! $obj = imagecreatefrompng('rectangle.png'); $depth = 5; $obj_width = imagesx($obj); $obj_height = imagesy($obj); imagesavealpha($obj, true); for($i=1;$i<=$depth;$i++){ $layer = imagecreatefrompng('rectangle.png'); imagealphablending( $layer, false ); imagesavealpha($layer, true); $new_obj = imagecreatetruecolor($obj_width+$i,$obj_height+$i); $new_obj_width = imagesx($new_obj); $new_obj_height = imagesy($new_obj); imagealphablending( $new_obj, false ); imagesavealpha($new_obj, true); $trans_color = imagecolorallocatealpha($new_obj, 0, 0, 0, 127); imagefill($new_obj, 0, 0, $trans_color); imagecopyresampled($new_obj, $layer, $i, $i, 0, 0, $obj_width, $obj_height, $obj_width, $obj_height); //imagesavealpha($new_obj, true); //imagesavealpha($obj, true); } header ("Content-type: image/png"); imagepng($new_obj); imagedestroy($new_obj);

    Read the article

  • Function Composition in Haskell

    - by Watts
    I have a function that takes 3 functions and switches the types and combine to make a new function. For example a test case call would be : (chain init tail reverse ) "Haskell!" the output should be lleksa I've tried to do this problem a few different ways including using the map function but I kept getting association problems. so i did chain :: Ord a => [a] -> a chain f g h x = f.g.h$x my error is Couldn't match expected type[t0->t1->t2->a0] When I type the problem directly into prelude like replacing f, g, h, x with the values it comes out right Is there even a way to do three functions, I've only seen two in examples

    Read the article

  • Java GC: top object classes promoted (by size)?

    - by Java Geek
    Hello! Please let me know what is the best way to determine composition of young generation memory promoted to old generation, after each young GC event? Ideally I would like to know class names which are responsible say, for 80% of heap in each "young gen - old gen" promotion chunk; Example: I have 600M young gen, each tenure promotes 6M; I want to know which objects compose this 6M. Thank you.

    Read the article

  • Can a problem have a relation of aggregation and composition both between two classes at same point

    - by learner
    Can a problem have a relation of aggregation and composition both between two classes at same point of time? Like any real time scenario where there can be aggregation corresponding to one method and composition related to other method. I m unable to figure out any scenario where both composition and aggregation occurs simultaneously between two classes. Any help will be appreciable.

    Read the article

  • Sharing base object with inheritance

    - by max
    I have class Base. I'd like to extend its functionality in a class Derived. I was planning to write: class Derived(Base): def __init__(self, base_arg1, base_arg2, derived_arg1, derived_arg2): super().__init__(base_arg1, base_arg2) # ... def derived_method1(self): # ... Sometimes I already have a Base instance, and I want to create a Derived instance based on it, i.e., a Derived instance that shares the Base object (doesn't re-create it from scratch). I thought I could write a static method to do that: b = Base(arg1, arg2) # very large object, expensive to create or copy d = Derived.from_base(b, derived_arg1, derived_arg2) # reuses existing b object but it seems impossible. Either I'm missing a way to make this work, or (more likely) I'm missing a very big reason why it can't be allowed to work. Can someone explain which one it is? [Of course, if I used composition rather than inheritance, this would all be easy to do. But I was hoping to avoid the delegation of all the Base methods to Derived through __getattr__.]

    Read the article

  • Composing Silverlight Applications With MEF

    - by PeterTweed
    Anyone who has written an application with complexity enough to warrant multiple controls on multiple pages/forms should understand the benefit of composite application development.  That is defining your application architecture that can be separated into separate pieces each with it’s own distinct purpose that can then be “composed” together into the solution. Composition can be useful in any layer of the application, from the presentation layer, the business layer, common services or data access.  Historically people have had different options to achieve composing applications from distinct well known pieces – their own version of dependency injection, containers to aid with composition like Unity, the composite application guidance for WPF and Silverlight and before that the composite application block. Microsoft has been working on another mechanism to aid composition and extension of applications for some time now – the Managed Extensibility Framework or MEF for short.  With Silverlight 4 it is part of the Silverlight environment.  MEF allows a much simplified mechanism for composition and extensibility compared to other mechanisms – which has always been the primary issue for adoption of the earlier mechanisms/frameworks. This post will guide you through the simple use of MEF for the scenario of composition of an application – using exports, imports and composition.  Steps: 1.     Create a new Silverlight 4 application. 2.     Add references to the following assemblies: System.ComponentModel.Composition.dll System.ComponentModel.Composition.Initialization.dll 3.     Add a new user control called LeftControl. 4.     Replace the LayoutRoot Grid with the following xaml:     <Grid x:Name="LayoutRoot" Background="Beige" Margin="40" >         <Button Content="Left Content" Margin="30"></Button>     </Grid> 5.     Add the following statement to the top of the LeftControl.xaml.cs file using System.ComponentModel.Composition; 6.     Add the following attribute to the LeftControl class     [Export(typeof(LeftControl))]   This attribute tells MEF that the type LeftControl will be exported – i.e. made available for other applications to import and compose into the application. 7.     Add a new user control called RightControl. 8.     Replace the LayoutRoot Grid with the following xaml:     <Grid x:Name="LayoutRoot" Background="Green" Margin="40"  >         <TextBlock Margin="40" Foreground="White" Text="Right Control" FontSize="16" VerticalAlignment="Center" HorizontalAlignment="Center" ></TextBlock>     </Grid> 9.     Add the following statement to the top of the RightControl.xaml.cs file using System.ComponentModel.Composition; 10.   Add the following attribute to the RightControl class     [Export(typeof(RightControl))] 11.   Add the following xaml to the LayoutRoot Grid in MainPage.xaml:         <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">             <Border Name="LeftContent" Background="Red" BorderBrush="Gray" CornerRadius="20"></Border>             <Border Name="RightContent" Background="Red" BorderBrush="Gray" CornerRadius="20"></Border>         </StackPanel>   The borders will hold the controls that will be imported and composed via MEF. 12.   Add the following statement to the top of the MainPage.xaml.cs file using System.ComponentModel.Composition; 13.   Add the following properties to the MainPage class:         [Import(typeof(LeftControl))]         public LeftControl LeftUserControl { get; set; }         [Import(typeof(RightControl))]         public RightControl RightUserControl { get; set; }   This defines properties accepting LeftControl and RightControl types.  The attrributes are used to tell MEF the discovered type that should be applied to the property when composition occurs. 14.   Replace the MainPage constructore with the following code:         public MainPage()         {             InitializeComponent();             CompositionInitializer.SatisfyImports(this);             LeftContent.Child = LeftUserControl;             RightContent.Child = RightUserControl;         }   The CompositionInitializer.SatisfyImports(this) function call tells MEF to discover types related to the declared imports for this object (the MainPage object).  At that point, types matching those specified in the import defintions are discovered in the executing assembly location of the application and instantiated and assigned to the matching properties of the current object. 15.   Run the application and you will see the left control and right control types displayed in the MainPage:   Congratulations!  You have used MEF to dynamically compose user controls into a parent control in a composite application model. In the next post we will build on this topic to cover using MEF to compose Silverlight applications dynamically in download on demand scenarios – so .xap packages can be downloaded only when needed, avoiding large initial download for the main application xap. Take the Slalom Challenge at www.slalomchallenge.com!

    Read the article

  • Calling services from the Orchestrating layer in SOA?

    - by Martin Lee
    The Service Oriented Architecture Principles site says that Service Composition is an important thing in SOA. But Service Loose Coupling is important as well. Does that mean that the "Orchestrating layer" should be the only one that is allowed to make calls to services in the system? As I understand SOA, the "Orchestrating layer" 'glues' all the services together into one software application. I tried to depict that on Fig.A and Fig.B. The difference between the two is that on Fig.A the application is composed of services and all the logic is done in the "Orchestrating layer" (all calls to services are done from the "Orchestrating layer" only). On Fig.B the application is composed from services, but one service calls another service. Does the architecture on Fig.B violate the "Service Loose Coupling" principle of SOA? Can a service call another service in SOA? And more generally, can the architecture on Fig.A be considered superior to the one on Fig.B in terms of service loose coupling, abstraction, reusability, autonomy, etc.? My guess is that the A architecture is much more universal, but it can add some unnecessary data transfers between the "Orchestrating layer" and all the called services.

    Read the article

  • Is dependency injection by hand a better alternative to composition and polymorphism?

    - by Drake Clarris
    First, I'm an entry level programmer; In fact, I'm finishing an A.S. degree with a final capstone project over the summer. In my new job, when there isn't some project for me to do (they're waiting to fill the team with more new hires), I've been given books to read and learn from while I wait - some textbooks, others not so much (like Code Complete). After going through these books, I've turned to the internet to learn as much as possible, and started learning about SOLID and DI (we talked some about Liskov's substitution principle, but not much else SOLID ideas). So as I've learned, I sat down to do to learn better, and began writing some code to utilize DI by hand (there are no DI frameworks on the development computers). Thing is, as I do it, I notice it feels familiar... and it seems like it is very much like work I've done in the past using composition of abstract classes using polymorphism. Am I missing a bigger picture here? Is there something about DI (at least by hand) that goes beyond that? I understand the possibility of having configurations not in code of some DI frameworks having some great benefits as far as changing things without having to recompile, but when doing it by hand, I'm not sure if it's any different than stated above... Some insight into this would be very helpful!

    Read the article

  • how do I import a targa sequence as a composition in after effects cs4 ?

    - by George Profenza
    I am a complete n00b with After Effects now, but I want to achieve something basic. I have a sequence of TARGA(.tga) files named alphanumerically(name_0000, where 0000 is the frame). I want to import those as a composition. What I'm after is having each .tga file siting in the timeline in sequence. I tried File Import File, selected the first, then selected the last, holding Shift, and ticked sequence, but I cannot select Composition from that Dialog, I can only select Footage and I don't knwow why. Hints ?

    Read the article

  • How to use gnlcomposition to concatenate video files?

    - by Hardy
    Hi All, I am trying to concatenate two video files with the gnonlin components of the gstreamer. The pipeline I am using is gst-launch-0.10 gnlcomposition { gnlfilesource name="s1" location="/home/s1.mp4" start=0 duration=2000000000 media-start=0 media-duration=2000000000 gnlfilesource name="s2" location="/home/s2.mp4" start=2000000000 duration=2000000000 media-start=0 media-duration=2000000000 } ! queue ! videorate ! progressreport name="Merging Progress" ! ffmpegcolorspace ! ffenc_mpeg4 ! ffmux_mp4 ! filesink location="/home/merge.mp4" As a result I am getting only the second file for the duration specified in the parameters. Tried several things and also searched on google but I could not figure out the problem with the above command. Can anyone point what i am doing wrong? Any other way of concatenating multiple files into one based on time is welcome too. Thanks

    Read the article

  • How do I stop inheritance in xaml?

    - by cfouche
    Hi Let's say I have some Control that has been disabled. It contains a bunch of elements, but I want one of those child elements to remain enabled. Something like this: <ContentControl IsEnabled="False"> <Border> <Button Content="Button" IsEnabled="True"/> </Border> </ContentControl> So in this example, the Button's IsEnabled="True" setting gets overridden by its parent. Is there a way of stopping this from happening? This seems like a strange thing to be doing, but I have a situation where, when a Control is disabled and a user mouses down on it, I still want an event to be triggered. I read in WPF Unleashed that wrapping something in a Frame control, "..isolates the content from the rest of the UI [and] properties that would normally be inherited down the element tree stop when they reach the Frame", but wrapping the Button in the example above in a Frame doesn't work. Am I on the wrong track here?

    Read the article

  • Pattern for sharing data between views (MVP or MVVM)

    - by Dovix
    What is a good pattern for sharing data between related views?. I have an application where 1 form contains many small views, each views behaves independently from each other more or less (they communicate/interact via an event bus). Every so often I need to pass the same objects to the child views. Sometimes I need this same object to be passed to a child view and then the child passes it onto another child itself contains. What is a good approach to sharing this data between all the views contained within the parent form (view) ? I have looked into CAB and their approach and every "view" has a "root work item" this work item has dictionary that contains a shared "state" between the views that are contained. Is this the best approach? just a shared dictionary all the views under a root view can access? My current approach right now is to have a function on the view that allows one to set the object for that view. Something like view.SetCustomer(Customer c); then if the view contains a child view it knows to set it on the child view ala: this.childview1.SetCustomer(c); The application is written in C# 3.5, for winforms using MVP with structure map as a IoC/DI provider.

    Read the article

  • Rails 1.0 - Using composed_of gives me a wrong number of arguments (1 for 5) error

    - by Tristan Havelick
    I am developing a Rails 1.0 application (I can't upgrade, it's a strange situation) for which I am trying to use the :composed_of functionality. I have a class called StreetAddress: class StreetAddress attr_reader :address, :address2, :city, :state_id, :zip_code def initialize(address, address2, city, state_id, zip_code) @address = address @address2 = address2 @city = city @state_id = state_id @zip_code = zip_code end end and a model class called Hotel class Hotel < ActiveRecord::Base composed_of :street_address # ... end which has columns: "id", "brand_id", "code", "location_name", "address", "address2", "city", "state_id", "zip_code", "phone_number", "phone_ext", "fax_number", "time_zone", "url", "room_service_email", "manager_name", "manager_email" However when I try to access the aggregation I get an error: >> h = Hotel.find(1) => #<Hotel:0x38ad718 @attributes={"fax_number"=>"1-623-420-0124", "city"=>"Twin Falls", "address2"=>"285", "brand_id"=>"1", "code"=>"XZWUXUSZ", "manager_email"= >"[email protected]", "url"=>"http://www.xycdkzolukfvu.hom", "ph one_number"=>"1-805-706-9995", "zip_code"=>"72436", "phone_ext"=>"48060", "id"=> "1", "manager_name"=>"Igor Mcdowell", "room_service_email"=>"Duis.risus@Donecvit ae.ca", "time_zone"=>"America/Boise", "state_id"=>"15", "address"=>"P.O. Box 457 , 7405 Dignissim Avenue", "location_name"=>"penatibus et magnis"}> >> h.street_address ArgumentError: wrong number of arguments (1 for 5) from (eval):3:in `initialize' from (eval):3:in `new' from (eval):3:in `street_address' from (irb):6 Why?

    Read the article

  • How to compose a Matcher[Iterable[A]] from a Matcher[A] with specs testing framework

    - by Garrett Rowe
    If I have a Matcher[A] how do create a Matcher[Iterable[A]] that is satisfied only if each element of the Iterable satisfies the original Matcher. class ExampleSpec extends Specification { def allSatisfy[A](m: => Matcher[A]): Matcher[Iterable[A]] = error("TODO") def notAllSatisfy[A](m: => Matcher[A]): Matcher[Iterable[A]] = allSatisfy(m).not "allSatisfy" should { "Pass if all elements satisfy the expectation" in { List(1, 2, 3, 4) must allSatisfy(beLessThan(5)) } "Fail if any elements do not satisfy the expectation" in { List(1, 2, 3, 5) must notAllSatisfy(beLessThan(5)) } } }

    Read the article

  • Using MEF to build a tabbed application dynamically

    - by Mmarquee
    I'm rather taken with MEF and plan to use it to build a demo application to load different tabs. I am a begineer at MEF and WPF and although MEF is loading the assemblies I'm stuck at loading the controls into the TabItem I have created. My code looks a bt like this .. foreach (var page in pages) { TabItem item = new TabItem(); item.Header = page.PageTitle; /// Errm??? // Add each page tcPageControl.Items.Add(item); } The tabs are Pages, so I might be doing it totally wrong, and any help would be appreciated. Thanks in advance

    Read the article

  • noncopyable static const member class in template class

    - by Dukales
    I have a non-copyable (inherited from boost::noncopyable) class that I use as a custom namespace. Also, I have another class, that uses previous one, as shown here: #include <boost/utility.hpp> #include <cmath> template< typename F > struct custom_namespace : boost::noncopyable { F sqrt_of_half(F const & x) const { using std::sqrt; return sqrt(x / F(2.0L)); } // ... maybe others are not so dummy const/constexpr methods }; template< typename F > class custom_namespace_user { static ::custom_namespace< F > const custom_namespace_; public : F poisson() const { return custom_namespace_.sqrt_of_half(M_PI); } static F square_diagonal(F const & a) { return a * custom_namespace_.sqrt_of_half(1.0L); } }; template< typename F > ::custom_namespace< F > const custom_namespace_user< F >::custom_namespace_(); this code leads to the next error (even without instantiation): error: no 'const custom_namespace custom_namespace_user::custom_namespace_()' member function declared in class 'custom_namespace_user' The next way is not legitimate: template< typename F ::custom_namespace< F const custom_namespace_user< F ::custom_namespace_ = ::custom_namespace< F (); What should I do to declare this two classes (first as noncopyable static const member class of second)? Is this feaseble?

    Read the article

  • Is it possible to parameterize a MEF import?

    - by Josh Einstein
    I am relatively new to MEF so I don't fully understand the capabilities. I'm trying to achieve something similar to Unity's InjectionMember. Let's say I have a class that imports MEF parts. For the sake of simplicity, let's take the following class as an example of the exported part. [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class Logger { public string Category { get; set; } public void Write(string text) { } } public class MyViewModel { [Import] public Logger Log { get; set; } } Now what I'm trying to figure out is if it's possible to specify a value for the Category property at the import. Something like: public class MyViewModel { [MyImportAttribute(Category="MyCategory")] public Logger Log { get; set; } } public class MyOtherViewModel { [MyImportAttribute(Category="MyOtherCategory")] public Logger Log { get; set; } } For the time being, what I'm doing is implementing IPartImportsSatisfiedNotification and setting the Category in code. But obviously I would rather keep everything neatly in one place.

    Read the article

  • Best practice to create WPF wrapper application displaying screens on demand.

    - by Robbie
    Context: I'm developing a WPF application which will contain a lot of different "screens". Each screen contains a which on its turn contains all the visual elements. Some elements trigger events (e.g., checkboxes), a screen has individual resources, etc. The main application is "wrapper" around these screens: it contains a menubar, toolbar, statusbar and alike (in a DockPanel) and space to display one screen. Through the menubar, the user can choose which screen he wants to display. Goal: I want to dynamically load & display & (event)handle one screen in the space in the main application. I don't want to copy & paste all the "wrapper" stuff in all the different screens. And As I have many complex screens (around 300 - luckily auto-generated), I don't want to load all of them at the start of the application, but only upon request. Question: What do you recommend as the best way to realize this? What kind of things should I use and investigate: Pages or windows or User Control for the screens? Does this affect the event handling?

    Read the article

  • Delegation, is this just opinionated or is there a common pattern?

    - by user1446714
    If I have a java class containing substantial code and I wish to add extra features, am I right in thinking the delegate class would have the additional features added as methods. Then my original class would create the delegate object and just call the extra functionality via the delegate instance? I am being told by somebody else that my original class should become the delegate and that the class containing the new functionality should contain an instance of the original class, to use as a delegate? This seemed a little backward to me, because there would be far more delegate calls because most of the code is now in the delegate.... I was always under the impression the delegate object would contain the additional new behaviour and an instance of it would be in the original class to inboke the new behaviour from?

    Read the article

  • MEF: Satisfy part on an Export using and Export from the composed part.

    - by Pop Catalin
    Hi, I have the following scenario in Silverlight 4: I have a notifications service Snippet [InheritedExport] public interface INotificationsService : IObservable<ReceivedNotification> { void IssueNotifications(IEnumerable<ClientIssuedNotification> notifications); } and and implementation of this service Snippet [PartCreationPolicy(CreationPolicy.NonShared)] public class ClientNotificationService : INotificationsService { [Import] IPlugin Plugin { get; set; } ... } How can I say to MEF that the Plugin property of the ClientNotificationService must be provided by the importing class that imports the INotificationsService. For example: Snippet public class Client { [Export] IPlugin Current { get; set; } [Import] INotificationService NotificationService; } How can I say that I want MEF to satisfy the ClientNotificationService.Plugin part with the exported IPlugin by the Client class. Basically I want the NotificationService, to receive a Unique ID provided by the importing class, whenever it is created and composed to a new class, or if there's and alternative method, like using meta data to do this I'd appreciate any insights. I've been struggling with this for a while. Thanks

    Read the article

  • Haskell: How to compose `not` with a function of arbitrary arity?

    - by Hynek -Pichi- Vychodil
    When I have some function of type like f :: (Ord a) => a -> a -> Bool f a b = a > b I should like make function which wrap this function with not. e.g. make function like this g :: (Ord a) => a -> a -> Bool g a b = not $ f a b I can make combinator like n f = (\a -> \b -> not $ f a b) But I don't know how. *Main> let n f = (\a -> \b -> not $ f a b) n :: (t -> t1 -> Bool) -> t -> t1 -> Bool Main> :t n f n f :: (Ord t) => t -> t -> Bool *Main> let g = n f g :: () -> () -> Bool What am I doing wrong? And bonus question how I can do this for function with more and lest parameters e.g. t -> Bool t -> t1 -> Bool t -> t1 -> t2 -> Bool t -> t1 -> t2 -> t3 -> Bool

    Read the article

  • Python - creating a list with 2 characteristics bug

    - by user2733911
    The goal is to create a list of 99 elements. All elements must be 1s or 0s. The first element must be a 1. There must be 7 1s in total. import random import math import time # constants determined through testing generation_constant = 0.96 def generate_candidate(): coin_vector = [] coin_vector.append(1) for i in range(0, 99): random_value = random.random() if (random_value > generation_constant): coin_vector.append(1) else: coin_vector.append(0) return coin_vector def validate_candidate(vector): vector_sum = sum(vector) sum_test = False if (vector_sum == 7): sum_test = True first_slot = vector[0] first_test = False if (first_slot == 1): first_test = True return (sum_test and first_test) vector1 = generate_candidate() while (validate_candidate(vector1) == False): vector1 = generate_candidate() print vector1, sum(vector1), validate_candidate(vector1) Most of the time, the output is correct, saying something like [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] 7 True but sometimes, the output is: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 2 False What exactly am I doing wrong?

    Read the article

  • How should an object that uses composition set its composed components?

    - by Casey
    After struggling with various problems and reading up on component-based systems and reading Bob Nystrom's excellent book "Game Programming Patterns" and in particular the chapter on Components I determined that this is a horrible idea: //Class intended to be inherited by all objects. Engine uses Objects exclusively. class Object : public IUpdatable, public IDrawable { public: Object(); Object(const Object& other); Object& operator=(const Object& rhs); virtual ~Object() =0; virtual void SetBody(const RigidBodyDef& body); virtual const RigidBody* GetBody() const; virtual RigidBody* GetBody(); //Inherited from IUpdatable virtual void Update(double deltaTime); //Inherited from IDrawable virtual void Draw(BITMAP* dest); protected: private: }; I'm attempting to refactor it into a more manageable system. Mr. Nystrom uses the constructor to set the individual components; CHANGING these components at run-time is impossible. It's intended to be derived and be used in derivative classes or factory methods where their constructors do not change at run-time. i.e. his Bjorne object is just a call to a factory method with a specific call to the GameObject constructor. Is this a good idea? Should the object have a default constructor and setters to facilitate run-time changes or no default constructor without setters and instead use a factory method? Given: class Object { public: //...See below for constructor implementation concerns. Object(const Object& other); Object& operator=(const Object& rhs); virtual ~Object() =0; //See below for Setter concerns IUpdatable* GetUpdater(); IDrawable* GetRenderer(); protected: IUpdatable* _updater; IDrawable* _renderer; private: }; Should the components be read-only and passed in to the constructor via: class Object { public: //No default constructor. Object(IUpdatable* updater, IDrawable* renderer); //...remainder is same as above... }; or Should a default constructor be provided and then the components can be set at run-time? class Object { public: Object(); //... SetUpdater(IUpdater* updater); SetRenderer(IDrawable* renderer); //...remainder is same as above... }; or both? class Object { public: Object(); Object(IUpdater* updater, IDrawable* renderer); //... SetUpdater(IUpdater* updater); SetRenderer(IDrawable* renderer); //...remainder is same as above... };

    Read the article

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