internal static bool TryParse(string text, NumberRange range, out double result, out string message) { if (!TryParse(text, range, out result)) { string prefix; switch (range) { case NumberRange.Positive: prefix = $"{GetInterfaceString("message", "positive")} "; break; case NumberRange.NonNegative: prefix = $"{GetInterfaceString("message", "non_negative")} "; break; case NumberRange.NonZero: prefix = $"{GetInterfaceString("message", "non_zero")} "; break; default: prefix = string.Empty; break; } message = string.Format(GetInterfaceString("message", "invalid_float"), prefix); return(false); } message = null; return(true); }
void NumberEditor_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { if (PropertyNode == null) return; var type = PropertyNode.FirstProperty.ReturnType; var range = Metadata.GetValueRange(PropertyNode.FirstProperty); if (range == null) { range = new NumberRange() { Min = 0, Max = double.MaxValue }; } if (range.Min == double.MinValue) { Minimum = minimums[type]; } else { Minimum = range.Min; } if (range.Max == double.MaxValue) { Maximum = maximums[type]; } else { Maximum = range.Max; } if (Minimum == 0 && Maximum == 1) { DecimalPlaces = 2; SmallChange = 0.01; LargeChange = 0.1; } else { ClearValue(DecimalPlacesProperty); ClearValue(SmallChangeProperty); ClearValue(LargeChangeProperty); } }
static List <long> found = new List <long>(); // 찾은 소수를 저장할 리스트 static void Main(string[] args) { // 소수를 판별할 숫자들의 범위 int startNum = 2, endNum = 100000; int threadCount = 8; NumberRange[] numberRanges = new NumberRange[threadCount]; Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { threads[i] = new Thread(FindPrimeNumFunc); } // Thread별 첫번째 작업범위 지정 int currentStartNum = startNum; int currentEndNum = endNum / threads.Length; // threadCount 숫자만큼 Thread 인스턴스의 작업 범위 지정 for (int i = 0; i < threads.Length; i++) { Console.WriteLine($"threads[{i}] : {currentStartNum} ~ {currentEndNum}"); numberRanges[i] = new NumberRange() { startNum = currentStartNum, endNum = currentEndNum }; // 다음 범위 세팅 currentStartNum = currentEndNum + 1; // 현재 검사한 범위보다 1큰 수를 currentStartNum으로 지정 if (threads.Length == 2) // Task의 개수가 2개라면 currentEndNum을 검사할 범위의 마지막 숫자로 지정 { currentEndNum = endNum; } else { currentEndNum = currentEndNum + (endNum / threads.Length); // Task의 개수가 2개 이상이라면 currentEndNum을 등분된 크기만큼 더한 숫자로 지정 } } Console.WriteLine("Started..."); DateTime startTime = DateTime.Now; // 시작 시간 // Thread[] 배열의 thread 모두 실행 for (int i = 0; i < threadCount; i++) { threads[i].Start(numberRanges[i]); } for (int i = 0; i < threadCount; i++) { threads[i].Join(); } DateTime endTime = DateTime.Now; TimeSpan elapsed = endTime - startTime; // TimeSpan 두 날짜 간의 시간 간격 Console.WriteLine($"소수 개수: {found.Count}"); Console.WriteLine($"실행 시간 : {elapsed}"); }
internal static bool TryParse(string text, NumberRange range, out double result) { bool error; if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out result)) { switch (range) { case NumberRange.Positive: error = result <= 0.0; break; case NumberRange.NonNegative: error = result < 0.0; break; case NumberRange.NonZero: error = result == 0.0; break; default: error = false; break; } } else { error = true; } return(!error); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is NumberRange && targetType.Name == "String") { NumberRange range = (NumberRange)value; switch (range) { case NumberRange.LessThan0: return("Less Than 0"); case NumberRange.Between0And10: return("Between 0 And 10"); case NumberRange.Between10And50: return("Between 10 And 50"); case NumberRange.Between50And100: return("Between 50 And 100"); case NumberRange.Between100And500: return("Between 100 And 500"); case NumberRange.Between500And1000: return("Between 500 And 1000"); case NumberRange.Between1000And5000: return("Between 1000 And 5000"); case NumberRange.GratherThan5000: return("Greater Than 5000"); } } return(null); }
/// <summary> /// Generates /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public static Vector2f Random(Vector2f min, Vector2f max) { NumberRange xRange = new NumberRange(min.X, max.X); NumberRange yRange = new NumberRange(min.Y, max.Y); return(new Vector2f(xRange.Random, yRange.Random)); }
void NumberEditor_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { if (PropertyNode == null) { return; } var type = PropertyNode.FirstProperty.ReturnType; var range = Metadata.GetValueRange(PropertyNode.FirstProperty); if (range == null) { range = new NumberRange() { Min = double.MinValue, Max = double.MaxValue }; } var nType = type; if (Nullable.GetUnderlyingType(type) != null) { nType = Nullable.GetUnderlyingType(type); } if (range.Min == double.MinValue) { Minimum = minimums[nType]; } else { Minimum = range.Min; } if (range.Max == double.MaxValue) { Maximum = maximums[nType]; } else { Maximum = range.Max; } if (type == typeof(double) || type == typeof(decimal)) { DecimalPlaces = 2; } // if (Minimum == 0 && Maximum == 1) { // DecimalPlaces = 2; // SmallChange = 0.01; // LargeChange = 0.1; // } // else { // ClearValue(DecimalPlacesProperty); // ClearValue(SmallChangeProperty); // ClearValue(LargeChangeProperty); // } }
public void CreateNumberPingPongList_CreatesListOfNumbersAndPingPongs_ExpectedList() { NumberRange testNewList = new NumberRange(); CollectionAssert.AreEqual(new List <string> { "1", "2", "ping", "4", "pong" }, testNewList.CreateNumberPingPongList(5)); }
public void defaultProfile() { drivers = defaultDrivers(); passengers = defaultPassengers(); symbolType = SymbolType.ExampleMath; textureSymbols = defaultTextureSymbols(); numberRange = defaultNumbers(); letters = defaultLetters(); customMappings = defaultCustomMappings(); exampleMath = exampleMathMappings(); exampleEnglish = exampleEnglishMappings(); }
public NumberRangePropertyEditorControl(NumberRange range) { InitializeComponent(); this.txtStart.Text = range.BeginValue.ToString(); this.txtEnd.Text = range.EndValue.ToString(); if (range == null) { throw new ArgumentNullException("range"); } this._range = range; }
void NumberEditor_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { if (PropertyNode == null) { return; } var type = PropertyNode.FirstProperty.ReturnType; var range = Metadata.GetValueRange(PropertyNode.FirstProperty); if (range == null) { range = new NumberRange() { Min = double.MinValue, Max = double.MaxValue }; } if (range.Min == double.MinValue) { Minimum = minimums[type]; } else { Minimum = range.Min; } if (range.Max == double.MaxValue) { Maximum = maximums[type]; } else { Maximum = range.Max; } if (Minimum == 0 && Maximum == 1) { DecimalPlaces = 2; SmallChange = 0.01; LargeChange = 0.1; } else { ClearValue(DecimalPlacesProperty); ClearValue(SmallChangeProperty); ClearValue(LargeChangeProperty); } }
this.low = new NumberRange() { low = data.lowStart, high = data.lowEnd }; this.high = new NumberRange() { low = data.highStart, high = data.highEnd }; this.rangeFilter = new bool[1000]; foreach (var num in low.Concat(high)) { rangeFilter[num] = true; } }
private static void FindPrimeNumFunc(object numRange) { NumberRange range = numRange as NumberRange; Console.WriteLine($"{range.startNum} ~ {range.endNum} 스레드 함수 실행"); // 소수를 찾으면 found 리스트에 추가 for (long i = range.startNum; i <= range.endNum; i++) { lock (found) { if (IsPrime(i)) { found.Add(i); } } } Console.WriteLine($"{range.startNum} ~ {range.endNum} 스레드 함수 종료"); }
protected override FrameworkElement CreateDynamicEditingElement(Entity curEntity) { var value = this.PropertyValue; //支持两种属性类型:DateRange,String,所以这里使用这个变量进行分辨 var useNumberRangeType = this.Meta.PropertyMeta.Runtime.PropertyType == typeof(NumberRange); var range = useNumberRangeType ? new NumberRange(value as NumberRange) : NumberRange.Parse(value != null ? value as string : string.Empty); var rangeControl = new NumberRangePropertyEditorControl(range); rangeControl.Confirm += (ss, ee) => { if (useNumberRangeType) { var raw = value as NumberRange; raw.BeginValue = ee.Range.BeginValue; raw.EndValue = ee.Range.EndValue; } else { this.PropertyValue = ee.Range.ToString(); } }; rangeControl.KeyDown += (oo, ee) => { if (ee.Key == Key.Enter) { FocusNavigationDirection focusDirection = FocusNavigationDirection.Next; TraversalRequest request = new TraversalRequest(focusDirection); rangeControl.MoveFocus(request); } }; this.AddReadOnlyComponent(rangeControl); this.SetAutomationElement(rangeControl); return(rangeControl); }
public async Task DoAsync(CancellationToken cancellationToken) { var config = _configProvider.Get <TestLocalizerConfig>(); foreach (var accountId in NumberRange.ToInts(config.AccountIds)) { Console.WriteLine($"Looking for account {accountId}"); var results = await _client.GetActivities(new ActivitiesQuery { AccountId = accountId }); Console.WriteLine($"Account has {results.Total} activities"); foreach (var activity in results.Activities) { Console.Write($"Activity {activity.Id} {activity.Type}"); TryAction(activity, TrySingular, "Singular"); TryAction(activity, TryPlural, "Plural"); Console.WriteLine(); } } }
public Task <GroupOperationCost> DoAsync(IStore store, CancellationToken cancellationToken) { return(Task.Run(async() => { var cost = new GroupOperationCost("Aggregate Activities"); foreach (var accountId in NumberRange.ToInts(_config.AccountIds)) { if (cancellationToken.IsCancellationRequested) { break; } var operationCost = await store.GetLatestActivitiesAsync(accountId); cost.StepCosts.Add(operationCost); } return cost; }, cancellationToken)); }
private void SetupBeepPlayer() { beepPlayer.FinishedPlaying += (s, e) => { beepPlayer.Stop(); buttonPlay.Text = "Play"; labelTitle.ForeColor = titleColor; note = 0; textBoxSequence.Select(0, 0); }; beepPlayer.NotePlaying += (s, e) => { NumberRange range = FreqAnalyzer.GetFreqRangeFromNotes(beepPlayer.Notes); FreqAnalyzer FA = new FreqAnalyzer(titleColor, e.Frequency, range); Color color = FA.GetNewColor(); labelTitle.ForeColor = color; textBoxSequence.SelectNote(note++); }; }
public async Task DoAsync(CancellationToken cancellationToken) { var config = _configProvider.Get <AggregateQueryConfig>(); foreach (var accountId in NumberRange.ToInts(config.AccountIds)) { var results = await _client.GetLatestActivities(accountId); var tubeStops = results.Aggregates.Count(); if (tubeStops == 0 && config.IgnoreNotFound) { continue; } var activitiesCount = results.Aggregates.Sum(a => a.Count); Console.WriteLine($"Account id {accountId} found {tubeStops} tube stops covering {activitiesCount} activities"); await _resultSaver.Save(results); } }
/// <summary/> public ParticleEmitter() { Acceleration = Vector3.Zero; Colour = new ColourSequence(dEngine.Colour.White); Drag = 0; EmissionDirection = NormalId.Top; Enabled = true; Lifetime = new NumberRange(5, 10); Blending = 0f; LockedToPart = false; Rate = 20; RotSpeed = new NumberRange(0); Rotation = new NumberRange(0); Size = new NumberSequence(1); Speed = new NumberRange(5); Texture = "rbxassetid://242201991"; Transparency = new NumberSequence(0); VelocityInheritance = 0; VelocitySpread = 0; ZOffset = 0; }
public static void SetBindToNumberRange(ComboBox comboBox, NumberRange value) { comboBox.SetValue(BindToNumberRangeProperty, value); }
public void CheckDivisibility_NotDivisbleByPreviousCriteria_True() { NumberRange checkDivisibility = new NumberRange(); Assert.AreEqual("1", checkDivisibility.CheckDivisibility(1)); }
/// <summary>Saves the content of a textbox into an output parameter and creates a message box if the textbox contains invalid data.</summary> /// <param name="Box">A textbox control.</param> /// <param name="Text">The description of the textbox.</param> /// <param name="Page">The tabpage the textbox resides in.</param> /// <param name="Range">The allowed number range.</param> /// <param name="Value">The output parameter that receives the numeric value of the textbox content.</param> /// <returns>A boolean indicating the success of the operation.</returns> private bool SaveControlContent(TextBox Box, string Text, TabPage Page, NumberRange Range, out double Value) { bool error; if (double.TryParse(Box.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out Value)) { switch (Range) { case NumberRange.Positive: error = Value <= 0.0; break; case NumberRange.NonNegative: error = Value < 0.0; break; default: error = false; break; } } else { error = true; } if (error) { string prefix; switch (Range) { case NumberRange.Positive: prefix = "positive "; break; case NumberRange.NonNegative: prefix = "non-negative "; break; default: prefix = ""; break; } MessageBox.Show(Text + " must be a " + prefix + "floating-point number.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); tabcontrolTabs.SelectedTab = Page; Box.SelectAll(); Box.Focus(); return false; } else { return true; } }
//get a random int in range public static float GetRandInt(int min, int max) { return(NumberRange.MapToRange(UnityEngine.Random.value, (float)min, (float)max)); }
public bool Contains(NumberRange other) => other.Start >= Start && other.End <= End;
//map val (0-1) to a range with optional weight (default 1.0) public static float MapToRange(float val, float min, float max) { return(NumberRange.MapToRange(val, min, max, 1.0f)); }
internal static IReadOnlyList <INumber> ParseNumberArray(string value) { var result = new List <INumber>(); INumber currentNumber = null; var numberStart = 0; var isRangeToken = false; var i = 0; while (true) { for (; i < value.Length; i++) { var c = value[i]; if (char.IsDigit(c)) { continue; } if (c == '-') { if (isRangeToken) { throw new ArgumentException("Can only have one range identifier per field"); } isRangeToken = true; currentNumber = new NumberRange(); ((NumberRange)currentNumber).Min = int.Parse(value.Substring(numberStart, i - numberStart)); numberStart = i + 1; continue; } if (c == ',') { break; } throw new ArgumentException("Invalid character found: " + c); } if (i == numberStart) { throw new ArgumentException( $"A number was expected at position {i} in string '{value}'"); } var num = int.Parse(value.Substring(numberStart, i - numberStart)); if (isRangeToken) { ((NumberRange)currentNumber).Max = num; } else { currentNumber = new StaticNumber(num); } result.Add(currentNumber); if (i == value.Length) { break; } currentNumber = null; isRangeToken = false; numberStart = ++i; } return(result); }
public void Save(BinaryRobloxFileWriter writer) { BinaryRobloxFile file = writer.File; File = file; INST inst = file.Classes[ClassIndex]; var props = new List <Property>(); foreach (int instId in inst.InstanceIds) { Instance instance = file.Instances[instId]; var instProps = instance.Properties; if (!instProps.TryGetValue(Name, out Property prop)) { throw new Exception($"Property {Name} must be defined in {instance.GetFullName()}!"); } else if (prop.Type != Type) { throw new Exception($"Property {Name} is not using the correct type in {instance.GetFullName()}!"); } props.Add(prop); } writer.Write(ClassIndex); writer.WriteString(Name); writer.Write(TypeId); switch (Type) { case PropertyType.String: props.ForEach(prop => { byte[] buffer = prop.HasRawBuffer ? prop.RawBuffer : null; if (buffer == null) { string value = prop.CastValue <string>(); buffer = Encoding.UTF8.GetBytes(value); } writer.Write(buffer.Length); writer.Write(buffer); }); break; case PropertyType.Bool: { props.ForEach(prop => { bool value = prop.CastValue <bool>(); writer.Write(value); }); break; } case PropertyType.Int: { var ints = props .Select(prop => prop.CastValue <int>()) .ToList(); writer.WriteInts(ints); break; } case PropertyType.Float: { var floats = props .Select(prop => prop.CastValue <float>()) .ToList(); writer.WriteFloats(floats); break; } case PropertyType.Double: { props.ForEach(prop => { double value = prop.CastValue <double>(); writer.Write(BinaryRobloxFileWriter.GetBytes(value)); }); break; } case PropertyType.UDim: { var UDim_Scales = new List <float>(); var UDim_Offsets = new List <int>(); props.ForEach(prop => { UDim value = prop.CastValue <UDim>(); UDim_Scales.Add(value.Scale); UDim_Offsets.Add(value.Offset); }); writer.WriteFloats(UDim_Scales); writer.WriteInts(UDim_Offsets); break; } case PropertyType.UDim2: { var UDim2_Scales_X = new List <float>(); var UDim2_Scales_Y = new List <float>(); var UDim2_Offsets_X = new List <int>(); var UDim2_Offsets_Y = new List <int>(); props.ForEach(prop => { UDim2 value = prop.CastValue <UDim2>(); UDim2_Scales_X.Add(value.X.Scale); UDim2_Scales_Y.Add(value.Y.Scale); UDim2_Offsets_X.Add(value.X.Offset); UDim2_Offsets_Y.Add(value.Y.Offset); }); writer.WriteFloats(UDim2_Scales_X); writer.WriteFloats(UDim2_Scales_Y); writer.WriteInts(UDim2_Offsets_X); writer.WriteInts(UDim2_Offsets_Y); break; } case PropertyType.Ray: { props.ForEach(prop => { Ray ray = prop.CastValue <Ray>(); Vector3 pos = ray.Origin; writer.Write(pos.X); writer.Write(pos.Y); writer.Write(pos.Z); Vector3 dir = ray.Direction; writer.Write(dir.X); writer.Write(dir.Y); writer.Write(dir.Z); }); break; } case PropertyType.Faces: case PropertyType.Axes: { props.ForEach(prop => { byte value = prop.CastValue <byte>(); writer.Write(value); }); break; } case PropertyType.BrickColor: { var brickColorIds = props .Select(prop => prop.CastValue <BrickColor>()) .Select(value => value.Number) .ToList(); writer.WriteInts(brickColorIds); break; } case PropertyType.Color3: { var Color3_R = new List <float>(); var Color3_G = new List <float>(); var Color3_B = new List <float>(); props.ForEach(prop => { Color3 value = prop.CastValue <Color3>(); Color3_R.Add(value.R); Color3_G.Add(value.G); Color3_B.Add(value.B); }); writer.WriteFloats(Color3_R); writer.WriteFloats(Color3_G); writer.WriteFloats(Color3_B); break; } case PropertyType.Vector2: { var Vector2_X = new List <float>(); var Vector2_Y = new List <float>(); props.ForEach(prop => { Vector2 value = prop.CastValue <Vector2>(); Vector2_X.Add(value.X); Vector2_Y.Add(value.Y); }); writer.WriteFloats(Vector2_X); writer.WriteFloats(Vector2_Y); break; } case PropertyType.Vector3: { var Vector3_X = new List <float>(); var Vector3_Y = new List <float>(); var Vector3_Z = new List <float>(); props.ForEach(prop => { Vector3 value = prop.CastValue <Vector3>(); Vector3_X.Add(value.X); Vector3_Y.Add(value.Y); Vector3_Z.Add(value.Z); }); writer.WriteFloats(Vector3_X); writer.WriteFloats(Vector3_Y); writer.WriteFloats(Vector3_Z); break; } case PropertyType.CFrame: case PropertyType.Quaternion: case PropertyType.OptionalCFrame: { var CFrame_X = new List <float>(); var CFrame_Y = new List <float>(); var CFrame_Z = new List <float>(); if (Type == PropertyType.OptionalCFrame) { writer.Write((byte)PropertyType.CFrame); } props.ForEach(prop => { CFrame value = null; if (prop.Value is Quaternion q) { value = q.ToCFrame(); } else { value = prop.CastValue <CFrame>(); } if (value == null) { value = new CFrame(); } Vector3 pos = value.Position; CFrame_X.Add(pos.X); CFrame_Y.Add(pos.Y); CFrame_Z.Add(pos.Z); int orientId = value.GetOrientId(); writer.Write((byte)(orientId + 1)); if (orientId == -1) { if (Type == PropertyType.Quaternion) { Quaternion quat = new Quaternion(value); writer.Write(quat.X); writer.Write(quat.Y); writer.Write(quat.Z); writer.Write(quat.W); } else { float[] components = value.GetComponents(); for (int i = 3; i < 12; i++) { float component = components[i]; writer.Write(component); } } } }); writer.WriteFloats(CFrame_X); writer.WriteFloats(CFrame_Y); writer.WriteFloats(CFrame_Z); if (Type == PropertyType.OptionalCFrame) { writer.Write((byte)PropertyType.Bool); props.ForEach(prop => { if (prop.Value is null) { writer.Write(false); return; } if (prop.Value is Optional <CFrame> optional) { writer.Write(optional.HasValue); return; } var cf = prop.Value as CFrame; writer.Write(cf != null); }); } break; } case PropertyType.Enum: { var enums = new List <uint>(); props.ForEach(prop => { if (prop.Value is uint raw) { enums.Add(raw); return; } int signed = (int)prop.Value; uint value = (uint)signed; enums.Add(value); }); writer.WriteInterleaved(enums); break; } case PropertyType.Ref: { var InstanceIds = new List <int>(); props.ForEach(prop => { int referent = -1; if (prop.Value != null) { Instance value = prop.CastValue <Instance>(); if (value.IsDescendantOf(File)) { string refValue = value.Referent; int.TryParse(refValue, out referent); } } InstanceIds.Add(referent); }); writer.WriteInstanceIds(InstanceIds); break; } case PropertyType.Vector3int16: { props.ForEach(prop => { Vector3int16 value = prop.CastValue <Vector3int16>(); writer.Write(value.X); writer.Write(value.Y); writer.Write(value.Z); }); break; } case PropertyType.NumberSequence: { props.ForEach(prop => { NumberSequence value = prop.CastValue <NumberSequence>(); var keyPoints = value.Keypoints; writer.Write(keyPoints.Length); foreach (var keyPoint in keyPoints) { writer.Write(keyPoint.Time); writer.Write(keyPoint.Value); writer.Write(keyPoint.Envelope); } }); break; } case PropertyType.ColorSequence: { props.ForEach(prop => { ColorSequence value = prop.CastValue <ColorSequence>(); var keyPoints = value.Keypoints; writer.Write(keyPoints.Length); foreach (var keyPoint in keyPoints) { Color3 color = keyPoint.Value; writer.Write(keyPoint.Time); writer.Write(color.R); writer.Write(color.G); writer.Write(color.B); writer.Write(keyPoint.Envelope); } }); break; } case PropertyType.NumberRange: { props.ForEach(prop => { NumberRange value = prop.CastValue <NumberRange>(); writer.Write(value.Min); writer.Write(value.Max); }); break; } case PropertyType.Rect: { var Rect_X0 = new List <float>(); var Rect_Y0 = new List <float>(); var Rect_X1 = new List <float>(); var Rect_Y1 = new List <float>(); props.ForEach(prop => { Rect value = prop.CastValue <Rect>(); Vector2 min = value.Min; Rect_X0.Add(min.X); Rect_Y0.Add(min.Y); Vector2 max = value.Max; Rect_X1.Add(max.X); Rect_Y1.Add(max.Y); }); writer.WriteFloats(Rect_X0); writer.WriteFloats(Rect_Y0); writer.WriteFloats(Rect_X1); writer.WriteFloats(Rect_Y1); break; } case PropertyType.PhysicalProperties: { props.ForEach(prop => { bool custom = (prop.Value != null); writer.Write(custom); if (custom) { PhysicalProperties value = prop.CastValue <PhysicalProperties>(); writer.Write(value.Density); writer.Write(value.Friction); writer.Write(value.Elasticity); writer.Write(value.FrictionWeight); writer.Write(value.ElasticityWeight); } }); break; } case PropertyType.Color3uint8: { var Color3uint8_R = new List <byte>(); var Color3uint8_G = new List <byte>(); var Color3uint8_B = new List <byte>(); props.ForEach(prop => { Color3uint8 value = prop.CastValue <Color3uint8>(); Color3uint8_R.Add(value.R); Color3uint8_G.Add(value.G); Color3uint8_B.Add(value.B); }); byte[] rBuffer = Color3uint8_R.ToArray(); writer.Write(rBuffer); byte[] gBuffer = Color3uint8_G.ToArray(); writer.Write(gBuffer); byte[] bBuffer = Color3uint8_B.ToArray(); writer.Write(bBuffer); break; } case PropertyType.Int64: { var longs = new List <long>(); props.ForEach(prop => { long value = prop.CastValue <long>(); longs.Add(value); }); writer.WriteInterleaved(longs, value => { // Move the sign bit to the front. return((value << 1) ^ (value >> 63)); }); break; } case PropertyType.SharedString: { var sharedKeys = new List <uint>(); SSTR sstr = file.SSTR; if (sstr == null) { sstr = new SSTR(); file.SSTR = sstr; } props.ForEach(prop => { var shared = prop.CastValue <SharedString>(); if (shared == null) { byte[] empty = Array.Empty <byte>(); shared = SharedString.FromBuffer(empty); } string key = shared.Key; if (!sstr.Lookup.ContainsKey(key)) { uint id = (uint)sstr.Lookup.Count; sstr.Strings.Add(id, shared); sstr.Lookup.Add(key, id); } uint hashId = sstr.Lookup[key]; sharedKeys.Add(hashId); }); writer.WriteInterleaved(sharedKeys); break; } case PropertyType.ProtectedString: { props.ForEach(prop => { var protect = prop.CastValue <ProtectedString>(); byte[] buffer = protect.RawBuffer; writer.Write(buffer.Length); writer.Write(buffer); }); break; } case PropertyType.UniqueId: { props.ForEach(prop => { var guid = prop.CastValue <Guid>(); byte[] buffer = guid.ToByteArray(); writer.Write(buffer); }); break; } default: { RobloxFile.LogError($"Unhandled property type: {Type} in {this}!"); break; } } }
internal NumberRangeCompare Compare(NumberRange B) { return(Compare(B.First, B.Last)); }
protected override void readFromXmlExtension(System.Xml.XmlNode node) { if (node.Attributes["languageId"] != null) Language = ParentGameLibrary.Languages[node.Attributes["languageId"].Value]; if (node.Attributes["platformId"] != null) Platform = ParentGameLibrary.Platforms[node.Attributes["platformId"].Value]; if (node.Attributes["players"] != null) players = new NumberRange(node.Attributes["players"].Value); if (node.Attributes["repositoryId"] != null) Repository = ParentGameLibrary.Repositories[node.Attributes["repositoryId"].Value]; if (node.Attributes["innerPath"] != null) innerPath = node.Attributes["innerPath"].Value; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { //类型 var valueType = validationContext.ObjectType.GetProperty(validationContext.MemberName).PropertyType; var valueBaseType = valueType.BaseType; //验证的属性 string valName = validationContext.MemberName; //消息中的字段名称 string valDisplayName = valName; //必填 bool valRequired = false; var fsColumnAttr = validationContext.ObjectType.GetProperty(valName).CustomAttributes.ToList().Where(p => p.AttributeType == typeof(Model.FsColumnAttribute)).FirstOrDefault(); if (fsColumnAttr != null) //FreeSQL实体类 { var attrCount = fsColumnAttr.ConstructorArguments.Count; if (attrCount > 0) { valDisplayName = fsColumnAttr.ConstructorArguments[0].Value.ObjToString(); //取是否必填 } if (attrCount > 1) { valRequired = fsColumnAttr.ConstructorArguments[1].Value.ObjToBool(); } } else { //ViewModel DTO实体类 valRequired = Required; if (!string.IsNullOrWhiteSpace(DisplayName)) { valDisplayName = DisplayName; } } if (VerRequired) { valRequired = VerRequired; } string inputText = value == null ? "" : Convert.ToString(value); if (valRequired) { if (string.IsNullOrEmpty(inputText)) { return(new ValidationResult($"{valDisplayName}不能为空", new[] { valName })); } } //枚举类型 if (typeof(Enum) == valueBaseType) { if (!Enum.IsDefined(valueType, value)) { return(new ValidationResult($"{valDisplayName}的值不在枚举限定范围内", new[] { valName })); } } if (string.IsNullOrWhiteSpace(inputText)) { return(ValidationResult.Success); } //验证时间 if (typeof(DateTime) == valueType) { if (value.ObjToDate() == DateTime.MinValue) { return(new ValidationResult($"缺少{valDisplayName}", new[] { valName })); } } //验证长度范围 if (!string.IsNullOrWhiteSpace(LengthRange)) { var arr = LengthRange.SplitString("-"); var ipnutTextByteLength = inputText.ByteLength(); if (arr.Length == 2) { if (ipnutTextByteLength < arr[0].ObjToInt() || ipnutTextByteLength > arr[1].ObjToInt()) { return(new ValidationResult($"{valDisplayName}长度范围在{LengthRange}之间", new[] { valName })); } } else { var tempLength = LengthRange.ObjToInt(0); if (tempLength <= 0) { return(new ValidationResult($"{valDisplayName}LengthRange属性值有误", new[] { valName })); } else { if (ipnutTextByteLength != tempLength) { return(new ValidationResult($"{valDisplayName}长度为{tempLength}个字符", new[] { valName })); } } } } switch (ValidateType) { case ValidateType.None: break; case ValidateType.Email: if (!Common.Helper.ValidateHelper.IsEmail(inputText)) { return(new ValidationResult($"{valDisplayName}内容不是合法的邮箱", new[] { valName })); } break; case ValidateType.Date: inputText = inputText.Split(' ')[0].Replace("/", "-"); if (!Common.Helper.ValidateHelper.IsDate(inputText)) { return(new ValidationResult($"{valDisplayName}内容不是合法的日期", new[] { valName })); } break; case ValidateType.DateYear: if (!Common.Helper.ValidateHelper.IsDateYear(inputText)) { return(new ValidationResult($"{valDisplayName}内容不是合法的年份", new[] { valName })); } break; case ValidateType.DateMonth: if (!Common.Helper.ValidateHelper.IsDateMonth(inputText)) { return(new ValidationResult($"{valDisplayName}内容不是合法的月份", new[] { valName })); } break; case ValidateType.DateTime: inputText = inputText.Replace("/", "-").Replace(" 0:", " 00:"); if (!Common.Helper.ValidateHelper.IsDateTime(inputText)) { return(new ValidationResult($"{valDisplayName}内容不是合法的时间日期", new[] { valName })); } break; case ValidateType.Number: if (!Common.Helper.ValidateHelper.IsNumeric(inputText)) { return(new ValidationResult($"{valDisplayName}内容不是合法的数字", new[] { valName })); } break; case ValidateType.Money: if (!Common.Helper.ValidateHelper.IsMoney(inputText)) { return(new ValidationResult($"{valDisplayName}内容不是合法的非负金额", new[] { valName })); } break; case ValidateType.MoneyIncloudMinus: if (!Common.Helper.ValidateHelper.IsMoneyIncloudMinus(inputText)) { return(new ValidationResult($"{valDisplayName}内容不是合法的金额", new[] { valName })); } break; case ValidateType.IdNo: if (!Common.Helper.ValidateHelper.IsIdCard(inputText)) { return(new ValidationResult($"{valDisplayName}内容不是合法的身份证号码", new[] { valName })); } break; case ValidateType.CellPhone: if (!Common.Helper.ValidateHelper.IsCellPhone(inputText)) { return(new ValidationResult($"{valDisplayName}内容不是合法的手机号", new[] { valName })); } break; case ValidateType.WebURL: if (!Common.Helper.ValidateHelper.IsWebUrl(inputText)) { return(new ValidationResult($"{valDisplayName}内容不是合法的网址", new[] { valName })); } break; case ValidateType.AccountName: if (!Common.Helper.ValidateHelper.IsAccountName(inputText)) { return(new ValidationResult($"{valDisplayName}只能由数字、字母、下划线组成", new[] { valName })); } break; default: break; } if (!string.IsNullOrWhiteSpace(NumberRange)) { var arr = NumberRange.SplitString("-"); if (arr.Length != 2) { return(new ValidationResult($"{valDisplayName}LengthRange属性值有误", new[] { valName })); } var inputTextDecimal = inputText.ObjToDecimal(0); if (inputTextDecimal < arr[0].ObjToDecimal(0) || inputTextDecimal > arr[1].ObjToDecimal(0)) { return(new ValidationResult($"{valDisplayName}值范围在{NumberRange}之间", new[] { valName })); } } return(ValidationResult.Success); }
public NumberRangeClickEventArgs(NumberRange range) { this._range = range; }
void NumberEditor_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { if (PropertyNode == null) return; var type = PropertyNode.FirstProperty.ReturnType; var range = Metadata.GetValueRange(PropertyNode.FirstProperty); if (range == null) { range = new NumberRange() { Min = double.MinValue, Max = double.MaxValue }; } var nType = type; if (Nullable.GetUnderlyingType(type) != null) { nType = Nullable.GetUnderlyingType(type); } if (range.Min == double.MinValue) { Minimum = minimums[nType]; } else { Minimum = range.Min; } if (range.Max == double.MaxValue) { Maximum = maximums[nType]; } else { Maximum = range.Max; } if (type == typeof(double) || type == typeof(decimal)) { DecimalPlaces = 2; } // if (Minimum == 0 && Maximum == 1) { // DecimalPlaces = 2; // SmallChange = 0.01; // LargeChange = 0.1; // } // else { // ClearValue(DecimalPlacesProperty); // ClearValue(SmallChangeProperty); // ClearValue(LargeChangeProperty); // } }
public void WriteProperty(Property prop, XmlDocument doc, XmlNode node) { NumberRange value = prop.CastValue <NumberRange>(); node.InnerText = value.ToString() + ' '; }
protected static FR_Bool Execute(DbConnection Connection, DbTransaction Transaction, P_L5ZW_SDfNC_1707 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null) { #region UserCode var returnValue = new FR_Bool(); returnValue.Result = false; //Put your code here #region get securityTicket and businessParticipantID by Paramter.AccountID and set defaultLanguageID Guid tenantID; Guid businessParticipantID; if (Parameter.AccountID == Guid.Empty) { return(returnValue); } ORM_USR_Account orm_account = new ORM_USR_Account(); var result = orm_account.Load(Connection, Transaction, Parameter.AccountID); if (result.Status != FR_Status.Success || orm_account.USR_AccountID == Guid.Empty) { return(returnValue); } tenantID = orm_account.Tenant_RefID; securityTicket = new CSV2Core.SessionSecurity.SessionSecurityTicket() { TenantID = tenantID }; ORM_CMN_BPT_BusinessParticipant.Query businessParticipantQuery = new ORM_CMN_BPT_BusinessParticipant.Query(); businessParticipantQuery.IfTenant_Tenant_RefID = tenantID; businessParticipantQuery.IsDeleted = false; ORM_CMN_BPT_BusinessParticipant businessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, businessParticipantQuery).FirstOrDefault(); if (businessParticipant == null) { return(returnValue); } businessParticipantID = businessParticipant.CMN_BPT_BusinessParticipantID; #endregion #region get languages for tenant and set parameter dict values P_L2LN_GALFTID_1530 languageParam = new P_L2LN_GALFTID_1530() { Tenant_RefID = tenantID }; L2LN_GALFTID_1530[] languages = cls_Get_All_Languages_ForTenantID.Invoke(Connection, Transaction, languageParam, securityTicket).Result; SetParameterDictValues(Parameter, languages); List <ISOLanguage> languagesISOs = new List <ISOLanguage>(); languagesISOs.AddRange(languages.Select(l => new ISOLanguage() { ISO = l.ISO_639_1, LanguageID = l.CMN_LanguageID }).ToList()); #endregion #region save defaultLanguage // We are setting language for bp and acc var defaultLanguage = languages.FirstOrDefault(i => i.ISO_639_1.ToLower().Contains(Parameter.DefaultLanguageCode.ToLower())); if (defaultLanguage != null) { businessParticipant.DefaultLanguage_RefID = defaultLanguage.CMN_LanguageID; businessParticipant.Save(Connection, Transaction); orm_account.DefaultLanguage_RefID = defaultLanguage.CMN_LanguageID; orm_account.Save(Connection, Transaction); } #endregion #region save default country if (Parameter.DefaultCountry != null) { ORM_CMN_Country country = new ORM_CMN_Country(); country.CMN_CountryID = Guid.NewGuid(); country.Country_ISOCode_Alpha3 = Parameter.DefaultCountry.Code; country.Country_Name = new Dict() { DictionaryID = Guid.NewGuid() }; country.Creation_Timestamp = DateTime.Now; country.Default_Currency_RefID = Guid.Empty; country.Default_Language_RefID = Guid.Empty; country.Tenant_RefID = tenantID; country.IsDeleted = false; country.IsDefault = true; foreach (var languageItem in languages) { country.Country_Name.UpdateEntry(languageItem.CMN_LanguageID, Parameter.DefaultCountry.Name); } country.Save(Connection, Transaction); } #endregion #region save default currency //asign currency if (Parameter.DefaultCurrency != null) { ORM_CMN_Currency currency = new ORM_CMN_Currency(); currency.CMN_CurrencyID = Guid.NewGuid(); currency.Creation_Timestamp = DateTime.Now; currency.IsDeleted = false; currency.ISO4127 = Parameter.DefaultCurrency.Code; currency.Name = new Dict() { DictionaryID = Guid.NewGuid() }; currency.Tenant_RefID = tenantID; foreach (var language in languages) { currency.Name.UpdateEntry(language.CMN_LanguageID, Parameter.DefaultCurrency.Name); } currency.Save(Connection, Transaction); //set default currency ORM_CMN_BPT_BusinessParticipant businessPart = new ORM_CMN_BPT_BusinessParticipant(); businessPart.Load(Connection, Transaction, businessParticipantID); businessPart.DefaultCurrency_RefID = currency.CMN_CurrencyID; businessPart.Save(Connection, Transaction); } #endregion #region save organisational units if (Parameter.OrganisationalUnitParameters.Length > 0) { foreach (var item in Parameter.OrganisationalUnitParameters) { cls_Save_Office.Invoke(Connection, Transaction, item, securityTicket); } } #endregion #region save cost centers if (Parameter.CostCenterParameters.Length > 0) { foreach (var item in Parameter.CostCenterParameters) { cls_Save_CostCenter.Invoke(Connection, Transaction, item, securityTicket); } } #endregion #region save warehouses if (Parameter.WarehousesParameters.Length > 0) { #region save warehouse group P_L2WH_SWHG_1327 warehouseGroupParam = new P_L2WH_SWHG_1327(); warehouseGroupParam.Parent_RefID = Guid.Empty; warehouseGroupParam.WarehouseGroup_Name = "Waregouse group"; warehouseGroupParam.WarehouseGroup_Description = new Dict() { DictionaryID = Guid.NewGuid() }; foreach (var language in languages) { warehouseGroupParam.WarehouseGroup_Description.UpdateEntry(language.CMN_LanguageID, String.Empty); } var warehouseGroupID = cls_Save_Warehouse_Group.Invoke(Connection, Transaction, warehouseGroupParam, securityTicket).Result; #endregion foreach (var item in Parameter.WarehousesParameters) { item.LOG_WRH_WarehouseGroupID = warehouseGroupID; cls_Save_Warehouse.Invoke(Connection, Transaction, item, securityTicket); } } #endregion #region create dimension templates string jsonTemplates = ReadFromFile.LoadContentFromFile(@"Dimensions.json"); List <Dimension> dimensionTemplates = JsonConvert.DeserializeObject <List <Dimension> >(jsonTemplates); int orderSequence = 1; ORM_CMN_PRO_Dimension orm_dimension; ORM_CMN_PRO_Dimension_Value orm_dimensionValue; foreach (var template in dimensionTemplates) { orderSequence = 1; #region save dimension orm_dimension = new ORM_CMN_PRO_Dimension(); orm_dimension.Product_RefID = Guid.Empty; orm_dimension.DimensionName = new Dict() { DictionaryID = Guid.NewGuid() }; orm_dimension.IsDimensionTemplate = true; orm_dimension.Tenant_RefID = tenantID; foreach (var language in languages) { orm_dimension.DimensionName.UpdateEntry(language.CMN_LanguageID, template.Name); } orm_dimension.Save(Connection, Transaction); #endregion #region save dimension values foreach (var templateValue in template.DimansionValues) { orm_dimensionValue = new ORM_CMN_PRO_Dimension_Value(); orm_dimensionValue.Dimensions_RefID = orm_dimension.CMN_PRO_DimensionID; orm_dimensionValue.DimensionValue_Text = new Dict() { DictionaryID = Guid.NewGuid() }; orm_dimensionValue.Tenant_RefID = tenantID; orm_dimensionValue.OrderSequence = orderSequence; foreach (var language in languages) { orm_dimensionValue.DimensionValue_Text.UpdateEntry(language.CMN_LanguageID, templateValue); } orm_dimensionValue.Save(Connection, Transaction); orderSequence++; } #endregion } #endregion #region create shipment types string shipmentTypesJson = ReadFromFile.LoadContentFromFile(@"ShipmentTypes.json"); List <ShipmentTypes> shipmentTypes = JsonConvert.DeserializeObject <List <ShipmentTypes> >(shipmentTypesJson); ORM_LOG_SHP_Shipment_Type orm_shipmentType; foreach (var type in shipmentTypes) { #region save LOG_SHP_Shipment_Type orm_shipmentType = new ORM_LOG_SHP_Shipment_Type(); orm_shipmentType.ShipmentType_Name = new Dict() { DictionaryID = Guid.NewGuid() }; orm_shipmentType.ShipmentType_Description = new Dict() { DictionaryID = Guid.NewGuid() }; orm_shipmentType.Tenant_RefID = tenantID; foreach (var language in languages) { orm_shipmentType.ShipmentType_Name.UpdateEntry(language.CMN_LanguageID, type.Name); orm_shipmentType.ShipmentType_Description.UpdateEntry(language.CMN_LanguageID, string.Empty); } orm_shipmentType.Save(Connection, Transaction); #endregion } #endregion #region create number ranges string numberRangesJson = ReadFromFile.LoadContentFromFile(@"NumberRanges.json"); NumberRange numberRanges = JsonConvert.DeserializeObject <NumberRange>(numberRangesJson); ORM_CMN_NumberRange_UsageArea numberRangeUsageArea; ORM_CMN_NumberRange orm_numberRanges; foreach (var item in numberRanges.NumberRanges) { if (Parameter.IsCustomerRegistration && item.Name == "Customer orders") { continue; } if (!Parameter.IsCustomerRegistration && item.Name == "Distribution orders") { continue; } if (!Parameter.IsCustomerRegistration && item.Name == "Procurement orders") { continue; } numberRangeUsageArea = new ORM_CMN_NumberRange_UsageArea(); numberRangeUsageArea.UsageArea_Name = new Dict() { DictionaryID = Guid.NewGuid() }; numberRangeUsageArea.UsageArea_Description = new Dict() { DictionaryID = Guid.NewGuid() }; foreach (var language in languages) { numberRangeUsageArea.UsageArea_Name.UpdateEntry(language.CMN_LanguageID, item.Name); numberRangeUsageArea.UsageArea_Description.UpdateEntry(language.CMN_LanguageID, string.Empty); } numberRangeUsageArea.Tenant_RefID = tenantID; numberRangeUsageArea.GlobalStaticMatchingID = item.GlobalStaticMatchingID; numberRangeUsageArea.Save(Connection, Transaction); orm_numberRanges = new ORM_CMN_NumberRange(); orm_numberRanges.NumberRange_Name = item.Name; orm_numberRanges.Tenant_RefID = tenantID; orm_numberRanges.NumberRange_UsageArea_RefID = numberRangeUsageArea.CMN_NumberRange_UsageAreaID; orm_numberRanges.FixedPrefix = item.FixedPrefix; orm_numberRanges.Formatting_LeadingFillCharacter = item.FillCharacter; orm_numberRanges.Formatting_NumberLength = item.Length; orm_numberRanges.Value_Current = item.CurrentValue; orm_numberRanges.Value_Start = item.StartValue; orm_numberRanges.Value_End = item.EndValue; orm_numberRanges.Save(Connection, Transaction); } #endregion #region create inventory change reasons string inventoryChangeReasonsJson = ReadFromFile.LoadContentFromFile(@"InventoryChangeReasons.json"); List <InventoryChangeReasons> inventoryChangeReasons = JsonConvert.DeserializeObject <List <InventoryChangeReasons> >(inventoryChangeReasonsJson); ORM_LOG_WRH_InventoryChangeReason orm_inventoryChangeReason; foreach (var reason in inventoryChangeReasons) { #region save inventory change reason orm_inventoryChangeReason = new ORM_LOG_WRH_InventoryChangeReason(); orm_inventoryChangeReason.GlobalPropertyMatchingID = InventoryChangeReasons.InventoryChangeReasonGlobalPropertyMatchingID + "-" + reason.Name; orm_inventoryChangeReason.InventoryChange_Name = new Dict() { DictionaryID = Guid.NewGuid() }; orm_inventoryChangeReason.InventoryChange_Description = new Dict() { DictionaryID = Guid.NewGuid() }; orm_inventoryChangeReason.Tenant_RefID = tenantID; foreach (var language in languages) { orm_inventoryChangeReason.InventoryChange_Name.UpdateEntry(language.CMN_LanguageID, reason.Name); orm_inventoryChangeReason.InventoryChange_Description.UpdateEntry(language.CMN_LanguageID, string.Empty); } orm_inventoryChangeReason.Save(Connection, Transaction); #endregion } #endregion #region create shipment statuses var shipmentStatuses = Enum.GetValues(typeof(EShipmentStatus)); var shipmentStatusDicts = EnumUtils.GetDictObjectsForStaticListData <EShipmentStatus>( ResourceFilePath.ShipmentStatus, ORM_LOG_SHP_Shipment_Status.TableName, languagesISOs); var statusCodeCount = 1; ORM_LOG_SHP_Shipment_Status shipmentStatus; foreach (EShipmentStatus status in shipmentStatuses) { shipmentStatus = new ORM_LOG_SHP_Shipment_Status(); shipmentStatus.GlobalPropertyMatchingID = EnumUtils.GetEnumDescription((EShipmentStatus)status); shipmentStatus.Status_Code = statusCodeCount++; shipmentStatus.Status_Name = shipmentStatusDicts[EnumUtils.GetEnumDescription((EShipmentStatus)status)]; shipmentStatus.Tenant_RefID = tenantID; shipmentStatus.Save(Connection, Transaction); } #endregion if (Parameter.IsCustomerRegistration) { #region create procurement order statuses var procurementStatuses = Enum.GetValues(typeof(EProcurementStatus)); ORM_ORD_PRC_ProcurementOrder_Status procurementOrderStatus; foreach (EProcurementStatus status in procurementStatuses) { procurementOrderStatus = new ORM_ORD_PRC_ProcurementOrder_Status(); procurementOrderStatus.GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(status); procurementOrderStatus.Tenant_RefID = tenantID; procurementOrderStatus.Save(Connection, Transaction); } #endregion } else { #region create customer order statuses var customerOrderStatuses = Enum.GetValues(typeof(ECustomerOrderStatus)); var customerOrderStatusesDicts = EnumUtils.GetDictObjectsForStaticListData <ECustomerOrderStatus>( ResourceFilePath.CustomerOrderStatus, ORM_ORD_CUO_CustomerOrder_Status.TableName, languagesISOs); var count = 1; ORM_ORD_CUO_CustomerOrder_Status customerOrderStatus; foreach (var status in customerOrderStatuses) { customerOrderStatus = new ORM_ORD_CUO_CustomerOrder_Status(); customerOrderStatus.GlobalPropertyMatchingID = EnumUtils.GetEnumDescription((ECustomerOrderStatus)status); customerOrderStatus.Status_Code = count++; customerOrderStatus.Status_Name = customerOrderStatusesDicts[EnumUtils.GetEnumDescription((ECustomerOrderStatus)status)]; customerOrderStatus.Tenant_RefID = tenantID; customerOrderStatus.Save(Connection, Transaction); } #endregion } returnValue.Result = true; return(returnValue); #endregion UserCode }