Inheritance: MonoBehaviour
Beispiel #1
0
			public Panos_1(String SVGPanos1String)
			{
				int tempInt;
				String[] valuesString = SVGPanos1String.Split(' ');
				if (int.TryParse(valuesString[0], out tempInt))
					family = (Family)tempInt;
				if (int.TryParse(valuesString[1], out tempInt))
					serifStyle = (Serif_Style)tempInt;
				if (int.TryParse(valuesString[2], out tempInt))
					weight = (Weight)tempInt;
				if (int.TryParse(valuesString[3], out tempInt))
					proportion = (Proportion)tempInt;
				if (int.TryParse(valuesString[4], out tempInt))
					contrast = (Contrast)tempInt;
				if (int.TryParse(valuesString[5], out tempInt))
					strokeVariation = (Stroke_Variation)tempInt;
				if (int.TryParse(valuesString[6], out tempInt))
					armStyle = (Arm_Style)tempInt;
				if (int.TryParse(valuesString[7], out tempInt))
					letterform = (Letterform)tempInt;
				if (int.TryParse(valuesString[8], out tempInt))
					midline = (Midline)tempInt;
				if (int.TryParse(valuesString[0], out tempInt))
					xHeight = (XHeight)tempInt;
			}
 public void GetWeight_Test()
 {
     Log log = new Log("khaled", false);
     Weight weight = new Weight();
     IWeighingUnit Interface = new WeighingUnit(log, weight);
     Assert.AreEqual(Interface.GetWeight(), 100);
 }
Beispiel #3
0
        public IFont GetFont(string name, int size, Weight weight, bool italic)
        {
            var fontStyle = GetFontStyle(weight, italic);

            var fce = new FontCacheEntry
            {
                FontFace = name,
                FontSize = size,
                FontStyle = fontStyle
            };

            QFont font;

            var config = new QFontBuilderConfiguration(false)
            {
                TextGenerationRenderHint = GetFontFaceRenderHintingPreference(name),
                GlyphMargin = 2,
                TransformToCurrentOrthogProjection = true,
                KerningConfig =
                {
                    alphaEmptyPixelTolerance = 40,
                },
            };

            if (!_fontCache.TryGetValue(fce, out font))
            {
                var sysFont = GetFontBestSizeFit(name, size, fontStyle);

                font = new QFont(sysFont, config);

                _fontCache[fce] = font;
            }

            return new WrappedFont(font);
        }
Beispiel #4
0
        public void TestEqualMethodWithIntegerParam()
        {
            var firstWeight = new Weight(7);
            var secondWeight = 5;
            var thirdWeight = 7;

            Assert.IsFalse(firstWeight.Equals(secondWeight), "Equal method (with integer param) of Weight class does not work properly !");
            Assert.IsTrue(firstWeight.Equals(thirdWeight), "Equal method (with integer param) of Weight class does not work properly !");
        }
 /// <summary>
 /// Construct a <code>DisjunctionScorer</code>. </summary>
 /// <param name="weight"> The weight to be used. </param>
 /// <param name="subScorers"> Array of at least two subscorers. </param>
 /// <param name="coord"> Table of coordination factors </param>
 internal DisjunctionSumScorer(Weight weight, Scorer[] subScorers, float[] coord)
     : base(weight, subScorers)
 {
     if (NumScorers <= 1)
     {
         throw new System.ArgumentException("There must be at least 2 subScorers");
     }
     this.Coord = coord;
 }
Beispiel #6
0
        protected internal SpanScorer(Spans spans, Weight weight, Similarity.SimScorer docScorer)
            : base(weight)
        {
            this.DocScorer = docScorer;
            this.Spans = spans;

            Doc = -1;
            More = spans.Next();
        }
        public IngredientNode(Guid id, string name, UnitType convtype, Weight unitweight, DefaultPairings pairings)
        {
            this.id = id;
            this.pairings = pairings;
            this.convtype = convtype;
            this.unitweight = unitweight;

            this.IngredientName = name;
        }
 public AnomalousIngredientNode(
     Guid id,
     string name,
     UnitType convtype,
     Weight unitweight,
     DefaultPairings pairings)
     : base(id, name, convtype, unitweight, pairings)
 {
 }
 public static FontWeight Convert(Weight weight)
 {
     switch (weight)
     {
         case Weight.Bold: return FontWeights.Bold;
         case Weight.Normal: return FontWeights.Normal;
         default: throw new NotImplementedException();
     }
 }
 protected void Btn_SubmitWeight_Click(object sender, EventArgs e)
 {
     double weight = double.Parse(Txt_Weight.Text);
     Weight w = new Weight( 
             new HealthServiceDateTime(DateTime.Now),
             new WeightValue(
                 weight * 1.6, new DisplayValue(weight, "lbs", "lbs")));
     
     PersonInfo.SelectedRecord.NewItem(w);
 }
		internal TermScorer(Weight weight, TermDocs td, Similarity similarity, byte[] norms) : base(similarity)
		{
			this.weight = weight;
			this.termDocs = td;
			this.norms = norms;
			this.weightValue = weight.Value;
			
			for (int i = 0; i < SCORE_CACHE_SIZE; i++)
				scoreCache[i] = GetSimilarity().Tf(i) * weightValue;
		}
Beispiel #12
0
        public void TestEquationOperator()
        {
            var firstWeight = new Weight(7);
            var secondWeight = new Weight(5);
            var thirdWeight = new Weight(7);

            Assert.IsFalse(firstWeight == secondWeight, "Operator for equation of Weight class does not work properly !");
            Assert.IsTrue(firstWeight == thirdWeight, "Operator for equation of Weight class does not work properly !");
            Assert.IsFalse(null == thirdWeight, "Operator for equation of Weight class does not work properly !");
        }
Beispiel #13
0
        public void TestCompareToMethodWithWeightParam()
        {
            var firstWeight = new Weight(36);
            var secondWeight = new Weight(25);
            var thirdWeight = new Weight(77);
            var fourthWeight = new Weight(36);

            Assert.AreEqual(1, firstWeight.CompareTo(secondWeight), "CompareTo method (with Weight param) of Weight class does not work properly");
            Assert.AreEqual(-1, firstWeight.CompareTo(thirdWeight), "CompareTo method (with Weight param) of Weight class does not work properly");
            Assert.AreEqual(0, firstWeight.CompareTo(fourthWeight), "CompareTo method (with Weight param) of Weight class does not work properly");
        }
Beispiel #14
0
 private static FontWeight MapWeight(Weight weight)
 {
     switch (weight)
     {
         case Weight.Normal:
             return FontWeight.Normal;
         case Weight.Bold:
             return FontWeight.Bold;
         default:
             throw new ArgumentOutOfRangeException("weight");
     }
 }
 static TimedTextStyle()
 {
     DefaultColor = Colors.White;
     DefaultBackgroundColor = Colors.Transparent;
     DefaultExtent = Extent.Auto;
     DefaultFontFamily = new FontFamily("Portable User Interface");
     DefaultFontStyle = FontStyles.Normal;
     DefaultFontWeight = Weight.Normal;
     DefaultOrigin = Origin.Empty;
     DefaultPadding = Padding.Empty;
     DefaultOutlineColor = Colors.Black;
 }
Beispiel #16
0
    public override void Setup()
    {
        timeRemaining = TIME_LIMIT;
        good = true;
        playerDied = false;
        status = PuzzleStatus.INPROGRESS;

        // Generates the "solution"
        // Need left torque = right torque
        float leftLoc = -Random.Range(AREA_X_MIN, AREA_X_MAX);
        float leftMass = 10.0f;
        float rightLoc = Random.Range(AREA_X_MIN, AREA_X_MAX);
        float rightMass = -leftLoc * leftMass / rightLoc;

        // Generates spawn points
        float leftSpawn =  -(AREA_X_MAX + AREA_X_MIN) / 2;//-Random.Range(AREA_X_MIN, AREA_X_MAX);
        float rightSpawn =  (AREA_X_MAX + AREA_X_MIN) / 2;// Random.Range(AREA_X_MIN, AREA_X_MAX);

        // Player 1 is on the left... for now.
        leftWeight = this.transform.FindChild("Left Weight").GetComponent<Weight>();
        leftBody = leftWeight.GetComponent<Rigidbody2D>();
        leftBody.position = new Vector2(leftSpawn, leftBody.position.y);
        leftBody.mass = leftMass;

        // Player 2
        rightWeight = this.transform.FindChild("Right Weight").GetComponent<Weight>();
        rightBody = rightWeight.GetComponent<Rigidbody2D>();
        rightBody.position = new Vector2(rightSpawn, rightBody.position.y);
        rightBody.mass = rightMass;

        // Adjust camera.
        // Save camera positions then move both to our camera point.
        camPosition = this.transform.FindChild("Camera Point").position;
        cam1 = GameObject.Find("P1 Camera").GetComponent<Camera>();
        Debug.Log("Cam position" + cam1.transform.position);
        oldCam1Pos = cam1.transform.position;
        cam1.transform.position = camPosition;
        cam2 = GameObject.Find("P2 Camera").GetComponent<Camera>();
        oldCam2Pos = cam2.transform.position;
        cam2.transform.position = camPosition;

        seeSawBody = this.transform.FindChild("SeeSaw Board").GetComponent<Rigidbody2D>();
        if(tutorialMode)
        {
            leftBody.mass = 10.0f;
            rightBody.mass = 11.0f;
            seeSawBody.angularDrag = 1;//1000000.0f;
        }
    }
Beispiel #17
0
		protected internal SpanScorer(Spans spans, Weight weight, Similarity similarity, byte[] norms):base(similarity)
		{
			this.spans = spans;
			this.norms = norms;
			this.weight = weight;
			this.value_Renamed = weight.Value;
			if (this.spans.Next())
			{
				doc = - 1;
			}
			else
			{
				doc = NO_MORE_DOCS;
				more = false;
			}
		}
Beispiel #18
0
        public IFont GetFont(string fontFace="Arial", int fontSize=16, Weight weight=Weight.Normal, bool italic=false)
        {
            var fontWeight = MapWeight(weight);

            var testEntry = new FontCacheEntry
                                {
                                    FontFace = fontFace,
                                    FontSize = fontSize,
                                    FontWeight = fontWeight,
                                    Italic = italic
                                };

            if (!_fontCache.ContainsKey(testEntry))
            {
                CreateFontCacheEntry(testEntry);
            }

            return _fontCache[testEntry];
        }
Beispiel #19
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        OfflineWebApplicationConnection conn = HVConnectionManager.CreateConnection(selectedParticipant.HVPersonID);
        HealthRecordAccessor accessor = new HealthRecordAccessor(conn, selectedParticipant.HVRecordID);

        double weight = 300.0;
        Weight w = new Weight(
            new HealthServiceDateTime(DateTime.Now),
            new WeightValue(weight * 1.6, new DisplayValue(weight, "lbs", "lbs")));
        accessor.NewItem(w);

        //CodableValue allergyCV = new CodableValue("Allergy");

        //Allergy allergy = new Allergy(allergyCV);
        //allergy.
        //allergy.Name = "Cats";
        //allergy.Reaction = "Itchy Eyes";
        //accessor.NewItem(allergy);
    }
		internal PhraseScorer(Weight weight, TermPositions[] tps, int[] positions, Similarity similarity, byte[] norms) : base(similarity)
		{
			this.norms = norms;
			this.weight = weight;
			this.value_Renamed = weight.Value;
			
			// convert tps to a list
			for (int i = 0; i < tps.Length; i++)
			{
				PhrasePositions pp = new PhrasePositions(tps[i], positions[i]);
				if (last != null)
				{
					// add next to end of list
					last.next = pp;
				}
				else
					first = pp;
				last = pp;
			}
			
			pq = new PhraseQueue(tps.Length); // construct empty pq
		}
Beispiel #21
0
        override public string Stats()
        {
            string str = Age.ToString() + Name + Weight.ToString() + orangecolor;

            return(str);
        }
 public void AddWeightToSync(Weight w)
 {
     weights.Add(w);
     status.NeedsToSync();
 }
Beispiel #23
0
    public static Weight GetCardWeight(int iValueCode)
    {
        Weight retWeight = Weight.One;
        int    iNum      = 0;

        if (iValueCode >= (mTotalCardCount - 1))
        {
            iNum = iValueCode;
        }
        else
        {
            iNum = iValueCode % mDiv;
            if (iNum == 0)
            {
                iNum = mDiv;
            }
        }

        switch (iNum)
        {
        case 1:
            retWeight = Weight.One;
            break;

        case 2:
            retWeight = Weight.Two;
            break;

        case 3:
            retWeight = Weight.Three;
            break;

        case 4:
            retWeight = Weight.Four;
            break;

        case 5:
            retWeight = Weight.Five;
            break;

        case 6:
            retWeight = Weight.Six;
            break;

        case 7:
            retWeight = Weight.Seven;
            break;

        case 8:
            retWeight = Weight.Eight;
            break;

        case 9:
            retWeight = Weight.Nine;
            break;

        case 10:
            retWeight = Weight.Ten;
            break;

        case 11:
            retWeight = Weight.Jack;
            break;

        case 12:
            retWeight = Weight.Queen;
            break;

        case 13:
            retWeight = Weight.King;
            break;

        case 53:
            retWeight = Weight.LJoker;
            break;

        case 54:
            retWeight = Weight.SJoker;
            break;
        }

        return(retWeight);
    }
Beispiel #24
0
 public Card(Weight weight, Suits suits)
 {
     this.CardWeight = weight;
     this.CardSuits  = suits;
 }
Beispiel #25
0
 public void TestIntegerImplicitOperator()
 {
     var newWeight = new Weight(7);
     int integeredWeight = newWeight;
     Assert.AreEqual(7, integeredWeight, "Implicit operator \"int\"  of Weight class does not work properly !");
 }
Beispiel #26
0
 // Returns a weighted value in range [-1, 1)
 public float WeightedSignedValue(Weight weight, int weightStrength = 4)
 {
     return(WeightedValue(weight, weightStrength) * 2 - 1);
 }
Beispiel #27
0
    // Returns a weighted value in range [min, max)
    public float WeightedRange(float min, float max, Weight weight, int weightStrength = 4)
    {
        float value01 = WeightedValue(weight, weightStrength);

        return(Mathf.Lerp(min, max, value01));
    }
Beispiel #28
0
 public override string ToString()
 {
     return(Weight.ToString());
 }
Beispiel #29
0
 public override string ToString()
 {
     return(Origin.VertexCircle.ID.ToString() + " → " + Destination.VertexCircle.ID.ToString() + " : " + Weight.ToString());
 }
Beispiel #30
0
 public override void BrowseWaitVisible()
 {
     base.BrowseWaitVisible();
     Weight.WaitVisible();
 }
Beispiel #31
0
        public virtual void Search(Weight weight, Filter filter, ICollector collector, int start, IBoboMapFunctionWrapper mapReduceWrapper)
        {
            FacetValidator validator = CreateFacetValidator();
            int            target    = 0;

            IndexReader        reader             = this.IndexReader;
            IndexReaderContext indexReaderContext = reader.Context;

            if (filter == null)
            {
                for (int i = 0; i < m_subReaders.Length; i++)
                {
                    AtomicReaderContext atomicContext = indexReaderContext.Children == null
                        ? (AtomicReaderContext)indexReaderContext
                        : (AtomicReaderContext)(indexReaderContext.Children.Get(i));
                    int docStart = start;

                    // NOTE: This code calls an internal constructor. Apparently, this was in the same namespace as Lucene,
                    // but was added to this project, which presumably allows you to call internal constructors in Java.
                    // In .NET, we can just use Activator.CreateInstance. Not great, but this code will be removed
                    // when applying commit https://github.com/senseidb/bobo/commit/924c8579d90dbb5d56103976d39b47daa2242ef3
                    // which includes several major changes after the 4.0.2 release.

                    // atomicContext = AtomicReaderContextUtil.UpdateDocBase(atomicContext, docStart);
                    object[] args = new object[] { (CompositeReaderContext)null, atomicContext.AtomicReader, 0, 0, 0, docStart };
                    Type[]   constructorSignature = { typeof(CompositeReaderContext), typeof(AtomicReader), typeof(int), typeof(int), typeof(int), typeof(int) };
                    var      constr = typeof(AtomicReaderContext).GetTypeInfo().DeclaredConstructors
                                      .Single(constructor =>
                                              constructor.GetParameters()
                                              .Select(parameter => parameter.ParameterType)
                                              .SequenceEqual(constructorSignature));
                    atomicContext = (AtomicReaderContext)constr.Invoke(args);

                    if (reader is BoboMultiReader)
                    {
                        docStart = start + ((BoboMultiReader)reader).SubReaderBase(i);
                    }
                    collector.SetNextReader(atomicContext);
                    validator.SetNextReader(m_subReaders[i], docStart);

                    // NOTE: The Weight.Scorer method lost the scoreDocsInOrder and topScorer parameters between
                    // Lucene 4.3.0 and 4.8.0. They are not used by BoboBrowse anyway, so the code here diverges
                    // from the original Java source to remove these two parameters.

                    // Scorer scorer = weight.Scorer(atomicContext, true, true, _subReaders[i].LiveDocs);
                    Scorer scorer = weight.GetScorer(atomicContext, m_subReaders[i].LiveDocs);
                    if (scorer != null)
                    {
                        collector.SetScorer(scorer);
                        target = scorer.NextDoc();
                        while (target != DocIdSetIterator.NO_MORE_DOCS)
                        {
                            if (validator.Validate(target))
                            {
                                collector.Collect(target);
                                target = scorer.NextDoc();
                            }
                            else
                            {
                                target = validator.m_nextTarget;
                                target = scorer.Advance(target);
                            }
                        }
                    }
                    if (mapReduceWrapper != null)
                    {
                        mapReduceWrapper.MapFullIndexReader(m_subReaders[i], validator.GetCountCollectors());
                    }
                }
                return;
            }

            for (int i = 0; i < m_subReaders.Length; i++)
            {
                AtomicReaderContext atomicContext = indexReaderContext.Children == null
                        ? (AtomicReaderContext)indexReaderContext
                        : (AtomicReaderContext)(indexReaderContext.Children.Get(i));

                DocIdSet filterDocIdSet = filter.GetDocIdSet(atomicContext, m_subReaders[i].LiveDocs);
                if (filterDocIdSet == null)
                {
                    return;                          //shall we use return or continue here ??
                }
                int docStart = start;
                if (reader is BoboMultiReader)
                {
                    docStart = start + ((BoboMultiReader)reader).SubReaderBase(i);
                }
                collector.SetNextReader(atomicContext);
                validator.SetNextReader(m_subReaders[i], docStart);

                // NOTE: The Weight.Scorer method lost the scoreDocsInOrder and topScorer parameters between
                // Lucene 4.3.0 and 4.8.0. They are not used by BoboBrowse anyway, so the code here diverges
                // from the original Java source to remove these two parameters.

                // Scorer scorer = weight.Scorer(atomicContext, true, false, _subReaders[i].LiveDocs);
                Scorer scorer = weight.GetScorer(atomicContext, m_subReaders[i].LiveDocs);
                if (scorer != null)
                {
                    collector.SetScorer(scorer);
                    DocIdSetIterator filterDocIdIterator = filterDocIdSet.GetIterator(); // CHECKME: use ConjunctionScorer here?

                    if (filterDocIdIterator == null)
                    {
                        continue;
                    }

                    int doc = -1;
                    target = filterDocIdIterator.NextDoc();
                    if (mapReduceWrapper == null)
                    {
                        while (target < DocIdSetIterator.NO_MORE_DOCS)
                        {
                            if (doc < target)
                            {
                                doc = scorer.Advance(target);
                            }

                            if (doc == target) // permitted by filter
                            {
                                if (validator.Validate(doc))
                                {
                                    collector.Collect(doc);

                                    target = filterDocIdIterator.NextDoc();
                                }
                                else
                                {
                                    // skip to the next possible docid
                                    target = filterDocIdIterator.Advance(validator.m_nextTarget);
                                }
                            }
                            else // doc > target
                            {
                                if (doc == DocIdSetIterator.NO_MORE_DOCS)
                                {
                                    break;
                                }
                                target = filterDocIdIterator.Advance(doc);
                            }
                        }
                    }
                    else
                    {
                        //MapReduce wrapper is not null
                        while (target < DocIdSetIterator.NO_MORE_DOCS)
                        {
                            if (doc < target)
                            {
                                doc = scorer.Advance(target);
                            }

                            if (doc == target) // permitted by filter
                            {
                                if (validator.Validate(doc))
                                {
                                    mapReduceWrapper.MapSingleDocument(doc, m_subReaders[i]);
                                    collector.Collect(doc);

                                    target = filterDocIdIterator.NextDoc();
                                }
                                else
                                {
                                    // skip to the next possible docid
                                    target = filterDocIdIterator.Advance(validator.m_nextTarget);
                                }
                            }
                            else // doc > target
                            {
                                if (doc == DocIdSetIterator.NO_MORE_DOCS)
                                {
                                    break;
                                }
                                target = filterDocIdIterator.Advance(doc);
                            }
                        }
                        mapReduceWrapper.FinalizeSegment(m_subReaders[i], validator.GetCountCollectors());
                    }
                }
            }
        }
Beispiel #32
0
        public FileData Read(string localFilename)
        {
            if (fail) throw new ProcessFailedException(id);
            if (freeze)
            {
                freezed.Enqueue(() => Read(localFilename));
                throw new ProcessFreezedException(id);
            }

            Console.WriteLine("READ " + localFilename);
            if (!files.ContainsKey(localFilename))
            {
                Console.WriteLine("CREATE FILE " + localFilename);
                files[localFilename] = new FileData();
                weights[localFilename] = new Weight();
            }

            weights[localFilename].Reads++;
            return files[localFilename];
        }
Beispiel #33
0
        public void Write(string localFilename, FileData newFile)
        {
            if (fail) throw new ProcessFailedException(id);
            if (freeze)
            {
                freezed.Enqueue(() => Write(localFilename, newFile));
                throw new ProcessFreezedException(id);
            }

            Console.WriteLine("WRITE " + localFilename
                + " : CONTENTS " + Helper.BytesToString(newFile.Contents)
                + " : VERSION " + newFile.Version);

            if (!files.ContainsKey(localFilename))
            {
                Console.WriteLine("CREATE FILE " + localFilename);
                files[localFilename] = newFile;
                weights[localFilename] = new Weight();
            }
            else
            {
                files[localFilename] = FileData.Latest(files[localFilename], newFile);
            }

            weights[localFilename].Writes++;
            Console.WriteLine("STORED = " + files[localFilename].Version);
        }
        public IEnumerable <NLP.IngredientNode> LoadSynonyms()
        {
            var nodes = new Dictionary <Guid, NLP.IngredientNode>();

            var forms      = store.GetIndexedIngredientForms();
            var ingsForNlp = store.Ingredients;
            var pairingMap = store.NlpDefaultPairings.ToDictionary(p => p.IngredientId);

            foreach (var ing in ingsForNlp)
            {
                var    ingId      = ing.IngredientId;
                var    name       = ing.DisplayName;
                var    convType   = ing.ConversionType;
                Weight unitWeight = ing.UnitWeight;
                var    pairings   = new DefaultPairings();

                NlpDefaultPairings defaultPairing;
                if (pairingMap.TryGetValue(ingId, out defaultPairing))
                {
                    if (defaultPairing.WeightFormId.HasValue)
                    {
                        var wf       = forms[defaultPairing.WeightFormId.Value];
                        var wfAmount = new Amount(wf.FormAmount, wf.FormUnit);
                        pairings.Weight = new IngredientForm(wf.IngredientFormId, ingId, Units.Ounce, null, null, wf.ConvMultiplier, wfAmount);
                    }

                    if (defaultPairing.VolumeFormId.HasValue)
                    {
                        var vf       = forms[defaultPairing.VolumeFormId.Value];
                        var vfAmount = new Amount(vf.FormAmount, vf.FormUnit);
                        pairings.Volume = new IngredientForm(vf.IngredientFormId, ingId, Units.Cup, null, null, vf.ConvMultiplier, vfAmount);
                    }

                    if (defaultPairing.UnitFormId.HasValue)
                    {
                        var uf       = forms[defaultPairing.UnitFormId.Value];
                        var ufAmount = new Amount(uf.FormAmount, uf.FormUnit);
                        pairings.Unit = new IngredientForm(uf.IngredientFormId, ingId, Units.Unit, null, null, uf.ConvMultiplier, ufAmount);
                    }
                }

                if (nodes.ContainsKey(ingId))
                {
                    Parser.Log.ErrorFormat("[NLP Loader] Duplicate ingredient key due to bad DB data: {0} ({1})", name, ingId);
                }
                else
                {
                    nodes.Add(ingId, new NLP.IngredientNode(ingId, name, convType, unitWeight, pairings));
                }
            }

            //Load synonyms
            var ingSynonyms = store.NlpIngredientSynonyms;

            var ret = new List <NLP.IngredientNode>();

            foreach (var syn in ingSynonyms)
            {
                var ingId    = syn.IngredientId;
                var alias    = syn.Alias;
                var prepnote = syn.Prepnote;

                NLP.IngredientNode node;
                if (nodes.TryGetValue(ingId, out node)) //TODO: If this fails, maybe throw an exception?
                {
                    ret.Add(new NLP.IngredientNode(node, alias, prepnote));
                }
            }

            ret.AddRange(nodes.Values);

            return(ret);
        }
Beispiel #35
0
        public override void Search(Query query, Filter filter, ICollector collector)
        {
            Weight weight = CreateNormalizedWeight(query);

            this.Search(weight, filter, collector, 0, null);
        }
Beispiel #36
0
 public Task <bool> UpdateItemAsync(Weight item)
 {
     throw new NotImplementedException();
 }
Beispiel #37
0
 /// <summary>
 /// Returns true if the given object equals this one.
 /// </summary>
 /// <param name="other"></param>
 /// <returns></returns>
 protected bool Equals(PathSegment <TIdType> other)
 {
     return(EqualityComparer <TIdType> .Default.Equals(VertexId, other.VertexId) && Weight.Equals(other.Weight) && Equals(From, other.From));
 }
Beispiel #38
0
        public void ProcessVerticesWithoutWeights(Mesh mesh, VertexData vertData, bool degenerateTriangles = false)
        {
            Packet pack = new Packet();


            List <Enums.GXVertexAttribute> activeAttribs = Descriptor.GetActiveAttributes();

            AttributeData.SetAttributesFromList(activeAttribs);

            //Console.WriteLine("Calculating triangle strips");

            uint[]                triindices = MakeTriIndexList(mesh);
            TriStripper           stripper   = new TriStripper(triindices);
            List <PrimitiveBrawl> primlist   = stripper.Strip();

            if (degenerateTriangles)
            {
                Console.WriteLine("Converting Triangle Lists into Triangle Strips with degenerate triangles.");

                for (int i = 0; i < primlist.Count; i++)
                {
                    PrimitiveBrawl primbrawl = primlist[i];

                    Enums.GXPrimitiveType primtype = (Enums.GXPrimitiveType)primbrawl.Type;

                    if (primtype == Enums.GXPrimitiveType.Triangles)
                    {
                        PrimitiveBrawl newprim  = new PrimitiveBrawl(PrimType.TriangleStrip);
                        uint           lastVert = 0;
                        for (int j = 0; j < primbrawl.Indices.Count / 3; j++)
                        {
                            if (j > 0)
                            {
                                newprim.Indices.Add(lastVert);
                                newprim.Indices.Add(primbrawl.Indices[(j) * 3 + 0]);
                            }

                            newprim.Indices.Add(primbrawl.Indices[(j) * 3 + 0]);

                            if (j % 2 == 0)
                            {
                                newprim.Indices.Add(primbrawl.Indices[(j) * 3 + 1]);
                                newprim.Indices.Add(primbrawl.Indices[(j) * 3 + 2]);

                                lastVert = primbrawl.Indices[(j) * 3 + 2];
                            }
                            else
                            {
                                newprim.Indices.Add(primbrawl.Indices[(j) * 3 + 2]);
                                newprim.Indices.Add(primbrawl.Indices[(j) * 3 + 1]);


                                lastVert = primbrawl.Indices[(j) * 3 + 1];
                            }
                        }
                        primlist[i] = newprim;
                    }
                }
            }

            //Console.WriteLine(String.Format("Done, {0} primitives", primlist.Count));

            foreach (PrimitiveBrawl primbrawl in primlist)
            {
                //Primitive prim = new Primitive(Enums.GXPrimitiveType.TriangleStrip);
                Primitive prim = new Primitive((Enums.GXPrimitiveType)primbrawl.Type);
                //Console.WriteLine(String.Format("Primitive type {0}", (Enums.GXPrimitiveType)primbrawl.Type));
                foreach (int vertIndex in primbrawl.Indices)
                {
                    Vertex vert = new Vertex();

                    Weight rootWeight = new Weight();
                    rootWeight.AddWeight(1.0f, 0);

                    vert.SetWeight(rootWeight);
                    //int vertIndex = face.Indices[i];

                    foreach (Enums.GXVertexAttribute attrib in activeAttribs)
                    {
                        switch (attrib)
                        {
                        case Enums.GXVertexAttribute.Position:
                            List <Vector3> posData = (List <Vector3>)vertData.GetAttributeData(Enums.GXVertexAttribute.Position);
                            Vector3        vertPos = mesh.Vertices[vertIndex].ToOpenTKVector3();

                            if (!posData.Contains(vertPos))
                            {
                                posData.Add(vertPos);
                            }
                            AttributeData.Positions.Add(vertPos);

                            vert.SetAttributeIndex(Enums.GXVertexAttribute.Position, (uint)posData.IndexOf(vertPos));
                            break;

                        case Enums.GXVertexAttribute.Normal:
                            List <Vector3> normData = (List <Vector3>)vertData.GetAttributeData(Enums.GXVertexAttribute.Normal);
                            Vector3        vertNrm  = mesh.Normals[vertIndex].ToOpenTKVector3();

                            if (!normData.Contains(vertNrm))
                            {
                                normData.Add(vertNrm);
                            }
                            AttributeData.Normals.Add(vertNrm);

                            vert.SetAttributeIndex(Enums.GXVertexAttribute.Normal, (uint)normData.IndexOf(vertNrm));
                            break;

                        case Enums.GXVertexAttribute.Color0:
                        case Enums.GXVertexAttribute.Color1:
                            int          colNo   = (int)attrib - 11;
                            List <Color> colData = (List <Color>)vertData.GetAttributeData(Enums.GXVertexAttribute.Color0 + colNo);
                            Color        vertCol = mesh.VertexColorChannels[colNo][vertIndex].ToSuperBMDColorRGBA();


                            if (colNo == 0)
                            {
                                AttributeData.Color_0.Add(vertCol);
                            }
                            else
                            {
                                AttributeData.Color_1.Add(vertCol);
                            }


                            vert.SetAttributeIndex(Enums.GXVertexAttribute.Color0 + colNo, (uint)colData.IndexOf(vertCol));
                            break;

                        case Enums.GXVertexAttribute.Tex0:
                        case Enums.GXVertexAttribute.Tex1:
                        case Enums.GXVertexAttribute.Tex2:
                        case Enums.GXVertexAttribute.Tex3:
                        case Enums.GXVertexAttribute.Tex4:
                        case Enums.GXVertexAttribute.Tex5:
                        case Enums.GXVertexAttribute.Tex6:
                        case Enums.GXVertexAttribute.Tex7:
                            int            texNo        = (int)attrib - 13;
                            List <Vector2> texCoordData = (List <Vector2>)vertData.GetAttributeData(Enums.GXVertexAttribute.Tex0 + texNo);
                            Vector2        vertTexCoord = mesh.TextureCoordinateChannels[texNo][vertIndex].ToOpenTKVector2();
                            vertTexCoord = new Vector2(vertTexCoord.X, 1.0f - vertTexCoord.Y);


                            switch (texNo)
                            {
                            case 0:
                                AttributeData.TexCoord_0.Add(vertTexCoord);
                                break;

                            case 1:
                                AttributeData.TexCoord_1.Add(vertTexCoord);
                                break;

                            case 2:
                                AttributeData.TexCoord_2.Add(vertTexCoord);
                                break;

                            case 3:
                                AttributeData.TexCoord_3.Add(vertTexCoord);
                                break;

                            case 4:
                                AttributeData.TexCoord_4.Add(vertTexCoord);
                                break;

                            case 5:
                                AttributeData.TexCoord_5.Add(vertTexCoord);
                                break;

                            case 6:
                                AttributeData.TexCoord_6.Add(vertTexCoord);
                                break;

                            case 7:
                                AttributeData.TexCoord_7.Add(vertTexCoord);
                                break;
                            }

                            vert.SetAttributeIndex(Enums.GXVertexAttribute.Tex0 + texNo, (uint)texCoordData.IndexOf(vertTexCoord));
                            break;
                        }
                    }

                    //triindices[vertIndex] = 1;
                    prim.Vertices.Add(vert);
                }

                pack.Primitives.Add(prim);
            }


            pack.MatrixIndices.Add(0);
            Packets.Add(pack);

            Bounds.GetBoundsValues(AttributeData.Positions);
            Console.Write("...✓");
        }
Beispiel #39
0
 public WeightAnonymousClass(DrillSidewaysQuery outerInstance, Weight baseWeight, object[] drillDowns)
 {
     this.outerInstance = outerInstance;
     this.baseWeight    = baseWeight;
     this.drillDowns    = drillDowns;
 }
Beispiel #40
0
        public void ProcessVerticesWithWeights(Mesh mesh, VertexData vertData, Dictionary <string, int> boneNames, EVP1 envelopes, DRW1 partialWeight,
                                               bool doStrip = true, bool degenerateTriangles = false)
        {
            Weight[] weights = new Weight[mesh.Vertices.Count];

            for (int i = 0; i < mesh.Vertices.Count; i++)
            {
                int    vertexid   = i;
                Weight vertWeight = new Weight();

                foreach (Assimp.Bone bone in mesh.Bones)
                {
                    foreach (VertexWeight weight in bone.VertexWeights)
                    {
                        if (weight.VertexID == vertexid)
                        {
                            vertWeight.AddWeight(weight.Weight, boneNames[bone.Name]);
                        }
                    }
                }
                vertWeight.reorderBones();
                weights[vertexid] = vertWeight;
            }

            //Primitive prim = new Primitive(Enums.GXPrimitiveType.Triangles);
            List <Enums.GXVertexAttribute> activeAttribs = Descriptor.GetActiveAttributes();

            AttributeData.SetAttributesFromList(activeAttribs);


            uint[] triindices = MakeTriIndexList(mesh);

            List <PrimitiveBrawl> primlist;

            if (doStrip)
            {
                //Console.WriteLine("Calculating triangle strips for Weighted");
                TriStripper stripper = new TriStripper(triindices, weights);
                primlist = stripper.Strip();
            }
            else
            {
                //Console.WriteLine("Calculating triangle list for Weighted");
                primlist = new List <PrimitiveBrawl>();
                PrimitiveBrawl prim = new PrimitiveBrawl(PrimType.TriangleList); // Trilist
                foreach (uint index in triindices)
                {
                    prim.Indices.Add(index);
                }
                primlist.Add(prim);
            }

            //Console.WriteLine(String.Format("Done, {0} primitives", primlist.Count));



            Packet        pack          = new Packet();
            List <Weight> packetWeights = new List <Weight>();
            int           numMatrices   = 0;

            if (degenerateTriangles)
            {
                Console.WriteLine("Converting Triangle Lists into Triangle Strips with degenerate triangles.");

                for (int i = 0; i < primlist.Count; i++)
                {
                    PrimitiveBrawl primbrawl = primlist[i];

                    Enums.GXPrimitiveType primtype = (Enums.GXPrimitiveType)primbrawl.Type;

                    if (primtype == Enums.GXPrimitiveType.Triangles)
                    {
                        PrimitiveBrawl newprim  = new PrimitiveBrawl(PrimType.TriangleStrip);
                        uint           lastVert = 0;
                        for (int j = 0; j < primbrawl.Indices.Count / 3; j++)
                        {
                            if (j > 0)
                            {
                                newprim.Indices.Add(lastVert);
                                newprim.Indices.Add(primbrawl.Indices[(j) * 3 + 0]);
                            }

                            newprim.Indices.Add(primbrawl.Indices[(j) * 3 + 0]);

                            if (j % 2 == 0)
                            {
                                newprim.Indices.Add(primbrawl.Indices[(j) * 3 + 1]);
                                newprim.Indices.Add(primbrawl.Indices[(j) * 3 + 2]);

                                lastVert = primbrawl.Indices[(j) * 3 + 2];
                            }
                            else
                            {
                                newprim.Indices.Add(primbrawl.Indices[(j) * 3 + 2]);
                                newprim.Indices.Add(primbrawl.Indices[(j) * 3 + 1]);


                                lastVert = primbrawl.Indices[(j) * 3 + 1];
                            }
                        }
                        primlist[i] = newprim;
                    }
                }
            }

            foreach (PrimitiveBrawl primbrawl in primlist)
            {
                int numNewMatricesForFirstThreeVerts = 0;
                if (!packetWeights.Contains(weights[primbrawl.Indices[0]]))
                {
                    numNewMatricesForFirstThreeVerts++;
                }
                if (!packetWeights.Contains(weights[primbrawl.Indices[1]]))
                {
                    numNewMatricesForFirstThreeVerts++;
                }
                if (!packetWeights.Contains(weights[primbrawl.Indices[2]]))
                {
                    numNewMatricesForFirstThreeVerts++;
                }
                if (numMatrices + numNewMatricesForFirstThreeVerts > MaxMatricesPerPacket)
                {
                    // We won't be able to fit even the first 3 vertices of this primitive without going over the matrix limit.
                    // So we need to start a new packet.
                    packetWeights.Clear();
                    numMatrices = 0;
                    Packets.Add(pack);
                    pack = new Packet();
                }


                Primitive prim = new Primitive((Enums.GXPrimitiveType)primbrawl.Type);
                //Primitive prim = new Primitive(Enums.GXPrimitiveType.TriangleStrip);

                int currvert = -1;
                int maxvert  = primbrawl.Indices.Count - 1;
                Enums.GXPrimitiveType primtype = (Enums.GXPrimitiveType)primbrawl.Type;

                if (primtype == Enums.GXPrimitiveType.TriangleStrip)
                {
                    //Console.WriteLine("Doing Tristrip");
                    foreach (int vertIndex in primbrawl.Indices)
                    {
                        currvert++;
                        Weight vertWeight = weights[vertIndex];

                        int oldmat = numMatrices;
                        if (!packetWeights.Contains(vertWeight))
                        {
                            packetWeights.Add(vertWeight);
                            numMatrices++;
                        }

                        //Console.WriteLine(String.Format("Added {0} matrices, is now {1}", numMatrices - oldmat, numMatrices));

                        // There are too many matrices, we need to create a new packet
                        if (numMatrices > MaxMatricesPerPacket)
                        {
                            // If we break up and the resulting TriStrip becomes invalid,
                            // then we need to handle those cases.

                            //Console.WriteLine(String.Format("Breaking up because over the limit: {0}", numMatrices));

                            if (prim.PrimitiveType == Enums.GXPrimitiveType.TriangleStrip)
                            {
                                Debug.Assert(prim.Vertices.Count >= 3);
                            }
                            else if (prim.PrimitiveType == Enums.GXPrimitiveType.Triangles)
                            {
                                Debug.Assert(prim.Vertices.Count % 3 == 0);
                            }
                            pack.Primitives.Add(prim);


                            Primitive newprim = new Primitive(Enums.GXPrimitiveType.TriangleStrip);
                            Vertex    prev3   = new Vertex(prim.Vertices[prim.Vertices.Count - 3]);
                            Vertex    prev2   = new Vertex(prim.Vertices[prim.Vertices.Count - 2]);
                            Vertex    prev    = new Vertex(prim.Vertices[prim.Vertices.Count - 1]);
                            bool      isOdd   = currvert % 2 != 0;
                            if (isOdd)
                            {
                                // Need to preserve whether each vertex is even or odd inside the triangle strip.
                                // Do this by adding an extra vertex from the previous packet to the start of this one.
                                newprim.Vertices.Add(prev3);
                            }
                            newprim.Vertices.Add(prev2);
                            newprim.Vertices.Add(prev);

                            prim = newprim;

                            packetWeights.Clear();
                            numMatrices = 0;
                            Packets.Add(pack);
                            Packet oldPack = pack;
                            pack = new Packet();

                            // Calculate matrices for current packet in case we added vertices
                            foreach (Vertex vertex in prim.Vertices)
                            {
                                if (!packetWeights.Contains(vertex.VertexWeight))
                                {
                                    packetWeights.Add(vertex.VertexWeight);
                                    numMatrices++;
                                }

                                // Re-add the matrix index for the duplicated verts to the new packet.
                                // And recalculate the matrix index index in each vert's attribute data.
                                uint oldMatrixIndexIndex = vertex.GetAttributeIndex(Enums.GXVertexAttribute.PositionMatrixIdx);
                                int  matrixIndex         = oldPack.MatrixIndices[(int)oldMatrixIndexIndex];

                                if (!pack.MatrixIndices.Contains(matrixIndex))
                                {
                                    pack.MatrixIndices.Add(matrixIndex);
                                }
                                vertex.SetAttributeIndex(Enums.GXVertexAttribute.PositionMatrixIdx, (uint)pack.MatrixIndices.IndexOf(matrixIndex));
                            }

                            if (!packetWeights.Contains(vertWeight))
                            {
                                packetWeights.Add(vertWeight);
                                numMatrices++;
                            }
                        }

                        Vertex vert      = new Vertex();
                        Weight curWeight = vertWeight;

                        vert.SetWeight(curWeight);

                        foreach (Enums.GXVertexAttribute attrib in activeAttribs)
                        {
                            switch (attrib)
                            {
                            case Enums.GXVertexAttribute.PositionMatrixIdx:
                                int newMatrixIndex = -1;

                                if (curWeight.WeightCount == 1)
                                {
                                    newMatrixIndex = partialWeight.MeshWeights.IndexOf(curWeight);
                                }
                                else
                                {
                                    if (!envelopes.Weights.Contains(curWeight))
                                    {
                                        envelopes.Weights.Add(curWeight);
                                    }

                                    int envIndex = envelopes.Weights.IndexOf(curWeight);
                                    int drwIndex = partialWeight.MeshWeights.IndexOf(curWeight);

                                    if (drwIndex == -1)
                                    {
                                        throw new System.Exception($"Model has unweighted vertices in mesh \"{mesh.Name}\". Please weight all vertices to at least one bone.");
                                    }

                                    newMatrixIndex = drwIndex;
                                    partialWeight.Indices[drwIndex] = envIndex;
                                }

                                if (!pack.MatrixIndices.Contains(newMatrixIndex))
                                {
                                    pack.MatrixIndices.Add(newMatrixIndex);
                                }

                                vert.SetAttributeIndex(Enums.GXVertexAttribute.PositionMatrixIdx, (uint)pack.MatrixIndices.IndexOf(newMatrixIndex));
                                break;

                            case Enums.GXVertexAttribute.Position:
                                List <Vector3> posData = (List <Vector3>)vertData.GetAttributeData(Enums.GXVertexAttribute.Position);
                                Vector3        vertPos = mesh.Vertices[vertIndex].ToOpenTKVector3();

                                if (curWeight.WeightCount == 1)
                                {
                                    Matrix4 ibm = envelopes.InverseBindMatrices[curWeight.BoneIndices[0]];

                                    Vector3 transVec = Vector3.TransformPosition(vertPos, ibm);
                                    if (!posData.Contains(transVec))
                                    {
                                        posData.Add(transVec);
                                    }
                                    AttributeData.Positions.Add(transVec);
                                    vert.SetAttributeIndex(Enums.GXVertexAttribute.Position, (uint)posData.IndexOf(transVec));
                                }
                                else
                                {
                                    if (!posData.Contains(vertPos))
                                    {
                                        posData.Add(vertPos);
                                    }
                                    AttributeData.Positions.Add(vertPos);

                                    vert.SetAttributeIndex(Enums.GXVertexAttribute.Position, (uint)posData.IndexOf(vertPos));
                                }
                                break;

                            case Enums.GXVertexAttribute.Normal:
                                List <Vector3> normData = (List <Vector3>)vertData.GetAttributeData(Enums.GXVertexAttribute.Normal);
                                Vector3        vertNrm  = mesh.Normals[vertIndex].ToOpenTKVector3();

                                if (curWeight.WeightCount == 1)
                                {
                                    Matrix4 ibm = envelopes.InverseBindMatrices[curWeight.BoneIndices[0]];
                                    vertNrm = Vector3.TransformNormal(vertNrm, ibm);
                                    if (!normData.Contains(vertNrm))
                                    {
                                        normData.Add(vertNrm);
                                    }
                                }
                                else
                                {
                                    if (!normData.Contains(vertNrm))
                                    {
                                        normData.Add(vertNrm);
                                    }
                                }

                                AttributeData.Normals.Add(vertNrm);
                                vert.SetAttributeIndex(Enums.GXVertexAttribute.Normal, (uint)normData.IndexOf(vertNrm));
                                break;

                            case Enums.GXVertexAttribute.Color0:
                            case Enums.GXVertexAttribute.Color1:
                                int          colNo   = (int)attrib - 11;
                                List <Color> colData = (List <Color>)vertData.GetAttributeData(Enums.GXVertexAttribute.Color0 + colNo);
                                Color        vertCol = mesh.VertexColorChannels[colNo][vertIndex].ToSuperBMDColorRGBA();

                                if (colNo == 0)
                                {
                                    AttributeData.Color_0.Add(vertCol);
                                }
                                else
                                {
                                    AttributeData.Color_1.Add(vertCol);
                                }

                                vert.SetAttributeIndex(Enums.GXVertexAttribute.Color0 + colNo, (uint)colData.IndexOf(vertCol));
                                break;

                            case Enums.GXVertexAttribute.Tex0:
                            case Enums.GXVertexAttribute.Tex1:
                            case Enums.GXVertexAttribute.Tex2:
                            case Enums.GXVertexAttribute.Tex3:
                            case Enums.GXVertexAttribute.Tex4:
                            case Enums.GXVertexAttribute.Tex5:
                            case Enums.GXVertexAttribute.Tex6:
                            case Enums.GXVertexAttribute.Tex7:
                                int            texNo        = (int)attrib - 13;
                                List <Vector2> texCoordData = (List <Vector2>)vertData.GetAttributeData(Enums.GXVertexAttribute.Tex0 + texNo);
                                Vector2        vertTexCoord = mesh.TextureCoordinateChannels[texNo][vertIndex].ToOpenTKVector2();
                                vertTexCoord = new Vector2(vertTexCoord.X, 1.0f - vertTexCoord.Y);

                                switch (texNo)
                                {
                                case 0:
                                    AttributeData.TexCoord_0.Add(vertTexCoord);
                                    break;

                                case 1:
                                    AttributeData.TexCoord_1.Add(vertTexCoord);
                                    break;

                                case 2:
                                    AttributeData.TexCoord_2.Add(vertTexCoord);
                                    break;

                                case 3:
                                    AttributeData.TexCoord_3.Add(vertTexCoord);
                                    break;

                                case 4:
                                    AttributeData.TexCoord_4.Add(vertTexCoord);
                                    break;

                                case 5:
                                    AttributeData.TexCoord_5.Add(vertTexCoord);
                                    break;

                                case 6:
                                    AttributeData.TexCoord_6.Add(vertTexCoord);
                                    break;

                                case 7:
                                    AttributeData.TexCoord_7.Add(vertTexCoord);
                                    break;
                                }

                                vert.SetAttributeIndex(Enums.GXVertexAttribute.Tex0 + texNo, (uint)texCoordData.IndexOf(vertTexCoord));
                                break;
                            }
                        }
                        prim.Vertices.Add(vert);
                    }
                }
                else if (primtype == Enums.GXPrimitiveType.Triangles)
                {
                    for (int j = 0; j < primbrawl.Indices.Count / 3; j++)
                    {
                        int    vert1Index  = (int)primbrawl.Indices[j * 3 + 0];
                        int    vert2Index  = (int)primbrawl.Indices[j * 3 + 1];
                        int    vert3Index  = (int)primbrawl.Indices[j * 3 + 2];
                        Weight vert1Weight = weights[vert1Index];
                        Weight vert2Weight = weights[vert2Index];
                        Weight vert3Weight = weights[vert3Index];
                        int    oldcount    = numMatrices;
                        if (!packetWeights.Contains(vert1Weight))
                        {
                            packetWeights.Add(vert1Weight);
                            numMatrices++;
                        }
                        if (!packetWeights.Contains(vert2Weight))
                        {
                            packetWeights.Add(vert2Weight);
                            numMatrices++;
                        }
                        if (!packetWeights.Contains(vert3Weight))
                        {
                            packetWeights.Add(vert3Weight);
                            numMatrices++;
                        }

                        // There are too many matrices, we need to create a new packet
                        if (numMatrices > MaxMatricesPerPacket)
                        {
                            //Console.WriteLine(String.Format("Making new packet because previous one would have {0}", numMatrices));
                            //Console.WriteLine(oldcount);
                            pack.Primitives.Add(prim);
                            Packets.Add(pack);

                            prim = new Primitive(Enums.GXPrimitiveType.Triangles);
                            pack = new Packet();

                            packetWeights.Clear();
                            numMatrices = 0;

                            if (!packetWeights.Contains(vert1Weight))
                            {
                                packetWeights.Add(vert1Weight);
                                numMatrices++;
                            }
                            if (!packetWeights.Contains(vert2Weight))
                            {
                                packetWeights.Add(vert2Weight);
                                numMatrices++;
                            }
                            if (!packetWeights.Contains(vert3Weight))
                            {
                                packetWeights.Add(vert3Weight);
                                numMatrices++;
                            }
                        }

                        int[]    vertexIndexArray = new int[] { vert1Index, vert2Index, vert3Index };
                        Weight[] vertWeightArray  = new Weight[] { vert1Weight, vert2Weight, vert3Weight };

                        for (int i = 0; i < 3; i++)
                        {
                            Vertex vert      = new Vertex();
                            int    vertIndex = vertexIndexArray[i];
                            Weight curWeight = vertWeightArray[i];

                            vert.SetWeight(curWeight);

                            foreach (Enums.GXVertexAttribute attrib in activeAttribs)
                            {
                                switch (attrib)
                                {
                                case Enums.GXVertexAttribute.PositionMatrixIdx:
                                    int newMatrixIndex = -1;

                                    if (curWeight.WeightCount == 1)
                                    {
                                        newMatrixIndex = partialWeight.MeshWeights.IndexOf(curWeight);
                                    }
                                    else
                                    {
                                        if (!envelopes.Weights.Contains(curWeight))
                                        {
                                            envelopes.Weights.Add(curWeight);
                                        }

                                        int envIndex = envelopes.Weights.IndexOf(curWeight);
                                        int drwIndex = partialWeight.MeshWeights.IndexOf(curWeight);

                                        if (drwIndex == -1)
                                        {
                                            throw new System.Exception($"Model has unweighted vertices in mesh \"{mesh.Name}\". Please weight all vertices to at least one bone.");
                                        }

                                        newMatrixIndex = drwIndex;
                                        partialWeight.Indices[drwIndex] = envIndex;
                                    }

                                    if (!pack.MatrixIndices.Contains(newMatrixIndex))
                                    {
                                        pack.MatrixIndices.Add(newMatrixIndex);
                                    }

                                    vert.SetAttributeIndex(Enums.GXVertexAttribute.PositionMatrixIdx, (uint)pack.MatrixIndices.IndexOf(newMatrixIndex));
                                    break;

                                case Enums.GXVertexAttribute.Position:
                                    List <Vector3> posData = (List <Vector3>)vertData.GetAttributeData(Enums.GXVertexAttribute.Position);
                                    Vector3        vertPos = mesh.Vertices[vertIndex].ToOpenTKVector3();

                                    if (curWeight.WeightCount == 1)
                                    {
                                        Matrix4 ibm = envelopes.InverseBindMatrices[curWeight.BoneIndices[0]];

                                        Vector3 transVec = Vector3.TransformPosition(vertPos, ibm);
                                        if (!posData.Contains(transVec))
                                        {
                                            posData.Add(transVec);
                                        }
                                        AttributeData.Positions.Add(transVec);
                                        vert.SetAttributeIndex(Enums.GXVertexAttribute.Position, (uint)posData.IndexOf(transVec));
                                    }
                                    else
                                    {
                                        if (!posData.Contains(vertPos))
                                        {
                                            posData.Add(vertPos);
                                        }
                                        AttributeData.Positions.Add(vertPos);

                                        vert.SetAttributeIndex(Enums.GXVertexAttribute.Position, (uint)posData.IndexOf(vertPos));
                                    }
                                    break;

                                case Enums.GXVertexAttribute.Normal:
                                    List <Vector3> normData = (List <Vector3>)vertData.GetAttributeData(Enums.GXVertexAttribute.Normal);
                                    Vector3        vertNrm  = mesh.Normals[vertIndex].ToOpenTKVector3();

                                    if (curWeight.WeightCount == 1)
                                    {
                                        Matrix4 ibm = envelopes.InverseBindMatrices[curWeight.BoneIndices[0]];
                                        vertNrm = Vector3.TransformNormal(vertNrm, ibm);
                                        if (!normData.Contains(vertNrm))
                                        {
                                            normData.Add(vertNrm);
                                        }
                                    }
                                    else
                                    {
                                        if (!normData.Contains(vertNrm))
                                        {
                                            normData.Add(vertNrm);
                                        }
                                    }

                                    AttributeData.Normals.Add(vertNrm);
                                    vert.SetAttributeIndex(Enums.GXVertexAttribute.Normal, (uint)normData.IndexOf(vertNrm));
                                    break;

                                case Enums.GXVertexAttribute.Color0:
                                case Enums.GXVertexAttribute.Color1:
                                    int          colNo   = (int)attrib - 11;
                                    List <Color> colData = (List <Color>)vertData.GetAttributeData(Enums.GXVertexAttribute.Color0 + colNo);
                                    Color        vertCol = mesh.VertexColorChannels[colNo][vertIndex].ToSuperBMDColorRGBA();

                                    if (colNo == 0)
                                    {
                                        AttributeData.Color_0.Add(vertCol);
                                    }
                                    else
                                    {
                                        AttributeData.Color_1.Add(vertCol);
                                    }

                                    vert.SetAttributeIndex(Enums.GXVertexAttribute.Color0 + colNo, (uint)colData.IndexOf(vertCol));
                                    break;

                                case Enums.GXVertexAttribute.Tex0:
                                case Enums.GXVertexAttribute.Tex1:
                                case Enums.GXVertexAttribute.Tex2:
                                case Enums.GXVertexAttribute.Tex3:
                                case Enums.GXVertexAttribute.Tex4:
                                case Enums.GXVertexAttribute.Tex5:
                                case Enums.GXVertexAttribute.Tex6:
                                case Enums.GXVertexAttribute.Tex7:
                                    int            texNo        = (int)attrib - 13;
                                    List <Vector2> texCoordData = (List <Vector2>)vertData.GetAttributeData(Enums.GXVertexAttribute.Tex0 + texNo);
                                    Vector2        vertTexCoord = mesh.TextureCoordinateChannels[texNo][vertIndex].ToOpenTKVector2();
                                    vertTexCoord = new Vector2(vertTexCoord.X, 1.0f - vertTexCoord.Y);

                                    switch (texNo)
                                    {
                                    case 0:
                                        AttributeData.TexCoord_0.Add(vertTexCoord);
                                        break;

                                    case 1:
                                        AttributeData.TexCoord_1.Add(vertTexCoord);
                                        break;

                                    case 2:
                                        AttributeData.TexCoord_2.Add(vertTexCoord);
                                        break;

                                    case 3:
                                        AttributeData.TexCoord_3.Add(vertTexCoord);
                                        break;

                                    case 4:
                                        AttributeData.TexCoord_4.Add(vertTexCoord);
                                        break;

                                    case 5:
                                        AttributeData.TexCoord_5.Add(vertTexCoord);
                                        break;

                                    case 6:
                                        AttributeData.TexCoord_6.Add(vertTexCoord);
                                        break;

                                    case 7:
                                        AttributeData.TexCoord_7.Add(vertTexCoord);
                                        break;
                                    }

                                    vert.SetAttributeIndex(Enums.GXVertexAttribute.Tex0 + texNo, (uint)texCoordData.IndexOf(vertTexCoord));
                                    break;
                                }
                            }

                            prim.Vertices.Add(vert);
                        }
                    }
                }

                /*
                 * if (prim.PrimitiveType == Enums.GXPrimitiveType.TriangleStrip) {
                 *  Debug.Assert(prim.Vertices.Count >= 3);
                 * }
                 * else if (prim.PrimitiveType == Enums.GXPrimitiveType.Triangles) {
                 *  Debug.Assert(prim.Vertices.Count % 3 == 0);
                 * }*/
                //Console.WriteLine(String.Format("We had this many matrices: {0}", numMatrices));
                pack.Primitives.Add(prim);
            }
            Packets.Add(pack);

            int mostmatrices = 0;

            if (true)
            {
                List <Weight> packWeights = new List <Weight>();
                foreach (Packet packet in Packets)
                {
                    int matrices = 0;

                    foreach (Primitive prim in packet.Primitives)
                    {
                        foreach (Vertex vert in prim.Vertices)
                        {
                            if (!packWeights.Contains(vert.VertexWeight))
                            {
                                packWeights.Add(vert.VertexWeight);
                                matrices++;
                            }
                        }


                        if (prim.PrimitiveType == Enums.GXPrimitiveType.TriangleStrip)
                        {
                            Debug.Assert(prim.Vertices.Count >= 3);
                        }
                        else if (prim.PrimitiveType == Enums.GXPrimitiveType.Triangles)
                        {
                            Debug.Assert(prim.Vertices.Count % 3 == 0);
                        }
                    }
                    if (matrices > mostmatrices)
                    {
                        mostmatrices = matrices;
                    }
                    //Debug.Assert(matrices <= MaxMatricesPerPacket);
                    //Console.WriteLine(matrices);
                    packWeights.Clear();
                }
            }
            //Console.WriteLine(String.Format("Most matrices: {0}", mostmatrices));
        }
Beispiel #41
0
 public PayloadTermSpanScorer(PayloadTermWeight enclosingInstance, TermSpans spans, Weight weight, Similarity similarity, byte[] norms) : base(spans, weight, similarity, norms)
 {
     InitBlock(enclosingInstance);
     positions = spans.Positions;
 }
 public virtual Weight Add(Weight unit)
 {
     return(unit);
 }
Beispiel #43
0
        public EVP1(EndianBinaryReader reader, int offset)
        {
            Weights             = new List <Weight>();
            InverseBindMatrices = new List <Matrix3x4>();

            reader.BaseStream.Seek(offset, System.IO.SeekOrigin.Begin);
            reader.SkipInt32();
            int evp1Size   = reader.ReadInt32();
            int entryCount = reader.ReadInt16();

            reader.SkipInt16();

            int weightCountsOffset        = reader.ReadInt32();
            int boneIndicesOffset         = reader.ReadInt32();
            int weightDataOffset          = reader.ReadInt32();
            int inverseBindMatricesOffset = reader.ReadInt32();

            List <int>   counts  = new List <int>();
            List <float> weights = new List <float>();
            List <int>   indices = new List <int>();

            for (int i = 0; i < entryCount; i++)
            {
                counts.Add(reader.ReadByte());
            }

            reader.BaseStream.Seek(boneIndicesOffset + offset, System.IO.SeekOrigin.Begin);

            for (int i = 0; i < entryCount; i++)
            {
                for (int j = 0; j < counts[i]; j++)
                {
                    indices.Add(reader.ReadInt16());
                }
            }

            reader.BaseStream.Seek(weightDataOffset + offset, System.IO.SeekOrigin.Begin);

            for (int i = 0; i < entryCount; i++)
            {
                for (int j = 0; j < counts[i]; j++)
                {
                    weights.Add(reader.ReadSingle());
                }
            }

            int totalRead = 0;

            for (int i = 0; i < entryCount; i++)
            {
                Weight weight = new Weight();

                for (int j = 0; j < counts[i]; j++)
                {
                    weight.AddWeight(weights[totalRead + j], indices[totalRead + j]);
                }

                Weights.Add(weight);
                totalRead += counts[i];
            }

            reader.BaseStream.Seek(inverseBindMatricesOffset + offset, System.IO.SeekOrigin.Begin);
            int matrixCount = (evp1Size - inverseBindMatricesOffset) / 48;

            for (int i = 0; i < matrixCount; i++)
            {
                Matrix3x4 invBind = new Matrix3x4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(),
                                                  reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(),
                                                  reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());

                InverseBindMatrices.Add(invBind);
            }

            reader.BaseStream.Seek(offset + evp1Size, System.IO.SeekOrigin.Begin);
        }
Beispiel #44
0
 public void TestEmptyConstructor()
 {
     var newWeight = new Weight();
     Assert.AreEqual(0, newWeight.Value, "Empty constructor of Weight class does not work properly !");
 }
Beispiel #45
0
        public double Addition(double element1, Weight firstElementUnit, double element2, Weight secondElementUnit)
        {
            double a = ConvertMethod(element1, firstElementUnit, Weight.kg);
            double b = ConvertMethod(element2, secondElementUnit, Weight.kg);

            return(a + b);
        }
Beispiel #46
0
 public Carnivore(Weight weight)
 {
     Weight = weight;
     Diet   = Diet.Carnivore;
 }
Beispiel #47
0
        public void MigrationWrite(string localFilename, FileData newFile, Weight weight)
        {
            if (fail) throw new ProcessFailedException(id);
            if (freeze)
            {
                freezed.Enqueue(() => MigrationWrite(localFilename, newFile, weight));
                throw new ProcessFreezedException(id);
            }

            Console.WriteLine("MIGRATION WRITE " + localFilename);

            files[localFilename] = newFile;
            weights[localFilename] = weight;
        }
Beispiel #48
0
        /// <inheritdoc/>
        protected override void OnApply(ImageBase <TColor> source, Rectangle sourceRectangle)
        {
            // Jump out, we'll deal with that later.
            if (source.Width == this.Width && source.Height == this.Height && sourceRectangle == this.ResizeRectangle)
            {
                return;
            }

            int width   = this.Width;
            int height  = this.Height;
            int sourceX = sourceRectangle.X;
            int sourceY = sourceRectangle.Y;
            int startY  = this.ResizeRectangle.Y;
            int endY    = this.ResizeRectangle.Bottom;
            int startX  = this.ResizeRectangle.X;
            int endX    = this.ResizeRectangle.Right;

            int minX = Math.Max(0, startX);
            int maxX = Math.Min(width, endX);
            int minY = Math.Max(0, startY);
            int maxY = Math.Min(height, endY);

            if (this.Sampler is NearestNeighborResampler)
            {
                // Scaling factors
                float widthFactor  = sourceRectangle.Width / (float)this.ResizeRectangle.Width;
                float heightFactor = sourceRectangle.Height / (float)this.ResizeRectangle.Height;

                using (PixelAccessor <TColor> targetPixels = new PixelAccessor <TColor>(width, height))
                {
                    using (PixelAccessor <TColor> sourcePixels = source.Lock())
                    {
                        Parallel.For(
                            minY,
                            maxY,
                            this.ParallelOptions,
                            y =>
                        {
                            // Y coordinates of source points
                            int originY = (int)(((y - startY) * heightFactor) + sourceY);

                            for (int x = minX; x < maxX; x++)
                            {
                                // X coordinates of source points
                                targetPixels[x, y] = sourcePixels[(int)(((x - startX) * widthFactor) + sourceX), originY];
                            }
                        });
                    }

                    // Break out now.
                    source.SwapPixelsBuffers(targetPixels);
                    return;
                }
            }

            // Interpolate the image using the calculated weights.
            // A 2-pass 1D algorithm appears to be faster than splitting a 1-pass 2D algorithm
            // First process the columns. Since we are not using multiple threads startY and endY
            // are the upper and lower bounds of the source rectangle.
            using (PixelAccessor <TColor> targetPixels = new PixelAccessor <TColor>(width, height))
            {
                using (PixelAccessor <TColor> sourcePixels = source.Lock())
                    using (PixelAccessor <TColor> firstPassPixels = new PixelAccessor <TColor>(width, source.Height))
                    {
                        Parallel.For(
                            0,
                            sourceRectangle.Bottom,
                            this.ParallelOptions,
                            y =>
                        {
                            for (int x = minX; x < maxX; x++)
                            {
                                // Ensure offsets are normalised for cropping and padding.
                                Weight[] horizontalValues = this.HorizontalWeights[x - startX].Values;

                                // Destination color components
                                Vector4 destination = Vector4.Zero;

                                for (int i = 0; i < horizontalValues.Length; i++)
                                {
                                    Weight xw    = horizontalValues[i];
                                    destination += sourcePixels[xw.Index + sourceX, y].ToVector4() * xw.Value;
                                }

                                TColor d = default(TColor);
                                d.PackFromVector4(destination);
                                firstPassPixels[x, y] = d;
                            }
                        });

                        // Now process the rows.
                        Parallel.For(
                            minY,
                            maxY,
                            this.ParallelOptions,
                            y =>
                        {
                            // Ensure offsets are normalised for cropping and padding.
                            Weight[] verticalValues = this.VerticalWeights[y - startY].Values;

                            for (int x = 0; x < width; x++)
                            {
                                // Destination color components
                                Vector4 destination = Vector4.Zero;

                                for (int i = 0; i < verticalValues.Length; i++)
                                {
                                    Weight yw    = verticalValues[i];
                                    destination += firstPassPixels[x, yw.Index + sourceY].ToVector4() * yw.Value;
                                }

                                TColor d = default(TColor);
                                d.PackFromVector4(destination);
                                targetPixels[x, y] = d;
                            }
                        });
                    }

                source.SwapPixelsBuffers(targetPixels);
            }
        }
Beispiel #49
0
        /**
         * IDataServerToClient Methods
         */
        public FileVersion Version(string localFilename)
        {
            if (fail) throw new ProcessFailedException(id);
            if (freeze)
            {
                freezed.Enqueue(() => Version(localFilename));
                throw new ProcessFreezedException(id);
            }

            Console.WriteLine("VERSION " + localFilename);

            if (!files.ContainsKey(localFilename))
            {
                Console.WriteLine("CREATE FILE " + localFilename);
                files[localFilename] = new FileData();
                weights[localFilename] = new Weight();
            }

            return files[localFilename].Version;
        }
Beispiel #50
0
        public double LearnByBackPropagation(int Epoch, double Lambda)
        {
            GenerateWeight();
            double GlobalError = 0;

            do
            {
                for (int x = 0; x < Input.Count; x++)
                {
                    NeuronLayers[0] = Input[x];

                    GetError();
                    double[] Etotal     = PowError(Output[x]);
                    int      weighIndex = Weight.Count() - 1;
                    int      Last       = NeuronLayers.Count() - 1;

                    double[] increment = new double[weighIndex + 1];

                    #region First Layer
                    for (int i = NeuronLayers[Last].Count() - 1; i > -1; i--)
                    {
                        double curentWeight = 1;
                        double err          = NeuronLayers.Last()[i] - Output[x][i];
                        double log          = NeuronLayers.Last()[i] * (1 - NeuronLayers.Last()[i]);
                        double total        = err * log * curentWeight;
                        increment[weighIndex--] = total;

                        for (int j = NeuronLayers[Last - 1].Count() - 1; j > -1; j--)
                        {
                            double curentWeight1 = NeuronLayers[NeuronLayers.Count() - 2][i];
                            double err1          = NeuronLayers.Last()[i] - Output[x][i];
                            double log1          = NeuronLayers.Last()[i] * (1 - NeuronLayers.Last()[i]);
                            double total1        = err1 * log1 * curentWeight1;
                            increment[weighIndex--] = total1;
                        }
                    }
                    #endregion

                    #region ErrorOutput

                    int           backIndex = weighIndex - 1;
                    List <double> sumsError = new List <double>();
                    for (int w = 0; w < NeuronLayers[NeuronLayers.Count() - 2].Count(); w++)
                    {
                        List <double> er = new List <double>();
                        for (int i = 0; i < Output[x].Count(); i++)
                        {
                            double err = NeuronLayers.Last()[i] - Output[x][i];
                            double log = NeuronLayers.Last()[i] * (1 - NeuronLayers.Last()[i]);
                            double ww  = (Weight[backIndex]);
                            double y   = err * log * ww;
                            er.Add(y);
                            backIndex += Output[x].Count() + 1;
                        }
                        sumsError.Add(er.Sum());
                        backIndex = weighIndex;
                    }

                    #endregion

                    #region Other Layers
                    for (int yy = NeuronLayers.Count() - 2; yy > 0; yy--)
                    {
                        for (int i = NeuronLayers[yy].Count() - 1; i > -1; i--)
                        {
                            double curentWeight = 1;
                            double err          = sumsError[i];
                            double log          = NeuronLayers[yy][i] * (1 - NeuronLayers[yy][i]);
                            double total        = err * log * curentWeight;
                            increment[weighIndex--] = total;

                            for (int j = NeuronLayers[yy - 1].Count() - 1; j > -1; j--)
                            {
                                double curentWeight1 = NeuronLayers[yy - 1][j];
                                double err1          = sumsError[i];
                                double log1          = NeuronLayers[yy][i] * (1 - NeuronLayers[yy][i]);
                                double total1        = err1 * log1 * curentWeight1;
                                increment[weighIndex--] = total1;
                            }
                        }

                        #region Error Hidden Layers
                        backIndex = weighIndex;
                        List <double> NewSumError = new List <double>();
                        for (int w = 0; w < NeuronLayers[yy - 1].Count(); w++)
                        {
                            List <double> er = new List <double>();
                            for (int k = 0; k < NeuronLayers[yy].Count() - 1; k++)
                            {
                                double y = (sumsError[k]) * (Weight[++backIndex]);
                                er.Add(y);
                            }
                            NewSumError.Add(er.Sum());
                        }
                        sumsError.Clear(); sumsError.AddRange(NewSumError);
                        #endregion
                    }
                    #endregion


                    for (int i = 0; i < Weight.Count(); i++)
                    {
                        Weight[i] -= increment[i] * Lambda;
                    }
                }
                //GlobalError = 0;
                //for (int x = 0; x < Input.Count; x++)
                //{
                //    NeuronLayers[0] = Input[x];
                //    GetError();
                //    GlobalError += AbsError(Output[x]);
                //}
                //Console.WriteLine("Epoch :{0}  Global_Error:{1}", Epoch, GlobalError);
            } while (Epoch-- > 0);

            for (int x = 0; x < Input.Count; x++)
            {
                NeuronLayers[0] = Input[x];
                GetError();
                GlobalError += AbsError(Output[x]);
            }
            Console.WriteLine(" Global_Error:{0}", GlobalError);
            return(GlobalError);
        }
Beispiel #51
0
 private Weight MyWeight()
 {
     Weight weight = new Weight();
     if (weights.Count != 0)
     {
         // SOM Fi(reads/writes) / nFiles
         foreach (var entry in weights)
         {
             Weight fileWeight = entry.Value;
             weight.Reads += fileWeight.Reads;
             weight.Writes += fileWeight.Writes;
         }
     }
     return weight;
 }
 public override Weight Add(Weight unit)
 {
     // ...
 }
Beispiel #53
0
        public void TestToStringMethod()
        {
            var firstWeight = new Weight(77);
            var firstWeightString = "77.00 g.";

            var secondWeight = new Weight(36);
            var secondWeightString = "36.00 g.";

            var thirdWeight = new Weight(9999);
            var thirdWeightString = "9999.00 g.";

            Assert.AreEqual(firstWeightString, firstWeight.ToString(), "ToString method of Weight class does not work properly !");
            Assert.AreEqual(secondWeightString, secondWeight.ToString(), "ToString method of Weight class does not work properly !");
            Assert.AreEqual(thirdWeightString, thirdWeight.ToString(), "ToString method of Weight class does not work properly !");
        }
Beispiel #54
0
        public Knowledge(Weight ionic, Weight reactJS, Weight reactNative, Weight android, Weight flutter, Weight sWIFT, Weight iOS, Weight hTML, Weight cSS, Weight bootstrap, Weight jquery, Weight angularJs, Weight angular, Weight java, Weight python, Weight flask, Weight aspNetMVC, Weight aspNetWebForm, Weight c, Weight csharp, Weight nodeJS, Weight expressNodeJs, Weight cake, Weight django, Weight majento, Weight pHP, Weight vue, Weight wordpress, Weight ruby, Weight mySQLServer, Weight mySQL, Weight salesforce, Weight photoshop, Weight illustrator, Weight sEO, Weight laravel)
        {
            Ionic         = ionic;
            ReactJS       = reactJS;
            ReactNative   = reactNative;
            Android       = android;
            Flutter       = flutter;
            SWIFT         = sWIFT;
            IOS           = iOS;
            HTML          = hTML;
            CSS           = cSS;
            Bootstrap     = bootstrap;
            Jquery        = jquery;
            AngularJs     = angularJs;
            Angular       = angular;
            Java          = java;
            Python        = python;
            Flask         = flask;
            AspNetMVC     = aspNetMVC;
            AspNetWebForm = aspNetWebForm;
            C             = c;
            Csharp        = csharp;
            NodeJS        = nodeJS;
            ExpressNodeJs = expressNodeJs;
            Cake          = cake;
            Django        = django;
            Majento       = majento;
            PHP           = pHP;
            Vue           = vue;
            Wordpress     = wordpress;
            Ruby          = ruby;
            MySQLServer   = mySQLServer;
            MySQL         = mySQL;
            Salesforce    = salesforce;
            Photoshop     = photoshop;
            Illustrator   = illustrator;
            SEO           = sEO;
            Laravel       = laravel;

            Validate();
        }
Beispiel #55
0
 public void TestConstructorWithParams()
 {
     var newWeight = new Weight(7);
     Assert.AreEqual(7, newWeight.Value, "Constructor with param(grams) of Weight class does not work properly !");
 }
 public PayloadTermSpanScorer(PayloadTermQuery.PayloadTermWeight outerInstance, TermSpans spans, Weight weight, Similarity.SimScorer docScorer)
     : base(spans, weight, docScorer)
 {
     this.outerInstance = outerInstance;
     termSpans          = spans;
 }
 public IActionResult CalculateRates(Request model)
 {
     HttpContext.Session.Clear();
     if (ModelState.IsValid)
     {
         //create dimensions object
         Dimensions.UnitEnum dimensionsUnit = new Dimensions.UnitEnum();
         foreach (KeyValuePair <string, Dimensions.UnitEnum> item in DimensionUnitsConfig.DimensionsUnitsList)
         {
             if (item.Key == model.shipment.package.dimensions.unit)
             {
                 dimensionsUnit = item.Value;
             }
         }
         Dimensions dimensions = new Dimensions
         {
             Length = model.shipment.package.dimensions.length,
             Width  = model.shipment.package.dimensions.width,
             Height = model.shipment.package.dimensions.height,
             Unit   = dimensionsUnit
         };
         //create weight object
         Weight.UnitEnum weightUnit = new Weight.UnitEnum();
         foreach (KeyValuePair <string, Weight.UnitEnum> item in WeightUnitsConfig.WeightUnitsList)
         {
             if (item.Key == model.shipment.package.weight.unit)
             {
                 weightUnit = item.Value;
             }
         }
         Weight weight = new Weight
         {
             Value = model.shipment.package.weight.value,
             Unit  = weightUnit
         };
         //create package list
         List <ShipmentPackage> packageList = new List <ShipmentPackage>();
         //create package and push to package list
         ShipmentPackage package = new ShipmentPackage
         {
             Weight     = weight,
             Dimensions = dimensions
         };
         packageList.Add(package);
         // create ship to address
         AddressDTO ship_to = new AddressDTO
         {
             Name          = model.shipment.ship_to.name,
             Phone         = model.shipment.ship_to.phone,
             PostalCode    = model.shipment.ship_to.postal_code,
             StateProvince = model.shipment.ship_to.state_province,
             CityLocality  = model.shipment.ship_to.city_locality,
             AddressLine1  = model.shipment.ship_to.address_line1,
             AddressLine2  = model.shipment.ship_to.address_line2,
             CompanyName   = model.shipment.ship_to.company_name,
             CountryCode   = model.shipment.ship_to.country_code
         };
         // create ship from address
         AddressDTO ship_from = new AddressDTO
         {
             Name          = model.shipment.ship_from.name,
             Phone         = model.shipment.ship_from.phone,
             PostalCode    = model.shipment.ship_from.postal_code,
             StateProvince = model.shipment.ship_from.state_province,
             CityLocality  = model.shipment.ship_from.city_locality,
             AddressLine1  = model.shipment.ship_from.address_line1,
             AddressLine2  = model.shipment.ship_from.address_line2,
             CompanyName   = model.shipment.ship_from.company_name,
             CountryCode   = model.shipment.ship_from.country_code
         };
         // create shipment
         AddressValidatingShipment shipment = new AddressValidatingShipment
         {
             Packages = packageList,
             ShipFrom = ship_from,
             ShipTo   = ship_to
         };
         // create rateoptions
         var           apiKey     = "2zWOj6zfmwc98DLwos4B9U5Jg9wOxkAjlX20vgEYtDs";
         var           carrierApi = new CarriersApi();
         List <string> carrierIds = new List <string>();
         try
         {
             List <Carrier> carrierList = carrierApi.CarriersList(apiKey).Carriers;
             foreach (Carrier carrier in carrierList)
             {
                 carrierIds.Add(carrier.CarrierId);
             }
         }
         catch (Exception e)
         {
             Debug.Print("Exception when calling CarriersApi.CarriersList: " + e.Message);
         }
         RateRequest rateOptions = new RateRequest
         {
             CarrierIds = carrierIds
         };
         // create request
         RateShipmentRequest request = new RateShipmentRequest
         {
             Shipment    = shipment,
             RateOptions = rateOptions
         };
         //send rate results to action through tempdata
         var rateApi = new RatesApi();
         try
         {
             RateShipmentResponse result = rateApi.RatesRateShipment(request, apiKey);
             RateResponse         rates  = result.RateResponse;
             HttpContext.Session.SetString("rates", JsonConvert.SerializeObject(rates));
             return(RedirectToAction("RateResults"));
         }
         catch (Exception e)
         {
             Debug.Print("Exception when calling RatesApi.RatesRateShipment: " + e.Message);
         }
     }
     return(RedirectToAction("Rates"));
 }
        internal override bool ParseNodeBodyElement(string id, VRMLParser parser)
        {
            int line = parser.Line;

            if (id == "controlPoint")
            {
                X3DNode node = parser.ParseSFNodeValue();
                if (node != null)
                {
                    ControlPoint = node as X3DCoordinateNode;
                    if (ControlPoint == null)
                    {
                        parser.ErrorParsingNode(VRMLReaderError.UnexpectedNodeType, this, id, node, line);
                    }
                }
            }
            else if (id == "texCoord")
            {
                X3DNode node = parser.ParseSFNodeValue();
                if (node != null)
                {
                    TexCoord = node as IX3DNurbsSurfaceGeometryNodeTexCoord;
                    if (TexCoord == null)
                    {
                        parser.ErrorParsingNode(VRMLReaderError.UnexpectedNodeType, this, id, node, line);
                    }
                }
            }
            else if (id == "trimmingContour")
            {
                List <X3DNode> nodes = parser.ParseSFNodeOrMFNodeValue();
                foreach (X3DNode node in nodes)
                {
                    IX3DContour2DNode contour = node as IX3DContour2DNode;
                    if (contour == null)
                    {
                        parser.ErrorParsingNode(VRMLReaderError.UnexpectedNodeType, this, id, node, line);
                    }
                    else
                    {
                        TrimmingContour.Add(contour);
                    }
                }
            }
            else if (id == "uTessellation")
            {
                UTessellation = parser.ParseIntValue();
            }
            else if (id == "vTessellation")
            {
                VTessellation = parser.ParseIntValue();
            }
            else if (id == "weight")
            {
                Weight.AddRange(parser.ParseSFFloatOrMFFloatValue());
            }
            else if (id == "solid")
            {
                Solid = parser.ParseBoolValue();
            }
            else if (id == "uClosed")
            {
                UClosed = parser.ParseBoolValue();
            }
            else if (id == "uDimension")
            {
                UDimension = parser.ParseIntValue();
            }
            else if (id == "uKnot")
            {
                UKnot.AddRange(parser.ParseSFFloatOrMFFloatValue());
            }
            else if (id == "uOrder")
            {
                UOrder = parser.ParseIntValue();
            }
            else if (id == "vClosed")
            {
                VClosed = parser.ParseBoolValue();
            }
            else if (id == "vDimension")
            {
                VDimension = parser.ParseIntValue();
            }
            else if (id == "vKnot")
            {
                VKnot.AddRange(parser.ParseSFFloatOrMFFloatValue());
            }
            else if (id == "vOrder")
            {
                VOrder = parser.ParseIntValue();
            }
            else
            {
                return(false);
            }
            return(true);
        }
Beispiel #59
0
        public void TestInequalityOperator()
        {
            var firstWeight = new Weight(7);
            var secondWeight = new Weight(5);
            var thirdWeight = new Weight(7);

            Assert.IsTrue(firstWeight != secondWeight, "Operator for inequality of Weight class does not work properly !");
            Assert.IsFalse(firstWeight != thirdWeight, "Operator for inequality of Weight class does not work properly !");
        }
 // Precondition: None
 // Postcondition: Returns all of the data about the package, each on a seperated line
 public override string ToString()
 {
     return("Origin Zip: " + OriginZip.ToString("D5") + System.Environment.NewLine + "Destination Zip: " + DestinationZip.ToString("D5") + System.Environment.NewLine + "Length: " + Length.ToString() + System.Environment.NewLine + "Width: " + Width.ToString() + System.Environment.NewLine + "Height: " + Height.ToString() + System.Environment.NewLine + "Weight: " + Weight.ToString());
 }