public void TwoNumberTest() { var exp = new Max(new[] { new Number(2), new Number(4) }, 2); var result = exp.Execute(); Assert.Equal(4.0, result); }
public void ThreeNumberTest() { var exp = new Max(new[] { new Number(9), new Number(2), new Number(4) }, 3); var result = exp.Execute(); Assert.Equal(9.0, result); }
public KPD(VS parent, string name) : base(parent, name) { #region Инициализация переменных объектов модели KOZ = InitModelObject<TIntVar>(); KPZ = InitModelObject<TIntVar>(); Zanyatost = InitModelObject<TRefVar<VS.Zayavka>>(); Q_Vhod = InitModelObject<SimpleModelList<QRec>>(); Q_Vozvrat = InitModelObject<SimpleModelList<QRec>>(); #endregion #region Инициализация сборщиков статистики Variance_Q_Vhod = InitModelObject<Variance<int>>(); Variance_Q_Vhod.ConnectOnSet(Q_Vhod.Count); Min_Q_Vhod = InitModelObject<Min<int>>(); Min_Q_Vhod.ConnectOnSet(Q_Vhod.Count); Max_Q_Vhod = InitModelObject<Max<int>>(); Max_Q_Vhod.ConnectOnSet(Q_Vhod.Count); Variance_Q_Vozvrat = InitModelObject<Variance<int>>(); Variance_Q_Vozvrat.ConnectOnSet(Q_Vozvrat.Count); Min_Q_Vozvrat = InitModelObject<Min<int>>(); Min_Q_Vozvrat.ConnectOnSet(Q_Vozvrat.Count); Max_Q_Vozvrat = InitModelObject<Max<int>>(); Max_Q_Vozvrat.ConnectOnSet(Q_Vozvrat.Count); Zanyato = InitModelObject<BoolCollector>(); Zanyato.ConnectOnSet(Zanyatost); #endregion }
TIntVar KVZ; //Количество вошедших заявок #endregion Fields #region Constructors public UstroystvoVvoda(VU parent, string name) : base(parent, name) { #region Инициализация переменных объектов модели KOZ = InitModelObject<TIntVar>(); KVZ = InitModelObject<TIntVar>(); Zanyatost = InitModelObject<TRefVar<VS.Zayavka>>(); Que = InitModelObject<SimpleModelList<QRec>>(); parentVU = parent; #endregion #region Инициализация сборщиков статистики Variance_QueCount = InitModelObject<Variance<int>>(); Variance_QueCount.ConnectOnSet(Que.Count); Min_QueCount = InitModelObject<Min<int>>(); Min_QueCount.ConnectOnSet(Que.Count); Max_QueCount = InitModelObject<Max<int>>(); Max_QueCount.ConnectOnSet(Que.Count); Zanyto = InitModelObject<BoolCollector>(); Zanyto.ConnectOnSet(Zanyatost); #endregion }
public void OneNumberTest() { var exp = new Max(new[] { new Number(2) }, 1); var result = exp.Execute(); Assert.Equal(2.0, result); }
public NumericValue(T value, T min, T max) { _value = value.CompareTo(max) > 0 ? max : value.CompareTo(min) < 0 ? min : value; Max = max; Min = min; if (Max.CompareTo(Min) < 0) { throw new ArgumentException(); } }
public void Enqueue(UnacknowledgedData data) { if (Max.HasValue) { Set(data, Max.GetValueOrDefault() + 1); } else { Set(data, 0); } }
public virtual void CopyFrom(Rect other) { Min.CopyFrom(other.Min); Max.CopyFrom(other.Max); Ps.Clear(); Ps.AddRange(other.Ps); Ls.Clear(); Ls.AddRange(other.Ls); LLs.Clear(); LLs.AddRange(other.LLs); }
public override int GetHashCode() { unchecked { int result = Mean.GetHashCode(); result = (result * 397) ^ Min.GetHashCode(); result = (result * 397) ^ Max.GetHashCode(); result = (result * 397) ^ Count.GetHashCode(); return(result); } }
public bool Inside(Vec3 circle_center, float radius) { return(Min.Distance(circle_center) < radius && Max.Distance(circle_center) < radius && new Vec3(Min.X, Max.Y, Max.Z).Distance(circle_center) < radius && new Vec3(Min.X, Max.Y, Min.Z).Distance(circle_center) < radius && new Vec3(Max.X, Min.Y, Max.Z).Distance(circle_center) < radius && new Vec3(Max.X, Min.Y, Min.Z).Distance(circle_center) < radius && new Vec3(Min.X, Min.Y, Max.Z).Distance(circle_center) < radius && new Vec3(Max.X, Max.Y, Min.Z).Distance(circle_center) < radius); }
public void WriteXmlSubtree(XmlWriter writer) { writer.WriteStartElement(XmlStrings.DatesGen); writer.WriteAttributeString("name", Name); writer.WriteStartElement(XmlStrings.ParamsNode); writer.WriteAttributeString("min", Min.ToBinary().ToString()); writer.WriteAttributeString("max", Max.ToBinary().ToString()); writer.WriteAttributeString("format", Format); writer.WriteEndElement(); writer.WriteEndElement(); }
public YAMLNode ExportYAML(IExportContainer container) { YAMLMappingNode node = new YAMLMappingNode(); node.Add(MinName, Min.ExportYAML(container)); node.Add(MaxName, Max.ExportYAML(container)); node.Add(ValueName, Value.ExportYAML(container)); node.Add(LengthName, Length); node.Add(ModifiedName, Modified); return(node); }
protected override void SaveNode( XmlDocument xmlDoc, XmlElement nodeElement, SaveContext context) { base.SaveNode(xmlDoc, nodeElement, context); XmlElement outEl = xmlDoc.CreateElement("Range"); outEl.SetAttribute("min", Min.ToString(CultureInfo.InvariantCulture)); outEl.SetAttribute("max", Max.ToString(CultureInfo.InvariantCulture)); nodeElement.AppendChild(outEl); }
/// <summary> Returns the range that represents the intersection of this range and <code>value</code>. </summary> /// <param name="value">The range to intersect with.</param> /// <returns> /// A range that contains the values that are common in both ranges, /// or null if there is no intersection. /// </returns> public Range <T> Intersect([NotNull] Range <T> value) { if (!Overlaps(value)) { return(null); } var start = Min.CompareTo(value.Min) > 0 ? Min : value.Min; return(Max.CompareTo(value.Max) < 0 ? new Range <T>(start, Max) : new Range <T>(start, value.Max)); }
/// <summary> /// クライアントでのバリデーションサポート /// </summary> /// <param name="context">バリデーションコンテキスト</param> public void AddValidation(ClientModelValidationContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } // データ型とMin,Max,Stepの型チェック var numericType = CheckRangeValues(context.ModelMetadata.ModelType); if (Min != null) { // 最小値が設定されている場合以下のタグ属性を設定する // minlength 最小桁数 // notsupported-min-length-err-msg 未サポートブラウザでのエラーメッセージ // min-length-err-msg バリデーションで設定されたエラーメッセージ MergeAttribute(context.Attributes, "min", Min.ToString()); MergeAttribute(context.Attributes, "numeric-type", numericType.ToString()); MergeAttribute(context.Attributes, "notsupported-min-err-msg", "最小値「" + Min.ToString() + "」より小さいです。"); if (!string.IsNullOrWhiteSpace(UnderMinErrorMessage)) { MergeAttribute(context.Attributes, "min-err-msg", UnderMinErrorMessage); } } if (Max != null) { // 最大値が設定されている場合以下のタグ属性を設定する // maxlength 最大桁数 // notsupported-max-length-err-msg 未サポートブラウザでのエラーメッセージ // max-length-err-msg バリデーションで設定されたエラーメッセージ MergeAttribute(context.Attributes, "max", Max.ToString()); MergeAttribute(context.Attributes, "numeric-type", numericType.ToString()); MergeAttribute(context.Attributes, "notsupported-max-err-msg", "値が最大値「" + Max.ToString() + "」を超えています。"); if (!string.IsNullOrWhiteSpace(OverMaxErrorMessage)) { MergeAttribute(context.Attributes, "max-err-msg", OverMaxErrorMessage); } } if (Step != null) { // 最大値が設定されている場合以下のタグ属性を設定する // maxlength 最大桁数 // notsupported-max-length-err-msg 未サポートブラウザでのエラーメッセージ // max-length-err-msg バリデーションで設定されたエラーメッセージ MergeAttribute(context.Attributes, "step", Step.ToString()); MergeAttribute(context.Attributes, "notsupported-step-err-msg", "値が刻み幅「" + Step.ToString() + "」に一致しません。"); if (!string.IsNullOrWhiteSpace(NoStepErrorMessage)) { MergeAttribute(context.Attributes, "step-err-msg", NoStepErrorMessage); } } }
/// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return(Min.GetHashCode() ^ Q1.GetHashCode() ^ Median.GetHashCode() ^ Mean.GetHashCode() ^ Q3.GetHashCode() ^ Max.GetHashCode() ^ StdDev.GetHashCode() ^ N.GetHashCode()); }
string GetMaxErrorMessage(string displayName) { if (string.IsNullOrWhiteSpace(OverMaxErrorMessage)) { return("[" + displayName + "]は最大値「" + Max.ToString() + "」より大きいです。"); } else { return(OverMaxErrorMessage); } }
public string Visit(Max node) { var stringBuilder = new StringBuilder(); var first = Visit((dynamic)node[0]); var second = Visit((dynamic)node[1]); stringBuilder.Append(first); stringBuilder.Append(second); stringBuilder.Append("\t\tcall float64 ['mscorlib']'System'.'Math'::Max(float64, float64)\n"); return(stringBuilder.ToString()); }
private void switchState(Actor.Actor actor, Max max) { double distance = calculateDistance(actor, max); Enemy enemy = (Enemy)actor; PatrolState patrol = (PatrolState)enemy.state.state; if (distance <= 200 && patrol.atitude != PatrolState.Atitude.pursue) { patrol.changeState(PatrolState.Atitude.pursue); } }
public override bool Equals(object obj) { var cmpr = obj as Box; if (cmpr == null) { return(false); } return(Min.Equals(cmpr.Min) && Max.Equals(cmpr.Max)); }
public override async Task Load(XElement node, bool requireName = true) { await base.Load(node, requireName); if (!HasRange) { return; } float minFloat, maxFloat; if (string.IsNullOrWhiteSpace(Min) && string.IsNullOrWhiteSpace(Max)) { throw new ArgumentException($"Value was not convertable to range: {Min}-{Max}"); } if (string.IsNullOrWhiteSpace(Min)) { minFloat = float.MinValue; Min = "float.MinValue"; } else if (!float.TryParse(Min, out minFloat)) { throw new ArgumentException($"Value was not convertable to float: {Min}"); } if (string.IsNullOrWhiteSpace(Max)) { maxFloat = float.MaxValue; Max = "float.MaxValue"; } else if (!float.TryParse(Max, out maxFloat)) { throw new ArgumentException($"Value was not convertable to float: {Max}"); } if (minFloat > maxFloat) { throw new ArgumentException($"Min {minFloat} was greater than max {maxFloat}"); } if (!minFloat.Equals(float.MinValue) && !Min.EndsWith("f")) { Min += "f"; } if (!maxFloat.Equals(float.MaxValue) && !Max.EndsWith("f")) { Max += "f"; } }
public Node Max() { Expect(Token.MAX); Expect(Token.COROPEN); var p = new Max() { ExprLst() }; Expect(Token.CORCLOSE); return(p); }
private bool CharValidation(string input) { int inputValue = Convert.ToInt32(input.ToCharArray()[0]); int min = Convert.ToInt32(Min.ToCharArray()[0]); int max = Convert.ToInt32(Max.ToCharArray()[0]); if (min <= inputValue && max >= inputValue) { return(true); } return(false); }
protected override void SerializeCore(XmlElement element, SaveContext context) { base.SerializeCore(element, context); // Base implementation must be called. var xmlDocument = element.OwnerDocument; var subNode = xmlDocument.CreateElement("Range"); subNode.SetAttribute("min", Min.ToString(CultureInfo.InvariantCulture)); subNode.SetAttribute("max", Max.ToString(CultureInfo.InvariantCulture)); subNode.SetAttribute("step", Step.ToString(CultureInfo.InvariantCulture)); element.AppendChild(subNode); }
private static NdArray ComputeTargets(NdArray src, NdArray targets) { var @base = src[R.All, R.NewAxis]; var target = src[R.All, R.All, R.NewAxis]; var tmp = (@base - target).Pow(2); tmp = Add.Reduce(tmp); Sqrt.Apply(tmp, tmp); return(Max.Reduce(tmp)); }
/// <summary> /// Generates xml element containing the settings. /// </summary> /// <param name="rootElemName">Name to be used as a name of the root element.</param> /// <param name="suppressDefaults">Specifies whether to ommit optional nodes having set default values</param> /// <returns>XElement containing the settings</returns> public override XElement GetXml(string rootElemName, bool suppressDefaults) { XElement rootElem = new XElement(rootElemName, new XAttribute("min", Min.ToString(CultureInfo.InvariantCulture)), new XAttribute("max", Max.ToString(CultureInfo.InvariantCulture))); if (!suppressDefaults || DistrType != RandomCommon.DistributionType.Uniform) { rootElem.Add(((RCNetBaseSettings)DistrCfg).GetXml(suppressDefaults)); } Validate(rootElem, XsdTypeName); return(rootElem); }
/// <inheritdoc/> public override int GetHashCode() { unchecked { var hashCode = FromSequenceNr.GetHashCode(); hashCode = (hashCode * 397) ^ ToSequenceNr.GetHashCode(); hashCode = (hashCode * 397) ^ Max.GetHashCode(); hashCode = (hashCode * 397) ^ (PersistenceId != null ? PersistenceId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (PersistentActor != null ? PersistentActor.GetHashCode() : 0); return(hashCode); } }
public void MaxShouldIgnoreHiddenValuesIfIgnoreHiddenValuesIsTrue() { var func = new Max(); func.IgnoreHiddenValues = true; var args = FunctionsHelper.CreateArgs(4, 2, 5, 2); args.ElementAt(2).SetExcelStateFlag(ExcelCellState.HiddenCell); var result = func.Execute(args, _parsingContext); Assert.AreEqual(4d, result.Result); }
public bool Includes(T value) { if (Min.CompareTo(value) > 0) { return(false); } if (Max.CompareTo(value) < 0) { return(false); } return(true); }
protected override void InitOption(TagHelperContext context, TagHelperOutput output) { Options.AddIf(DateType.HasValue, "type", DateType.ToString().ToLower()); Options.AddIf(Format.IsNotNullOrWhiteSpace(), "format", Format); Options.AddIf(IsRange, "range", true); Options.AddIf(Max.IsNotNullOrWhiteSpace(), "max", Max); Options.AddIf(Max.IsNotNullOrWhiteSpace(), "min", Min); Options.AddIf(Value.IsNotNullOrWhiteSpace(), "value", Value); base.InitOption(context, output); }
/// <summary> /// Creates a geometry (Polygon) that resembles this bounding box. /// </summary> /// <returns></returns> public Geometry ToGeometry() { var linearRing = new LinearRing(new[] { Min.Clone(), new Point(Min.X, Max.Y), Max.Clone(), new Point(Max.X, Min.Y), Min.Clone() }); return(new Polygon(linearRing, null)); }
public bool EqualsTol(double tol, BBox3D other) { if (IsEmpty) { return(other.IsEmpty); } if (other.IsEmpty) { return(false); } return(Min.EqualsTol(tol, other.Min) && Max.EqualsTol(tol, other.Max)); }
// Runs whenever the game needs to be reset public static void Reset() { Grid.Reset(); Max.Reset(); Min.Reset(); ActivePlayer = Max; if (OnTurnPlayEvent != null) { OnTurnPlayEvent(); } }
private void button3_Click(object sender, EventArgs e) { Max = Numbers[0]; for (int i = 1; i < N; i++) { if (Numbers[i] > Max) { Max = Numbers[i]; } } button3.Text = "Max = " + Max.ToString(); }
/// <summary> /// Determines if the property is valid /// </summary> /// <param name="value">Value to check</param> /// <param name="validationContext">Validation context</param> /// <returns>The validation result</returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var Comparer = new GenericComparer <IComparable>(); var MaxValue = (IComparable)Max.To <object>(value.GetType()); var MinValue = (IComparable)Min.To <object>(value.GetType()); var TempValue = value as IComparable; return((Comparer.Compare(MaxValue, TempValue) < 0 || Comparer.Compare(TempValue, MinValue) < 0) ? new ValidationResult(FormatErrorMessage(validationContext.DisplayName)) : ValidationResult.Success); }
public SMOModel(Model parent, string name) : base(parent, name) { KVZS = InitModelObject<TIntVar>(); KVZ = InitModelObjectArray<TIntVar>(3, ""); KPZ = InitModelObjectArray<TIntVar>(3, ""); KZ = InitModelObjectArray<TBoolVar>(2, ""); TZKO = InitModelObjectArray<TRealVar>(2, ""); KPZ = InitModelObjectArray<TIntVar>(3, ""); queue = InitModelObjectArray<SimpleModelList<QueueRec>>(3, ""); TimeIn_FirstFlow = InitModelObject<TRealVar>(); TimeIn_SecondFlow = InitModelObject<TRealVar>(); inFlowGenerator = InitModelObjectArray<PoissonStream>(2, ""); servFlowGenerator = InitModelObjectArray<ExpStream>(2, ""); repeateGenerator = InitModelObject<UniformStream>(); Variance_QueueCount = InitModelObjectArray<Variance<int>>(3, ""); Variance_QueueCount[0].ConnectOnSet(queue[0].Count); Variance_QueueCount[1].ConnectOnSet(queue[1].Count); Variance_QueueCount[2].ConnectOnSet(queue[2].Count); Variance_TimeIn_FirstFlow = InitModelObject<Variance<double>>(); Variance_TimeIn_FirstFlow.ConnectOnSet(TimeIn_FirstFlow); Variance_TimeIn_SecondFlow = InitModelObject<Variance<double>>(); Variance_TimeIn_SecondFlow.ConnectOnSet(TimeIn_SecondFlow); Min_TimeIn_FirstFlow = InitModelObject<Min<double>>(); Min_TimeIn_FirstFlow.ConnectOnSet(TimeIn_FirstFlow); Min_TimeIn_SecondFlow = InitModelObject<Min<double>>(); Min_TimeIn_SecondFlow.ConnectOnSet(TimeIn_SecondFlow); Max_TimeIn_FirstFlow = InitModelObject<Max<double>>(); Max_TimeIn_FirstFlow.ConnectOnSet(TimeIn_FirstFlow); Max_TimeIn_SecondFlow = InitModelObject<Max<double>>(); Max_TimeIn_SecondFlow.ConnectOnSet(TimeIn_SecondFlow); Bool_Kanal = InitModelObjectArray<BoolCollector>(2, ""); Bool_Kanal[0].ConnectOnSet(KZ[0]); Bool_Kanal[1].ConnectOnSet(KZ[1]); }
TRealVar TOZ; //Время обработки заявки в системе #endregion Fields #region Constructors public VU(VS parent, string name) : base(parent, name) { ParentVS = parent; UVD = new UstroystvoVvoda(this, "УВД" + "(" + name + ")"); UR = new UstroystvoRabota(this, "УОД" + "(" + name + ")"); UV = new UstroystvoVyvoda(this, "УВР" + "(" + name + ")"); this.AddModelObject(UVD); this.AddModelObject(UR); this.AddModelObject(UV); #region Инициализация переменных объектов модели KVZ = InitModelObject<TIntVar>(); KOZ = InitModelObject<TIntVar>(); TOZ = InitModelObject<TRealVar>(); KPZ = new int[3]; Gener_Vhod = InitModelObject<ExpStream>(); Gener_RazmerVvod = InitModelObject<UniformStream>(); Gener_RazmerVyvoda = InitModelObject<NormalStream>(); // Gener_RazmerRabota = InitModelObject<ExpStream>(); #endregion #region Инициализация сборщиков статистики Variance_TOZ = InitModelObject<Variance<Double>>(); //создаем сборщик Variance_TOZ.ConnectOnSet(TOZ); //подключаем сборщик к переменной Min_TOZ = InitModelObject<Min<double>>(); //создаем сборщик Min_TOZ.ConnectOnSet(TOZ); //подключаем сборщик к переменной Max_TOZ = InitModelObject<Max<double>>(); //создаем сборщик Max_TOZ.ConnectOnSet(TOZ); //подключаем сборщик к переменной His_TOZ = InitModelObject<DynamicHistogram>(); His_TOZ.ConnectOnSet(TOZ); #endregion }
public void Visit(Max max) { _sb.Append("max("); max.Left.Accept(this); _sb.Append(", "); max.Right.Accept(this); _sb.Append(")"); }
public void Visit(Max max) { // Nothing to do here... }
// Which starting number, under one million, produces the longest chain? //NOTE this problem is begging to be solved with a tree, too bad I don't feel like rolling my own tree in C# right now public static long CollatzSequence(long maxStart) { Max max = new Max(); long x; for(long i = 1; i < maxStart; i++) { max.mCurrentLevels = 1; x = Max.CollatzRecurse(i, max); if(x > max.mLevels) { max.mLevels = x; max.mMaxIndex = i; //DEBUG Console.WriteLine(x); } } return max.mMaxIndex; }
private static void GenerateTrees() { Terrain t = Terrain.activeTerrain; TerrainData td = t.terrainData; TreePrototype[] treeprototypes = new TreePrototype[] { new TreePrototype() { prefab = (GameObject)Resources.Load("BigTree") }, new TreePrototype() { prefab = (GameObject)Resources.Load("Tree") } }; td.treePrototypes = treeprototypes; //float[, ,] splatmaps = td.GetAlphamaps(0, 0, td.alphamapWidth, td.alphamapHeight); td.treeInstances = new TreeInstance[0]; List<Vector3> treePos = new List<Vector3>(); float[,] noisemap = new float[td.alphamapWidth, td.alphamapHeight]; Generator noise_tree = new Max( new PinkNoise((int)UnityEngine.Random.Range(0, int.MaxValue)) { Frequency = 0.01f, OctaveCount = 6, Persistence = 0.66f, Lacunarity = 0.1f }, new PinkNoise((int)UnityEngine.Random.Range(0, int.MaxValue)) { Frequency = 0.015f, OctaveCount = 2, Persistence = 0.66f, Lacunarity = 0.2f }); for (int ny = 0; ny < noisemap.GetLength(1); ny++) { for (int nx = 0; nx < noisemap.GetLength(0); nx++) { noisemap[nx, ny] = noise_tree.GetValue(nx, ny, 0); } } if (maxSteepness == 0) { maxSteepness = 70.0f; } if (waterLevel == 0) { waterLevel = 0.0f; } float x = 0.0f; while (x < td.alphamapWidth) { float y = 0.0f; while (y < td.alphamapHeight) { float height = td.GetHeight((int)x, (int)y); float heightScaled = height / td.size.y; float xScaled = (x + Random.Range(-1f, 1f)) / td.alphamapWidth; float yScaled = (y + Random.Range(-1f, 1f)) / td.alphamapHeight; float steepness = td.GetSteepness(xScaled, yScaled); if (Random.Range(0f, 1f) > 1f - noisemap[(int)x, (int)y] * 2f && steepness < maxSteepness && height > waterLevel) { treePos.Add(new Vector3(xScaled, heightScaled, yScaled)); } y++; } x++; } TreeInstance[] treeInstances = new TreeInstance[treePos.Count]; for (int ii = 0; ii < treeInstances.Length; ii++) { treeInstances[ii].position = treePos[ii]; treeInstances[ii].prototypeIndex = Random.Range(0, treeprototypes.Length); treeInstances[ii].color = Color.white;//new Color(Random.Range(200, 255), Random.Range(200, 255), Random.Range(200, 255)); treeInstances[ii].lightmapColor = Color.white; treeInstances[ii].heightScale = 1.0f + Random.Range(-0.25f, 0.5f); treeInstances[ii].widthScale = 1.0f + Random.Range(-0.5f, 0.25f); } td.treeInstances = treeInstances; }
public void Visit(Max max) { ResultIsIntAndBothOperandsMustBeInt(max); }
public void VectorTest() { var exp = new Max(new[] { new Vector(new[] { new Number(1), new Number(2), new Number(3) }) }, 1); var result = exp.Execute(); Assert.Equal(3.0, result); }
public void Visit(Max max) { Visit(max, _max); }
/// <summary> /// Creates an expression object from <see cref="FunctionToken"/>. /// </summary> /// <param name="token">The function token.</param> /// <returns>An expression.</returns> protected virtual IExpression CreateFunction(FunctionToken token) { IExpression exp; switch (token.Function) { case Functions.Add: exp = new Add(); break; case Functions.Sub: exp = new Sub(); break; case Functions.Mul: exp = new Mul(); break; case Functions.Div: exp = new Div(); break; case Functions.Pow: exp = new Pow(); break; case Functions.Absolute: exp = new Abs(); break; case Functions.Sine: exp = new Sin(); break; case Functions.Cosine: exp = new Cos(); break; case Functions.Tangent: exp = new Tan(); break; case Functions.Cotangent: exp = new Cot(); break; case Functions.Secant: exp = new Sec(); break; case Functions.Cosecant: exp = new Csc(); break; case Functions.Arcsine: exp = new Arcsin(); break; case Functions.Arccosine: exp = new Arccos(); break; case Functions.Arctangent: exp = new Arctan(); break; case Functions.Arccotangent: exp = new Arccot(); break; case Functions.Arcsecant: exp = new Arcsec(); break; case Functions.Arccosecant: exp = new Arccsc(); break; case Functions.Sqrt: exp = new Sqrt(); break; case Functions.Root: exp = new Root(); break; case Functions.Ln: exp = new Ln(); break; case Functions.Lg: exp = new Lg(); break; case Functions.Lb: exp = new Lb(); break; case Functions.Log: exp = new Log(); break; case Functions.Sineh: exp = new Sinh(); break; case Functions.Cosineh: exp = new Cosh(); break; case Functions.Tangenth: exp = new Tanh(); break; case Functions.Cotangenth: exp = new Coth(); break; case Functions.Secanth: exp = new Sech(); break; case Functions.Cosecanth: exp = new Csch(); break; case Functions.Arsineh: exp = new Arsinh(); break; case Functions.Arcosineh: exp = new Arcosh(); break; case Functions.Artangenth: exp = new Artanh(); break; case Functions.Arcotangenth: exp = new Arcoth(); break; case Functions.Arsecanth: exp = new Arsech(); break; case Functions.Arcosecanth: exp = new Arcsch(); break; case Functions.Exp: exp = new Exp(); break; case Functions.GCD: exp = new GCD(); break; case Functions.LCM: exp = new LCM(); break; case Functions.Factorial: exp = new Fact(); break; case Functions.Sum: exp = new Sum(); break; case Functions.Product: exp = new Product(); break; case Functions.Round: exp = new Round(); break; case Functions.Floor: exp = new Floor(); break; case Functions.Ceil: exp = new Ceil(); break; case Functions.Derivative: exp = new Derivative(); break; case Functions.Simplify: exp = new Simplify(); break; case Functions.Del: exp = new Del(); break; case Functions.Define: exp = new Define(); break; case Functions.Vector: exp = new Vector(); break; case Functions.Matrix: exp = new Matrix(); break; case Functions.Transpose: exp = new Transpose(); break; case Functions.Determinant: exp = new Determinant(); break; case Functions.Inverse: exp = new Inverse(); break; case Functions.If: exp = new If(); break; case Functions.For: exp = new For(); break; case Functions.While: exp = new While(); break; case Functions.Undefine: exp = new Undefine(); break; case Functions.Im: exp = new Im(); break; case Functions.Re: exp = new Re(); break; case Functions.Phase: exp = new Phase(); break; case Functions.Conjugate: exp = new Conjugate(); break; case Functions.Reciprocal: exp = new Reciprocal(); break; case Functions.Min: exp = new Min(); break; case Functions.Max: exp = new Max(); break; case Functions.Avg: exp = new Avg(); break; case Functions.Count: exp = new Count(); break; case Functions.Var: exp = new Var(); break; case Functions.Varp: exp = new Varp(); break; case Functions.Stdev: exp = new Stdev(); break; case Functions.Stdevp: exp = new Stdevp(); break; default: exp = null; break; } var diff = exp as DifferentParametersExpression; if (diff != null) diff.ParametersCount = token.CountOfParams; return exp; }
public void ToStringTest() { var sum = new Max(new[] { new Number(1), new Number(2) }, 2); Assert.Equal("max(1, 2)", sum.ToString()); }
public void ToStringTest2() { var sum = new Max(new[] { new Vector(new[] { new Number(1), new Number(2) }) }, 1); Assert.Equal("max({1, 2})", sum.ToString()); }
public static long CollatzRecurse(long val, Max max) { if( val == 1) { return max.mCurrentLevels; } else if( val % 2 == 0) { max.mCurrentLevels++; return CollatzRecurse(val / 2, max); } else { max.mCurrentLevels++; return CollatzRecurse((3 * val) + 1, max); } }
public void MaxTest() { var tokens = new List<IToken> { new FunctionToken(Functions.Max, 2), new SymbolToken(Symbols.OpenBracket), new NumberToken(1), new SymbolToken(Symbols.Comma), new NumberToken(2), new SymbolToken(Symbols.CloseBracket) }; var exp = parser.Parse(tokens); var expected = new Max(new[] { new Number(1), new Number(2) }, 2); Assert.Equal(expected, exp); }
Variance<Double> Variance_TOZ; //МО и дисперсия #endregion Fields #region Constructors public VS(Model parent, string name) : base(parent, name) { #region Инициализация переменных объектов модели KVZ = InitModelObject<TIntVar>(); KOZ = InitModelObject<TIntVar>(); TOZ = InitModelObject<TRealVar>(); UZEL = new VU[3]; UZEL[0] = new VU(this, "ВУ1"); UZEL[1] = new VU(this, "ВУ2"); UZEL[2] = new VU(this, "ВУ3"); this.AddModelObject(UZEL[0]); this.AddModelObject(UZEL[1]); this.AddModelObject(UZEL[2]); KANAL = new KPD[3]; KANAL[0] = new KPD(this, "КПД(1,2)"); KANAL[1] = new KPD(this, "КПД(1,3)"); KANAL[2] = new KPD(this, "КПД(2,3)"); this.AddModelObject(KANAL[0]); this.AddModelObject(KANAL[1]); this.AddModelObject(KANAL[2]); KANAL[0].VU_1 = UZEL[0]; KANAL[0].VU_2 = UZEL[1]; KANAL[1].VU_1 = UZEL[0]; KANAL[1].VU_2 = UZEL[2]; KANAL[2].VU_1 = UZEL[1]; KANAL[2].VU_2 = UZEL[2]; #endregion #region Инициализация сборщиков статистики Variance_TOZ = InitModelObject<Variance<Double>>(); //создаем сборщик Variance_TOZ.ConnectOnSet(TOZ); //подключаем сборщик к переменной Min_TOZ = InitModelObject<Min<double>>(); //создаем сборщик Min_TOZ.ConnectOnSet(TOZ); //подключаем сборщик к переменной Max_TOZ = InitModelObject<Max<double>>(); //создаем сборщик Max_TOZ.ConnectOnSet(TOZ); //подключаем сборщик к переменной His_TOZ = InitModelObject<DynamicHistogram>(); His_TOZ.ConnectOnSet(TOZ); //-------------------------------------------------- allValuesTest = InitModelObject<AllValues<int>>("Сборщик полной статистики"); dhTest = InitModelObject<DynamicHistogram>("Динамическая гистограмма"); testAV = InitModelObject<TIntVar>("Тестовая переменная 1"); testDH = InitModelObject<TRealVar>("Тестовая переменная 2"); testAV.AddCollectors_OnSet(allValuesTest); testDH.AddCollectors_OnSet(dhTest); //-------------------------------------------------- #endregion /*Tracer.AddAutoTabModel(this); UZEL.ToList().ForEach(u => Tracer.AddAutoTabModel(u)); KANAL.ToList().ForEach(k => Tracer.AddAutoTabModel(k));*/ }
public virtual void loadFunctions(Rete engine) { Abs abs = new Abs(); engine.declareFunction(abs); funcs.Add(abs); Acos acos = new Acos(); engine.declareFunction(acos); funcs.Add(acos); Add add = new Add(); engine.declareFunction(add); funcs.Add(add); Asin asin = new Asin(); engine.declareFunction(asin); funcs.Add(asin); Atan atan = new Atan(); engine.declareFunction(atan); funcs.Add(atan); Ceil ceil = new Ceil(); engine.declareFunction(ceil); funcs.Add(ceil); Const cnst = new Const(); engine.declareFunction(cnst); funcs.Add(cnst); Cos cos = new Cos(); engine.declareFunction(cos); funcs.Add(cos); Degrees degrees = new Degrees(); engine.declareFunction(degrees); funcs.Add(degrees); Divide div = new Divide(); engine.declareFunction(div); funcs.Add(div); EqFunction eqf = new EqFunction(); engine.declareFunction(eqf); funcs.Add(eqf); Evenp evenp = new Evenp(); engine.declareFunction(evenp); funcs.Add(evenp); Exp exp = new Exp(); engine.declareFunction(exp); funcs.Add(exp); Floor floor = new Floor(); engine.declareFunction(floor); funcs.Add(floor); Greater gr = new Greater(); engine.declareFunction(gr); funcs.Add(gr); GreaterOrEqual gre = new GreaterOrEqual(); engine.declareFunction(gre); funcs.Add(gre); Less le = new Less(); engine.declareFunction(le); funcs.Add(le); LessOrEqual leoe = new LessOrEqual(); engine.declareFunction(leoe); funcs.Add(leoe); Log log = new Log(); engine.declareFunction(log); funcs.Add(log); Max max = new Max(); engine.declareFunction(max); funcs.Add(max); Min min = new Min(); engine.declareFunction(min); funcs.Add(min); Multiply mul = new Multiply(); engine.declareFunction(mul); funcs.Add(mul); NeqFunction neq = new NeqFunction(); engine.declareFunction(neq); funcs.Add(neq); Oddp oddp = new Oddp(); engine.declareFunction(oddp); funcs.Add(oddp); Pow pow = new Pow(); engine.declareFunction(pow); funcs.Add(pow); Radians radians = new Radians(); engine.declareFunction(radians); funcs.Add(radians); Random random = new Random(); engine.declareFunction(random); funcs.Add(random); Rint rint = new Rint(); engine.declareFunction(rint); funcs.Add(rint); Round round = new Round(); engine.declareFunction(round); funcs.Add(round); Sin sin = new Sin(); engine.declareFunction(sin); funcs.Add(sin); Sqrt sqrt = new Sqrt(); engine.declareFunction(sqrt); funcs.Add(sqrt); Subtract sub = new Subtract(); engine.declareFunction(sub); funcs.Add(sub); Tan tan = new Tan(); engine.declareFunction(tan); funcs.Add(tan); // now we Add the functions under alias engine.declareFunction("+", add); engine.declareFunction("-", sub); engine.declareFunction("*", mul); engine.declareFunction("/", div); engine.declareFunction("**", pow); engine.declareFunction(">", gr); engine.declareFunction(">=", gre); engine.declareFunction("<", le); engine.declareFunction("<=", leoe); }
public static void genNoise(int channelId) { moduleBase[channelId] = new Perlin(); if (teNoiseChanTypeIndex[channelId] == 1) { int tIdx = teNoiseTypeIndex[channelId]; if (tIdx == 0) { moduleBase[channelId] = new Perlin(frequency[channelId], lacunarity[channelId], persistance[channelId], octaves[channelId], seed[channelId], QualityMode.High); } if (tIdx == 1) { moduleBase[channelId] = new Billow(frequency[channelId], lacunarity[channelId], persistance[channelId], octaves[channelId], seed[channelId], QualityMode.High); } if (tIdx == 2) { moduleBase[channelId] = new RidgedMultifractal(frequency[channelId], lacunarity[channelId], octaves[channelId], seed[channelId], QualityMode.High); } if (tIdx == 3) { moduleBase[channelId] = new Voronoi(frequency[channelId], displacement[channelId], seed[channelId], distance[channelId]); } if (tIdx == 4) { moduleBase[channelId] = new BrownianMotion(frequency[channelId], lacunarity[channelId], octaves[channelId], seed[channelId], QualityMode.High); } if (tIdx == 5) { moduleBase[channelId] = new HeterogeneousMultiFractal(frequency[channelId], lacunarity[channelId], octaves[channelId], persistance[channelId], seed[channelId], offset[channelId], QualityMode.High); } if (tIdx == 6) { moduleBase[channelId] = new HybridMulti(frequency[channelId], lacunarity[channelId], octaves[channelId], persistance[channelId], seed[channelId], offset[channelId], gain[channelId], QualityMode.High); } if (tIdx == 7) { moduleBase[channelId] = new LinearGradientNoise(frequency[channelId]); } } if (teNoiseChanTypeIndex[channelId] == 2) { int fIdx = teFunctionTypeIndex[channelId]; if (fIdx == 0) { moduleBase[channelId] = new Add(moduleBase[srcChannel1Id[channelId]], moduleBase[srcChannel2Id[channelId]]); } if (fIdx == 1) { moduleBase[channelId] = new Subtract(moduleBase[srcChannel1Id[channelId]], moduleBase[srcChannel2Id[channelId]]); } if (fIdx == 2) { moduleBase[channelId] = new Multiply(moduleBase[srcChannel1Id[channelId]], moduleBase[srcChannel2Id[channelId]]); } if (fIdx == 3) { moduleBase[channelId] = new Min(moduleBase[srcChannel1Id[channelId]], moduleBase[srcChannel2Id[channelId]]); } if (fIdx == 4) { moduleBase[channelId] = new Max(moduleBase[srcChannel1Id[channelId]], moduleBase[srcChannel2Id[channelId]]); } if (fIdx == 5) { moduleBase[channelId] = new Blend(moduleBase[srcChannel1Id[channelId]], moduleBase[srcChannel2Id[channelId]], moduleBase[srcChannel3Id[channelId]]); } if (fIdx == 6) { moduleBase[channelId] = new Clamp((double)noiseFuncMin[channelId], (double)noiseFuncMax[channelId], moduleBase[srcChannel1Id[channelId]]); } if (fIdx == 7) { moduleBase[channelId] = new Power(moduleBase[srcChannel1Id[channelId]],moduleBase[srcChannel2Id[channelId]]);} if (fIdx == 8) { Curve tmpCurve = new Curve(moduleBase[srcChannel1Id[channelId]]); double adjust = double.Parse((controlpointcount[channelId]-1).ToString())*0.5; for(int i=0;i<controlpointcount[channelId];i++){ tmpCurve.Add(double.Parse(i.ToString())-adjust,(double)cpval[channelId,i]); moduleBase[channelId] = tmpCurve; } } if(fIdx==9){Terrace tmpTerrace = new Terrace(invertTerrace[channelId],moduleBase[srcChannel1Id[channelId]]); for(int i=0;i<controlpointcount[channelId];i++){ tmpTerrace.Add((double)cpval[channelId,i]-0.5); moduleBase[channelId] = tmpTerrace; } } if (fIdx == 18) { moduleBase[channelId] = new Mask(moduleBase[srcChannel1Id[channelId]], (double)noiseFuncMin[channelId], (double)noiseFuncMax[channelId]); } if (fIdx == 17) { moduleBase[channelId] = new WindexWarp(moduleBase[srcChannel1Id[channelId]]); } if (fIdx == 16) { moduleBase[channelId] = new TEWarp(moduleBase[srcChannel1Id[channelId]]); } if (fIdx == 15) { moduleBase[channelId] = new Select((double)noiseFuncMin[channelId], (double)noiseFuncMax[channelId], falloff[channelId], moduleBase[srcChannel1Id[channelId]], moduleBase[srcChannel2Id[channelId]], moduleBase[srcChannel3Id[channelId]]); } if (fIdx == 14) { moduleBase[channelId] = new Turbulence(power[channelId],moduleBase[srcChannel1Id[channelId]]); } if (fIdx == 13) { moduleBase[channelId] = new ScaleBias(scale[channelId],bias[channelId],moduleBase[srcChannel1Id[channelId]]); } if (fIdx == 12) { moduleBase[channelId] = new Invert(moduleBase[srcChannel1Id[channelId]]);} if (fIdx == 11) { moduleBase[channelId] = new Exponent(exponent[channelId],moduleBase[srcChannel1Id[channelId]]); } if (fIdx == 10) { moduleBase[channelId] = new Abs(moduleBase[srcChannel1Id[channelId]]);} } int resolution = 64; int xoffset = 0; int yoffset = 0; m_noiseMap[channelId] = new Noise2D(resolution, resolution, moduleBase[channelId]); float x1 = xoffset * zoom[channelId]; float x2 = (xoffset * zoom[channelId]) + ((zoom[channelId] / resolution) * (resolution + 1)); float y1 = -yoffset * zoom[channelId]; float y2 = (-yoffset * zoom[channelId]) + ((zoom[channelId] / resolution) * (resolution + 1)); m_noiseMap[channelId].GeneratePlanar(x1, x2, y1, y2); m_textures[channelId] = m_noiseMap[channelId].GetTexture(); m_textures[channelId].Apply(); }