Example #1
0
        public BlackConstantVol(int settlementDays, Calendar cal, Handle<Quote> volatility, DayCounter dc)
            : base(settlementDays, cal, BusinessDayConvention.Following, dc)
        {
            volatility_ = volatility;

            volatility_.registerWith(update);
        }
 public void SetXDataForMainDescription(Handle handle)
 {
     XDataCollection descriptionSignXData = new XDataCollection()
     {
         new XData("skd", 1040, 0),
         new XData("l2p", 1040, barLength),
         new XData("l1p", 1040, barLength),
         new XData("g_d", 1000, signType),
         new XData("kom", 1000, "\u0020"),
         new XData("dds", 1040, scale),
         new XData("typ", 1070, 1),
         new XData("ilp", 1070, barsAmount),
         new XData("ilw", 1070, tiersAmount),
         new XData("sko", 1040, spanStep),
         new XData("sre", 1040, barDiameter),
         new XData(barNumberRecordName, 1000, "bw"),
         new XData(opNumberRecordName, 1000, "bw"),
         new XData("pro", 1000, "sys01-v4"),
         new XData("nop", 1070, operationNumber),
         new XData("npo", 1070, barNumber),
         new XData("zn1", 1000, "bw"),
         new XData("zna", 1000, "zn1")
     };
     SetXData(handle, descriptionSignXData);
 }
Example #3
0
        public BlackConstantVol(Date referenceDate, Calendar cal, Handle<Quote> volatility, DayCounter dc)
            : base(referenceDate, cal, BusinessDayConvention.Following, dc)
        {
            volatility_ = volatility;

            volatility_.registerWith(update);
        }
Example #4
0
        /// <summary>
        /// Gets the Offset of the text when applying a relativeHandle to a text
        /// </summary>
        /// <param name="relativeHandle">The applied handle.</param>
        /// <param name="text">The given text.</param>
        /// <returns>A Vector2 representing the offset of the handle.</returns>
        /// <remarks>When used on a text, the negative value needs to be used.</remarks>
        public Vector2 GetHandleOffset(Handle relativeHandle, string text)
        {
            Vector2 offset = this.GetDimension(text);

            switch (relativeHandle)
            {
                case Handle.BottomCenter:
                    return new Vector2(offset.X/2, offset.Y);
                case Handle.BottomLeft:
                    return new Vector2(0, offset.Y);
                case Handle.BottomRight:
                    return offset;
                case Handle.MiddleCenter:
                    return offset/2;
                case Handle.MiddleLeft:
                    return new Vector2(0, offset.Y/2);
                case Handle.MiddleRight:
                    return new Vector2(offset.X, offset.Y/2);
                case Handle.TopCenter:
                    return new Vector2(offset.X/2, 0);
                case Handle.TopRight:
                    return new Vector2(offset.X, 0);
                default:
                    return new Vector2();
            }
        }
Example #5
0
      // Handle<YieldTermStructure> discountCurve = Handle<YieldTermStructure>());
      public ForwardRateAgreement(Date valueDate, Date maturityDate, Position.Type type, double strikeForwardRate,
                                  double notionalAmount, IborIndex index, Handle<YieldTermStructure> discountCurve)
         : base(index.dayCounter(), index.fixingCalendar(), index.businessDayConvention(), index.fixingDays(), new Payoff(),
                 valueDate, maturityDate, discountCurve) {

         fraType_ = type;
         notionalAmount_ = notionalAmount;
         index_ = index;

         if (notionalAmount <= 0.0)
            throw new ApplicationException("notional Amount must be positive");

         // do I adjust this ?
         // valueDate_ = calendar_.adjust(valueDate_,businessDayConvention_);
         Date fixingDate = calendar_.advance(valueDate_, -settlementDays_, TimeUnit.Days);
         forwardRate_ = new InterestRate(index.fixing(fixingDate), index.dayCounter(), Compounding.Simple, Frequency.Once);
         strikeForwardRate_ = new InterestRate(strikeForwardRate, index.dayCounter(), Compounding.Simple, Frequency.Once);
         double strike = notionalAmount_ * strikeForwardRate_.compoundFactor(valueDate_, maturityDate_);
         payoff_ = new ForwardTypePayoff(fraType_, strike);
         // incomeDiscountCurve_ is irrelevant to an FRA
         incomeDiscountCurve_ = discountCurve_;
         // income is irrelevant to FRA - set it to zero
         underlyingIncome_ = 0.0;
         
         index_.registerWith(update);
      }
 public Block GetAllocatedBlock(Handle handle)
 {
     Block block;
     if (!_allocatedBlocks.TryGetValue(handle, out block))
         throw new Exception("invalid handle");
     return block;
 }
 public DiscountingBasisSwapEngine(Handle<YieldTermStructure> discountCurve1 , 
                              Handle<YieldTermStructure> discountCurve2) 
 {
    discountCurve_ = new List<Handle<YieldTermStructure>>();
    discountCurve_.Add(discountCurve1);
    discountCurve_.Add(discountCurve2);
 }
Example #8
0
        protected ConvertibleBond( Exercise exercise,
                                 double conversionRatio,
                                 DividendSchedule dividends,
                                 CallabilitySchedule callability,
                                 Handle<Quote> creditSpread,
                                 Date issueDate,
                                 int settlementDays,
                                 Schedule schedule,
                                 double redemption)
            : base(settlementDays, schedule.calendar(), issueDate)
        {
            conversionRatio_ = conversionRatio;
             callability_ = callability;
             dividends_ = dividends;
             creditSpread_ = creditSpread;

             maturityDate_ = schedule.endDate();

             if (!callability.empty())
             {
            Utils.QL_REQUIRE( callability.Last().date() <= maturityDate_, () =>
                              "last callability date ("
                              + callability.Last().date()
                              + ") later than maturity ("
                              + maturityDate_.ToShortDateString() + ")");
            }

             creditSpread.registerWith(update);
        }
Example #9
0
        public BMAIndex(Handle<YieldTermStructure> h)
            : base("BMA", new Period(1, TimeUnit.Weeks), 1, new USDCurrency(),
				   new UnitedStates(UnitedStates.Market.NYSE), new ActualActual(ActualActual.Convention.ISDA))
        {
            termStructure_ = h;
            h.registerWith(update);
        }
Example #10
0
        // --------------------------------------------------------------------------------------------------------------------

        /// <summary>
        /// Returns an existing or new handle to wrap the proxy reference.
        /// </summary>
        internal Handle _GetHandle(HandleProxy* hp)
        {
            _DoWorkStep(); // (attempt to dispose of at least one handle on each call to attempt to keep reusing handles whenever possible)

            if (hp == null) return null;

            if (hp->ManagedHandleID >= 0)
                return _Handles[hp->ManagedHandleID].Object._Reset();

            Handle handle;

            switch (hp->ValueType)
            {
                case JSValueType.Bool: handle = new Handle<bool>(this); break;
                case JSValueType.Date: handle = new Handle<DateTime>(this); break;
                case JSValueType.Int32: handle = new Handle<Int32>(this); break;
                case JSValueType.Number: handle = new Handle<double>(this); break;
                case JSValueType.String: handle = new Handle<string>(this); break;

                case JSValueType.CompilerError: handle = new Handle<string>(this); break;
                case JSValueType.ExecutionError: handle = new Handle<string>(this); break;
                case JSValueType.InternalError: handle = new Handle<string>(this); break;

                default: handle = new Handle<object>(this); break;
            }

            handle._Initialize(hp);

            lock (_Handles) // (whole list may be affected internally, so this needs to be thread protected)
            {
                hp->ManagedHandleID = handle._ID = _Handles.Add(new ObservableWeakReference<Handle>(handle));
            }

            return handle;
        }
Example #11
0
        public virtual SwapIndex clone(Handle<YieldTermStructure> forwarding)
        {
            if (exogenousDiscount_)
            {
                return new SwapIndex(familyName(),
                                     tenor(),
                                     fixingDays(),
                                     currency(),
                                     fixingCalendar(),
                                     fixedLegTenor(),
                                     fixedLegConvention(),
                                     dayCounter(),
                                     iborIndex_.clone(forwarding),
                                     discount_);
            }

            return new SwapIndex(familyName(),
                                 tenor(),
                                 fixingDays(),
                                 currency(),
                                 fixingCalendar(),
                                 fixedLegTenor(),
                                 fixedLegConvention(),
                                 dayCounter(),
                                 iborIndex_.clone(forwarding));
        }
Example #12
0
        public G2(Handle<YieldTermStructure> termStructure,
            double a,
            double sigma,
            double b,
            double eta,
            double rho)
            : base(5)
        {
            //TermStructureConsistentModel = termStructure;
            /* regroupement car plant!!
             * *a_ = arguments_[0];
            sigma_ = arguments_[1];
            b_ = arguments_[2];
            eta_ = arguments_[3];
            rho_ = arguments_[4];*/

            termStructure_ = termStructure;
            a_ = arguments_[0] = new ConstantParameter(a, new PositiveConstraint());
            sigma_ = arguments_[1] = new ConstantParameter(sigma, new PositiveConstraint());
            b_ = arguments_[2] = new ConstantParameter(b, new PositiveConstraint());
            eta_ =  arguments_[3] = new ConstantParameter(eta, new PositiveConstraint());
            rho_ = arguments_[4] = new ConstantParameter(rho, new BoundaryConstraint(-1.0, 1.0));

            generateArguments();
            termStructure.registerWith(update);
        }
Example #13
0
 private static void TestGenerationHandle(MetadataAggregator aggregator, Handle handle, Handle expectedHandle, int expectedGeneration)
 {
     int actualGeneration;
     var actualHandle = aggregator.GetGenerationHandle(handle, out actualGeneration);
     Assert.Equal(expectedGeneration, actualGeneration);
     Assert.Equal(expectedHandle, actualHandle);
 }
		private void AsyncRead (Handle handle, Result result, byte[] buf,
					ulong bytesRequested, ulong bytesRead)
		{
			if (result == Result.Ok) {
				Array.Copy (buf, 0, buffer, offset + count - bytesRemaining, (int)bytesRead);
				bytesRemaining -= (int)bytesRead;
				if (bytesRemaining > 0) {
					buf = new byte[bytesRemaining];
					Async.Read (handle, out buf[0], (uint)bytesRemaining,
						    new AsyncReadCallback (AsyncRead));
				} else if (cback != null) {
					asyncResult.SetComplete (null, count);
					cback (asyncResult);
				}
			} else if (result == Result.ErrorEof) {
				Array.Copy (buf, 0, buffer, offset + count - bytesRemaining, (int)bytesRead);
				bytesRemaining -= (int)bytesRead;
				asyncResult.SetComplete (null, count - bytesRemaining);
				
				if (cback != null)
					cback (asyncResult);
			} else if (cback != null) {
				Exception e = new IOException (Vfs.ResultToString (result));
				asyncResult.SetComplete (e, -1);
				cback (asyncResult);
			}
		}
Example #15
0
 public BlackProcess(Handle<Quote> x0,
                     Handle<YieldTermStructure> riskFreeTS,
                     Handle<BlackVolTermStructure> blackVolTS,
                     IDiscretization1D d)
     : base(x0, riskFreeTS, riskFreeTS, blackVolTS, d)
 {
 }
 private RuntimeFatMethodParameterInfo(MethodBase member, MethodHandle methodHandle, int position, ParameterHandle parameterHandle, ReflectionDomain reflectionDomain, MetadataReader reader, Handle typeHandle, TypeContext typeContext)
     : base(member, position, reflectionDomain, reader, typeHandle, typeContext)
 {
     _methodHandle = methodHandle;
     _parameterHandle = parameterHandle;
     _parameter = parameterHandle.GetParameter(reader);
 }
Example #17
0
        public DerivedQuote(Handle<Quote> element, Func<double, double> f)
        {
            element_ = element;
             f_ = f;

             element_.registerWith(this.update);
        }
Example #18
0
 public BlackScholesMertonProcess(Handle<Quote> x0,
                                  Handle<YieldTermStructure> dividendTS,
                                  Handle<YieldTermStructure> riskFreeTS,
                                  Handle<BlackVolTermStructure> blackVolTS)
     : this(x0, dividendTS, riskFreeTS, blackVolTS, new EulerDiscretization())
 {
 }
 public BlackSwaptionEngine(Handle<YieldTermStructure> termStructure,
                          double vol, DayCounter dc )
 {
     termStructure_ = termStructure;
     volatility_ = new Handle<SwaptionVolatilityStructure>(new ConstantSwaptionVolatility(0, new NullCalendar(), BusinessDayConvention.Following, vol, dc));
     termStructure_.registerWith(update);
 }
Example #20
0
        public static bool GetDefaultValueIfAny(MemberType memberType, MetadataReader reader, Handle constantHandle, Type declaredType, IEnumerable<CustomAttributeData> customAttributes, out Object defaultValue)
        {
            if (!(constantHandle.IsNull(reader)))
            {
                defaultValue = ParseMetadataConstant(reader, constantHandle);
                if (declaredType.GetTypeInfo().IsEnum)
                    defaultValue = Enum.ToObject(declaredType, defaultValue);
                return true;
            }

            if (memberType != MemberType.Property)  // the attributes in question cannot be applied to properties.
            {
                // Legacy: If there are multiple default value attribute, the desktop picks one at random (and so do we...)
                foreach (CustomAttributeData cad in customAttributes)
                {
                    Type attributeType = cad.AttributeType;
                    TypeInfo attributeTypeInfo = attributeType.GetTypeInfo();
                    if (attributeTypeInfo.IsSubclassOf(typeof(CustomConstantAttribute)))
                    {
                        CustomConstantAttribute customConstantAttribute = (CustomConstantAttribute)(cad.Instantiate());
                        defaultValue = customConstantAttribute.Value;
                        return true;
                    }
                    if (attributeType.Equals(typeof(DecimalConstantAttribute)))
                    {
                        DecimalConstantAttribute decimalConstantAttribute = (DecimalConstantAttribute)(cad.Instantiate());
                        defaultValue = decimalConstantAttribute.Value;
                        return true;
                    }
                }
            }

            defaultValue = null;
            return false;
        }
Example #21
0
        public LocalVolCurve(Handle<BlackVarianceCurve> curve)
            : base(curve.link.businessDayConvention(), curve.link.dayCounter())
        {
            blackVarianceCurve_ = curve;

            blackVarianceCurve_.registerWith(update);
        }
Example #22
0
        public Player(uint id, DotaGameState state) : base(id, state)
        {
            const string t = "DT_DOTAPlayer";

            PlayerId = bind<uint>(t, "m_iPlayerID");
            Hero = handle(t, "m_hAssignedHero");
        }
Example #23
0
        SwaptionHelper( Date exerciseDate,
            Period length,
            Handle<Quote> volatility,
            IborIndex index,
            Period fixedLegTenor,
            DayCounter fixedLegDayCounter,
            DayCounter floatingLegDayCounter,
            Handle<YieldTermStructure> termStructure,
            CalibrationErrorType errorType = CalibrationErrorType.RelativePriceError,
            double? strike = null,
            double nominal = 1.0)
            : base(volatility, termStructure, errorType)
        {
            exerciseDate_ = exerciseDate;
            endDate_ = null;
            maturity_ = new Period(0,TimeUnit.Days);
            length_ = length;
            fixedLegTenor_ = fixedLegTenor;
            index_ = index;
            fixedLegDayCounter_ = fixedLegDayCounter;
            floatingLegDayCounter_ = floatingLegDayCounter;
            strike_ = strike;
            nominal_ = nominal;

            index_.registerWith( update );
        }
Example #24
0
        public SwapRateHelper(Handle<Quote> rate, Period tenor, Calendar calendar,
            Frequency fixedFrequency, BusinessDayConvention fixedConvention, DayCounter fixedDayCount,
            IborIndex iborIndex)
            : this(rate, tenor, calendar, fixedFrequency, fixedConvention, fixedDayCount, iborIndex,
		                      	     new Handle<Quote>(), new Period(0, TimeUnit.Days))
        {
        }
 public MoveHandleAction(Handle handle, Session session, PointD oldLocation)
 {
     this.handle = handle;
       this.session = session;
       this.oldLocation = oldLocation;
       this.newLocation = handle.Location;
 }
Example #26
0
        public void Start()
        {
            api.app_Start (Update, Render);
            unlitShader = Data.CreateUnlitShader (api);
            checkerboardTexture = Data.CreateCheckerboardTexture (api);

            elements = new IElement[]
            {
                new Element <CubePosTex, VertPosTex> (unlitShader, 1, checkerboardTexture),
                //new Element <CylinderPosTex, VertPosTex> (unlitShader, 0, checkerboardTexture),
                //new Element <BillboardPosTexCol, VertPosTexCol> (unlitShader, 0, checkerboardTexture),
                //new Element <BillboardPosTex, VertPosTex> (unlitShader, 0, checkerboardTexture),
                //new Element <CylinderPosNormTex, VertPosNormTex> (unlitShader, 0, checkerboardTexture),
                //new Element <CylinderNormTexPos, VertNormTexPos> (unlitShader, 0, checkerboardTexture),
                //new Element <FlowerPosCol, VertPosCol> (unlitShader, 0, null),
                //new Element <FlowerPos, VertPos> (unlitShader, 0, null),
            };

            Double s = Math.Sqrt (elements.Length);

            numCols = (Int32) Math.Ceiling (s);

            numRows = (Int32) Math.Floor (s);

            while (elements.Length > numCols * numRows) ++numRows;

            foreach (var element in elements) element.Load (api);
            timer.Start ();
        }
        public Handle<YieldTermStructure> dividendCurve(Underlying item)
        {
            double riskFreeRate = 0.06;

            var termStructure = new Handle<YieldTermStructure>(new FlatForward(referenceDate_, riskFreeRate, dayCounter_));
            return termStructure;
        }
 public CallableBondConstantVolatility(int settlementDays, Calendar calendar, double volatility, DayCounter dayCounter)
    :base(settlementDays, calendar)
 {
    volatility_ = new Handle<Quote>(new SimpleQuote(volatility));
    dayCounter_ = dayCounter;
    maxBondTenor_ = new Period(100,TimeUnit.Years);
 }
 public CallableBondConstantVolatility(Date referenceDate, double volatility, DayCounter dayCounter)
    :base(referenceDate)
 {
    volatility_ = new Handle<Quote>(new SimpleQuote(volatility));
    dayCounter_ = dayCounter;
    maxBondTenor_ = new Period(100,TimeUnit.Years);
 }
 public CallableBondConstantVolatility(int settlementDays, Calendar calendar, Handle<Quote> volatility,DayCounter dayCounter)
     :base(settlementDays, calendar)
 {
    volatility_ = volatility;
    dayCounter_ = dayCounter;
    maxBondTenor_ = new Period(100,TimeUnit.Years);
    volatility_.registerWith(update);
 }
Example #31
0
 /// <summary>
 /// Waits for the <see cref="Session"/> to finish all pending downloads.
 /// </summary>
 /// <returns>An awaitable <see cref="Task"/> that will be completed when all pending downloads for this <see cref="Session"/> are completed.</returns>
 /// <exception cref="InvalidOperationException">Thrown when a faulted session is waited on.</exception>
 public Task WaitForDownloadAsync() => Handle.WaitAsync(ProgressDirection.Download);
Example #32
0
    //------------------------------------------------------------------------------
    //たまにSEをループさせたいことがある
    public void SetEnableSeLoop(Handle handle, bool enable)
    {
        AudioSource source = seHandles[handle];

        source.loop = enable;
    }
Example #33
0
 /// <summary>
 /// Stops any synchronization with the server until the Realm is re-opened again
 /// after fully closing it.
 /// <br/>
 /// Synchronization can be re-enabled by calling <see cref="Start"/> again.
 /// </summary>
 /// <remarks>
 /// If the session is already stopped, calling this method will do nothing.
 /// </remarks>
 public void Stop()
 {
     Handle.Stop();
 }
Example #34
0
        public T Delete(IPriorityQueueHandle <T> handle)
        {
            stamp++;
            int    cell;
            bool   isfirst;
            Handle myhandle = checkHandle(handle, out cell, out isfirst);

            T retval;

            myhandle.index = -1;
            int lastcell = (size - 1) / 2;

            if (cell == lastcell)
            {
                if (isfirst)
                {
                    retval = heap[cell].first;
                    if (size % 2 == 0)
                    {
                        updateFirst(cell, heap[cell].last, heap[cell].lasthandle);
                        heap[cell].last       = default(T);
                        heap[cell].lasthandle = null;
                    }
                    else
                    {
                        heap[cell].first       = default(T);
                        heap[cell].firsthandle = null;
                    }
                }
                else
                {
                    retval                = heap[cell].last;
                    heap[cell].last       = default(T);
                    heap[cell].lasthandle = null;
                }
                size--;
            }
            else if (isfirst)
            {
                retval = heap[cell].first;

                if (size % 2 == 0)
                {
                    updateFirst(cell, heap[lastcell].last, heap[lastcell].lasthandle);
                    heap[lastcell].last       = default(T);
                    heap[lastcell].lasthandle = null;
                }
                else
                {
                    updateFirst(cell, heap[lastcell].first, heap[lastcell].firsthandle);
                    heap[lastcell].first       = default(T);
                    heap[lastcell].firsthandle = null;
                }

                size--;
                if (heapifyMin(cell))
                {
                    bubbleUpMax(cell);
                }
                else
                {
                    bubbleUpMin(cell);
                }
            }
            else
            {
                retval = heap[cell].last;

                if (size % 2 == 0)
                {
                    updateLast(cell, heap[lastcell].last, heap[lastcell].lasthandle);
                    heap[lastcell].last       = default(T);
                    heap[lastcell].lasthandle = null;
                }
                else
                {
                    updateLast(cell, heap[lastcell].first, heap[lastcell].firsthandle);
                    heap[lastcell].first       = default(T);
                    heap[lastcell].firsthandle = null;
                }

                size--;
                if (heapifyMax(cell))
                {
                    bubbleUpMin(cell);
                }
                else
                {
                    bubbleUpMax(cell);
                }
            }

            raiseItemsRemoved(retval, 1);
            raiseCollectionChanged();

            return(retval);
        }
Example #35
0
        bool heapifyMax(int i)
        {
            bool   swappedroot = false;
            int    cell = i, currentmax = cell;
            T      currentitem   = heap[cell].last;
            Handle currenthandle = heap[cell].lasthandle;

            if (i > 0)
            {
                T other = heap[cell].first;
                if (comparer.Compare(currentitem, other) < 0)
                {
                    swappedroot = true;
                    Handle otherhandle = heap[cell].firsthandle;
                    updateFirst(cell, currentitem, currenthandle);
                    currentitem   = other;
                    currenthandle = otherhandle;
                }
            }

            T      maxitem   = currentitem;
            Handle maxhandle = currenthandle;

            while (true)
            {
                int l = 2 * cell + 1, r = l + 1;
                T   lv, rv;

                if (2 * l + 1 < size && comparer.Compare(lv = heap[l].last, maxitem) > 0)
                {
                    currentmax = l; maxitem = lv;
                }

                if (2 * r + 1 < size && comparer.Compare(rv = heap[r].last, maxitem) > 0)
                {
                    currentmax = r; maxitem = rv;
                }

                if (currentmax == cell)
                {
                    break;
                }

                maxhandle = heap[currentmax].lasthandle;
                updateLast(cell, maxitem, maxhandle);
                cell = currentmax;

                //Maybe swap first and last
                T other = heap[cell].first;
                if (comparer.Compare(currentitem, other) < 0)
                {
                    Handle otherhandle = heap[cell].firsthandle;
                    updateFirst(cell, currentitem, currenthandle);
                    currentitem   = other;
                    currenthandle = otherhandle;
                }

                maxitem   = currentitem;
                maxhandle = currenthandle;
            }

            if (cell != i || swappedroot) //Check could be better?
            {
                updateLast(cell, maxitem, maxhandle);
            }
            return(swappedroot);
        }
Example #36
0
 public void GenerateHandle()
 {
     MyPrefix     = P_List[Random.Range(0, P_List.Length)];
     MyHandle     = H_List[Random.Range(0, H_List.Length)];
     MyMidSection = M_List[Random.Range(0, M_List.Length)];
 }
Example #37
0
        public TextWave1()
        {
            this.TextPath           = true;
            this.AdjustmentValues   = "2809,10800";
            this.Path               = "m@25@0c@26@3@27@1@28@0m@21@4c@22@5@23@6@24@4e";
            this.ConnectorLocations = "@35,@0;@38,10800;@37,@4;@36,10800";
            this.ConnectorAngles    = "270,180,90,0";

            this.Handles = new List <Handle>();
            var h1 = new Handle
            {
                position = "topLeft,#0",
                yrange   = "0,4459"
            };
            var h2 = new Handle
            {
                position = "#1,bottomRight",
                xrange   = "8640,12960"
            };

            this.Handles.Add(h1);
            this.Handles.Add(h2);

            this.Formulas = new List <string>();
            this.Formulas.Add("val #0");
            this.Formulas.Add("prod @0 41 9");
            this.Formulas.Add("prod @0 23 9");
            this.Formulas.Add("sum 0 0 @2");
            this.Formulas.Add("sum 21600 0 #0");
            this.Formulas.Add("sum 21600 0 @1");
            this.Formulas.Add("sum 21600 0 @3");
            this.Formulas.Add("sum #1 0 10800");
            this.Formulas.Add("sum 21600 0 #1");
            this.Formulas.Add("prod @8 2 3");
            this.Formulas.Add("prod @8 4 3");
            this.Formulas.Add("prod @8 2 1");
            this.Formulas.Add("sum 21600 0 @9");
            this.Formulas.Add("sum 21600 0 @10");
            this.Formulas.Add("sum 21600 0 @11");
            this.Formulas.Add("prod #1 2 3");
            this.Formulas.Add("prod #1 4 3");
            this.Formulas.Add("prod #1 2 1");
            this.Formulas.Add("sum 21600 0 @15");
            this.Formulas.Add("sum 21600 0 @16");
            this.Formulas.Add("sum 21600 0 @17");
            this.Formulas.Add("if @7 @14 0");
            this.Formulas.Add("if @7 @13 @15");
            this.Formulas.Add("if @7 @12 @16");
            this.Formulas.Add("if @7 21600 @17");
            this.Formulas.Add("if @7 0 @20");
            this.Formulas.Add("if @7 @9 @19");
            this.Formulas.Add("if @7 @10 @18");
            this.Formulas.Add("if @7 @11 21600");
            this.Formulas.Add("sum @24 0 @21");
            this.Formulas.Add("sum @4 0 @0");
            this.Formulas.Add("max @21 @25");
            this.Formulas.Add("min @24 @28");
            this.Formulas.Add("prod @0 2 1");
            this.Formulas.Add("sum 21600 0 @33");
            this.Formulas.Add("mid @26 @27");
            this.Formulas.Add("mid @24 @28");
            this.Formulas.Add("mid @22 @23");
            this.Formulas.Add("mid @21 @25");
        }
Example #38
0
        /// <summary>
        /// Evaluates the specified option contract to compute a theoretical price, IV and greeks
        /// </summary>
        /// <param name="security">The option security object</param>
        /// <param name="slice">The current data slice. This can be used to access other information
        /// available to the algorithm</param>
        /// <param name="contract">The option contract to evaluate</param>
        /// <returns>An instance of <see cref="OptionPriceModelResult"/> containing the theoretical
        /// price of the specified option contract</returns>
        public OptionPriceModelResult Evaluate(Security security, Slice slice, OptionContract contract)
        {
            if (!AllowedOptionStyles.Contains(contract.Symbol.ID.OptionStyle))
            {
                throw new ArgumentException($"{contract.Symbol.ID.OptionStyle} style options are not supported by option price model '{this.GetType().Name}'");
            }

            try
            {
                // expired options have no price
                if (contract.Time.Date > contract.Expiry.Date)
                {
                    return(OptionPriceModelResult.None);
                }

                // setting up option pricing parameters
                var calendar       = new UnitedStates();
                var dayCounter     = new Actual365Fixed();
                var optionSecurity = (Option)security;

                var securityExchangeHours = security.Exchange.Hours;
                var settlementDate        = AddDays(contract.Time.Date, Option.DefaultSettlementDays, securityExchangeHours);
                var maturityDate          = AddDays(contract.Expiry.Date, Option.DefaultSettlementDays, securityExchangeHours);
                var underlyingQuoteValue  = new SimpleQuote((double)optionSecurity.Underlying.Price);

                var dividendYieldValue = new SimpleQuote(_dividendYieldEstimator.Estimate(security, slice, contract));
                var dividendYield      = new Handle <YieldTermStructure>(new FlatForward(0, calendar, dividendYieldValue, dayCounter));

                var riskFreeRateValue = new SimpleQuote(_riskFreeRateEstimator.Estimate(security, slice, contract));
                var riskFreeRate      = new Handle <YieldTermStructure>(new FlatForward(0, calendar, riskFreeRateValue, dayCounter));

                var underlyingVolValue = new SimpleQuote(_underlyingVolEstimator.Estimate(security, slice, contract));
                var underlyingVol      = new Handle <BlackVolTermStructure>(new BlackConstantVol(0, calendar, new Handle <Quote>(underlyingVolValue), dayCounter));

                if (!_underlyingVolEstimator.IsReady)
                {
                    return(OptionPriceModelResult.None);
                }

                // preparing stochastic process and payoff functions
                var stochasticProcess = new BlackScholesMertonProcess(new Handle <Quote>(underlyingQuoteValue), dividendYield, riskFreeRate, underlyingVol);
                var payoff            = new PlainVanillaPayoff(contract.Right == OptionRight.Call ? QLNet.Option.Type.Call : QLNet.Option.Type.Put, (double)contract.Strike);

                // creating option QL object
                var option = contract.Symbol.ID.OptionStyle == OptionStyle.American ?
                             new VanillaOption(payoff, new AmericanExercise(settlementDate, maturityDate)) :
                             new VanillaOption(payoff, new EuropeanExercise(maturityDate));

                QLNet.Settings.setEvaluationDate(settlementDate);

                // preparing pricing engine QL object
                option.setPricingEngine(_pricingEngineFunc(contract.Symbol, stochasticProcess));

                // running calculations
                // can return negative value in neighbourhood of 0
                var npv = Math.Max(0, EvaluateOption(option));

                // function extracts QL greeks catching exception if greek is not generated by the pricing engine and reevaluates option to get numerical estimate of the seisitivity
                Func <Func <double>, Func <double>, decimal> tryGetGreekOrReevaluate = (greek, reevalFunc) =>
                {
                    try
                    {
                        return((decimal)greek());
                    }
                    catch (Exception)
                    {
                        return(EnableGreekApproximation ? (decimal)reevalFunc() : 0.0m);
                    }
                };

                // function extracts QL greeks catching exception if greek is not generated by the pricing engine
                Func <Func <double>, decimal> tryGetGreek = greek => tryGetGreekOrReevaluate(greek, () => 0.0);

                // function extracts QL IV catching exception if IV is not generated by the pricing engine
                Func <decimal> tryGetImpliedVol = () =>
                {
                    try
                    {
                        return((decimal)option.impliedVolatility((double)optionSecurity.Price, stochasticProcess));
                    }
                    catch (Exception err)
                    {
                        Log.Debug($"tryGetImpliedVol() error: {err.Message}");
                        return(0m);
                    }
                };

                Func <Tuple <decimal, decimal> > evalDeltaGamma = () =>
                {
                    try
                    {
                        return(Tuple.Create((decimal)option.delta(), (decimal)option.gamma()));
                    }
                    catch (Exception)
                    {
                        if (EnableGreekApproximation)
                        {
                            var step    = 0.01;
                            var initial = underlyingQuoteValue.value();
                            underlyingQuoteValue.setValue(initial - step);
                            var npvMinus = EvaluateOption(option);
                            underlyingQuoteValue.setValue(initial + step);
                            var npvPlus = EvaluateOption(option);
                            underlyingQuoteValue.setValue(initial);

                            return(Tuple.Create((decimal)((npvPlus - npvMinus) / (2 * step)),
                                                (decimal)((npvPlus - 2 * npv + npvMinus) / (step * step))));
                        }
                        else
                        {
                            return(Tuple.Create(0.0m, 0.0m));
                        }
                    }
                };

                Func <double> reevalVega = () =>
                {
                    var step    = 0.001;
                    var initial = underlyingVolValue.value();
                    underlyingVolValue.setValue(initial + step);
                    var npvPlus = EvaluateOption(option);
                    underlyingVolValue.setValue(initial);

                    return((npvPlus - npv) / step);
                };

                Func <double> reevalTheta = () =>
                {
                    var step = 1.0 / 365.0;

                    Settings.setEvaluationDate(security.Exchange.Hours.GetPreviousTradingDay(settlementDate));
                    var npvMinus = EvaluateOption(option);
                    QLNet.Settings.setEvaluationDate(settlementDate);

                    return((npv - npvMinus) / step);
                };

                Func <double> reevalRho = () =>
                {
                    var step    = 0.001;
                    var initial = riskFreeRateValue.value();
                    riskFreeRateValue.setValue(initial + step);
                    var npvPlus = EvaluateOption(option);
                    riskFreeRateValue.setValue(initial);

                    return((npvPlus - npv) / step);
                };

                // producing output with lazy calculations of IV and greeks

                return(new OptionPriceModelResult((decimal)npv,
                                                  tryGetImpliedVol,
                                                  () => new Greeks(evalDeltaGamma,
                                                                   () => tryGetGreekOrReevaluate(() => option.vega(), reevalVega),
                                                                   () => tryGetGreekOrReevaluate(() => option.theta(), reevalTheta),
                                                                   () => tryGetGreekOrReevaluate(() => option.rho(), reevalRho),
                                                                   () => tryGetGreek(() => option.elasticity()))));
            }
            catch (Exception err)
            {
                Log.Debug($"QLOptionPriceModel.Evaluate() error: {err.Message}");
                return(OptionPriceModelResult.None);
            }
        }
Example #39
0
        /// <summary>
        /// Construct the textual representation of a given metadata handle.
        /// </summary>
        /// <param name="metadataReader">Metadata reader corresponding to the handle</param>
        /// <param name="handle">Metadata handle to parse</param>
        /// <param name="namespaceQualified">Include namespace in type names</param>
        public static string FormatHandle(MetadataReader metadataReader, Handle handle, bool namespaceQualified = true)
        {
            MetadataNameFormatter formatter = new MetadataNameFormatter(metadataReader);

            return(formatter.EmitHandleName(handle, namespaceQualified));
        }
Example #40
0
 public void SetMaxVersion(int version)
 {
     CheckThrow();
     mono_btls_ssl_ctx_set_max_version(Handle.DangerousGetHandle(), version);
 }
Example #41
0
 public bool IsCipherSupported(short value)
 {
     CheckThrow();
     return(mono_btls_ssl_ctx_is_cipher_supported(Handle.DangerousGetHandle(), value) != 0);
 }
Example #42
0
        public void testInArrears()
        {
            // Testing in-arrears swap calculation
            CommonVars vars = new CommonVars();

            /* See Hull, 4th ed., page 550
             * Note: the calculation in the book is wrong (work out the adjustment and you'll get 0.05 + 0.000115 T1) */
            Date     maturity = vars.today + new Period(5, TimeUnit.Years);
            Calendar calendar = new NullCalendar();
            Schedule schedule = new Schedule(vars.today, maturity, new Period(Frequency.Annual), calendar,
                                             BusinessDayConvention.Following, BusinessDayConvention.Following,
                                             DateGeneration.Rule.Forward, false);
            DayCounter dayCounter = new SimpleDayCounter();

            List <double> nominals = new List <double>()
            {
                100000000.0
            };

            IborIndex index = new IborIndex("dummy", new Period(1, TimeUnit.Years), 0, new EURCurrency(), calendar,
                                            BusinessDayConvention.Following, false, dayCounter, vars.termStructure);
            double oneYear = 0.05;
            double r       = Math.Log(1.0 + oneYear);

            vars.termStructure.linkTo(Utilities.flatRate(vars.today, r, dayCounter));

            List <double> coupons = new List <double>()
            {
                oneYear
            };
            List <CashFlow> fixedLeg = new FixedRateLeg(schedule)
                                       .withCouponRates(coupons, dayCounter)
                                       .withNotionals(nominals);

            List <double> gearings   = new List <double>();
            List <double> spreads    = new List <double>();
            int           fixingDays = 0;

            double capletVolatility = 0.22;
            var    vol = new Handle <OptionletVolatilityStructure>(
                new ConstantOptionletVolatility(vars.today, new NullCalendar(),
                                                BusinessDayConvention.Following, capletVolatility, dayCounter));
            IborCouponPricer pricer = new BlackIborCouponPricer(vol);

            List <CashFlow> floatingLeg = new IborLeg(schedule, index)
                                          .withPaymentDayCounter(dayCounter)
                                          .withFixingDays(fixingDays)
                                          .withGearings(gearings)
                                          .withSpreads(spreads)
                                          .inArrears()
                                          .withNotionals(nominals);

            Utils.setCouponPricer(floatingLeg, pricer);

            Swap swap = new Swap(floatingLeg, fixedLeg);

            swap.setPricingEngine(new DiscountingSwapEngine(vars.termStructure));

            double storedValue = -144813.0;
            double tolerance   = 1.0;

            if (Math.Abs(swap.NPV() - storedValue) > tolerance)
            {
                QAssert.Fail("Wrong NPV calculation:\n"
                             + "    expected:   " + storedValue + "\n"
                             + "    calculated: " + swap.NPV());
            }
        }
Example #43
0
 public override bool OnDrawGo(Component comp, Handle h, string title = null)
 {
     return(DrawGoField(comp, h, title));
 }
Example #44
0
 //框架,绘制属性(不包含游戏对象),syncGo的话结束值变化会同步到m_go。这里是最小化绘制,只绘制最需要的属性
 public override void OnDrawMid(Component comp, Handle h, System.Action <Handle.WndType, object> onOpenWnd, bool syncGo = false)
 {
     DrawStartEndSlider(comp, h, true, true, false, true, false, syncGo, 0f, 1f, GetAlpha);
     DrawCommonDuationMid(comp, h);
 }
        private void btnCreateMovie_Click(object sender, EventArgs e)
        {
            if (!_imageToVideo.IsRunning)
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "WMV files (*.wmv)|*.wmv|AVI files (*.avi)|*.avi|All files (*.*)|*.*";

                if (tabControl2.SelectedIndex == 0)
                {
                    dlg.DefaultExt  = "*.wmv";
                    dlg.FilterIndex = 1;
                }
                else
                {
                    dlg.DefaultExt  = "*.avi";
                    dlg.FilterIndex = 2;
                }

                dlg.FileName = "movie";
                dlg.Title    = "Save generated video as";

                if (String.IsNullOrEmpty(Settings.Default.LastUsedFolder2))
                {
                    Settings.Default.LastUsedFolder2 = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                }

                dlg.InitialDirectory = Settings.Default.LastUsedFolder2;

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    Settings.Default.LastUsedFolder2 = Path.GetDirectoryName(dlg.FileName);

                    int   intValue;
                    float floatValue;

                    _imageToVideo.AutoFitImages   = cbAutoFitImages.Checked;
                    _imageToVideo.KeepAspectRatio = cbKeepAspectRatio.Checked;
                    _imageToVideo.BackgroundColor = (uint)ColorTranslator.ToOle(btnBackgroundColor.BackColor);

                    if (tbBackgroundImage.Text.Length > 0)
                    {
                        _imageToVideo.SetBackgroundPictureFileName(tbBackgroundImage.Text);
                    }

                    if (int.TryParse(tbMovieWidth.Text, out intValue))
                    {
                        _imageToVideo.OutputWidth = intValue;
                    }
                    if (int.TryParse(tbMovieHeight.Text, out intValue))
                    {
                        _imageToVideo.OutputHeight = intValue;
                    }

                    if (tbAudioTrack.Text.Length > 0)
                    {
                        _imageToVideo.ExternalAudioTrackFromFileName = tbAudioTrack.Text;
                    }

                    _imageToVideo.CurrentAudioCodec     = cmbAviAudioCodecs.SelectedIndex;
                    _imageToVideo.CurrentVideoCodec     = cmbAviVideoCodecs.SelectedIndex;
                    _imageToVideo.CurrentWMVAudioCodec  = cmbWmvAudioCodecs.SelectedIndex;
                    _imageToVideo.CurrentWMVAudioFormat = cmbWmvAudioFormats.SelectedIndex;
                    _imageToVideo.CurrentWMVVideoCodec  = cmbWmvVideoCodecs.SelectedIndex;

                    if (int.TryParse(tbBitrate.Text, out intValue))
                    {
                        _imageToVideo.WMVVideoBitrate = intValue * 1024;
                    }

                    if (float.TryParse(tbFPS.Text, out floatValue))
                    {
                        _imageToVideo.FPS = floatValue;
                    }

                    _outputFile = dlg.FileName;
                    _imageToVideo.OutputVideoFileName = _outputFile;
                    _imageToVideo.SetProgressNotifyWindow(Handle.ToInt32(), WM_CONVERSION_PROGRESS, 0);

                    _imageToVideo.Slides.Clear();

                    foreach (ListViewItem item in lvInputFiles.Items)
                    {
                        SlideOptions slideInfo = (SlideOptions)item.Tag;
                        Slide        slide     = _imageToVideo.AddImageFromFileName(slideInfo.ImageFile);
                        slide.Duration          = slideInfo.SlideDuration;
                        slide.RotationAngle     = slideInfo.SlideRotation;
                        slide.VisualEffect      = slideInfo.VisualEffect;
                        slide.Effect            = slideInfo.VisualEffectTransition;
                        slide.EffectDuration    = slideInfo.VisualEffectDuration;
                        slide.InEffect          = slideInfo.RandomTransitionEffectBefore ? GetRandomEffect() : slideInfo.TransitionEffectBefore;
                        slide.InEffectDuration  = slideInfo.TransitionEffectBeforeDuration;
                        slide.OutEffect         = slideInfo.RandomTransitionEffectAfter ? GetRandomEffect() : slideInfo.TransitionEffectAfter;
                        slide.OutEffectDuration = slideInfo.TransitionEffectAfterDuration;
                    }

                    _imageToVideo.Run();

                    toolStripStatusLabel1.Text = "Generating video...";
                    btnCreateMovie.Text        = "Stop";
                    btnCreateMovie.Image       = Resources.stop;
                }
            }
            else
            {
                // Stop generation
                _imageToVideo.Stop();

                // wait a bit the converter finished and released resources
                while (_imageToVideo.IsRunning)
                {
                    Thread.Sleep(200);
                }

                toolStripStatusLabel1.Text  = "Interrupted by user.";
                btnCreateMovie.Text         = "Create Movie";
                btnCreateMovie.Image        = Resources.film;
                toolStripProgressBar1.Value = 0;
            }
        }
Example #46
0
 public bool CapturesVariable(VarDecl var) => Handle.CapturesVariable(var.Handle);
        public void AddBindings(Method[] methods, string rootUri, ushort port)
        {
            methods.ForEach(method => Handle.CUSTOM
                            (
                                port: port,
                                methodSpaceUri: $"{method} {rootUri}{{?}}",
                                handler: (Request scRequest, string uri) =>
            {
                var headers = new Headers(scRequest.HeadersDictionary);
                var client  = GetClient(scRequest);
                if (!client.TryAuthenticate(ref uri, headers, out var error))
                {
                    return(ToResponse(error));
                }
                var context = new ScContext(client, scRequest);
                using (var request = context.CreateRequest(uri, method, scRequest.BodyBytes, headers))
                {
                    switch (request.Evaluate().Serialize())
                    {
                    case WebSocketUpgradeSuccessful _: return(HandlerStatus.Handled);

                    case var result:
                        Admin.Console.Log(request, result);
                        return(ToResponse(result));
                    }
                }
            }
                            ));

            Handle.OPTIONS
            (
                port: port,
                uriTemplate: $"{rootUri}{{?}}",
                handler: (Request scRequest, string query) =>
            {
                var context = new ScContext(GetClient(scRequest), scRequest);
                var headers = new Headers(scRequest.HeadersDictionary);
                return(ToResponse(context.GetOptions(query, headers)));
            }
            );

            Handle.WebSocket
            (
                port: port,
                groupName: WsGroupName,
                handler: async(textInput, webSocket) =>
            {
                try
                {
                    await WebSocketController.HandleTextInput(ScWebSocket.GetRESTarWsId(webSocket), textInput);
                }
                catch (Exception e)
                {
                    webSocket.Send(e.Message);
                    webSocket.Disconnect();
                }
            }
            );

            Handle.WebSocket
            (
                port: port,
                groupName: WsGroupName,
                handler: (binaryInput, webSocket) =>
            {
                try
                {
                    WebSocketController.HandleBinaryInput(ScWebSocket.GetRESTarWsId(webSocket), binaryInput);
                }
                catch (Exception e)
                {
                    webSocket.Send(e.Message);
                    webSocket.Disconnect();
                }
            }
            );

            Handle.WebSocketDisconnect
            (
                port: port,
                groupName: WsGroupName,
                handler: webSocket =>
            {
                try
                {
                    WebSocketController.HandleDisconnect(ScWebSocket.GetRESTarWsId(webSocket));
                }
                catch { }
            }
            );
        }
Example #48
0
        public static void GET(string Url, Action <UploadTask> UploadingAction)
        {
            string url = Url + "?{?}";

            Handle.GET(url, (string parameters, Request request) =>
            {
                string sessionId;
                string fileName;
                long fileSize;
                string error;

                if (!ResolveUploadParameters(parameters, out sessionId, out fileName, out fileSize, out error))
                {
                    return(new Response()
                    {
                        StatusCode = (ushort)System.Net.HttpStatusCode.BadRequest,
                        Body = error
                    });
                }

                if (!request.WebSocketUpgrade)
                {
                    return(404);
                }

                WebSocket ws    = request.SendUpgrade(WebSocketGroupName);
                UploadTask task = new UploadTask(sessionId, fileName, fileSize, parameters);

                task.StateChange += (s, a) => { UploadingAction(s as UploadTask); };

                if (!Uploads.TryAdd(ws.ToUInt64(), task))
                {
                    return(new Response()
                    {
                        StatusCode = (ushort)System.Net.HttpStatusCode.BadRequest,
                        Body = "Unable to create upload task"
                    });
                }

                return(HandlerStatus.Handled);
            }, new HandlerOptions()
            {
                SkipRequestFilters = true
            });

            Handle.WebSocket(WebSocketGroupName, (byte[] data, WebSocket ws) =>
            {
                if (!Uploads.ContainsKey(ws.ToUInt64()))
                {
                    ws.Disconnect("Could not find correct socket to handle the incoming data.",
                                  WebSocket.WebSocketCloseCodes.WS_CLOSE_CANT_ACCEPT_DATA);
                    return;
                }

                UploadTask task = Uploads[ws.ToUInt64()];

                task.Write(data);

                if (task.FileSize > 0)
                {
                    ws.Send(task.Progress.ToString());
                }
            });

            Handle.WebSocketDisconnect(WebSocketGroupName, (ws) =>
            {
                UploadTask task;

                if (Uploads.TryRemove(ws.ToUInt64(), out task))
                {
                    task.Close();
                }
            });
        }
Example #49
0
 public VHacd()
 {
     gcHandle = GCHandle.Alloc(this);
     handle   = VHACD_CreateContext(async: true, GCHandle.ToIntPtr(gcHandle), UserCallback, UserLogger);
 }
Example #50
0
        doStretchMove(List <EM_EData> enData)
        {
            foreach (EM_EData eData in enData)
            {
                List <ObjectId> ids = null;
                ObjectId        idP3d, idLdr;
                List <Handle>   handles = null;
                ObjectId        idCgPnt, idMTxt;
                bool            exists;

                TypedValue[] tvs     = eData.tvs;
                string       nameApp = tvs[0].Value.ToString();

                switch (nameApp)
                {
                case apps.lnkGS:
                    switch (eData.objType)
                    {
                    case "CogoPoint":
                        idCgPnt = eData.id;
                        Grading_Utility.updateGS(tvs, "Grip_Stretch_Move");
                        break;

                    case "MText":
                        idMTxt = eData.id;
                        LdrText_Move.moveLdrGS(idMTxt, tvs, eData.pnt3d);
                        break;

                    case "Leader":
                        idLdr = eData.id;
                        LdrText_Move.moveTxtGS(idLdr, tvs);
                        break;
                    }
                    break;

                case apps.lnkBrks:
                    ids     = tvs.getObjectIdList();
                    handles = tvs.getHandleList();

                    foreach (Handle handle in handles)
                    {
                        idP3d = Grading_Utility.update3dPoly_lnkBrks1_2(apps.lnkBrks, eData.id, handle);
                        if (idP3d == ObjectId.Null)
                        {
                            handles.Remove(handle);
                        }
                    }
                    break;

                case apps.lnkBrks2:
                    ids     = tvs.getObjectIdList();
                    handles = tvs.getHandleList();
                    foreach (Handle handle in handles)
                    {
                        idP3d = Grading_Utility.update3dPoly_lnkBrks1_2(apps.lnkBrks2, eData.id, handle);
                        if (idP3d == ObjectId.Null)
                        {
                            handles.Remove(handle);
                        }
                    }
                    ObjectId idDictM   = Dict.getNamedDictionary(apps.lnkBrks3, out exists);
                    ObjectId idDictPnt = Dict.getSubEntry(idDictM, eData.id.getHandle().ToString());

                    List <DBDictionaryEntry> entries = Dict.getEntries(idDictPnt);
                    foreach (DBDictionaryEntry entry in entries)
                    {
                        ObjectId idDictX = Dict.getSubEntry(idDictPnt, entry.Key);

                        ResultBuffer rb2 = Dict.getXRec(idDictX, "Offset");
                        tvs = rb2.AsArray();
                        double offset = (double)tvs[0].Value;

                        rb2 = Dict.getXRec(idDictX, "DeltaZ");
                        tvs = rb2.AsArray();
                        double deltaZ = (double)tvs[0].Value;

                        rb2 = Dict.getXRec(idDictX, "HandleFL");
                        tvs = rb2.AsArray();
                        Handle handleFL = (Handle)tvs[0].Value;

                        rb2 = Dict.getXRec(idDictX, "Beg");
                        tvs = rb2.AsArray();
                        double beg = (double)tvs[0].Value;

                        rb2 = Dict.getXRec(idDictX, "End");
                        tvs = rb2.AsArray();
                        double end = (double)tvs[0].Value;

                        Grading_Utility.update3dPoly_lnkBrks3(idDictX.getHandle(), offset, deltaZ, handleFL, beg, end);
                    }
                    break;

                case apps.lnkBubs:
                    switch (eData.objType)
                    {
                    case "MText":
                        BB_Events.modTXlnkBubs(eData.id, tvs);
                        break;

                    case "Leader":
                        BB_Events.modLDRlnkBubs(eData.id, tvs);
                        break;
                    }
                    break;

                case apps.lnkCO:
                case apps.lnkLD:
                    switch (eData.objType)
                    {
                    case "CogoPoint":
                        idCgPnt = eData.id;
                        idMTxt  = tvs.getObjectId(3);
                        ResultBuffer rbMTxt  = idMTxt.getXData(nameApp);
                        TypedValue[] tvsMTxt = rbMTxt.AsArray();

                        idLdr = tvsMTxt.getObjectId(3);
                        Point3d pnt3dCgPoint = idCgPnt.getCogoPntCoordinates();
                        Point3d pnt3dLdr     = idLdr.getBegPnt();
                        if (!pnt3dCgPoint.X.Equals(pnt3dLdr.X) || !pnt3dCgPoint.Y.Equals(pnt3dLdr.Y))
                        {
                            idLdr.adjLdrBegPnt(pnt3dCgPoint);
                        }
                        Grading_Utility.updatePntCalloutElev(pnt3dCgPoint.Z, tvs);
                        break;

                    case "MText":
                        idMTxt = eData.id;
                        try
                        {
                            LdrText_Move.moveTX(idMTxt, tvs, eData.pnt3d);
                        }
                        catch (System.Exception ex)
                        {
                            BaseObjs.writeDebug(ex.Message + " EM_StretchMove.cs: line: 147");
                        }
                        break;

                    case "Leader":
                        idLdr = eData.id;
                        LdrText_Rotate.adjTxt(idLdr, nameApp);
                        break;
                    }
                    break;


                //case apps.lnkLD:
                //    switch (eData.objType)
                //    {
                //        case "CogoPoint":
                //            break;

                //        case "MText":
                //            idMTxt = eData.id;
                //            try
                //            {
                //                LdrText_Move.moveTX(idMTxt, tvs, eData.pnt3d);
                //            }
                //            catch (System.Exception ex)
                //            {
                //                BaseObjs.writeDebug(string.Format("{0} EM_StretchMove.cs: line: 138", ex.Message));
                //            }
                //            break;

                //        case "Leader":
                //            idLdr = eData.id;
                //            LdrText_Rotate.adjTxt(idLdr, nameApp);
                //            break;
                //    }
                //    break;

                case apps.lnkDimPL:
                    if (eData.objType == "MText")
                    {
                        idMTxt = eData.id;
                        DimPL_Move.modTXlnkDimPl(idMTxt, tvs, idMTxt.getMTextLocation());
                    }
                    break;

                case apps.lnkMNP:
                    ObjectId id = eData.id;
                    switch (eData.objType)
                    {
                    case "Pipe":
                        using (Transaction tr = BaseObjs.startTransactionDb())
                        {
                            Pipe pipe = (Pipe)tr.GetObject(id, OpenMode.ForWrite);
                            idCgPnt = tvs.getObjectId(1);
                            CogoPoint cgPNt = (CogoPoint)tr.GetObject(idCgPnt, OpenMode.ForWrite);

                            double dZ  = pipe.InnerDiameterOrWidth / (2 * System.Math.Cos(System.Math.Atan(System.Math.Abs(pipe.Slope))));
                            double inv = pipe.StartPoint.Z - dZ;
                            cgPNt.Elevation = inv;

                            ResultBuffer rb = idCgPnt.getXData(apps.lnkCO);
                            if (rb != null)
                            {
                                TypedValue[] tvsCgPNt = rb.AsArray();

                                Grading.Grading_Utility.updatePntCalloutElev(inv, tvsCgPNt);
                                BaseObjs.updateGraphics();
                            }

                            idCgPnt         = tvs.getObjectId(2);
                            cgPNt           = (CogoPoint)tr.GetObject(idCgPnt, OpenMode.ForWrite);
                            inv             = pipe.EndPoint.Z - dZ;
                            cgPNt.Elevation = inv;

                            rb = idCgPnt.getXData(apps.lnkCO);
                            if (rb != null)
                            {
                                TypedValue[] tvsCgPNt = rb.AsArray();

                                Grading.Grading_Utility.updatePntCalloutElev(inv, tvsCgPNt);
                                BaseObjs.updateGraphics();
                            }
                            tr.Commit();
                        }

                        break;

                    case "Structure":
                        Structure s = (Structure)id.getEnt();
                        break;
                    }
                    break;
                }
            }
        }
Example #51
0
        public T Replace(IPriorityQueueHandle <T> handle, T item)
        {
            stamp++;
            int  cell;
            bool isfirst;

            checkHandle(handle, out cell, out isfirst);
            if (size == 0)
            {
                throw new NoSuchItemException();
            }

            T retval;

            if (isfirst)
            {
                retval           = heap[cell].first;
                heap[cell].first = item;
                if (size == 1)
                {
                }
                else if (size == 2 * cell + 1) // cell == lastcell
                {
                    int p = (cell + 1) / 2 - 1;
                    if (comparer.Compare(item, heap[p].last) > 0)
                    {
                        Handle thehandle = heap[cell].firsthandle;
                        updateFirst(cell, heap[p].last, heap[p].lasthandle);
                        updateLast(p, item, thehandle);
                        bubbleUpMax(p);
                    }
                    else
                    {
                        bubbleUpMin(cell);
                    }
                }
                else if (heapifyMin(cell))
                {
                    bubbleUpMax(cell);
                }
                else
                {
                    bubbleUpMin(cell);
                }
            }
            else
            {
                retval          = heap[cell].last;
                heap[cell].last = item;
                if (heapifyMax(cell))
                {
                    bubbleUpMin(cell);
                }
                else
                {
                    bubbleUpMax(cell);
                }
            }

            raiseItemsRemoved(retval, 1);
            raiseItemsAdded(item, 1);
            raiseCollectionChanged();

            return(retval);
        }
Example #52
0
 public override int GetHashCode()
 {
     return(Handle.GetHashCode());
 }
Example #53
0
        bool heapifyMin(int i)
        {
            bool   swappedroot = false;
            int    cell = i, currentmin = cell;
            T      currentitem   = heap[cell].first;
            Handle currenthandle = heap[cell].firsthandle;

            if (i > 0)
            {
                T other = heap[cell].last;
                if (2 * cell + 1 < size && comparer.Compare(currentitem, other) > 0)
                {
                    swappedroot = true;
                    Handle otherhandle = heap[cell].lasthandle;
                    updateLast(cell, currentitem, currenthandle);
                    currentitem   = other;
                    currenthandle = otherhandle;
                }
            }

            T      minitem   = currentitem;
            Handle minhandle = currenthandle;

            while (true)
            {
                int l = 2 * cell + 1, r = l + 1;
                T   lv, rv;

                if (2 * l < size && comparer.Compare(lv = heap[l].first, minitem) < 0)
                {
                    currentmin = l; minitem = lv;
                }

                if (2 * r < size && comparer.Compare(rv = heap[r].first, minitem) < 0)
                {
                    currentmin = r; minitem = rv;
                }

                if (currentmin == cell)
                {
                    break;
                }

                minhandle = heap[currentmin].firsthandle;
                updateFirst(cell, minitem, minhandle);
                cell = currentmin;

                //Maybe swap first and last
                T other = heap[cell].last;
                if (2 * currentmin + 1 < size && comparer.Compare(currentitem, other) > 0)
                {
                    Handle otherhandle = heap[cell].lasthandle;
                    updateLast(cell, currentitem, currenthandle);
                    currentitem   = other;
                    currenthandle = otherhandle;
                }


                minitem   = currentitem;
                minhandle = currenthandle;
            }

            if (cell != i || swappedroot)
            {
                updateFirst(cell, minitem, minhandle);
            }
            return(swappedroot);
        }
Example #54
0
 /// <summary>
 /// Attempts to resume the session and enable synchronization with the server.
 /// </summary>
 /// <remarks>
 /// All sessions will be active by default and calling this method only makes sense if
 /// <see cref="Stop"/> was called before that.
 /// </remarks>
 public void Start()
 {
     Handle.Start();
 }
Example #55
0
 //------------------------------------------------------------------------------
 public AudioSource GetSeAudioSource(Handle handle)
 {
     return(seHandles[handle]);
 }
Example #56
0
        public async Task <BusHandle> StartAsync(CancellationToken cancellationToken)
        {
            LogContext.SetCurrentIfNull(_logContext);

            if (_busHandle != null)
            {
                LogContext.Warning?.Log("StartAsync called, but the bus was already started: {Address} ({Reason})", Address, "Already Started");
                return(_busHandle);
            }

            await _busObservable.PreStart(this).ConfigureAwait(false);

            Handle busHandle = null;

            CancellationTokenSource tokenSource = null;

            try
            {
                if (cancellationToken == default)
                {
                    tokenSource       = new CancellationTokenSource(TimeSpan.FromSeconds(60));
                    cancellationToken = tokenSource.Token;
                }

                var hostHandle = _host.Start(cancellationToken);

                busHandle = new Handle(hostHandle, this, _busObservable, _logContext);

                try
                {
                    await busHandle.Ready.OrCanceled(cancellationToken).ConfigureAwait(false);
                }
                catch (OperationCanceledException exception) when(exception.CancellationToken == cancellationToken)
                {
                    try
                    {
                        await busHandle.StopAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        LogContext.Warning?.Log(ex, "Bus start faulted, and failed to stop host");
                    }

                    await busHandle.Ready.ConfigureAwait(false);
                }

                await _busObservable.PostStart(this, busHandle.Ready).ConfigureAwait(false);

                _busHandle = busHandle;

                LogContext.Debug?.Log("Bus started: {HostAddress}", _host.Address);

                return(_busHandle);
            }
            catch (Exception ex)
            {
                try
                {
                    if (busHandle != null)
                    {
                        LogContext.Debug?.Log(ex, "Bus start faulted, stopping host");

                        await busHandle.StopAsync(cancellationToken).ConfigureAwait(false);
                    }
                }
                catch (OperationCanceledException)
                {
                }
                catch (Exception stopException)
                {
                    LogContext.Warning?.Log(stopException, "Bus start faulted, and failed to stop host");
                }

                await _busObservable.StartFaulted(this, ex).ConfigureAwait(false);

                throw;
            }
            finally
            {
                tokenSource?.Dispose();
            }
        }
Example #57
0
        private TEntity GetValue <TEntity>(Handle handle, Func <MetadataReader, Handle, TEntity> getter)
        {
            var genHandle = _aggregator.GetGenerationHandle(handle, out var generation);

            return(getter(Readers[generation], genHandle));
        }
Example #58
0
 public void SetDebugBio(MonoBtlsBio bio)
 {
     CheckThrow();
     mono_btls_ssl_ctx_set_debug_bio(Handle.DangerousGetHandle(), bio.Handle.DangerousGetHandle());
 }
Example #59
0
            // setup
            public CommonVars()
            {
                backup = new SavedSettings();

                Calendar calendar = new TARGET();

                Date referenceDate = calendar.adjust(Date.Today);

                Settings.setEvaluationDate(referenceDate);

                termStructure = new RelinkableHandle <YieldTermStructure>();
                termStructure.linkTo(Utilities.flatRate(referenceDate, 0.05, new Actual365Fixed()));

                // ATM Volatility structure
                List <Period> atmOptionTenors = new List <Period>();

                atmOptionTenors.Add(new Period(1, TimeUnit.Months));
                atmOptionTenors.Add(new Period(6, TimeUnit.Months));
                atmOptionTenors.Add(new Period(1, TimeUnit.Years));
                atmOptionTenors.Add(new Period(5, TimeUnit.Years));
                atmOptionTenors.Add(new Period(10, TimeUnit.Years));
                atmOptionTenors.Add(new Period(30, TimeUnit.Years));

                List <Period> atmSwapTenors = new List <Period>();

                atmSwapTenors.Add(new Period(1, TimeUnit.Years));
                atmSwapTenors.Add(new Period(5, TimeUnit.Years));
                atmSwapTenors.Add(new Period(10, TimeUnit.Years));
                atmSwapTenors.Add(new Period(30, TimeUnit.Years));

                Matrix m = new Matrix(atmOptionTenors.Count, atmSwapTenors.Count);

                m[0, 0] = 0.1300; m[0, 1] = 0.1560; m[0, 2] = 0.1390; m[0, 3] = 0.1220;
                m[1, 0] = 0.1440; m[1, 1] = 0.1580; m[1, 2] = 0.1460; m[1, 3] = 0.1260;
                m[2, 0] = 0.1600; m[2, 1] = 0.1590; m[2, 2] = 0.1470; m[2, 3] = 0.1290;
                m[3, 0] = 0.1640; m[3, 1] = 0.1470; m[3, 2] = 0.1370; m[3, 3] = 0.1220;
                m[4, 0] = 0.1400; m[4, 1] = 0.1300; m[4, 2] = 0.1250; m[4, 3] = 0.1100;
                m[5, 0] = 0.1130; m[5, 1] = 0.1090; m[5, 2] = 0.1070; m[5, 3] = 0.0930;

                atmVol = new Handle <SwaptionVolatilityStructure>(
                    new SwaptionVolatilityMatrix(calendar, BusinessDayConvention.Following, atmOptionTenors,
                                                 atmSwapTenors, m, new Actual365Fixed()));

                // Vol cubes
                List <Period> optionTenors = new List <Period>();

                optionTenors.Add(new Period(1, TimeUnit.Years));
                optionTenors.Add(new Period(10, TimeUnit.Years));
                optionTenors.Add(new Period(30, TimeUnit.Years));

                List <Period> swapTenors = new List <Period>();

                swapTenors.Add(new Period(2, TimeUnit.Years));
                swapTenors.Add(new Period(10, TimeUnit.Years));
                swapTenors.Add(new Period(30, TimeUnit.Years));

                List <double> strikeSpreads = new List <double>();

                strikeSpreads.Add(-0.020);
                strikeSpreads.Add(-0.005);
                strikeSpreads.Add(+0.000);
                strikeSpreads.Add(+0.005);
                strikeSpreads.Add(+0.020);

                int    nRows            = optionTenors.Count * swapTenors.Count;
                int    nCols            = strikeSpreads.Count;
                Matrix volSpreadsMatrix = new Matrix(nRows, nCols);

                volSpreadsMatrix[0, 0] = 0.0599;
                volSpreadsMatrix[0, 1] = 0.0049;
                volSpreadsMatrix[0, 2] = 0.0000;
                volSpreadsMatrix[0, 3] = -0.0001;
                volSpreadsMatrix[0, 4] = 0.0127;

                volSpreadsMatrix[1, 0] = 0.0729;
                volSpreadsMatrix[1, 1] = 0.0086;
                volSpreadsMatrix[1, 2] = 0.0000;
                volSpreadsMatrix[1, 3] = -0.0024;
                volSpreadsMatrix[1, 4] = 0.0098;

                volSpreadsMatrix[2, 0] = 0.0738;
                volSpreadsMatrix[2, 1] = 0.0102;
                volSpreadsMatrix[2, 2] = 0.0000;
                volSpreadsMatrix[2, 3] = -0.0039;
                volSpreadsMatrix[2, 4] = 0.0065;

                volSpreadsMatrix[3, 0] = 0.0465;
                volSpreadsMatrix[3, 1] = 0.0063;
                volSpreadsMatrix[3, 2] = 0.0000;
                volSpreadsMatrix[3, 3] = -0.0032;
                volSpreadsMatrix[3, 4] = -0.0010;

                volSpreadsMatrix[4, 0] = 0.0558;
                volSpreadsMatrix[4, 1] = 0.0084;
                volSpreadsMatrix[4, 2] = 0.0000;
                volSpreadsMatrix[4, 3] = -0.0050;
                volSpreadsMatrix[4, 4] = -0.0057;

                volSpreadsMatrix[5, 0] = 0.0576;
                volSpreadsMatrix[5, 1] = 0.0083;
                volSpreadsMatrix[5, 2] = 0.0000;
                volSpreadsMatrix[5, 3] = -0.0043;
                volSpreadsMatrix[5, 4] = -0.0014;

                volSpreadsMatrix[6, 0] = 0.0437;
                volSpreadsMatrix[6, 1] = 0.0059;
                volSpreadsMatrix[6, 2] = 0.0000;
                volSpreadsMatrix[6, 3] = -0.0030;
                volSpreadsMatrix[6, 4] = -0.0006;

                volSpreadsMatrix[7, 0] = 0.0533;
                volSpreadsMatrix[7, 1] = 0.0078;
                volSpreadsMatrix[7, 2] = 0.0000;
                volSpreadsMatrix[7, 3] = -0.0045;
                volSpreadsMatrix[7, 4] = -0.0046;

                volSpreadsMatrix[8, 0] = 0.0545;
                volSpreadsMatrix[8, 1] = 0.0079;
                volSpreadsMatrix[8, 2] = 0.0000;
                volSpreadsMatrix[8, 3] = -0.0042;
                volSpreadsMatrix[8, 4] = -0.0020;

                List <List <Handle <Quote> > > volSpreads = new InitializedList <List <Handle <Quote> > >(nRows);

                for (int i = 0; i < nRows; ++i)
                {
                    volSpreads[i] = new InitializedList <Handle <Quote> >(nCols);
                    for (int j = 0; j < nCols; ++j)
                    {
                        volSpreads[i][j] = new Handle <Quote>(new SimpleQuote(volSpreadsMatrix[i, j]));
                    }
                }

                iborIndex = new Euribor6M(termStructure);
                SwapIndex swapIndexBase      = new EuriborSwapIsdaFixA(new Period(10, TimeUnit.Years), termStructure);
                SwapIndex shortSwapIndexBase = new EuriborSwapIsdaFixA(new Period(2, TimeUnit.Years), termStructure);

                bool vegaWeightedSmileFit = false;

                SabrVolCube2 = new Handle <SwaptionVolatilityStructure>(
                    new SwaptionVolCube2(atmVol,
                                         optionTenors,
                                         swapTenors,
                                         strikeSpreads,
                                         volSpreads,
                                         swapIndexBase,
                                         shortSwapIndexBase,
                                         vegaWeightedSmileFit));
                SabrVolCube2.link.enableExtrapolation();

                List <List <Handle <Quote> > > guess = new InitializedList <List <Handle <Quote> > >(nRows);

                for (int i = 0; i < nRows; ++i)
                {
                    guess[i]    = new InitializedList <Handle <Quote> >(4);
                    guess[i][0] = new Handle <Quote>(new SimpleQuote(0.2));
                    guess[i][1] = new Handle <Quote>(new SimpleQuote(0.5));
                    guess[i][2] = new Handle <Quote>(new SimpleQuote(0.4));
                    guess[i][3] = new Handle <Quote>(new SimpleQuote(0.0));
                }
                List <bool> isParameterFixed = new InitializedList <bool>(4, false);

                isParameterFixed[1] = true;

                // FIXME
                bool isAtmCalibrated = false;

                SabrVolCube1 = new Handle <SwaptionVolatilityStructure>(
                    new SwaptionVolCube1x(atmVol,
                                          optionTenors,
                                          swapTenors,
                                          strikeSpreads,
                                          volSpreads,
                                          swapIndexBase,
                                          shortSwapIndexBase,
                                          vegaWeightedSmileFit,
                                          guess,
                                          isParameterFixed,
                                          isAtmCalibrated));
                SabrVolCube1.link.enableExtrapolation();

                yieldCurveModels = new List <GFunctionFactory.YieldCurveModel>();
                yieldCurveModels.Add(GFunctionFactory.YieldCurveModel.Standard);
                yieldCurveModels.Add(GFunctionFactory.YieldCurveModel.ExactYield);
                yieldCurveModels.Add(GFunctionFactory.YieldCurveModel.ParallelShifts);
                yieldCurveModels.Add(GFunctionFactory.YieldCurveModel.NonParallelShifts);
                yieldCurveModels.Add(GFunctionFactory.YieldCurveModel.NonParallelShifts); // for linear tsr model

                Handle <Quote> zeroMeanRev = new Handle <Quote>(new SimpleQuote(0.0));

                numericalPricers = new List <CmsCouponPricer>();
                analyticPricers  = new List <CmsCouponPricer>();
                for (int j = 0; j < yieldCurveModels.Count; ++j)
                {
                    if (j < yieldCurveModels.Count - 1)
                    {
                        numericalPricers.Add(new NumericHaganPricer(atmVol, yieldCurveModels[j], zeroMeanRev));
                    }
                    else
                    {
                        numericalPricers.Add(new LinearTsrPricer(atmVol, zeroMeanRev));
                    }

                    analyticPricers.Add(new AnalyticHaganPricer(atmVol, yieldCurveModels[j], zeroMeanRev));
                }
            }
Example #60
0
 public bool ShouldShow(Handle handle)
 {
     return((handles & handle) != 0);
 }