/// <summary>
        /// Looks up __init__ avoiding calls to __getattribute__ and handling both
        /// new-style and old-style classes in the MRO.
        /// </summary>
        private static object GetInitMethod(CodeContext /*!*/ context, PythonType dt, object newObject)
        {
            // __init__ is never searched for w/ __getattribute__
            for (int i = 0; i < dt.ResolutionOrder.Count; i++)
            {
                PythonType     cdt = dt.ResolutionOrder[i];
                PythonTypeSlot dts;
                object         value;
                if (cdt.IsOldClass)
                {
                    OldClass oc = PythonOps.ToPythonType(cdt) as OldClass;

                    if (oc != null && oc.TryGetBoundCustomMember(context, "__init__", out value))
                    {
                        return(oc.GetOldStyleDescriptor(context, value, newObject, oc));
                    }
                    // fall through to new-style only case.  We might accidently
                    // detect old-style if the user imports a IronPython.NewTypes
                    // type.
                }

                if (cdt.TryLookupSlot(context, "__init__", out dts) &&
                    dts.TryGetValue(context, newObject, dt, out value))
                {
                    return(value);
                }
            }
            return(null);
        }
示例#2
0
 PyClass_New(IntPtr basesPtr, IntPtr dictPtr, IntPtr namePtr)
 {
     try
     {
         PythonTuple bases = new PythonTuple();
         if (basesPtr != IntPtr.Zero)
         {
             bases = (PythonTuple)this.Retrieve(basesPtr);
         }
         return(this.Store(OldClass.__new__(this.scratchContext,
                                            TypeCache.OldClass, (string)this.Retrieve(namePtr), bases, (PythonDictionary)this.Retrieve(dictPtr))));
     }
     catch (Exception e)
     {
         this.LastException = e;
         return(IntPtr.Zero);
     }
 }
        private List <OldClass> FindPythonClasses()
        {
            List <OldClass> pythonClasses = new List <OldClass>();

            foreach (object obj in _engine.Globals.Values)
            {
                OldClass pythonClass = obj as OldClass;
                if (pythonClass != null)
                {
                    if (IsNUnitFixture(pythonClass))
                    {
                        pythonClasses.Add(pythonClass);
                    }
                }
            }

            return(pythonClasses);
        }
        public override FrameworkElement CreateLogIcon()
        {
            var current_source = IconUtils.GetImageSource(CurrentClass.ToLowerInvariant());
            var old_source     = IconUtils.GetImageSource(OldClass.ToLowerInvariant());
            var arrow_source   = IconUtils.GetImageSource("icon_arrow");

            var color = IconUtils.GetTeamColor(Player.Team);

            var old_image = new Image
            {
                Source              = old_source,
                Stretch             = Stretch.Uniform,
                HorizontalAlignment = HorizontalAlignment.Left,
                Margin              = new Thickness(2),
                Width = 26,
            };

            var arrow_image = new Image
            {
                Source              = arrow_source,
                Stretch             = Stretch.Uniform,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin              = new Thickness(2),
                Width = 26,
            };

            var current_image = new Image
            {
                Source              = current_source,
                Stretch             = Stretch.Uniform,
                HorizontalAlignment = HorizontalAlignment.Right,
                Margin              = new Thickness(2),
                Width = 26,
            };

            var grid = IconUtils.CreateBaseLogIcon(color);

            grid.Children.Add(current_image);
            grid.Children.Add(arrow_image);
            grid.Children.Add(old_image);

            return(grid);
        }
示例#5
0
        StoreTyped(OldClass cls)
        {
            uint   size = (uint)Marshal.SizeOf(typeof(PyClassObject));
            IntPtr ptr  = this.allocator.Alloc(size);

            CPyMarshal.Zero(ptr, size);

            CPyMarshal.WriteIntField(ptr, typeof(PyObject), "ob_refcnt", 2); // leak classes deliberately
            CPyMarshal.WritePtrField(ptr, typeof(PyObject), "ob_type", this.PyClass_Type);

            CPyMarshal.WritePtrField(ptr, typeof(PyClassObject), "cl_bases",
                                     this.Store(Builtin.getattr(this.scratchContext, cls, "__bases__")));
            CPyMarshal.WritePtrField(ptr, typeof(PyClassObject), "cl_dict",
                                     this.Store(Builtin.getattr(this.scratchContext, cls, "__dict__")));
            CPyMarshal.WritePtrField(ptr, typeof(PyClassObject), "cl_name",
                                     this.Store(Builtin.getattr(this.scratchContext, cls, "__name__")));

            this.map.Associate(ptr, cls);
            return(ptr);
        }
示例#6
0
        public static bool TryGetMixedNewStyleOldStyleSlot(CodeContext context, object instance, string name, out object value)
        {
            IPythonObject sdo = instance as IPythonObject;

            if (sdo != null)
            {
                PythonDictionary dict = sdo.Dict;
                if (dict != null && dict.TryGetValue(name, out value))
                {
                    return(true);
                }
            }

            PythonType dt = DynamicHelpers.GetPythonType(instance);

            foreach (PythonType type in dt.ResolutionOrder)
            {
                PythonTypeSlot dts;
                if (type != TypeCache.Object && type.OldClass != null)
                {
                    // we're an old class, check the old-class way
                    OldClass oc = type.OldClass;

                    if (oc.TryGetBoundCustomMember(context, name, out value))
                    {
                        value = oc.GetOldStyleDescriptor(context, value, instance, oc);
                        return(true);
                    }
                }
                else if (type.TryLookupSlot(context, name, out dts))
                {
                    // we're a dynamic type, check the dynamic type way
                    return(dts.TryGetValue(context, instance, dt, out value));
                }
            }

            value = null;
            return(false);
        }
        private PythonFixture BuildFixture(OldClass pythonClass)
        {
            PythonFixture fixture = new PythonFixture((string)pythonClass.__name__);

            OldInstance instance = _createInstance(pythonClass);

            // assing the test methods

            foreach (string methodName in FindTestMethods(pythonClass, TestMethodPrefix))
            {
                fixture.Add(new PythonTestCase(methodName, MakeProc(instance, methodName)));
            }

            // assign the setup and tear down methods

            fixture.SetFixtureSetup(MakeProc(instance, "setUpFixture"));
            fixture.SetFixtureTeardown(MakeProc(instance, "tearDownFixture"));
            fixture.SetSetup(MakeProc(instance, "setUp"));
            fixture.SetTeardown(MakeProc(instance, "tearDown"));

            // all done

            return(fixture);
        }
 public MetaOldClass(Expression /*!*/ expression, BindingRestrictions /*!*/ restrictions, OldClass /*!*/ value)
     : base(expression, BindingRestrictions.Empty, value)
 {
     Assert.NotNull(value);
 }
示例#9
0
 public AdaptorWithEncapsulation()
 {
     _cls = new OldClass();
 }
        private List <string> FindTestMethods(OldClass obj, string prefix)
        {
            List list = _findTestMethods(obj, prefix);

            return(new List <string>(new StrongEnumerator <string>(list)));
        }
 private bool IsNUnitFixture(OldClass obj)
 {
     return(_isNUnitFixture(obj));
 }
示例#12
0
 private List <string> FindTestMethods(OldClass obj, string prefix)
 {
     return(_findTestMethods(obj, prefix).ToList <string>());
 }
示例#13
0
        static void Main(string[] args)
        {
            #region Creational Patterns
            //Singleton
            Singleton singleton = Singleton.GetInstance();
            singleton.someUsefulCode();

            Separate();

            //Builder
            Item ciastko = new ItemBuilder(0).SetName("Ciastko").SetType("Food").build();
            Console.WriteLine($"{ciastko.id}. {ciastko.name}, {ciastko.type}");

            Separate();

            //Prototype
            Person person      = new Person(1, 15, "John");
            Person shallowCopy = (Person)person.ShallowCopy();
            Person deepCopy    = (Person)person.DeepCopy();
            Console.WriteLine(person);
            Console.WriteLine(shallowCopy);
            Console.WriteLine(deepCopy);
            person.name = "Max";
            person.age  = 20;
            person.id   = new IdInfo(99);
            Console.WriteLine(person);
            Console.WriteLine(shallowCopy);
            Console.WriteLine(deepCopy);

            Separate();

            //AbstractFactory
            Car miniCar = CarFactory.CarBuilder(CarType.MINI);
            Car lumiCar = CarFactory.CarBuilder(CarType.LUXURY);

            Separate();

            //FactoryPattern
            ShapeFactory shapeFactory = new ShapeFactory();
            Shape        circle       = shapeFactory.GetShape("circle");
            circle.print();

            Separate();

            //ObjectPool
            SomeObject so1 = Pool.GetObject();
            SomeObject so2 = Pool.GetObject();
            Pool.ReleaseObject(so1);
            SomeObject so3 = Pool.GetObject();
            Console.WriteLine($"so1: {so1}");
            Console.WriteLine($"so2: {so2}");
            Console.WriteLine($"so3: {so3}");

            Separate();

            #endregion

            #region Structural Patterns

            //Adapter
            OldClass oldClass = new OldClass();
            IWrite   write    = new Adapter(oldClass);
            write.PrintMessage();

            Separate();

            //Bridge
            Thing triangle = new Ball(new Blue());
            triangle.print();

            Separate();

            //Composite
            Component leaf1 = new Leaf("leaf1");
            Component leaf2 = new Leaf("leaf2");
            Component leaf3 = new Leaf("leaf3");

            Component branch1 = new Composite("branch1");
            branch1.Add(leaf1);
            branch1.Add(leaf2);

            Component root = new Composite("root");
            root.Add(branch1);
            root.Add(leaf3);

            root.Display(1);

            Separate();

            //Decorator
            Weapon weapon = new BaseWeapon();
            weapon.shot();
            Weapon modifiedWeapon = new Stock(weapon);
            modifiedWeapon.shot();

            Separate();

            //Facade
            Student student = new Student();
            student.StartLearning();
            student.EndLearning();

            Separate();

            //Flyweight
            Particle p1 = ParticleFactory.getSmallParticle("red");  //new key
            Particle p2 = ParticleFactory.getSmallParticle("red");  //no new one
            Particle p3 = ParticleFactory.getSmallParticle("blue"); //new key

            Separate();

            //Proxy
            IBank proxyBank = new ProxyBank();
            proxyBank.Pay();

            Separate();

            #endregion

            #region Behavioral Patterns

            //ChainOfResponsibility
            Chain chain = new Chain();
            chain.Process(5);

            Separate();

            //Command
            var modifyPrice = new ModifyPrice();
            var product     = new Product("Brick", 200);

            Console.WriteLine(product);
            modifyPrice.SetCommandAndInvoke(new ProductCommand(product, PriceAction.Increase, 50));
            Console.WriteLine(product);

            Separate();


            //Iterator
            CarRepository carRepository = new CarRepository(new string[] { "Renault", "BMW", "VW" });

            for (IIterator i = carRepository.GetIterator(); i.hasNext();)
            {
                Console.WriteLine($"Car: {i.next()}");
            }

            Separate();

            //Mediator
            Mediator mediator = new RealMediator();
            APerson  jhon     = new RealPerson(mediator, "Jhon");
            APerson  max      = new RealPerson(mediator, "Max");
            APerson  emma     = new RealPerson(mediator, "Emma");
            mediator.AddPerson(jhon);
            mediator.AddPerson(max);
            mediator.AddPerson(emma);

            jhon.Send("I'm a jhon and this is my message! ");
            emma.Send("henlo");

            Separate();

            //Memento
            Localization         localization = new Localization("NY", 123, 111);
            LocalizationSnapshot snapshot     = localization.CreateSnapshot();
            Console.WriteLine(localization);

            localization.City = "Berlin";
            localization.X    = 999;
            Console.WriteLine(localization);

            snapshot.Restore();
            Console.WriteLine(localization);

            Separate();

            //Observer
            Customer james   = new Customer("James");
            Customer william = new Customer("William");
            Customer evelyn  = new Customer("Evelyn");

            Shop grocery = new Shop("YourFood");
            Shop DIYshop = new Shop("Tooler");

            grocery.AddSubscriber(james);
            grocery.AddSubscriber(william);
            grocery.AddSubscriber(evelyn);

            DIYshop.AddSubscriber(james);
            DIYshop.AddSubscriber(william);

            grocery.AddMerchandise(new Merchandise("pizza", 19));
            DIYshop.AddMerchandise(new Merchandise("hammer", 399));

            Separate();

            //State
            AudioPlayer ap = new AudioPlayer();
            ap.ClickPlay();
            ap.ClickLock();
            ap.ClickPlay();
            ap.ClickPlay();
            ap.ClickPlay();
            ap.ClickLock();
            ap.NextSong();
            ap.PreviousSong();

            Separate();

            //Strategy
            Calculator calculator = new Calculator(new AddingStrategy());
            calculator.Calculate(5, 2);
            calculator.ChangeStrategy(new SubtractingStrategy());
            calculator.Calculate(5, 2);

            Separate();

            //TemplateMethod
            Algorithm a1 = new AlgorithmWithStep2();
            a1.Execute();
            Algorithm a2 = new AlgorithmWithStep2and3();
            a2.Execute();

            Separate();

            //Visitor
            ElementA ea = new ElementA("ElementA");
            ElementA eb = new ElementA("ElementB");
            Visitor1 v1 = new Visitor1();
            Visitor2 v2 = new Visitor2();
            ea.Accept(v1);
            ea.Accept(v2);
            eb.Accept(v1);
            eb.Accept(v2);
            #endregion
        }