public override object FormatValue(object value) { if (value == null) { return("NULL"); } else { var type = UtilMethods.GetUnderType(value.GetType()); if (type == UtilConstants.DateType) { var date = value.ObjToDate(); if (date < Convert.ToDateTime("1900-1-1")) { date = Convert.ToDateTime("1900-1-1"); } return("'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'"); } else if (type.IsEnum()) { return(Convert.ToInt64(value)); } else if (type == UtilConstants.ByteArrayType) { string bytesString = "0x" + BitConverter.ToString((byte[])value); return(bytesString); } else if (type == UtilConstants.BoolType) { return(value.ObjToBool() ? "1" : "0"); } else if (type == UtilConstants.StringType || type == UtilConstants.ObjType) { return("'" + value.ToString().ToSqlFilter() + "'"); } else { return("'" + value.ToString() + "'"); } } }
private static void AddIdentificationList(QueryBuilder queryBuilder, CacheKey result) { result.IdentificationList = new List <string>(); result.IdentificationList.Add(queryBuilder.GetTableNameString); result.IdentificationList.Add(queryBuilder.GetJoinValueString); result.IdentificationList.Add(queryBuilder.GetOrderByString); result.IdentificationList.Add(queryBuilder.GetGroupByString); result.IdentificationList.Add(queryBuilder.GetWhereValueString); result.IdentificationList.Add(queryBuilder.PartitionByValue); result.IdentificationList.Add(queryBuilder.Take.ObjToString()); result.IdentificationList.Add(queryBuilder.Skip.ObjToString()); result.IdentificationList.Add(queryBuilder.IsCount.ObjToString()); result.IdentificationList.Add(UtilMethods.GetMD5(queryBuilder.GetSelectValue.ObjToString())); if (queryBuilder.Parameters.HasValue()) { foreach (var item in queryBuilder.Parameters) { result.IdentificationList.Add(item.ParameterName + "_" + item.Value); } } }
public bool LoadScript(TextAsset textAsset) { #if txt index = 0; txt = new List <string>(); StreamReader stream = new StreamReader(path); while (!stream.EndOfStream) { txt.Add(stream.ReadLine()); } stream.Close(); #elif json #region 读取json文件 fDatas = UtilMethods <BaseData> .JsonToEntity(textAsset.text, true); return(true); #endregion #elif test #endif }
private void ToWalkState() { bool targetWithinMap = false; int debugCounter = 0; while (!targetWithinMap && debugCounter < 20) { Vector3 offset = new Vector3( Random.Range(minDistance, maxDistance) * UtilMethods.RandSign(), Random.Range(minDistance, maxDistance) * UtilMethods.RandSign()); Vector3.ClampMagnitude(offset, maxDistance); target = player.transform.position + offset; targetWithinMap = map.WithinOpenCells(target); debugCounter++; } if (debugCounter >= 20) { Debug.LogError("Took 20+ tries to find a position!"); } state = State.Walk; }
private IEnumerator CameraShake(float time, float magnitude, bool vertical, bool horizontal) { while (time > 0) { time -= Time.unscaledDeltaTime; float randX = 0; float randY = 0; if (horizontal) { randX = UtilMethods.RandSign() * magnitude; } if (vertical) { randY = UtilMethods.RandSign() * magnitude; } cam.transform.localPosition = new Vector3(randX, randY, -10); yield return(null); } cam.transform.localPosition = new Vector3(0, 0, -10); }
private static void GetValueTypeList <T>(Type type, IDataReader dataReader, List <T> result) { var value = dataReader.GetValue(0); if (type == UtilConstants.GuidType) { value = Guid.Parse(value.ToString()); } if (value == DBNull.Value) { result.Add(default(T)); } else if (type.IsEnum) { result.Add((T)Enum.Parse(type, value.ObjToString())); } else { result.Add((T)Convert.ChangeType(value, UtilMethods.GetUnderType(type))); } }
protected virtual bool IsSamgeType(EntityColumnInfo ec, DbColumnInfo dc) { if (!string.IsNullOrEmpty(ec.DataType)) { return(ec.DataType != dc.DataType); } var propertyType = UtilMethods.GetUnderType(ec.PropertyInfo); var properyTypeName = string.Empty; if (propertyType.IsEnum()) { properyTypeName = this.Context.Ado.DbBind.GetDbTypeName(ec.Length > 9 ? UtilConstants.LongType.Name : UtilConstants.IntType.Name); } else { properyTypeName = this.Context.Ado.DbBind.GetDbTypeName(propertyType.Name); } var dataType = dc.DataType; return(properyTypeName != dataType); }
public async Task <IActionResult> StoreHistory(int?id) { /// <summary> /// The store order history page /// </summary> if (id == null) { return(NotFound()); } int thisLocId = (int)id; if (!UtilMethods.LogInCheck(_cache)) { return(Redirect("/Login")); } var thisLocation = await _context.Locations .FirstOrDefaultAsync(m => m.LocationId == thisLocId); if (thisLocation == null) { return(NotFound()); } var foundOrderItems = from thisTableItem in _context.OrderItems where thisTableItem.LocationId == thisLocation.LocationId select thisTableItem; List <OrderItem> theseOrderItems = foundOrderItems.ToList <OrderItem>(); List <OrderItemViewModel> theseOrderItemViewModels = new List <OrderItemViewModel>(); foreach (OrderItem thisOrderItem in theseOrderItems) { Customer thisCustomer = await _context.Customers .FirstOrDefaultAsync(m => m.CustomerId == thisOrderItem.CustomerId); OrderItemViewModel thisOrderItemViewModel = UtilMethods.BuildOrderItemViewModelFromCustOrder(thisCustomer, thisOrderItem, _context); theseOrderItemViewModels.Add(thisOrderItemViewModel); } ViewData["storeaddress"] = thisLocation.LocationAddress; ViewData["cartcount"] = UtilMethods.GetCartCount(_cache); return(View(theseOrderItemViewModels)); }
private async Task LoadAssets(LoadAssets payload, Action onCompleteCallback) { LoaderFunction loader; switch (payload.Source.ContainerType) { case AssetContainerType.GLTF: loader = LoadAssetsFromGLTF; break; default: throw new Exception( $"Cannot load assets from unknown container type {payload.Source.ContainerType.ToString()}"); } IList <Asset> assets = null; string failureMessage = null; // attempt to get cached assets instead of loading try { assets = await loader(payload.Source, payload.ContainerId, payload.ColliderType); } catch (Exception e) { failureMessage = UtilMethods.FormatException( $"An unexpected error occurred while loading the asset [{payload.Source.Uri}].", e); } _app.Protocol.Send(new Message() { ReplyToId = payload.MessageId, Payload = new AssetsLoaded() { FailureMessage = failureMessage, Assets = assets ?? new Asset[] { } } }); onCompleteCallback?.Invoke(); }
public bool ClearCacheForFiles(IEnumerable <string> filenames) { string cachePath = GetCachePath(); bool allFilesCleared = true; try { if (Directory.Exists(cachePath)) { var files = UtilMethods.EnumerateFiles(cachePath, "*.png", SearchOption.AllDirectories); files = files.Where(f => filenames.Any(n => f.Contains(n))); logger.Info("Clearing cache for specific files. Detected {fileCount} files.", files.Count()); foreach (var filePath in files) { try { File.Delete(filePath); } catch (Exception ex) { allFilesCleared = false; logger.Trace(ex, "Error deleting cache for specific file: {filePath}", filePath); } } } else { logger.Info("Clearing cache for specific files... Cache path not found! {cachePath}", cachePath); } } catch (Exception ex) { logger.Trace(ex, "Exception calculating cache size for specific files"); return(false); } return(allFilesCleared); }
public static async Task EditableKomponents([EntityTrigger] IDurableEntityContext context, ILogger logger) { int currentValue = context.GetState <int>(); int operant = context.GetInput <int>(); switch (context.OperationName) { case "add": currentValue += operant; break; case "remove": currentValue -= operant; break; case "reset": await UtilMethods.SendKnotifyAsync(); currentValue = 0; break; } context.SetState(currentValue); }
protected override DbColumnInfo EntityColumnToDbColumn(EntityInfo entityInfo, string tableName, EntityColumnInfo item) { var propertyType = UtilMethods.GetUnderType(item.PropertyInfo); var result = new DbColumnInfo() { TableId = entityInfo.Columns.IndexOf(item), DbColumnName = item.DbColumnName.HasValue() ? item.DbColumnName : item.PropertyName, IsPrimarykey = item.IsPrimarykey, IsIdentity = item.IsIdentity, TableName = tableName, IsNullable = item.IsNullable, DefaultValue = item.DefaultValue, ColumnDescription = item.ColumnDescription, Length = item.Length }; GetDbType(item, propertyType, result); if (result.DataType.Equals("varchar", StringComparison.CurrentCultureIgnoreCase) && result.Length == 0) { result.Length = 1; } return(result); }
public IActionResult History() { /// <summary> /// User order history page /// </summary> if (!UtilMethods.LogInCheck(_cache)) { return(Redirect("/Login")); } Customer thisCustomer = (Customer)_cache.Get("thisCustomer"); var foundOrderItems = _context.OrderItems.Where(m => m.CustomerId == thisCustomer.CustomerId); List <OrderItem> theseOrderItems = foundOrderItems.ToList <OrderItem>(); List <OrderItemViewModel> theseOrderItemViewModels = new List <OrderItemViewModel>(); foreach (OrderItem thisOrderItem in theseOrderItems) { OrderItemViewModel thisOrderItemViewModel = UtilMethods.BuildOrderItemViewModelFromCustOrder(thisCustomer, thisOrderItem, _context); theseOrderItemViewModels.Add(thisOrderItemViewModel); } ViewData["userName"] = $"{thisCustomer.FirstName} {thisCustomer.LastName}"; ViewData["cartcount"] = UtilMethods.GetCartCount(_cache); return(View(theseOrderItemViewModels)); }
private void ResolveHasValue(ExpressionParameter parameter, MemberExpression expression) { parameter.CommonTempData = CommonTempDataType.Result; this.Expression = expression.Expression; this.Start(); var methodParamter = new MethodCallExpressionArgs() { IsMember = true, MemberName = parameter.CommonTempData, MemberValue = null }; if (expression.Expression?.Type != null) { methodParamter.Type = UtilMethods.GetUnderType(expression.Expression?.Type); } var result = this.Context.DbMehtods.HasValue(new MethodCallExpressionModel() { Args = new List <MethodCallExpressionArgs>() { methodParamter } }); if (parameter.BaseExpression != null && ExpressionTool.IsLogicOperator(parameter.BaseExpression) && parameter.IsLeft == true) { if (base.Context.Result.Contains(ExpressionConst.FormatSymbol)) { base.Context.Result.Replace(ExpressionConst.FormatSymbol, ""); } this.Context.Result.Append(result + " " + ExpressionTool.GetOperator(parameter.BaseExpression.NodeType) + " "); } else { this.Context.Result.Append(result); } parameter.CommonTempData = null; }
public async Task <IActionResult> LocationDetails(int?id) { /// <summary> /// The store stocks page /// </summary> if (id == null) { return(NotFound()); } int thisLocId = (int)id; if (!UtilMethods.LogInCheck(_cache)) { return(Redirect("/Login")); } var thisLocation = await _context.Locations .FirstOrDefaultAsync(m => m.LocationId == thisLocId); if (thisLocation == null) { return(NotFound()); } var foundStockItems = from thisTableItem in _context.StockItems where thisTableItem.LocationId == thisLocation.LocationId select thisTableItem; List <StockItem> theseStockItems = foundStockItems.ToList <StockItem>(); List <StockItemViewModel> theseStockItemViewModels = new List <StockItemViewModel>(); foreach (StockItem thisStockItem in theseStockItems) { StockItemViewModel thisStockItemViewModel = UtilMethods.BuildStockItemViewModelFromLocStock(thisLocation, thisStockItem, _context); theseStockItemViewModels.Add(thisStockItemViewModel); } ViewData["cartcount"] = UtilMethods.GetCartCount(_cache); return(View(theseStockItemViewModels)); }
public async Task <IActionResult> Register([Bind("CustomerId,UserName,FirstName,LastName,Password,DateAdded")] Customer customer) { /// <summary> /// Registers a new customer /// </summary> if (ModelState.IsValid) { Customer checkCust = UtilMethods.GetCustomerByUserName(customer.UserName, _context); if (checkCust.UserName != null) { System.Diagnostics.Debug.WriteLine($"Customer with user name {customer.UserName} already exists"); return(Redirect("/Login/Register?warn=duplicate")); } else { customer.DateAdded = DateTime.Now; _context.Add(customer); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } return(View(customer)); }
public static RigidBodyPatch GeneratePatch(RigidBody _old, Rigidbody _new, Transform sceneRoot) { if (_old == null && _new != null) { return(new RigidBodyPatch(_new, sceneRoot)); } else if (_new == null) { return(null); } var patch = new RigidBodyPatch() { // Do not include Position or Rotation in the patch. Velocity = GeneratePatch(_old.Velocity, sceneRoot.InverseTransformDirection(_new.velocity)), AngularVelocity = GeneratePatch(_old.AngularVelocity, sceneRoot.InverseTransformDirection(_new.angularVelocity)), CollisionDetectionMode = GeneratePatch( _old.CollisionDetectionMode, UtilMethods.ConvertEnum <MRECollisionDetectionMode, UnityCollisionDetectionMode>(_new.collisionDetectionMode)), ConstraintFlags = GeneratePatch( _old.ConstraintFlags, UtilMethods.ConvertEnum <MRERigidBodyConstraints, UnityRigidBodyConstraints>(_new.constraints)), DetectCollisions = GeneratePatch(_old.DetectCollisions, _new.detectCollisions), Mass = GeneratePatch(_old.Mass, _new.mass), UseGravity = GeneratePatch(_old.UseGravity, _new.useGravity), }; if (patch.IsPatched()) { return(patch); } else { return(null); } }
public IEnumerable <Tuple <int, BitmapSource> > GetThumbnailsImages(string filePath, string fileName, RenderAspectEnum renderType) { Tuple <int, BitmapSource>[] loadedFiles = new Tuple <int, BitmapSource> [0]; string cachePath = GetCachePath(); string filesNameForFilter = GetComposedFileNameForFilter(fileName, filePath, renderType); try { if (Directory.Exists(cachePath)) { var files = UtilMethods.EnumerateFiles(cachePath, filesNameForFilter, SearchOption.AllDirectories); loadedFiles = new Tuple <int, BitmapSource> [files.Count()]; int i = 0; foreach (var foundFile in files) { using (var file = File.OpenRead(foundFile)) { BitmapSource bmp = LoadImageFromStream(file); loadedFiles[i] = new Tuple <int, BitmapSource>(GetFileSizeFromFileName(foundFile), bmp); } i++; } } } catch (Exception ex) { logger.Trace(ex, "Exception loading cache file images for {fullpath} as {renderType}", Path.Combine(filePath, fileName), renderType.ToString()); } /* * if (loadedFiles.Length == 0) logger.Info("No cache files found for {filePath} as {filesNameForFilter}", Path.Combine(filePath, fileName), filesNameForFilter); * else logger.Info("Loaded {fileCount} cache files found for {filePath} as {filesNameForFilter}", loadedFiles.Length, Path.Combine(filePath, fileName), filesNameForFilter); */ return(loadedFiles); }
private void SetInsertItemByEntity(int i, T item, List <DbColumnInfo> insertItem) { if (item == null) { return; } foreach (var column in EntityInfo.Columns) { if (column.IsIgnore || column.IsOnlyIgnoreInsert) { continue; } var columnInfo = new DbColumnInfo() { Value = column.PropertyInfo.GetValue(item, null), DbColumnName = GetDbColumnName(column.PropertyName), PropertyName = column.PropertyName, PropertyType = UtilMethods.GetUnderType(column.PropertyInfo), TableId = i }; if (columnInfo.PropertyType.IsEnum()) { columnInfo.Value = Convert.ToInt64(columnInfo.Value); } if (column.IsJson && columnInfo.Value != null) { columnInfo.Value = this.Context.Utilities.SerializeObject(columnInfo.Value); } var tranColumn = EntityInfo.Columns.FirstOrDefault(it => it.IsTranscoding && it.DbColumnName.Equals(column.DbColumnName, StringComparison.CurrentCultureIgnoreCase)); if (tranColumn != null && columnInfo.Value.HasValue()) { columnInfo.Value = UtilMethods.EncodeBase64(columnInfo.Value.ToString()); } insertItem.Add(columnInfo); } }
/// <summary> /// Generate rigid body transform snapshot for owned transforms with specified timestamp. /// </summary> /// <param name="time">Snapshot timestamp.</param> /// <param name="rootTransform">Root transform.</param> /// <returns>Generated snapshot.</returns> public Snapshot GenerateSnapshot(float time, UnityEngine.Transform rootTransform) { // collect transforms from owned rigid bodies // and generate update packet/snapshot // these constants define when a body is considered to be sleeping const float globalToleranceMultipier = 1.0F; const float maxSleepingSqrtLinearVelocity = 0.1F * globalToleranceMultipier; const float maxSleepingSqrtAngularVelocity = 0.1F * globalToleranceMultipier; const float maxSleepingSqrtPositionDiff = 0.02F * globalToleranceMultipier; const float maxSleepingSqrtAngularEulerDiff = 0.15F * globalToleranceMultipier; const short limitNoUpdateForSleepingBodies = 500; const short numConsecutiveSleepingTrueConditionForNoUpdate = 5; int numSleepingBodies = 0; int numOwnedBodies = 0; List <Snapshot.TransformInfo> transforms = new List <Snapshot.TransformInfo>(_rigidBodies.Count); foreach (var rb in _rigidBodies.Values) { if (!rb.Ownership) { rb.numOfConsequentSleepingFrames = 0; continue; } RigidBodyTransform transform; { transform.Position = rootTransform.InverseTransformPoint(rb.RigidBody.transform.position); transform.Rotation = UnityEngine.Quaternion.Inverse(rootTransform.rotation) * rb.RigidBody.transform.rotation; } numOwnedBodies++; Patching.Types.MotionType mType = (rb.IsKeyframed) ? (Patching.Types.MotionType.Keyframed) : (Patching.Types.MotionType.Dynamic); UnityEngine.Vector3 posDiff = rb.lastValidLinerVelocityOrPos - transform.Position; UnityEngine.Vector3 rotDiff = UtilMethods.TransformEulerAnglesToRadians(rb.lastValidAngularVelocityorAng - transform.Rotation.eulerAngles); bool isBodySleepingInThisFrame = (!rb.IsKeyframed) && // if body is key framed and owned then we should just feed the jitter buffer (rb.RigidBody.velocity.sqrMagnitude < maxSleepingSqrtLinearVelocity && rb.RigidBody.angularVelocity.sqrMagnitude < maxSleepingSqrtAngularVelocity && posDiff.sqrMagnitude < maxSleepingSqrtPositionDiff && rotDiff.sqrMagnitude < maxSleepingSqrtAngularEulerDiff); if (isBodySleepingInThisFrame) { rb.numOfConsequentSleepingFrames++; rb.numOfConsequentSleepingFrames = (rb.numOfConsequentSleepingFrames > (short)limitNoUpdateForSleepingBodies) ? (short)limitNoUpdateForSleepingBodies : rb.numOfConsequentSleepingFrames; } else { rb.numOfConsequentSleepingFrames = 0; } // this is the real condition to put a body to sleep bool isBodySleeping = (rb.numOfConsequentSleepingFrames > numConsecutiveSleepingTrueConditionForNoUpdate); // test if this is sleeping, and when this was newly added then if (rb.lastTimeKeyFramedUpdate > 0.001F && isBodySleeping && rb.sendMotionType == Patching.Types.MotionType.Sleeping && rb.numOfConsequentSleepingFrames < limitNoUpdateForSleepingBodies) { // condition for velocity and positions are triggered and we already told the consumers to make body sleep, so just skip this update numSleepingBodies++; continue; } mType = (isBodySleeping) ? (Patching.Types.MotionType.Sleeping) : mType; // here we handle the case when after of 300 frames with no update we should send one update at least if (rb.numOfConsequentSleepingFrames >= limitNoUpdateForSleepingBodies) { rb.numOfConsequentSleepingFrames = numConsecutiveSleepingTrueConditionForNoUpdate + 1; } // store the last update informations rb.sendMotionType = mType; rb.lastTimeKeyFramedUpdate = time; rb.lastValidLinerVelocityOrPos = transform.Position; rb.lastValidAngularVelocityorAng = transform.Rotation.eulerAngles; transforms.Add(new Snapshot.TransformInfo(rb.Id, transform, mType)); #if MRE_PHYSICS_DEBUG Debug.Log(" SEND Remote body: " + rb.Id.ToString() + " OriginalRot:" + transform.Rotation + " RigidBodyRot:" + rb.RigidBody.transform.rotation + " lv:" + rb.RigidBody.velocity + " av:" + rb.RigidBody.angularVelocity + " posDiff:" + posDiff + " rotDiff:" + rotDiff + " isKeyF:" + rb.IsKeyframed); #endif } Snapshot.SnapshotFlags snapshotFlag = Snapshot.SnapshotFlags.NoFlags; bool allBodiesAreSleepingNew = numOwnedBodies == numSleepingBodies; if (allBodiesAreSleepingNew != _allOwnedBodiesAreSleeping) { _allOwnedBodiesAreSleeping = allBodiesAreSleepingNew; snapshotFlag = Snapshot.SnapshotFlags.ResetJitterBuffer; } _lastNumberOfTransformsToBeSent = numOwnedBodies; var ret = new Snapshot(time, transforms, snapshotFlag); #if MRE_PHYSICS_DEBUG Debug.Log(" Client:" + " Total number of sleeping bodies: " + numSleepingBodies + " total RBs" + _rigidBodies.Count + " num owned " + numOwnedBodies + " num sent transforms " + transforms.Count + " send:" + ret.DoSendThisSnapshot()); #endif return(ret); }
public List <Note> Detection() { List <Note> noteList = new List <Note>(); //Console.WriteLine("Press any key to convert to .WAV file..."); //Console.ReadLine(); int i; //Open MP3 file and convert to WAV file. WaveOutEvent waveOut = new WaveOutEvent(); Mp3FileReader mp3Reader = new Mp3FileReader(@"C:\Users\Fazle\source\repos\Practice\Media\twinkle.mp3"); toWAV(mp3Reader); //Console.WriteLine(".WAV file created! Press any key to continue..."); //Console.ReadLine(); StereoToMono(@"C:\Users\Fazle\source\repos\Practice\Media\current.wav"); int sampleRate; double[] data = null, R = null; ReadWavFile(out sampleRate); openWav(@"C:\Users\Fazle\source\repos\Practice\Media\currentMono.wav", out data, out R); //Console.WriteLine(data.Length); Progress <string> progress = new Progress <string>(); OnsetDetector detector = new OnsetDetector(DetectorOptions.Default, progress); List <Onset> list = detector.Detect(@"C:\Users\Fazle\source\repos\Practice\Media\currentMono.wav"); /*Console.WriteLine("Time Amp"); * for (i = 0; i < list.Count; i++) * { * Console.Write(list[i].OnsetTime); * Console.Write(" "); * Console.Write(list[i].OnsetAmplitude); * Console.Write(" "); * Console.WriteLine(); * } * Console.WriteLine();*/ int startPos = 0, stopPos = 0, flag = 0; double freq = 0, duration = 0; double[] temp; double[] result; CSCore.Utils.Complex[] complex; for (i = 0; i < list.Count - 1; i++) { startPos = (int)Math.Ceiling(list[i].OnsetTime * sampleRate); stopPos = (int)Math.Floor(list[i + 1].OnsetTime * sampleRate); temp = new double[stopPos - startPos]; result = new double[stopPos - startPos]; complex = new CSCore.Utils.Complex[stopPos - startPos]; Array.ConstrainedCopy(data, startPos, temp, 0, temp.Length); for (int j = 0; j < complex.Length; j++) { complex[j] = new Complex((float)temp[j]); //Console.WriteLine(complex[j]); } //Console.ReadLine(); Note note = new Note(); note.Frequency = CalculateFFT(result, complex, flag); note.Name = UtilMethods.FreqToNote(note.Frequency); note.Duration = list[i + 1].OnsetTime - list[i].OnsetTime; noteList.Add(note); } //Last Note startPos = (int)Math.Floor(list[i].OnsetTime * sampleRate); stopPos = data.Length - 1; temp = new double[stopPos - startPos]; result = new double[stopPos - startPos]; complex = new CSCore.Utils.Complex[stopPos - startPos]; Array.ConstrainedCopy(data, startPos, temp, 0, temp.Length); for (int j = 0; j < complex.Length; j++) { complex[j] = new Complex((float)temp[j]); } flag = 1; Note lastNote = new Note(); lastNote.Frequency = CalculateFFT(result, complex, flag); lastNote.Name = UtilMethods.FreqToNote(lastNote.Frequency); lastNote.Duration = (data.Length / sampleRate) - list[i].OnsetTime; noteList.Add(lastNote); //Console.WriteLine("Press any key to terminate."); //Console.ReadLine(); mp3Reader.Dispose(); return(noteList); }
protected static FR_CAS_CGR_1400 Execute(DbConnection connection, DbTransaction transaction, P_CAS_CGR_1400 parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null) { #region UserCode var returnValue = new FR_CAS_CGR_1400(); returnValue.Result = new CAS_CGR_1400(); Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE"); string downloadURL = ""; Guid prev_case_id = Guid.Empty; DateTime DateForElastic = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local); var cases = cls_Generate_Report.Invoke(connection, transaction, new P_CAS_GR_1608() { }, securityTicket, parameter.ShowOnlyAok).Result.cases.ToList(); List <Documents> documentList = new List <Documents>(); if (cases.Count() > 0) { Documents documentExcel = new Documents(); // documentExcel.documentName = "ExcelReport" + DateTime.Now.ToString("dd.MM.yyyy_HH.mm"); if (parameter.ShowOnlyAok.HasValue) { if (parameter.ShowOnlyAok.Value == true) { documentExcel.documentName = "AokReport" + DateTime.Now.ToString("dd.MM.yyyy_HH.mm"); } else { documentExcel.documentName = "!AokReport" + DateTime.Now.ToString("dd.MM.yyyy_HH.mm"); } } else { documentExcel.documentName = "ExcelReport" + DateTime.Now.ToString("dd.MM.yyyy_HH.mm"); } documentExcel.documentOutputLocation = GenerateReportCases.CreateCaseXlsReport(cases, documentExcel.documentName); documentExcel.mimeType = UtilMethods.GetMimeType(documentExcel.documentOutputLocation); documentExcel.receiver = "MM"; documentList.Add(documentExcel); foreach (var item in documentList) { MemoryStream ms = new MemoryStream(File.ReadAllBytes(item.documentOutputLocation)); byte[] byteArrayFile = ms.ToArray(); var _providerFactory = ProviderFactory.Instance; var documentProvider = _providerFactory.CreateDocumentServiceProvider(); var uploadedFrom = HttpContext.Current.Request.UserHostAddress; Guid documentID = documentProvider.UploadDocument(byteArrayFile, item.documentOutputLocation, securityTicket.SessionTicket, uploadedFrom); downloadURL = documentProvider.GenerateDownloadLink(documentID, securityTicket.SessionTicket, true, true); P_ARCH_UD_1326 parameterDoc = new P_ARCH_UD_1326(); parameterDoc.DocumentID = documentID; parameterDoc.Mime = UtilMethods.GetMimeType(item.documentName + ".xlsx"); parameterDoc.DocumentName = item.documentName; parameterDoc.DocumentDate = DateForElastic; parameterDoc.Receiver = "MM"; parameterDoc.Description = "Vollständiger Bericht"; cls_Upload_Report.Invoke(connection, transaction, parameterDoc, securityTicket); } } returnValue.Result.DownloadURL = downloadURL; return(returnValue); #endregion UserCode }
public GlobeToLicManagerSteps(IWebDriver driver) { _utilMethods = new UtilMethods(driver); _snowHome = new SnowHome(driver); _globeCommunity = new GlobeCommunity(driver); }
public GooglePageObject(IWebDriver driver) { PageFactory.InitElements(driver, this); set = new UtilMethods(driver); }
public bool validarNascimento() { return(UtilMethods.validarData(this.DataNascimento) && UtilMethods.validarHora(this.HoraNascimento)); }
private void InitializeHUDTexts(float time) { Font speedFont, kmFont, relojFont, actualWeaponFont, ammoQuantityFont, turboFont; var scale = screenWidth / 1920f; speedFont = UtilMethods.createFont("Open 24 Display St", (int)(32 * scale)); kmFont = UtilMethods.createFont("Open 24 Display St", (int)(20 * scale)); relojFont = UtilMethods.createFont("appleberry", (int)(40 * scale)); actualWeaponFont = UtilMethods.createFont("Insanibc", (int)(23 * scale)); ammoQuantityFont = UtilMethods.createFont("Insanibc", (int)(26 * scale)); turboFont = UtilMethods.createFont("Speed", (int)(30 * scale)); // Nombre del Arma weaponName = new TgcText2D { Text = "[ None ]", Color = Color.Black, Format = DrawTextFormat.Bottom | DrawTextFormat.Center, Position = new Point(-(int)(screenWidth * 0.4230f), -(int)(screenHeight * 0.0345f)) }; weaponName.changeFont(actualWeaponFont); // Cantidad de balas ammoQuantity = new TgcText2D { Text = "-", Color = Color.Black, Format = DrawTextFormat.Bottom | DrawTextFormat.Center, Position = new Point(-(int)(screenWidth * 0.3755f), -(int)(screenHeight * 0.0875f)) }; ammoQuantity.changeFont(ammoQuantityFont); // Velocidad del Player 1 speed = new TgcText2D { Text = "0", Color = Color.Green, Format = DrawTextFormat.Bottom | DrawTextFormat.Center, Position = new Point((int)(screenWidth * 0.4105f), -(int)(screenHeight * 0.0310f)) }; speed.changeFont(speedFont); // KM km = new TgcText2D { Text = "km", Color = Color.Black, Format = DrawTextFormat.Bottom | DrawTextFormat.Center, Position = new Point((int)(screenWidth * 0.4405f), -(int)(screenHeight * 0.0320f)) }; km.changeFont(kmFont); // Reloj reloj = new TgcText2D { Text = formatTime(time), Color = Color.Black, Position = new Point(0, 0) }; reloj.changeFont(relojFont); // Turbo turbo = new TgcText2D { Text = "TURBO MODE", Color = Color.Blue, Position = new Point(0, (int)(screenHeight * 0.15f)) }; turbo.changeFont(turboFont); }
private async Task <IList <Asset> > LoadAssetsFromGLTF(AssetSource source, Guid containerId, ColliderType colliderType) { WebRequestLoader loader = null; Stream stream = null; source.ParsedUri = new Uri(_app.ServerAssetUri, source.ParsedUri); var rootUri = URIHelper.GetDirectoryName(source.ParsedUri.AbsoluteUri); var cachedVersion = MREAPI.AppsAPI.AssetCache.SupportsSync ? MREAPI.AppsAPI.AssetCache.GetVersionSync(source.ParsedUri) : await MREAPI.AppsAPI.AssetCache.GetVersion(source.ParsedUri); // Wait asynchronously until the load throttler lets us through. using (var scope = await AssetLoadThrottling.AcquireLoadScope()) { // set up loader loader = new WebRequestLoader(rootUri); if (!string.IsNullOrEmpty(cachedVersion)) { loader.BeforeRequestCallback += (msg) => { if (msg.RequestUri == source.ParsedUri) { msg.Headers.Add("If-None-Match", cachedVersion); } }; } // download root gltf file, check for cache hit try { stream = await loader.LoadStreamAsync(URIHelper.GetFileFromUri(source.ParsedUri)); source.Version = loader.LastResponse.Headers.ETag?.Tag ?? ""; } catch (HttpRequestException) { if (loader.LastResponse.StatusCode == System.Net.HttpStatusCode.NotModified) { source.Version = cachedVersion; } else { throw; } } } IList <Asset> assetDefs = new List <Asset>(30); DeterministicGuids guidGenerator = new DeterministicGuids(UtilMethods.StringToGuid( $"{containerId}:{source.ParsedUri.AbsoluteUri}")); IList <UnityEngine.Object> assets; // fetch assets from glTF stream or cache if (source.Version != cachedVersion) { assets = await LoadGltfFromStream(loader, stream, colliderType); MREAPI.AppsAPI.AssetCache.StoreAssets(source.ParsedUri, assets, source.Version); } else { var assetsEnum = MREAPI.AppsAPI.AssetCache.SupportsSync ? MREAPI.AppsAPI.AssetCache.LeaseAssetsSync(source.ParsedUri) : await MREAPI.AppsAPI.AssetCache.LeaseAssets(source.ParsedUri); assets = assetsEnum.ToList(); } // catalog assets int textureIndex = 0, meshIndex = 0, materialIndex = 0, prefabIndex = 0; foreach (var asset in assets) { var assetDef = GenerateAssetPatch(asset, guidGenerator.Next()); assetDef.Name = asset.name; string internalId = null; if (asset is UnityEngine.Texture) { internalId = $"texture:{textureIndex++}"; } else if (asset is UnityEngine.Mesh) { internalId = $"mesh:{meshIndex++}"; } else if (asset is UnityEngine.Material) { internalId = $"material:{materialIndex++}"; } else if (asset is GameObject) { internalId = $"scene:{prefabIndex++}"; } assetDef.Source = new AssetSource(source.ContainerType, source.ParsedUri.AbsoluteUri, internalId, source.Version); ColliderGeometry colliderGeo = null; if (asset is UnityEngine.Mesh mesh) { colliderGeo = colliderType == ColliderType.Mesh ? (ColliderGeometry) new MeshColliderGeometry() { MeshId = assetDef.Id } : (ColliderGeometry) new BoxColliderGeometry() { Size = (mesh.bounds.size * 0.8f).CreateMWVector3(), Center = mesh.bounds.center.CreateMWVector3() }; } _app.AssetManager.Set(assetDef.Id, containerId, asset, colliderGeo, assetDef.Source); assetDefs.Add(assetDef); } return(assetDefs); }
public string GeDateFormat(string formatString, string value) { var parameter = new MethodCallExpressionArgs() { IsMember = true, MemberValue = DateType.Year }; var parameter2 = new MethodCallExpressionArgs() { IsMember = true, MemberName = value }; var parameters = new MethodCallExpressionModel() { Args = new List <MethodCallExpressionArgs>() { parameter2, parameter } }; var begin = @"^"; var end = @"$"; formatString = formatString.Replace("yyyy", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end); formatString = formatString.Replace("yy", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end); parameters.Args.Last().MemberValue = DateType.Month; formatString = formatString.Replace("MM", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end); formatString = formatString.Replace("M", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end); parameters.Args.Last().MemberValue = DateType.Day; formatString = formatString.Replace("dd", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end); formatString = formatString.Replace("d", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end); parameters.Args.Last().MemberValue = DateType.Hour; formatString = Regex.Replace(formatString, "hh", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end, RegexOptions.IgnoreCase); formatString = Regex.Replace(formatString, "h", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end, RegexOptions.IgnoreCase); parameters.Args.Last().MemberValue = DateType.Minute; formatString = formatString.Replace("mm", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end); formatString = formatString.Replace("m", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end); parameters.Args.Last().MemberValue = DateType.Second; formatString = formatString.Replace("ss", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end); formatString = formatString.Replace("s", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end); parameters.Args.Last().MemberValue = DateType.Millisecond; formatString = formatString.Replace("ms", begin + UtilMethods.ConvertStringToNumbers(this.GetMethodValue("DateValue", parameters).ObjToString()) + end); var items = Regex.Matches(formatString, @"\^\d+\$").Cast <Match>().ToList(); foreach (var item in items) { formatString = formatString.Replace(item.Value, "$@" + UtilMethods.ConvertNumbersToString(item.Value.TrimStart('^').TrimEnd('$')) + "$"); } var strings = formatString.TrimStart('$').TrimEnd('$').Split('$'); var joinStringParameter = new MethodCallExpressionModel() { Args = new List <MethodCallExpressionArgs>() }; foreach (var r in strings) { if (r.Substring(0, 1) == "@") { joinStringParameter.Args.Add(new MethodCallExpressionArgs() { MemberName = r.TrimStart('@') }); } else { var name = base.AppendParameter(r); joinStringParameter.Args.Add(new MethodCallExpressionArgs() { MemberName = name }); } } return(this.GetMethodValue("MergeString", joinStringParameter).ObjToString()); }
private void ProcessCreatedActors(CreateActor originalMessage, IList <Actor> createdActors, Action onCompleteCallback, string guidSeed = null) { Guid guidGenSeed; if (originalMessage != null) { guidGenSeed = originalMessage.Actor.Id; } else { guidGenSeed = UtilMethods.StringToGuid(guidSeed); } var guids = new DeterministicGuids(guidGenSeed); // find the actors with no actor parents var rootActors = GetDistinctTreeRoots( createdActors.Select(a => a.gameObject).ToArray() ).Select(go => go.GetComponent <Actor>()).ToArray(); var rootActor = createdActors.FirstOrDefault(); var createdAnims = new List <Animation.BaseAnimation>(5); if (rootActors.Length == 1 && rootActor.transform.parent == null) { // Delete entire hierarchy as we no longer have a valid parent actor for the root of this hierarchy. It was likely // destroyed in the process of the async operation before this callback was called. foreach (var actor in createdActors) { actor.Destroy(); } createdActors.Clear(); SendCreateActorResponse( originalMessage, failureMessage: "Parent for the actor being created no longer exists. Cannot create new actor."); return; } var secondPassXfrms = new List <Transform>(2); foreach (var root in rootActors) { ProcessActors(root.transform, root.transform.parent != null ? root.transform.parent.GetComponent <Actor>() : null); } // some things require the whole hierarchy to have actors on it. run those here foreach (var pass2 in secondPassXfrms) { ProcessActors2(pass2); } if (originalMessage != null && rootActors.Length == 1) { rootActor?.ApplyPatch(originalMessage.Actor); } Actor.ApplyVisibilityUpdate(rootActor); _actorManager.UponStable( () => SendCreateActorResponse(originalMessage, actors: createdActors, anims: createdAnims, onCompleteCallback: onCompleteCallback)); void ProcessActors(Transform xfrm, Actor parent) { // Generate actors for all GameObjects, even if the loader didn't. Only loader-generated // actors are returned to the app though. We do this so library objects get enabled/disabled // correctly, even if they're not tracked by the app. var actor = xfrm.gameObject.GetComponent <Actor>() ?? xfrm.gameObject.AddComponent <Actor>(); _actorManager.AddActor(guids.Next(), actor); _ownedGameObjects.Add(actor.gameObject); actor.ParentId = parent?.Id ?? actor.ParentId; if (actor.Renderer != null) { actor.MaterialId = AssetCache.GetId(actor.Renderer.sharedMaterial) ?? Guid.Empty; actor.MeshId = AssetCache.GetId(actor.UnityMesh) ?? Guid.Empty; } // native animation construction requires the whole actor hierarchy to already exist. defer to second pass var nativeAnim = xfrm.gameObject.GetComponent <UnityEngine.Animation>(); if (nativeAnim != null && createdActors.Contains(actor)) { secondPassXfrms.Add(xfrm); } foreach (Transform child in xfrm) { ProcessActors(child, actor); } } void ProcessActors2(Transform xfrm) { var actor = xfrm.gameObject.GetComponent <Actor>(); var nativeAnim = xfrm.gameObject.GetComponent <UnityEngine.Animation>(); if (nativeAnim != null && createdActors.Contains(actor)) { var animTargets = xfrm.gameObject.GetComponent <PrefabAnimationTargets>(); int stateIndex = 0; foreach (AnimationState state in nativeAnim) { var anim = new NativeAnimation(AnimationManager, guids.Next(), nativeAnim, state); anim.TargetIds = animTargets != null ? animTargets.GetTargets(xfrm, stateIndex ++, addRootToTargets : true).Select(a => a.Id).ToList() : new List <Guid>() { actor.Id }; AnimationManager.RegisterAnimation(anim); createdAnims.Add(anim); } } } }
private void ProcessCreatedActors(CreateActor originalMessage, IList <Actor> createdActors, Action onCompleteCallback, string guidSeed = null) { Guid guidGenSeed; if (originalMessage != null) { guidGenSeed = originalMessage.Actor.Id; } else { guidGenSeed = UtilMethods.StringToGuid(guidSeed); } var guids = new DeterministicGuids(guidGenSeed); // find the actors with no actor parents var rootActors = GetDistinctTreeRoots( createdActors.ToArray() ).Select(go => go as Actor).ToArray(); var rootActor = createdActors.FirstOrDefault(); var createdAnims = new List <Animation.BaseAnimation>(5); if (rootActors.Length == 1 && rootActor.GetParent() == null) { // Delete entire hierarchy as we no longer have a valid parent actor for the root of this hierarchy. It was likely // destroyed in the process of the async operation before this callback was called. foreach (var actor in createdActors) { actor.Destroy(); } createdActors.Clear(); SendCreateActorResponse( originalMessage, failureMessage: "Parent for the actor being created no longer exists. Cannot create new actor."); return; } var secondPassXfrms = new List <Spatial>(2); foreach (var root in rootActors) { ProcessActors(root.Node3D, root.GetParent() as Actor); } // some things require the whole hierarchy to have actors on it. run those here foreach (var pass2 in secondPassXfrms) { ProcessActors2(pass2); } if (originalMessage != null && rootActors.Length == 1) { rootActor?.ApplyPatch(originalMessage.Actor); } Actor.ApplyVisibilityUpdate(rootActor); _actorManager.UponStable( () => SendCreateActorResponse(originalMessage, actors: createdActors, anims: createdAnims, onCompleteCallback: onCompleteCallback)); void ProcessActors(Spatial node3D, Actor parent) { // Generate actors for all node3D, even if the loader didn't. Only loader-generated // actors are returned to the app though. We do this so library objects get enabled/disabled // correctly, even if they're not tracked by the app. Actor actor = (node3D as Actor) ?? Actor.Instantiate(node3D); _actorManager.AddActor(guids.Next(), actor); _ownedNodes.Add(actor); actor.ParentId = parent?.Id ?? actor.ParentId; if (actor.MeshInstance != null) { // only overwrite material if there's something in the cache, i.e. not a random library material if (actor.MeshInstance.MaterialOverride != null) { var matId = AssetManager.GetByObject(actor.MeshInstance.MaterialOverride)?.Id; if (matId.HasValue) { actor.MaterialId = matId.Value; } } actor.MeshId = AssetManager.GetByObject(actor.GodotMesh)?.Id ?? Guid.Empty; } // native animation construction requires the whole actor hierarchy to already exist. defer to second pass var nativeAnim = node3D.GetChild <Godot.AnimationPlayer>(); if (nativeAnim != null && createdActors.Contains(actor)) { secondPassXfrms.Add(node3D); } foreach (object node in actor.GetChildren()) { if (node is Spatial) { ProcessActors((Spatial)node, actor); } } } void ProcessActors2(Spatial node3D) { var actor = node3D as Actor; var animationPlayer = node3D.GetChild <Godot.AnimationPlayer>(); if (animationPlayer != null && createdActors.Contains(actor)) { var animTargets = node3D.GetChild <PrefabAnimationTargets>(); int animIndex = 0; foreach (string animationString in animationPlayer.GetAnimationList()) { var anim = new NativeAnimation(AnimationManager, guids.Next(), animationPlayer, animationPlayer.GetAnimation(animationString)); anim.TargetIds = animTargets != null ? animTargets.GetTargets(node3D, animIndex ++, addRootToTargets : true).Select(a => a.Id).ToList() : new List <Guid>() { actor.Id }; AnimationManager.RegisterAnimation(anim); createdAnims.Add(anim); } } } }