Example #1
0
        private OlsplPattern GetPatternByLabelOfProperty(OwlObjectProperty property, INode label)
        {
            var domain          = property.Domain;
            var range           = property.Range;
            var domainLocalName = domain.GetLocalName();
            var rangeLocalName  = range.GetLocalName();

            var rule    = $"{domainLocalName} {label} {rangeLocalName}";
            var entity1 = new RdfEntity
            {
                //Type = domain.ToString(),
                TypeTerm    = domainLocalName,
                Label       = Var1,
                EntityIndex = 1,
            };

            var entity2 = new RdfEntity
            {
                //Type = range.ToString(),
                TypeTerm    = rangeLocalName,
                Label       = Var2,
                EntityIndex = 2,
            };

            var totalTriplet = new Triplet(domain, property, range, 1, 2);

            return(new OlsplPattern
            {
                Rule = rule,
                Entity1 = entity1,
                Entity2 = entity2,
                TotalTriplet = totalTriplet,
                Comment = "Generated via domain and ranges",
            });
        }
Example #2
0
        public static int[] FindMaxProduct(int[] arr)
        {
            var tripleProducts = new int[arr.Length];

            Triplet triplet = null;

            for (int i = 0; i < arr.Length; i++)
            {
                if (i < 2)
                {
                    tripleProducts[i] = -1;
                    continue;
                }
                if (i == 2)
                {
                    triplet           = new Triplet(arr[0], arr[1], arr[2]);
                    tripleProducts[i] = triplet.Product;
                    continue;
                }

                triplet.ChallengeItem(arr[i]);
                tripleProducts[i] = triplet.Product;
            }

            return(tripleProducts);
        }
 /// <devdoc>
 ///     Loads the view state for the control.
 /// </devdoc>
 protected override void LoadViewState(object savedState)
 {
     if (savedState != null)
     {
         Triplet stateTriplet = (Triplet)savedState;
         base.LoadViewState(stateTriplet.First);
         if (stateTriplet.Second != null)
         {
             if (_inputAttributesState == null)
             {
                 _inputAttributesState = new StateBag();
                 _inputAttributesState.TrackViewState();
             }
             _inputAttributesState.LoadViewState(stateTriplet.Second);
         }
         if (stateTriplet.Third != null)
         {
             if (_labelAttributesState == null)
             {
                 _labelAttributesState = new StateBag();
                 _labelAttributesState.TrackViewState();
             }
             _labelAttributesState.LoadViewState(stateTriplet.Second);
         }
     }
 }
Example #4
0
    public void Can_make_triplets_up_to_10()
    {
        var triplets = Triplet.Where(maxFactor: 10);
        var products = triplets.Select(x => x.Product()).OrderBy(x => x);

        Assert.Equal(new[] { 60, 480 }, products);
    }
Example #5
0
 /// <devdoc>
 ///     Loads the view state for the control.
 /// </devdoc>
 protected override void LoadViewState(object savedState)
 {
     if (savedState != null)
     {
         Triplet stateTriplet = (Triplet)savedState;
         base.LoadViewState(stateTriplet.First);
         if (stateTriplet.Second != null)
         {
             if (_inputAttributesState == null)
             {
                 _inputAttributesState = new StateBag();
                 _inputAttributesState.TrackViewState();
             }
             _inputAttributesState.LoadViewState(stateTriplet.Second);
         }
         if (stateTriplet.Third != null)
         {
             if (_labelAttributesState == null)
             {
                 _labelAttributesState = new StateBag();
                 _labelAttributesState.TrackViewState();
             }
             _labelAttributesState.LoadViewState(BinaryCompatibility.Current.TargetsAtLeastFramework48 ? stateTriplet.Third : stateTriplet.Second);
         }
     }
 }
Example #6
0
        private void AddPricingStructure(PricingStructure ps, PricingStructureValuation psv, NamedValueSet nvs)
        {
            var triple     = new Triplet <PricingStructure, PricingStructureValuation, NamedValueSet>(ps, psv, nvs);
            var identifier = nvs.GetValue <string>("UniqueIdentifier");

            _curves.Add(identifier, triple);
        }
        public virtual AntiForgeryData Deserialize(string serializedToken)
        {
            if (String.IsNullOrEmpty(serializedToken))
            {
                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "serializedToken");
            }

            // call property getter outside try { } block so that exceptions bubble up for debugging
            IStateFormatter formatter = Formatter;

            try
            {
                Triplet deserializedObj = (Triplet)formatter.Deserialize(serializedToken);
                return(new AntiForgeryData()
                {
                    Salt = (string)deserializedObj.First,
                    Value = (string)deserializedObj.Second,
                    CreationDate = (DateTime)deserializedObj.Third
                });
            }
            catch (Exception ex)
            {
                throw CreateValidationException(ex);
            }
        }
Example #8
0
    public void Can_make_triplets_from_11_to_20()
    {
        var triplets = Triplet.Where(minFactor: 11, maxFactor: 20);
        var products = triplets.Select(x => x.Product());

        Assert.Equal(new[] { 3840 }, products);
    }
Example #9
0
        protected override void LoadViewState(object savedState)
        {
            if (savedState == null)
            {
                base.LoadViewState(null);
                return;
            }

            Triplet saved = (Triplet)savedState;

            base.LoadViewState(saved.First);

            if (saved.Second != null)
            {
                if (inputAttributesState == null)
                {
                    inputAttributesState = new StateBag(true);
                    inputAttributesState.TrackViewState();
                }
                inputAttributesState.LoadViewState(saved.Second);
            }

            if (saved.Third != null)
            {
                if (labelAttributesState == null)
                {
                    labelAttributesState = new StateBag(true);
                    labelAttributesState.TrackViewState();
                }
                labelAttributesState.LoadViewState(saved.Third);
            }
        }
        // TODO: make chunks variable
        public static void ProgressiveQuantization(Triplet <short[]> input, ProgressiveQuantizationFactors progQuants, bool UseReduceExtrapolate, out List <Triplet <short[]> > output)
        {
            output = new List <Triplet <short[]> >();
            DwtTile DRS = new DwtTile(input.X, input.Y, input.Z);

            foreach (var quantArray in progQuants.ProgQuants)
            {
                DwtBands yBD  = DwtBands.GetFromLinearizationResult(DRS.Y_DwtQ, UseReduceExtrapolate);
                DwtBands cbBD = DwtBands.GetFromLinearizationResult(DRS.Cb_DwtQ, UseReduceExtrapolate);
                DwtBands crBD = DwtBands.GetFromLinearizationResult(DRS.Cr_DwtQ, UseReduceExtrapolate);

                RFX_PROGRESSIVE_CODEC_QUANT quant = Utility.ConvertProgQuant(quantArray);

                ProgressiveQuantization_Component(yBD, TileComponents.Y, quant);
                ProgressiveQuantization_Component(cbBD, TileComponents.Cb, quant);
                ProgressiveQuantization_Component(crBD, TileComponents.Cr, quant);

                DwtBands yDTS  = DwtBands.GetFromLinearizationResult(DRS.Y_DwtQ, UseReduceExtrapolate);
                DwtBands cbDTS = DwtBands.GetFromLinearizationResult(DRS.Cb_DwtQ, UseReduceExtrapolate);
                DwtBands crDTS = DwtBands.GetFromLinearizationResult(DRS.Cr_DwtQ, UseReduceExtrapolate);

                DTS_Component(yDTS, TileComponents.Y, quant);
                DTS_Component(cbDTS, TileComponents.Cb, quant);
                DTS_Component(crDTS, TileComponents.Cr, quant);
                DwtTile dwtDts = new DwtTile(yDTS.GetLinearizationData(), cbDTS.GetLinearizationData(), crDTS.GetLinearizationData());
                DRS.Sub(dwtDts);

                var triplet = new Triplet <short[]>(yBD.GetLinearizationData(), cbBD.GetLinearizationData(), crBD.GetLinearizationData());
                output.Add(triplet);
            }
        }
        /// <summary>
        /// return an index page according to the inputs
        /// </summary>
        /// <returns></returns>
        public ActionResult IndexWithInputs()
        {
            dynamic obj = GetJsonObject(Request.InputStream);

            // retrieve the quant
            QuantizationFactorsArray quantArray = JsonHelper.RetrieveQuantsArray(obj.Params.QuantizationFactorsArray);
            EntropyAlgorithm         algorithm  = JsonHelper.CastTo <EntropyAlgorithm>(obj.Params.EntropyAlgorithm);


            _viewModel = new RFXDecodeViewModel();
            // Updates parameters
            ((RFXDecodeViewModel)_viewModel).ProvideParam(quantArray, algorithm);
            Triplet <string> triplet = JsonHelper.RetrieveTriplet(obj.Inputs);

            ((RFXDecodeViewModel)_viewModel).ProvidePanelInputs(triplet.ToArray());

            var envValues = new Dictionary <string, object>()
            {
                { ModelKey, _viewModel },
                { isModelValid, true }
            };

            SaveToSession(envValues);

            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
Example #12
0
        private double NearestCollision(Ray MoveRay, Vector2f Point, double Maximum)
        {
            double dx = (Point.X - MoveRay.Point.X);
            double dy = (Point.Y - MoveRay.Point.Y);

            if (dx * dx + dy * dy > (_Radius + Maximum) * (_Radius + Maximum))
            {
                return(Maximum);
            }
            else
            {
                double A = MoveRay.DX * MoveRay.DX + MoveRay.DY * MoveRay.DY;
                double B = 2 * MoveRay.Point.Y * MoveRay.DY - 2 * Point.Y * MoveRay.DY +
                           2 * MoveRay.Point.X * MoveRay.DX - 2 * Point.X * MoveRay.DX;
                double C = Point.Y * Point.Y - 2 * Point.Y * MoveRay.Point.Y + MoveRay.Point.Y * MoveRay.Point.Y +
                           Point.X * Point.X - 2 * Point.X * MoveRay.Point.X + MoveRay.Point.X * MoveRay.Point.X - _Radius * _Radius;

                Triplet <bool, double, double> I = Quadratic(A, B, C);
                if (I.First)
                {
                    if (I.Second > 0 && I.Second < I.Third)
                    {
                        return(I.Second);
                    }
                    else
                    {
                        return(I.Third);
                    }
                }
                else
                {
                    return(Maximum);
                }
            }
        }
Example #13
0
File: 2.cs Project: qifanyyy/CLCDSA
 static public Triplet <FT, ST, TT> Min <FT, ST, TT>(Triplet <FT, ST, TT> p, Triplet <FT, ST, TT> q)
     where FT : IComparable <FT>
     where ST : IComparable <ST>
     where TT : IComparable <TT>
 {
     return(p.CompareTo(q) <= 0 ? p : q);
 }
        public async Task <IActionResult> IndexWithInputs()
        {
            try
            {
                using (var bodyStream = new StreamReader(Request.Body))
                {
                    var bodyText = await bodyStream.ReadToEndAsync();

                    dynamic obj = JsonConvert.DeserializeObject(bodyText);

                    // retrieve the quant
                    QuantizationFactorsArray quantArray = JsonHelper.RetrieveQuantsArray(obj.Params.QuantizationFactorsArray);
                    EntropyAlgorithm         algorithm  = JsonHelper.CastTo <EntropyAlgorithm>(obj.Params.EntropyAlgorithm);

                    _viewModel = new RFXDecodeViewModel();
                    // Updates parameters
                    ((RFXDecodeViewModel)_viewModel).ProvideParam(quantArray, algorithm);
                    Triplet <string> triplet = JsonHelper.RetrieveTriplet(obj.Inputs);
                    ((RFXDecodeViewModel)_viewModel).ProvidePanelInputs(triplet.ToArray());

                    var envValues = new Dictionary <string, object>()
                    {
                        { ModelKey, _viewModel },
                        { isModelValid, true }
                    };

                    SaveToSession(envValues);
                }
                return(Json(ReturnResult <string> .Success("Success")));
            }
            catch (Exception ex)
            {
                return(Json(ReturnResult <string> .Fail(ex.Message)));
            }
        }
Example #15
0
    public void Can_make_triplets_filtered_on_sum()
    {
        var triplets = Triplet.Where(sum: 180, maxFactor: 100);
        var products = triplets.Select(x => x.Product()).OrderBy(x => x);

        Assert.Equal(new[] { 118080, 168480, 202500 }, products);
    }
Example #16
0
        protected override void LoadViewState(object savedState)
        {
            if (savedState == null)
            {
                base.LoadViewState(null);
                return;
            }
            else
            {
                Triplet t = savedState as Triplet;

                if (t != null)
                {
                    // Always invoke LoadViewState on the base class even if
                    // the saved state is null.
                    base.LoadViewState(t.First);

                    if ((t.Second) != null)
                    {
                        ((IStateManager)ButtonStyle).LoadViewState(t.Second);
                    }

                    if ((t.Third) != null)
                    {
                        ((IStateManager)TextBoxStyle).LoadViewState(t.Third);
                    }
                }
                else
                {
                    throw new ArgumentException("Invalid view state .");
                }
            }
        }
        private Tile ReadTileFromFile(string path)
        {
            FileStream   fs        = new FileStream(path, FileMode.Open);
            StreamReader sr        = new StreamReader(fs);
            var          arrayList = new List <int[]>();

            for (int i = 0; i < 3; i++)
            {
                int[]  x;
                string line = sr.ReadLine();
                if (line.Equals("NULL"))
                {
                    x = null;
                }
                else if (line.Equals(""))
                {
                    x = new int[0];
                }
                else
                {
                    string[] strs = line.Split(new[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    x = new int[strs.Length];
                    for (int j = 0; j < strs.Length; j++)
                    {
                        x[j] = Convert.ToInt16(strs[j]);
                    }
                }
                arrayList.Add(x);
            }
            Triplet <int[]> triplet = new Triplet <int[]>(arrayList[0], arrayList[1], arrayList[2]);

            return(Tile.FromArrays <int>(triplet));
        }
Example #18
0
    private static void establishRemoteConnection(String strToIP, Triplet triplet, byte[] msg, int offset, int size)
    {
        Console.WriteLine("Boxit::establishRemoteConnection ENTER");

        byte[]     byteIP    = { 127, 0, 0, 1 };
        IPAddress  ipAddress = new IPAddress(byteIP);
        IPEndPoint ipEnd     = new IPEndPoint(ipAddress, triplet.portNo);

        Console.WriteLine("Boxit::establishRemoteConnection endPoint created");
        //AsyncCallback beginConnectCallBack = new AsyncCallback(beginConnectCallBackFor_establishRemoteConnection);

        Console.WriteLine("Boxit::establishRemoteConnection before calling Connect");
        triplet.sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


        try
        {
            triplet.sock.Connect(ipEnd);
        }
        catch (SocketException se)
        {
            Console.WriteLine("Connect SOCKET EXCEPTION!! ERROR CODE = {0}", se.ErrorCode);
            if (se.ErrorCode == 10056)
            {
                Console.WriteLine("10056: socket is already connected");
            }
//
            //throw se;
        }
        Console.WriteLine("Boxit::establishRemoteConnection connect DONE");

        SocketFlags f = new SocketFlags();

        triplet.sock.BeginSend(msg, 0, msg.Length, f, null, null);
    }
Example #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RateBasisCurve"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="cache">The cache.</param>
        /// <param name="nameSpace">The client namespace</param>
        /// <param name="referenceCurveData">The market data. This must contain both the underlying base curve and the spread curve.
        /// Otherwise the RateBasisInterpolator can not instantiate.</param>
        /// <param name="derivedCurveData">The spread Curve Data</param>
        /// <param name="fixingCalendar">The fixingCalendar.</param>
        /// <param name="rollCalendar">The rollCalendar.</param>
        public ClearedRateCurve(ILogger logger, ICoreCache cache, String nameSpace,
                                Triplet <PricingStructure, PricingStructureValuation, NamedValueSet> referenceCurveData,
                                Triplet <PricingStructure, PricingStructureValuation, NamedValueSet> derivedCurveData, IBusinessCalendar fixingCalendar, IBusinessCalendar rollCalendar)
            : base(derivedCurveData.Third, GenerateHolder(logger, cache, nameSpace, derivedCurveData.Third))
        {
            PricingStructureData = new PricingStructureData(CurveType.Child, AssetClass.Rates, derivedCurveData.Third);
            var curveId = GetRateCurveId();
            //Set the identifier.
            var nvs = derivedCurveData.Third;
            var pricingStructureId = GetRateCurveId();
            var refCurveId         = PropertyHelper.ExtractReferenceCurveUniqueId(nvs);

            ReferenceDiscountingCurveId = refCurveId != null ? new Identifier(refCurveId) : ReferenceDiscountingCurveId = null;
            if (pricingStructureId.PricingStructureType != PricingStructureTypeEnum.ClearedRateCurve)
            {
                return;
            }
            //Set the reference curve
            var baseCurveFpml  = new Pair <PricingStructure, PricingStructureValuation>(referenceCurveData.First, referenceCurveData.Second);
            var baseCurveProps = referenceCurveData.Third;

            BaseDiscountingCurve = (IRateCurve)PricingStructureFactory.Create(logger, cache, nameSpace, fixingCalendar, rollCalendar, baseCurveFpml, baseCurveProps);
            //Get the spread Data
            var spreadCurveFpml = new Pair <PricingStructure, PricingStructureValuation>(derivedCurveData.First, derivedCurveData.Second);
            //Override properties.
            //var optimize = PropertyHelper.ExtractOptimizeBuildFlag(properties);
            var bootstrap    = PropertyHelper.ExtractBootStrapOverrideFlag(nvs);
            var tempFpml     = (YieldCurveValuation)spreadCurveFpml.Second;
            var spreadAssets = tempFpml.inputs;
            //This is to catch it when there are no discount factor points.
            var discountsAbsent = tempFpml.discountFactorCurve?.point == null || tempFpml.discountFactorCurve.point.Length == 0;
            var indexTenor      = curveId.ForecastRateIndex?.indexTenor;

            if (bootstrap || discountsAbsent)
            {
                //There must be a valid quoted asset set in order to bootstrap.
                if (!XsdClassesFieldResolver.QuotedAssetSetIsValid(spreadAssets))
                {
                    return;
                }
                PriceableClearedRateAssets =
                    PriceableAssetFactory.CreatePriceableClearedRateAssetsWithBasisSwaps(logger, cache, nameSpace, indexTenor, spreadAssets, pricingStructureId.BaseDate, fixingCalendar, rollCalendar);
                GetYieldCurveValuation().zeroCurve = null;
                TermCurve termCurve = tempFpml.discountFactorCurve ?? SetConfigurationData();
                DateTime  baseDate  = GetYieldCurveValuation().baseDate.Value;
                termCurve.point = ClearedRateBootstrapper.Bootstrap(PriceableClearedRateAssets, BaseDiscountingCurve, baseDate, termCurve.extrapolationPermitted, termCurve.interpolationMethod, Tolerance);
                SetFpMLData(new Pair <PricingStructure, PricingStructureValuation>(PricingStructure, PricingStructureValuation), false);
                SetInterpolator(termCurve);
            }
            else
            {
                // the discount curve is already built, so don't rebuild
                PriceableClearedRateAssets = PriceableAssetFactory.CreatePriceableClearedRateAssetsWithBasisSwaps(logger, cache, nameSpace, indexTenor, spreadAssets, pricingStructureId.BaseDate, fixingCalendar, rollCalendar);
                //Order the assets.
                PriceableClearedRateAssets = PriceableClearedRateAssets.OrderBy(a => a.GetRiskMaturityDate()).ToList();
                CreatePricingStructure(pricingStructureId, tempFpml.discountFactorCurve, spreadAssets);
                // CreatePricingStructure(pricingStructureId, tempFpml.discountFactorCurve, PriceableAssetFactory.Parse(PriceableClearedRateAssets));
                SetInterpolator(GetYieldCurveValuation().discountFactorCurve);
            }
        }
Example #20
0
		/// <summary> Ctor used by factory method.</summary>
		/// <param name="byte">raw tag data
		/// </param>
		protected internal ICCTagTable(byte[] data)
		{
            tagCount = ICCProfile.getInt(data, offTagCount);
			
			int offset = offTags;
			for (int i = 0; i < tagCount; ++i)
			{
                int signature = ICCProfile.getInt(data, offset);
                int tagOffset = ICCProfile.getInt(data, offset + ICCProfile.int_size);
                int length = ICCProfile.getInt(data, offset + 2 * ICCProfile.int_size);
				trios.Add(new Triplet(signature, tagOffset, length));
				offset += 3 * ICCProfile.int_size;
			}
			
			
			System.Collections.IEnumerator Enum = trios.GetEnumerator();
			//UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
			while (Enum.MoveNext())
			{
				//UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
				Triplet trio = (Triplet) Enum.Current;
				ICCTag tag = ICCTag.createInstance(trio.signature, data, trio.offset, trio.count);
				System.Object tempObject;
				tempObject = this[(System.Int32) tag.signature];
				this[(System.Int32) tag.signature] = tag;
				System.Object generatedAux2 = tempObject;
			}
		}
Example #21
0
        /// <summary>
        /// 取得审批XML
        /// </summary>
        /// <param name="approveNodeXml"></param>
        /// <returns></returns>
        public static string GetApproveXML(string requestor, string approveNodeXml, string xml, string infoSource)
        {
            string retXml = string.Empty;                       //返回XML

            List <Triplet> nodeUserList = new List <Triplet>(); //保存节点人员对应关系

            XmlDocument xDoc = new XmlDocument();

            xDoc.LoadXml(approveNodeXml);

            //循环查询每个Node节点
            XmlNodeList nodeList = xDoc.SelectNodes("RuleTable/Node");

            if (nodeList != null && nodeList.Count > 0)
            {
                foreach (XmlNode node in nodeList)
                {
                    //是否需要写入节点
                    if (node.ChildNodes[2].FirstChild.Value == "True")
                    {
                        //查询该节点的
                        string  processNodeId = node.ChildNodes[1].FirstChild.Value; //取得审批节点的ID
                        Triplet triplet       = new Triplet();
                        //triplet.First = K2DBHelper.GetProcessNodeName(processNodeId);
                        triplet.First  = processNodeId;
                        triplet.Second = GetProcessNodeApprover(processNodeId, xml);        //需要修改取得审批人的方法
                        triplet.Third  = GetProcessNodeURL(processNodeId);
                        nodeUserList.Add(triplet);
                    }
                }
                retXml = CreateApproveXML(requestor, nodeUserList, xml, infoSource);    //创建审批XML
            }
            return(retXml);
        }
Example #22
0
File: Zone.cs Project: jascou/ROTNS
        public Trade BestTrade(Zone Neighbor, IEnumerable <Good> PermittedGoods)
        {
            Triplet <double, double, double> O = new Triplet <double, double, double>(0, 0, 0);
            Good Good1 = null;
            Good Good2 = null;

            foreach (Good G1 in PermittedGoods)
            {
                foreach (Good G2 in PermittedGoods)
                {
                    Triplet <double, double, double> T = Calculator.OptimumTrade(
                        this[G1],
                        Neighbor[G1],
                        this[G2],
                        Neighbor[G2],
                        this[Economy.Labor],
                        _Population,
                        Neighbor.Population);
                    if (Good1 == null || T.Third > O.Third && T.First > 0 && T.Second > 0)
                    {
                        O     = T;
                        Good1 = G1;
                        Good2 = G2;
                    }
                }
            }

            return(new Trade(Good1, Good2, O.First, O.Second, this, Neighbor));
        }
Example #23
0
        public static BigInteger EuclidAlgorithm(BigInteger a, BigInteger b, out BigInteger x, out BigInteger y)
        {
            if (b > a)
            {
                BigInteger t;
                t = a;
                a = b;
                b = t;
            }

            Triplet prev = new Triplet(a, 1, 0);
            Triplet cur  = new Triplet(b, 0, 1);
            Triplet temp;

            while (cur.X != 0)
            {
                temp = cur;
                cur  = prev - (prev.X / cur.X) * cur;
                prev = temp;
            }

            x = prev.Y;
            y = prev.Z;
            return(prev.X);
        }
        // Save the state of the object.
        protected override object SaveViewState()
        {
            // Create a new triplet with the three properties.
            Triplet tri = new Triplet(Text, Value, Selected);

            return(tri);
        }
Example #25
0
        static List <Triplet> GenerateDESDataset(int samples, int keySize = 64, int msgSize = 64)
        {
            Random rand = new Random();
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            des.KeySize = keySize;

            List <Triplet> triplets = new List <Triplet>(samples);

            for (int i = 0; i < samples; i++)
            {
                des.GenerateKey();
                byte[] key      = des.Key; // save this!
                byte[] original = new byte[msgSize];
                rand.NextBytes(original);
                ICryptoTransform encryptor = des.CreateEncryptor();
                byte[]           encrypted = encryptor.TransformFinalBlock(original, 0, msgSize);

                //ICryptoTransform decryptor = des.CreateDecryptor();
                //byte[] originalAgain = decryptor.TransformFinalBlock(encrypted, 0, encrypted.Length);

                Triplet triplet = new Triplet(original, encrypted, key);
                triplets.Add(triplet);


                //string msg = "Original = " + System.Text.Encoding.UTF8.GetString(original) + '\n';
                //msg += "Encrypted = " + System.Text.Encoding.UTF8.GetString(encrypted) + '\n';
                //msg += "Key = " + System.Text.Encoding.UTF8.GetString(key) + '\n';
                //Console.WriteLine(msg);
                //Console.WriteLine(triplet.GetBytesForm());
            }
            return(triplets);
        }
Example #26
0
        public IList <IList <int> > ThreeSum(int[] nums)
        {
            var result = new List <IList <int> >();

            if (nums.Length < 3)
            {
                return(result);
            }
            var found = new HashSet <Triplet>();
            var n     = nums.OrderBy(x => x).ToArray();

            for (var i = 0; i < n.Length - 2; i++)
            {
                for (var j = i + 1; j < n.Length - 1; j++)
                {
                    var sum = n[i] + n[j];
                    var k   = Array.BinarySearch(n, j + 1, n.Length - (j + 1), -sum);
                    if (k >= 0)
                    {
                        var triplet = new Triplet(n[i], n[j], n[k]);
                        if (!found.Contains(triplet))
                        {
                            found.Add(triplet);
                            result.Add(triplet);
                        }
                    }
                }
            }
            return(result);
        }
Example #27
0
        private bool CheckEmptyViewState(Object viewState)
        {
            Triplet triplet = viewState as Triplet;

            if (triplet == null || triplet.Second != null)
            {
                return(false);
            }

            if (triplet.Third != null)
            {
                // If the only thing in viewstate is the set of controls
                // requiring postback, then save the information in client-side
                // state instead.

                ArrayList arr = (ArrayList)triplet.Third;
                if (!EnableViewState || arr.Count <= 1)
                {
                    AddClientViewState(_controlsRequiringPostBackKey, triplet.Third);
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
Example #28
0
    public static IEnumerable <Triplet> Where(int maxFactor, int minFactor = 1, int sum = 0)
    {
        for (int _a = minFactor; _a < maxFactor - 1; _a++)
        {
            for (int _b = _a + 1; _b < maxFactor; _b++)
            {
                for (int _c = _b + 1; _c <= maxFactor; _c++)
                {
                    Triplet newTriplet = new Triplet(_a, _b, _c);

                    if (!newTriplet.IsPythagorean())
                    {
                        continue;
                    }

                    if (sum != 0 && newTriplet.Sum() != sum)
                    {
                        continue;
                    }

                    yield return(newTriplet);
                }
            }
        }
    }
Example #29
0
        private static Triplet <int, double, quaternion> GetBendsCentroid(ref Containers container, double densityB = 1.0, double densityN = 1.0)
        {
            Triplet <int, double, quaternion> rez =
                new Triplet <int, double, quaternion>(-1, 0.0, new quaternion());

            double     mass = 0.0;
            quaternion Q    = new quaternion();

            foreach (WorkClasses.Bend bend in container.Bends)
            {
                if (!bend.IsFictive())
                {
                    Triplet <int, double, quaternion> tQ = bend.CenterOfGravity(densityB, densityN);
                    if (tQ.First > 0)
                    {
                        mass += tQ.Second;
                        Q    += tQ.Second * tQ.Third;
                    }
                }
            }
            if (mass > 0.0)
            {
                Q  /= mass;
                rez = new Triplet <int, double, quaternion>(1, mass, Q);
            }

            return(rez);
        }
Example #30
0
        private static Triplet <int, double, quaternion> GetNodesCentroid(ref Containers container, double density = 1.0)
        {
            Triplet <int, double, quaternion> rez =
                new Triplet <int, double, quaternion>(-1, 0.0, new quaternion());

            double     mass = 0.0;
            quaternion Q    = new quaternion();

            foreach (WorkClasses.Node node in container.Nodes)
            {
                if (!node.IsFictive(ref container))
                {
                    if (node.SolidHandle.First >= 0)
                    {
                        Triplet <int, double, quaternion> tQ = node.CenterOfGravity(ref container, density);
                        if (tQ.First > 0)
                        {
                            mass += tQ.Second;
                            Q    += tQ.Second * tQ.Third;
                        }
                    }
                }
            }
            if (mass > 0.0)
            {
                Q  /= mass;
                rez = new Triplet <int, double, quaternion>(1, mass, Q);
            }

            return(rez);
        }
Example #31
0
    public static Triplet HUSLPToLCH(Triplet triple)
    {
        double H = triple.a;
        double S = triple.b;
        double L = triple.c;

        if (L > 99.9999999)
        {
            triple.a = 100;
            triple.b = 0;
            triple.c = H;

            return triple;
        }

        if (L < 0.00000001)
        {
            triple.a = 0;
            triple.b = 0;
            triple.c = H;

            return triple;
        }

        double max = MaxSafeChromaForL(L);
        double C = max / 100 * S;

        triple.a = L;
        triple.b = C;
        triple.c = H;

        return triple;
    }
Example #32
0
        public void CanCompareTwoNullableDifferentTypeTriplets()
        {
            var triplet1 = new Triplet<string, int?, Type>("1", 2, typeof(Console));
            var triplet2 = new Triplet<string, int?, Type>("1", 2, typeof(Console));
            var triplet3 = new Triplet<string, int?, Type>("1", null, typeof(Console));

            triplet2.Should().Be(triplet1);
            triplet3.Should().Not.Be(triplet1);
        }
Example #33
0
        public void CanCompareTwoNullableTriplets()
        {
            var pair1 = new Triplet<int?>(1, null, 42);
            var pair2 = new Triplet<int?>(1, null, 42);
            var pair3 = new Triplet<int?>(null, 2, null);

            pair2.Should().Be(pair1);
            pair3.Should().Not.Be(pair1);
        }
Example #34
0
		public static LNode unroll(LNode var, LNode cases, LNode body, IMessageSink sink)
		{
			if (!cases.Calls(S.Tuple) && !cases.Calls(S.Braces))
				return Reject(sink, cases, "unroll: the right-hand side of 'in' should be a tuple");

			// Maps identifiers => replacements. The integer counts how many times replacement occurred.
			var replacements = InternalList<Triplet<Symbol, LNode, int>>.Empty;
			if (var.IsId && !var.HasPAttrs()) {
				replacements.Add(Pair.Create(var.Name, (LNode)LNode.Missing, 0));
			} else {
				var vars = var.Args;
				if ((var.Calls(S.Tuple) || var.Calls(S.Braces)) && vars.All(a => a.IsId && !a.HasPAttrs())) {
					replacements = new Triplet<Symbol, LNode, int>[vars.Count].AsInternalList();
					for (int i = 0; i < vars.Count; i++) {
						replacements.InternalArray[i].A = vars[i].Name;
						
						// Check for duplicate names
						for (int j = 0; j < i; j++)
							if (replacements[i].A == replacements[j].A && replacements[i].A.Name != "_")
								sink.Write(Severity.Error, vars[i], "unroll: duplicate name in the left-hand tuple"); // non-fatal
					}
				} else
					return Reject(sink, cases, "unroll: the left-hand side of 'in' should be a simple identifier or a tuple of simple identifiers.");
			}

			UnrollCtx ctx = new UnrollCtx { Replacements = replacements };
			WList<LNode> output = new WList<LNode>();
			int iteration = 0;
			foreach (LNode replacement in cases.Args)
			{
				iteration++;
				bool tuple = replacement.Calls(S.Tuple) || replacement.Calls(S.Braces);
				int count = tuple ? replacement.ArgCount : 1;
				if (replacements.Count != count)
				{
					sink.Write(Severity.Error, replacement, "unroll, iteration {0}: Expected {1} replacement items, got {2}", iteration, replacements.Count, count);
					if (count < replacements.Count)
						continue; // too few
				}
				for (int i = 0; i < replacements.Count; i++)
					replacements.InternalArray[i].B = tuple ? replacement.Args[i] : replacement;

				if (body.Calls(S.Braces)) {
					foreach (LNode stmt in body.Args)
						output.Add(ctx.Replace(stmt).Value);
				} else
					output.Add(ctx.Replace(body).Value);
			}

			foreach (var r in replacements)
				if (r.C == 0 && !r.A.Name.StartsWith("_"))
					sink.Write(Severity.Warning, var, "Replacement variable '{0}' was never used", r.A);
			
			return body.With(S.Splice, output.ToVList());
		}
        private void AddSensingProbabilityButton_Click(object sender, RoutedEventArgs e)
        {
            TextBox stateTextBox = FindTextBoxSibling(sender, "SensedStateTextBox");
            TextBox sensedPerceptionTextBox = FindTextBoxSibling(sender, "SensedPerceptionTextBox");
            TextBox probabilityTextBox = FindTextBoxSibling(sender, "SensingProbabilityTextBox");
            Triplet<String, String, Double> tuple = new Triplet<string, string, double>(stateTextBox.Text, sensedPerceptionTextBox.Text, Double.Parse(probabilityTextBox.Text));

            ModelItem.Properties["SensingProbabilities"].Collection.Add(tuple);
            stateTextBox.Clear();
            sensedPerceptionTextBox.Clear();
            probabilityTextBox.Clear();
        }
Example #36
0
 public static IEnumerable<Triplet> Where(int maxFactor, int minFactor = 1, int sum = 0)
 {
     var triplets = new List<Triplet>();
     for (int i = minFactor; i < maxFactor - 1; i++)
     {
         for (int j = i + 1; j < maxFactor; j++)
         {
             for (int k = j + 1; k <= maxFactor; k++)
             {
                 var triplet = new Triplet(i, j, k);
                 if (ShouldIncludeTriplet(sum, triplet))
                     triplets.Add(triplet);
             }
         }
     }
     return triplets;
 }
Example #37
0
        static Triplet[] ParentChildRelationships(int a, int b, int c)
        {
            var p1 = new Triplet();
            p1.a = a - 2 * b + 2 * c;
            p1.b = 2 * a - b + 2 * c;
            p1.c = 2 * a - 2 * b + 3 * c;

            var p2 = new Triplet();
            p2.a = a + 2 * b + 2 * c;
            p2.b = 2 * a + b + 2 * c;
            p2.c = 2 * a + 2 * b + 3 * c;

            var p3 = new Triplet();
            p3.a = -a + 2 * b + 2 * c;
            p3.b = -2 * a + b + 2 * c;
            p3.c = -2 * a + 2 * b + 3 * c;

            return new Triplet[3] { p1, p2, p3 };
        }
Example #38
0
        protected virtual WebQueryAsyncResult ExecuteGetOrDeleteAsync(GetDeleteHeadOptions method, string url, object userState)
        {
            WebResponse = null;

            var request = BuildGetDeleteHeadOptionsWebRequest(method, url);
            var state = new Triplet<WebRequest, object, object>
                            {
                                First = request,
                                Second = null,
                                Third = userState
                            };

            var args = new WebQueryRequestEventArgs(url);
            OnQueryRequest(args);

            var inner = request.BeginGetResponse(GetAsyncResponseCallback, state);
            RegisterAbortTimer(request, inner); 
            var result = new WebQueryAsyncResult { InnerResult = inner };
            return result;
        }
Example #39
0
    public static List<Triplet> Where(int maxFactor, int minFactor = 1)
    {
        List<Triplet> triplets = new List<Triplet>();

        for (int a = minFactor; a <= maxFactor; a++)
        {
            for (int b = a; b <= maxFactor; b++)
            {
                for (int c = b; c <= maxFactor; c++)
                {
                    Triplet triplet = new Triplet(a, b, c);
                    if (triplet.IsPythagorean())
                    {
                        triplets.Add(triplet);
                    };
                }
            }
        }
        return triplets;
    }
Example #40
0
        private WebQueryAsyncResult ExecuteGetOrDeleteAsync(ICache cache, 
                                                            string key, 
                                                            string url, 
                                                            WebRequest request,
                                                            object userState)
        {
            var fetch = cache.Get<Stream>(key);
            if (fetch != null)
            {
                var args = new WebQueryResponseEventArgs(fetch);
                OnQueryResponse(args);

                var result = new WebQueryAsyncResult
                {
                    CompletedSynchronously = true
                };
                return result;
            }
            else
            {
                var state = new Triplet<WebRequest, Pair<ICache, string>, object>
                                {
                                    First = request,
                                    Second = new Pair<ICache, string>
                                                 {
                                        First = cache,
                                        Second = key
                                    },
                                    Third = userState
                                };

                var args = new WebQueryRequestEventArgs(url);
                OnQueryRequest(args);

                var inner = request.BeginGetResponse(GetAsyncResponseCallback, state);
                RegisterAbortTimer(request, inner); 
                var result = new WebQueryAsyncResult { InnerResult = inner };
                return result;
            }
        }
Example #41
0
        private Triplet<WebRequest, byte[], Pair<TimeSpan, int>> OnPostStreamQueryRequest(string url, WebRequest request, byte[] content, TimeSpan duration, int resultCount)
        {
            var state = new Triplet<WebRequest, byte[], Pair<TimeSpan, int>>
            {
                First = request,
                Second = content,
                Third = new Pair<TimeSpan, int>
                {
                    First = duration,
                    Second = resultCount
                }
            };

            var args = new WebQueryRequestEventArgs(url);
            OnQueryRequest(args);
            return state;
        }
Example #42
0
        protected virtual WebQueryAsyncResult ExecutePostOrPutAsync(PostOrPut method,
                                                                    string url,
                                                                    IEnumerable<HttpPostParameter> parameters,
                                                                    object userState)
        {
            WebResponse = null;

            string boundary;
            var request = BuildMultiPartFormRequest(method, url, parameters, out boundary);

            var state = new Triplet<WebRequest, Pair<string, IEnumerable<HttpPostParameter>>, object>
                            {
                                First = request,
                                Second = new Pair<string, IEnumerable<HttpPostParameter>>
                                             {
                                                 First = boundary,
                                                 Second = parameters
                                             },
                                Third = userState
                            };
            var args = new WebQueryRequestEventArgs(url);

            OnQueryRequest(args);
            
            var inner = request.BeginGetRequestStream(PostAsyncRequestCallbackMultiPart, state);
            var result = new WebQueryAsyncResult { InnerResult = inner };
            RegisterAbortTimer(request, result);
            return result;
        }
Example #43
0
        protected virtual WebQueryAsyncResult ExecutePostOrPutAsync(PostOrPut method, 
                                                                    string url, 
                                                                    string prefixKey,
                                                                    ICache cache, 
                                                                    TimeSpan slidingExpiration,
                                                                    object userState)
        {
            WebResponse = null;

            byte[] content;
            var request = BuildPostOrPutWebRequest(method, url, out content);

            var state = new Triplet<WebRequest, Pair<byte[], Triplet<ICache, TimeSpan, string>>, object>
                            {
                                First = request,
                                Second = new Pair<byte[], Triplet<ICache, TimeSpan, string>>
                                             {
                                                 First = content,
                                                 Second = new Triplet<ICache, TimeSpan, string>
                                                              {
                                                                  First = cache,
                                                                  Second = slidingExpiration,
                                                                  Third = prefixKey
                                                              }
                                             },
                                Third = userState
                            };

            var args = new WebQueryRequestEventArgs(url);
            OnQueryRequest(args);

            var inner = request.BeginGetRequestStream(PostAsyncRequestCallback, state);
            var result = new WebQueryAsyncResult { InnerResult = inner };
            RegisterAbortTimer(request, result);
            return result;
        }
 public PlayersTurn(Triplet _tripltetToTurn, bool _isClockwise)
 {
     TripltetToTurn = _tripltetToTurn;
     IsClockwise = _isClockwise;
 }
Example #45
0
        protected virtual WebQueryAsyncResult ExecutePostOrPutAsync(PostOrPut method, string url, object userState)
        {
            WebResponse = null;

            byte[] content;
            var request = BuildPostOrPutWebRequest(method, url, out content);

            var state = new Triplet<WebRequest, byte[], object>
                            {
                                First = request,
                                Second = content,
                                Third = userState
                            };

            var args = new WebQueryRequestEventArgs(url);
            OnQueryRequest(args);

            var inner = request.BeginGetRequestStream(PostAsyncRequestCallback, state);
            var result = new WebQueryAsyncResult { InnerResult = inner };
            RegisterAbortTimer(request, result);
            return result;
        }
Example #46
0
        public void CanHashCodeTwoNullableTriplets()
        {
            var pair1 = new Triplet<int?>(1, null, 42);
            var pair2 = new Triplet<int?>(1, null, 42);
            var pair3 = new Triplet<int?>(null, 2, null);

            pair2.GetHashCode().Should().Be(pair1.GetHashCode());
            pair3.GetHashCode().Should().Not.Be(pair1.GetHashCode());
        }
Example #47
0
 public static Triplet HUSLPToRGB(Triplet triple)
 {
     return LCHToRGB(HUSLPToLCH(triple));
 }
Example #48
0
 private static bool ShouldIncludeTriplet(int sum, Triplet triplet)
 {
     return triplet.IsPythagorean() && (sum == 0 || triplet.Sum() == sum);
 }
Example #49
0
 // Добавляет триплет в буфер обработки
 protected override void AddTripletToBuffer(Triplet triplet)
 {
     b_triplets.Add(triplet);
 }
Example #50
0
        protected virtual void PostAsyncRequestCallback(IAsyncResult asyncResult)
        {
            WebRequest request;
            byte[] post;
            object userState;
            Triplet<ICache, object, string> store;

            var state = asyncResult.AsyncState as Triplet<WebRequest, byte[], object>;
            if (state == null)
            {
                // No expiration specified
                if (asyncResult is Triplet<WebRequest, Triplet<byte[], ICache, string>, object>)
                {
                    var cacheScheme = (Triplet<WebRequest, Triplet<byte[], ICache, string>, object>)asyncResult;
                    var cache = cacheScheme.Second.Second;

                    var url = cacheScheme.First.RequestUri.ToString();
                    var prefix = cacheScheme.Second.Third;
                    var key = CreateCacheKey(prefix, url);

                    var fetch = cache.Get<Stream>(key);
                    if (fetch != null)
                    {
                        var args = new WebQueryResponseEventArgs(fetch);
                        OnQueryResponse(args);
                        return;
                    }

                    request = cacheScheme.First;
                    post = cacheScheme.Second.First;
                    userState = cacheScheme.Third;
                    store = new Triplet<ICache, object, string>
                    {
                        First = cache,
                        Second = null,
                        Third = prefix
                    };
                }
                else
                    // Absolute expiration specified
                    if (asyncResult is Triplet<WebRequest, Pair<byte[], Triplet<ICache, DateTime, string>>, object>)
                    {
                        var cacheScheme = (Triplet<WebRequest, Pair<byte[], Triplet<ICache, DateTime, string>>, object>)asyncResult;
                        var url = cacheScheme.First.RequestUri.ToString();
                        var cache = cacheScheme.Second.Second.First;
                        var expiry = cacheScheme.Second.Second.Second;

                        var prefix = cacheScheme.Second.Second.Third;
                        var key = CreateCacheKey(prefix, url);

                        var fetch = cache.Get<Stream>(key);
                        if (fetch != null)
                        {
                            var args = new WebQueryResponseEventArgs(fetch);
                            OnQueryResponse(args);
                            return;
                        }

                        request = cacheScheme.First;
                        post = cacheScheme.Second.First;
                        userState = cacheScheme.Third;
                        store = new Triplet<ICache, object, string>
                        {
                            First = cache,
                            Second = expiry,
                            Third = prefix
                        };
                    }
                    else
                        // Sliding expiration specified
                        if (asyncResult is Triplet<WebRequest, Pair<byte[], Triplet<ICache, TimeSpan, string>>, object>)
                        {
                            var cacheScheme = (Triplet<WebRequest, Pair<byte[], Triplet<ICache, TimeSpan, string>>, object>)asyncResult;
                            var url = cacheScheme.First.RequestUri.ToString();
                            var cache = cacheScheme.Second.Second.First;
                            var expiry = cacheScheme.Second.Second.Second;

                            var prefix = cacheScheme.Second.Second.Third;
                            var key = CreateCacheKey(prefix, url);

                            var fetch = cache.Get<Stream>(key);
                            if (fetch != null)
                            {
                                var args = new WebQueryResponseEventArgs(fetch);
                                OnQueryResponse(args);
                                return;
                            }

                            request = cacheScheme.First;
                            post = cacheScheme.Second.First;
                            userState = cacheScheme.Third;
                            store = new Triplet<ICache, object, string>
                            {
                                First = cache,
                                Second = expiry,
                                Third = prefix
                            };
                        }
                        else
                        {
                            // Unrecognized state signature
                            throw new ArgumentNullException("asyncResult",
                                                            "The asynchronous post failed to return its state");
                        }
            }
            else
            {
                request = state.First;
                post = state.Second;
                userState = state.Third;
                store = null;
            }

            // No cached response
            using (var stream = request.EndGetRequestStream(asyncResult))
            {
                WritePostContentToRequestStream(post, stream);

                var inner = request.BeginGetResponse(PostAsyncResponseCallback,
                                         new Triplet<WebRequest, Triplet<ICache, object, string>, object>
                                         {
                                             First = request,
                                             Second = store,
                                             Third = userState
                                         });

                RegisterAbortTimer(request, new WebQueryAsyncResult { InnerResult = inner });
            }
        }
Example #51
0
    private static void establishRemoteConnection(String strToIP, Triplet triplet, byte[] msg, int offset, int size)
    {
        Console.WriteLine("Boxit::establishRemoteConnection ENTER");

                                byte[] byteIP = {127, 0, 0, 1};
                                IPAddress ipAddress = new IPAddress(byteIP);
                                IPEndPoint ipEnd = new IPEndPoint (ipAddress, triplet.portNo);

                                Console.WriteLine("Boxit::establishRemoteConnection endPoint created");
                                //AsyncCallback beginConnectCallBack = new AsyncCallback(beginConnectCallBackFor_establishRemoteConnection);

                                Console.WriteLine("Boxit::establishRemoteConnection before calling Connect");
                                triplet.sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                                try
            {
                  triplet.sock.Connect(ipEnd);
            }
            catch (SocketException se)
            {
                Console.WriteLine("Connect SOCKET EXCEPTION!! ERROR CODE = {0}",se.ErrorCode);
                if(se.ErrorCode == 10056)
                    Console.WriteLine("10056: socket is already connected");
        //
                //throw se;

            }
                                Console.WriteLine("Boxit::establishRemoteConnection connect DONE");

                                SocketFlags f = new SocketFlags();
                                triplet.sock.BeginSend(msg, 0, msg.Length, f, null, null);
    }
Example #52
0
    /// <summary>
    /// Returns the Triplet{width, height, radius} with coordinates containnig respictive width and height of the image
    /// </summary>
    /// <returns>Triplet{width, height, radius}</returns>
    public static Triplet<int, int, int> GetImageSize(ImageType type)
    {
        GlobalData gd = new GlobalData("");
        int thumbnailSize = gd.GetIntegerValue("ThumbnailSize");
        int previewSize = gd.GetIntegerValue("PreviewSize");
        int thumbnailSizeSmall = gd.GetIntegerValue("ThumbnailSizeSmall");//110 gd.GetIntegerValue("ThumbnailSize");
        int thumbnailSizeSlideShow = gd.GetIntegerValue("ThumbnailSizeSlideShow");

        Triplet<int, int, int> dimensions;
        switch (type)
        {
            case ImageType.UserPreview: //1
                dimensions = new Triplet<int, int, int>(previewSize, previewSize, 0);
                break;
            case ImageType.UserThumbnail: //2
                dimensions = new Triplet<int, int, int>(thumbnailSize, thumbnailSize, 0);
                break;
            case ImageType.EventPreview: //3
                dimensions = new Triplet<int, int, int>(previewSize, previewSize, 0);
                break;
            case ImageType.EventThumbnail: //4
                dimensions = new Triplet<int, int, int>(thumbnailSize, thumbnailSize, 0);
                break;
            case ImageType.EventCommentPreview: //5
                dimensions = new Triplet<int, int, int>(previewSize, previewSize, 0);
                break;
            case ImageType.EventCommentThumbnail: //6
                dimensions = new Triplet<int, int, int>(thumbnailSize, thumbnailSize, 0);
                break;
            case ImageType.EventPicturePreview: //7
                dimensions = new Triplet<int, int, int>(previewSize, previewSize, 0);
                break;
            case ImageType.EventPictureThumbnail: //8
                dimensions = new Triplet<int, int, int>(thumbnailSize, thumbnailSize, 0);
                break;
            case ImageType.EventPictureThumbnailSmall: //13
                dimensions = new Triplet<int, int, int>(thumbnailSizeSmall, thumbnailSizeSmall, 0);
                break;
            case ImageType.EventPictureThumbnailSlideShow: //14
                dimensions = new Triplet<int, int, int>(thumbnailSizeSlideShow, thumbnailSizeSlideShow, 0);
                break;
            default:
                dimensions = new Triplet<int, int, int>();
                break;
        }
        return dimensions;
    }
Example #53
0
    public static Triplet XYZToRGB(Triplet triple)
    {
        double R = FromLinear(DotProduct(Mt[0], triple));
        double G = FromLinear(DotProduct(Mt[1], triple));
        double B = FromLinear(DotProduct(Mt[2], triple));

        triple.a = R;
        triple.b = G;
        triple.c = B;

        return triple;
    }
Example #54
0
        protected virtual void PostAsyncRequestCallback(IAsyncResult asyncResult)
        {
            WebRequest request;
            byte[] content;
            Triplet<IClientCache, object, string> store;

            var state = asyncResult.AsyncState as Pair<WebRequest, byte[]>;
            if (state == null)
            {
                // no expiration specified
                if (asyncResult is Pair<WebRequest, Triplet<byte[], IClientCache, string>>)
                {
                    var cacheScheme = (Pair<WebRequest, Triplet<byte[], IClientCache, string>>) asyncResult;
                    var cache = cacheScheme.Second.Second;

                    var url = cacheScheme.First.RequestUri.ToString();
                    var prefix = cacheScheme.Second.Third;
                    var key = CreateCacheKey(prefix, url);

                    var fetch = cache.Get<string>(key);
                    if (fetch != null)
                    {
                        var args = new WebQueryResponseEventArgs(fetch);
                        OnQueryResponse(args);
                        return;
                    }

                    request = cacheScheme.First;
                    content = cacheScheme.Second.First;
                    store = new Triplet<IClientCache, object, string> {First = cache, Second = null, Third = prefix};
                }
                else
                    // absolute expiration specified
                    if (asyncResult is Pair<WebRequest, Pair<byte[], Triplet<IClientCache, DateTime, string>>>)
                    {
                        var cacheScheme =
                            (Pair<WebRequest, Pair<byte[], Triplet<IClientCache, DateTime, string>>>) asyncResult;
                        var url = cacheScheme.First.RequestUri.ToString();
                        var cache = cacheScheme.Second.Second.First;
                        var expiry = cacheScheme.Second.Second.Second;

                        var prefix = cacheScheme.Second.Second.Third;
                        var key = CreateCacheKey(prefix, url);

                        var fetch = cache.Get<string>(key);
                        if (fetch != null)
                        {
                            var args = new WebQueryResponseEventArgs(fetch);
                            OnQueryResponse(args);
                            return;
                        }

                        request = cacheScheme.First;
                        content = cacheScheme.Second.First;
                        store = new Triplet<IClientCache, object, string>
                                    {First = cache, Second = expiry, Third = prefix};
                    }
                    else
                        // sliding expiration specified
                        if (asyncResult is Pair<WebRequest, Pair<byte[], Triplet<IClientCache, TimeSpan, string>>>)
                        {
                            var cacheScheme =
                                (Pair<WebRequest, Pair<byte[], Triplet<IClientCache, TimeSpan, string>>>) asyncResult;
                            var url = cacheScheme.First.RequestUri.ToString();
                            var cache = cacheScheme.Second.Second.First;
                            var expiry = cacheScheme.Second.Second.Second;

                            var prefix = cacheScheme.Second.Second.Third;
                            var key = CreateCacheKey(prefix, url);

                            var fetch = cache.Get<string>(key);
                            if (fetch != null)
                            {
                                var args = new WebQueryResponseEventArgs(fetch);
                                OnQueryResponse(args);
                                return;
                            }

                            request = cacheScheme.First;
                            content = cacheScheme.Second.First;
                            store = new Triplet<IClientCache, object, string>
                                        {First = cache, Second = expiry, Third = prefix};
                        }
                        else
                        {
                            // unrecognized state signature
                            throw new ArgumentNullException("asyncResult",
                                                            "The asynchronous post failed to return its state");
                        }
            }
            else
            {
                request = state.First;
                content = state.Second;
                store = null;
            }

            // no cached response
            using (var stream = request.EndGetRequestStream(asyncResult))
            {
                if (content != null)
                {
                    stream.Write(content, 0, content.Length);
                }
                stream.Close();

                request.BeginGetResponse(PostAsyncResponseCallback,
                                         new Pair<WebRequest, Triplet<IClientCache, object, string>>
                                             {First = request, Second = store});
            }
        }
Example #55
0
 protected static double DotProduct(Triplet a,
     Triplet b)
 {
     return a.a * b.a
          + a.b * b.b
          + a.c * b.c;
 }
 private static bool ValidTriplet(Triplet triplet, int sum)
 {
     return triplet.IsPythagorean() && (triplet.Sum() == sum || sum == 0);
 }
Example #57
0
        public void CompareToTest()
        {
            var A = new Triplet<float>(1.0f, 2.0f, 1.0f);
            var B = new Triplet<float>(2.0f, 1.0f, 1.0f);
            var C = new Triplet<float>(2.0f, 2.0f, 2.0f);

            Assert.AreEqual(0, A.CompareTo(A));
            Assert.AreEqual(-1, A.CompareTo(B));
            Assert.AreEqual(-1, B.CompareTo(C));
            Assert.AreEqual(-1, A.CompareTo(C));
            Assert.AreEqual(1, C.CompareTo(B));
            Assert.AreEqual(1, C.CompareTo(A));
            Assert.AreEqual(1, B.CompareTo(A));
        }
Example #58
0
 public void CanToStringNullableTriplet()
 {
     var pair1 = new Triplet<int?>(1, null, 42);
     pair1.ToString().Should().Be("1, , 42");
 }
Example #59
0
        protected virtual void PostAsyncRequestCallbackMultiPart(IAsyncResult asyncResult)
        {
            WebRequest request;
            string boundary;
            IEnumerable<HttpPostParameter> parameters;
            object userState;
            Triplet<ICache, object, string> store;

            var state = asyncResult.AsyncState as Triplet<WebRequest, Pair<string, IEnumerable<HttpPostParameter>>, object>;
            if (state == null)
            {
                // No expiration specified
                if (asyncResult is Triplet<WebRequest, Triplet<Pair<string, IEnumerable<HttpPostParameter>>, ICache, string>, object>)
                {
                    #region No Expiration
                    var cacheScheme = (Triplet<WebRequest, Triplet<Pair<string, IEnumerable<HttpPostParameter>>, ICache, string>, object>)asyncResult;
                    var cache = cacheScheme.Second.Second;

                    var url = cacheScheme.First.RequestUri.ToString();
                    var prefix = cacheScheme.Second.Third;
                    var key = CreateCacheKey(prefix, url);

                    var fetch = cache.Get<Stream>(key);
                    if (fetch != null)
                    {
                        var args = new WebQueryResponseEventArgs(fetch);
                        OnQueryResponse(args);
                        return;
                    }

                    request = cacheScheme.First;
                    boundary = cacheScheme.Second.First.First;
                    parameters = cacheScheme.Second.First.Second;
                    userState = cacheScheme.Third;
                    store = new Triplet<ICache, object, string>
                                {
                                    First = cache,
                                    Second = null,
                                    Third = prefix
                                };
                    #endregion
                }
                else
                    // Absolute expiration specified
                    if (asyncResult is Triplet<WebRequest, Pair<Pair<string, IEnumerable<HttpPostParameter>>, Triplet<ICache, DateTime, string>>, object>)
                    {
                        #region Absolute Expiration
                        var cacheScheme = (Triplet<WebRequest, Pair<Pair<string, IEnumerable<HttpPostParameter>>, Triplet<ICache, DateTime, string>>, object>)asyncResult;
                        var url = cacheScheme.First.RequestUri.ToString();
                        var cache = cacheScheme.Second.Second.First;
                        var expiry = cacheScheme.Second.Second.Second;

                        var prefix = cacheScheme.Second.Second.Third;
                        var key = CreateCacheKey(prefix, url);

                        var fetch = cache.Get<Stream>(key);
                        if (fetch != null)
                        {
                            var args = new WebQueryResponseEventArgs(fetch);
                            OnQueryResponse(args);
                            return;
                        }

                        request = cacheScheme.First;
                        boundary = cacheScheme.Second.First.First;
                        parameters = cacheScheme.Second.First.Second;
                        userState = cacheScheme.Third;
                        store = new Triplet<ICache, object, string>
                                    {
                                        First = cache,
                                        Second = expiry,
                                        Third = prefix
                                    };
                        #endregion
                    }
                    else
                        // Sliding expiration specified
                        if (asyncResult is Triplet<WebRequest, Pair<Pair<string, IEnumerable<HttpPostParameter>>, Triplet<ICache, TimeSpan, string>>, object>)
                        {
                            #region Sliding Expiration
                            var cacheScheme = (Triplet<WebRequest, Pair<Pair<string, IEnumerable<HttpPostParameter>>, Triplet<ICache, TimeSpan, string>>, object>)asyncResult;
                            var url = cacheScheme.First.RequestUri.ToString();
                            var cache = cacheScheme.Second.Second.First;
                            var expiry = cacheScheme.Second.Second.Second;

                            var prefix = cacheScheme.Second.Second.Third;
                            var key = CreateCacheKey(prefix, url);

                            var fetch = cache.Get<Stream>(key);
                            if (fetch != null)
                            {
                                var args = new WebQueryResponseEventArgs(fetch);
                                OnQueryResponse(args);
                                return;
                            }

                            request = cacheScheme.First;
                            boundary = cacheScheme.Second.First.First;
                            parameters = cacheScheme.Second.First.Second;
                            userState = cacheScheme.Third;
                            store = new Triplet<ICache, object, string>
                                        {
                                            First = cache,
                                            Second = expiry,
                                            Third = prefix
                                        };
                            #endregion
                        }
                        else
                        {
                            // Unrecognized state signature
                            throw new ArgumentNullException("asyncResult",
                                                            "The asynchronous post failed to return its state");
                        }
            }
            else
            {
                request = state.First;
                boundary = state.Second.First;
                parameters = state.Second.Second;
                userState = state.Third;
                store = null;
            }

#if !Smartphone
            var encoding = Encoding ?? Encoding.GetEncoding("ISO-8859-1");
#else
            var encoding = Encoding ?? Encoding.GetEncoding(1252);
#endif
            var expected = WriteMultiPartImpl(
                false /* write */, parameters, boundary, encoding, null
                );
            
            // No cached response
            using (var requestStream = request.EndGetRequestStream(asyncResult))
            {
                var actual = WriteMultiPartImpl(
                        true /* write */, parameters, boundary, encoding, requestStream
                        );

                Debug.Assert(expected == actual, string.Format("Expected {0} bytes but wrote {1}!", expected, actual));

                var inner = request.BeginGetResponse(PostAsyncResponseCallback,
                                         new Triplet<WebRequest, Triplet<ICache, object, string>, object>
                                             {
                                                 First = request,
                                                 Second = store,
                                                 Third = userState
                                             });

                RegisterAbortTimer(request, new WebQueryAsyncResult { InnerResult = inner });
            }
        }
Example #60
0
    public static Triplet LUVToXYZ(Triplet triple)
    {
        double L = triple.a;
        double U = triple.b;
        double V = triple.c;

        if (L == 0)
        {
            triple.a = 0;
            triple.b = 0;
            triple.c = 0;

            return triple;
        }

        double varU = U / (13 * L) + RefU;
        double varV = V / (13 * L) + RefV;

        double Y = LToY(L);
        double X = 0 - (9 * Y * varU) / ((varU - 4) * varV - varU * varV);
        double Z = (9 * Y - (15 * varV * Y) - (varV * X)) / (3 * varV);

        triple.a = X;
        triple.b = Y;
        triple.c = Z;

        return triple;
    }