Helpers
public ServerProxy GetProxy(Helpers.EclipseWorkspace workspace) { if (workspace == null) return null; ServerProxy retVal = null; lock (proxyList) { if (!proxyList.TryGetValue(workspace, out retVal)) { Telemetry.Client.Get().TrackEvent("App.ServerLaunch"); retVal = new ServerProxy("javapkgsrv-" + Guid.NewGuid()); retVal.LIFORequests.Add(Protocol.Request.RequestType.ParamHelpPositionUpdate); if (retVal.Start(workspace.Name)) { proxyList.Add(workspace, retVal); refCounts.Add(retVal, 1); Telemetry_MaxInstances = Math.Max(proxyList.Count, Telemetry_MaxInstances); } else return null; } else ++refCounts[retVal]; } retVal.TerminatedAbnormally += ServerProxy_TerminatedAbnormally; return retVal; }
public static Tabla_Catalogo_ConceptoPagoDTO GetLast() { Helpers h = new Helpers(); string query = "select * from Tabla_Catalogo_ConceptoPago"; var lFichas = h.GetAllParametized(query, new Tabla_Catalogo_ConceptoPagoDTO()); return lFichas.Last(); }
public void Delete(ConsultaProcedimientoDTO oneConsulta) { string query = "delete Tabla_Registro_ConsultaProcedimiento where Id_ConsultaProcedimiento = @Id_ConsultaProcedimiento"; Helpers h = new Helpers(); h.ExecuteNonQueryParam(query, oneConsulta); }
/// <summary> /// Get parameters from input request stream /// </summary> /// <param name="mime">File mime type</param> /// <param name="encoding">File encoding</param> /// <param name="fileName">File name</param> private void GetInputRequestHeaders(out string mime, out Encoding encoding, out string fileName, Helpers.Log.SessionInfo upperLogSession) { if (upperLogSession == null) throw new ArgumentNullException(nameof(upperLogSession)); mime = null; encoding = null; fileName = null; using (var logSession = Helpers.Log.Session($"{GetType()}.{System.Reflection.MethodBase.GetCurrentMethod().Name}()", VerboseLog, ss => ss.ToList().ForEach(s => upperLogSession.Add(s)))) try { var webContext = System.ServiceModel.Web.WebOperationContext.Current; if (webContext != null) { var ct = webContext.IncomingRequest.ContentType.Split(new char[] { ';' }, StringSplitOptions.None).Select(i => i.Trim()); mime = ct.FirstOrDefault(); var encName = ct.Skip(1).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(encName)) try { encoding = Encoding.GetEncoding(encName); } catch { } var cd = webContext.IncomingRequest.Headers.Get("Content-Disposition"); if (!string.IsNullOrWhiteSpace(cd)) { var fName = cd.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).FirstOrDefault(i => i.ToLower().StartsWith("filename=")); fileName = fName.Substring(fName.IndexOf("=") + 1); } } } catch (Exception ex) { logSession.Add(ex); logSession.Enabled = true; upperLogSession.Enabled = true; } }
public async void GetWeatherInfo() { var helpers = new Helpers(); Coordinate positon = await helpers.GetCoordinates(); ForecastIOResponse info = null; MessageDialog msg = null; try { info = await DataPersister.GetInfo(positon.Lat, positon.Lon); Currently rawData = info.Currently; DateTime date = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(rawData.Time); rawData.FormatedTime = date.ToString("dd/MMM/yyyy hh:mm"); } catch (Exception) { msg = new MessageDialog("Info loading failed!"); } if (msg != null) { await msg.ShowAsync(); return; } this.AllInfo = info; this.WeatherInfo = info.Currently; }
private static String getHandlerDetails(UserShows userShow, User currentUser, int ShowDetailsID) { String html = "<div class='handlerDetails'>"; html += "<div class='handler'>Handler Name:" + currentUser.Name + "</div>"; html += "<div class='showRef'>Show Ref:" + userShow.ID.ToString("000000") + "</div>"; UserCamping userCamping = new UserCamping(userShow.ID); if (userCamping.ID > -1) { String tmp = ""; if (userCamping.PitchNo == -1) { tmp = "Not Allocated"; } else { tmp = userCamping.PitchNo.ToString(); } html += "<div class='campingDetails'>Camping Pitch No:" + tmp + "</div>"; } Helpers helper = new Helpers(currentUser.UserID, ShowDetailsID); if (helper.ID > -1) { html += "<div class='helpingDetails'>Helping on Ring " + helper.RingNo.ToString() + " - " + helper.expandJob() +"</div>"; } html += "</div>"; return html; }
public DataSet ExecuteQuery(EDtxReaderType type, int timeout, string cmdText, Helpers.ParamHelper[] paramList, ref TimeSpan span) { DataSet retv = new DataSet(); try { //Technically you only need to register once, but as a showcase of what one would do, here is a quick example. int retcode = Helpers.HelperFunctions.RegisterUser(keyFileTB.Text); returnCodeTB.Text = retcode.ToString(); if(retcode == 0) { IDbConnection conn = QueryHelper.GetConnection(type, HelperFunctions.GetUniqueKey(10), HelperFunctions.GetUniqueKey(20), string.Empty, string.Empty); if (conn != null) { retv = QueryHelper.ExecuteSelect(type, timeout, conn, cmdText, paramList, ref span); } else { MessageBox.Show("Unable to build connection object"); } } } catch(Exception e) { MessageBox.Show("Execute Query Failed with an unknown error: " + e.Message + Environment.NewLine + e.StackTrace); Console.WriteLine(e); } return retv; }
public static PerfilDTO GetLast() { Helpers h = new Helpers(); var lPerfiles = GetAll(); var onePerfil = lPerfiles.Last(); return onePerfil; }
public static Tabla_Catalogo_FichaIdentificacionDTO GetLast() { Helpers h = new Helpers(); string query = "select * from Tabla_Catalogo_FichaIdentificacion"; var lFichas = h.GetAllParametized(query, new Tabla_Catalogo_FichaIdentificacionDTO()); return lFichas.Last(); }
//called on GUI thread private void ReceivedLogMessage(string message, Helpers.LogLevel level) { RichTextBox rtb = null; switch (level) { case Helpers.LogLevel.Info: rtb = rtbInfo; break; case Helpers.LogLevel.Warning: rtb = rtbWarning; break; case Helpers.LogLevel.Error: rtb = rtbError; break; case Helpers.LogLevel.Debug: rtb = rtbDebug; break; } rtb.AppendText("[" + DateTime.Now.ToString() + "] " + message + "\n"); }
public static List<ModuloDTO> GetAll() { string query = "select * from Tabla_Catalogo_Modulo where Estatus_Modulo = 1"; Helpers h = new Helpers(); var lModulos = h.GetAllParametized(query, new ModuloDTO()); return lModulos; }
protected virtual Repository.Logic.Repository GetNewRepository(Helpers.Log.SessionInfo logSession) { var rep = new Repository.Logic.Repository(); rep.SqlLog += (s, e) => RaiseSqlLog(e); rep.Log += (s, e) => logSession.Add(e, "[REPOSITORY]"); return rep; }
//comes in on separate thread private void client_OnLogMessage(string message, Helpers.LogLevel level) { if (this.IsHandleCreated) BeginInvoke(new SecondLife.LogCallback(ReceivedLogMessage), new object[] { message, level }); else initQueue.Add(new DebugLogMessage(message, level)); }
public void Insert(Tabla_Registro_AgendaDTO oneAgenda) { string query = "insert into Tabla_Registro_Agenda (Fecha_Agenda, Asunto_Agenda, Prioridad_Agenda, EstadoCitas_Agenda, Descripcion_Agenda, Inicio_Agenda, Fin_Agenda, Id_FichaIdentificacion, Id_Categoria, Estatus_Agenda) values(@Fecha_Agenda, @Asunto_Agenda, @Prioridad_Agenda, @EstadoCitas_Agenda, @Descripcion_Agenda, @Inicio_Agenda, @Fin_Agenda, @Id_FichaIdentificacion, @Id_Categoria, @Estatus_Agenda)"; Helpers h = new Helpers(); h.ExecuteNonQueryParam(query, oneAgenda); }
public async void GetWeatherInfo() { var helper = new Helpers(); Coordinate positon = await helper.GetCoordinates(); ForecastIOResponse info = null; MessageDialog msg = null; try { info = await DataPersister.GetInfo(positon.Lat, positon.Lon); } catch (Exception) { msg = new MessageDialog("Info loading failed!"); } if (msg != null) { await msg.ShowAsync(); return; } this.allInfo = info; List<HourForecast> rawData = info.Hourly.Data; for (int i = 0; i < rawData.Count; i++) { rawData[i].IconPath = string.Format("/Assets/WeatherIcons/{0}.png", rawData[i].Icon); DateTime date = new DateTime(1970,1,1,0,0,0).AddSeconds(rawData[i].Time); rawData[i].FormatedDate = date; } this.HourWeatherInfo = rawData; }
public BTFileLoader(Helpers mh) { m_Helpers = mh; m_Helpers.m_Blob.CreateContainer("log"); //m_LogBlob.SetContainerACL("log", "private"); CloudBlobContainer container = m_Helpers.m_Blob.BlobClient.GetContainerReference("log"); /* CloudBlobContainer blobContainer = blobClient.GetContainerReference("azurecontainer"); CloudBlob blob = Container.GetBlobReference(blobname + ".res"); BlobStream bs = blob.OpenWrite(); TextWriter tw = new StreamWriter(bs); string append = resultsLine + ", "; tw.WriteLine(append); */ CloudBlob blob = container.GetBlobReference("AudibleLoader.Log"); BlobStream bs = blob.OpenWrite(); TextWriter tw = new StreamWriter(bs); tw.WriteLine("test"); tw.Flush(); //content = new UTF8Encoding().GetString(data); bs.Close(); //BlobStream OpenWrite () }
public void Insert(ConsultaProcedimientoDTO oneConsulta) { string query = "insert into Tabla_Registro_ConsultaProcedimiento(Id_Consulta, Id_Procedimiento, Id_FichaIdentificacion, Fecha_ConsultaProcedimiento, Observaciones_ConsultaProcedimiento, Estatus_ConsultaProcedimiento) values(@Id_Consulta, @Id_Procedimiento, @Id_FichaIdentificacion, @Fecha_ConsultaProcedimiento, @Observaciones_ConsultaProcedimiento, @Estatus_ConsultaProcedimiento)"; Helpers h = new Helpers(); h.ExecuteNonQueryParam(query, oneConsulta); }
public static ModuloDTO GetOne(ModuloDTO oneModulo) { Helpers h = new Helpers(); var lModulos = GetAll(); oneModulo = lModulos.Single(x => x.Id_Modulo == oneModulo.Id_Modulo); return oneModulo; }
public void LlenarPaquete() { // Isertar analisis en paquetes string query = "select * from Tabla_Temporal_AnalisisClinico where Id_Consulta = @Id_Consulta and Id_FichaIdentificacion = @Id_FichaIdentificacion"; Helpers h = new Helpers(); var oneTemp = new Tabla_Temporal_AnalisisClinicoDTO(); oneTemp.Id_Consulta = Id_Consulta; oneTemp.Id_FichaIdentificacion = Id_FichaIdentificacion; var lTemporal = h.GetAllParametized(query, oneTemp); string queryInsert = "insert into Tabla_Registro_AnalisisClinicoPaquetes (Id_AnalisisClinico, Id_AnalisisClinicoPaquetes) values (@Id_AnalisisClinico, @Id_AnalisisClinicoPaquetes)"; var oneT = new Tabla_Analsis_TemplateDTO(); string queryLast = "SELECT TOP 1 Id_AnalisisClinicoPaquetes FROM Tabla_Registro_AnalisisClinicoPaquetes ORDER BY Id_AnalisisClinicoPaquetes DESC"; var lIdTemplate = h.GetAllParametized(queryLast, oneT); if (lIdTemplate.Count == 0) { oneT.Id_AnalisisClinicoPaquetes = 0; } else { oneT.Id_AnalisisClinicoPaquetes = lIdTemplate[0].Id_AnalisisClinicoPaquetes + 1; } foreach (var y in lTemporal) { var oneTemplate = new Tabla_Analsis_TemplateDTO(); oneTemplate.Id_AnalisisClinico = y.Id_AnalisisClinico; oneTemplate.Id_AnalisisClinicoPaquetes = oneT.Id_AnalisisClinicoPaquetes; h.ExecuteNonQueryParam(queryInsert, oneTemplate); } // string script = "AlertaGuardar();"; // ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true); Page.Response.Redirect(Page.Request.Url.ToString(), true); return; }
public static ModuloDTO GetOneByName(ModuloDTO oneModulo) { Helpers h = new Helpers(); var lModulos = GetAll(); oneModulo = lModulos.Single(x => x.Nombre_Modulo == oneModulo.Nombre_Modulo && x.Programa_Modulo == oneModulo.Programa_Modulo); return oneModulo; }
public void Update(NotaClinicaDTO oneNota) { string query = "update Tabla_Registro_Consulta set Subjetivo_Consulta = @Subjetivo_Consulta, Objetivo_Consulta = @Objetivo_Consulta, Analisis_Consulta = @Analisis_Consulta, Plan_Consulta = @Plan_Consulta where ID_Consulta = @Id_Consulta and Id_FichaIdentificacion = @Id_FichaIdentificacion"; Helpers h = new Helpers(); h.ExecuteNonQueryParam(query, oneNota); }
protected override void ReceiveMessage(Helpers.NotificationMessageType messageType) { base.ReceiveMessage(messageType); var view = new SelectDataset(); switch (messageType.MessageType) { case NotificationMessageEnum.SelectDatasetForOperand1: view.ShowDialog(); if (view.SelectedDataset == null) return; _dataContext.SetOperand1(view.SelectedDataset.ID); break; case NotificationMessageEnum.SelectDatasetForOperand2: view.ShowDialog(); if (view.SelectedDataset == null) return; _dataContext.SetOperand2(view.SelectedDataset.ID); break; case NotificationMessageEnum.ShouldDeleteEquation: var sbuilder = new StringBuilder(); sbuilder.AppendLine("This equation has been used with another equations"); sbuilder.AppendLine("Deleting this equation could cause a chain reaction and might remove several equations."); sbuilder.Append("Are you sure you want to continue"); if (MessageBox.Show(sbuilder.ToString(), GlobalData.CompanyName, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes) { _dataContext.ShouldDelete = true; } break; } }
public void Delete(PerfilDTO onePerfil) { string query = "Delete Tabla_Catalogo_Perfil where Id_Perfil = @Id_Perfil"; Helpers h = new Helpers(); h.ExecuteNonQueryParam(query, onePerfil); string queryB = "delete Tabla_Registro_Permisos_Perfil where Id_Perfil = @Id_Perfil"; h.ExecuteNonQueryParam(queryB, onePerfil); }
public void Delete(ModuloDTO oneModulo) { string query = "Delete Tabla_Catalogo_Modulo where Id_Modulo = @Id_Modulo"; Helpers h = new Helpers(); h.ExecuteNonQueryParam(query, oneModulo); string queryB = "delete Tabla_Registro_Permisos_Perfil where Id_Modulo = @Id_Modulo"; h.ExecuteNonQueryParam(queryB, oneModulo); }
public XmlEntryService(string path, TextBox erroLogTextBox) { _xmlDocument = new XmlDocument(); var entryNode = _xmlDocument.CreateElement(Resources.Service_Entries); _xmlDocument.AppendChild(entryNode); _helpers = new Helpers(path, erroLogTextBox); _helpers.ClearFile(); }
public static NotaClinicaDTO GetOneByAgenda(NotaClinicaDTO oneNota) { Helpers h = new Helpers(); string query = "select * from Tabla_Registro_Consulta where Id_Agenda = @Id_Agenda"; oneNota = h.GetAllParametized(query, oneNota)[0]; oneNota.lDiagnosticos = ConsultaDiagnosticoDAO.GetAllByConsulta(new ConsultaDiagnosticoDTO {Id_Consulta = oneNota.Id_Consulta}); return oneNota; }
public MetaDataEntry() { InitializeComponent(); metaImagePath = ""; webURL = ""; type = ""; _helper = new Helpers(); }
private static void GetsInfo(HttpClient client, Helpers.ContainerizerProcess process, string handle, Dictionary<string, string> properties) { var infoPath = "/api/containers/" + handle + "/info"; var infoResponse = client.GetAsync(infoPath).Result.Content.ReadAsJson() as JObject; infoResponse["ExternalIP"].ToString().should_be(process.MachineIP); infoResponse["Properties"].ToObject<Dictionary<string, string>>().should_be(properties); }
public MainWindow() { _helpers = new Helpers(); InitializeComponent(); this.load(); this.setWindowSize(); }
public void loadUsuario() { string query = "select * from Tabla_Catalogo_FichaIdentificacion where Id_FichaIdentificacion = @Id_FichaIdentificacion"; Helpers h = new Helpers(); var oneFicha = h.GetAllParametized(query, new Tabla_Catalogo_FichaIdentificacionDTO { Id_FichaIdentificacion = Id_FichaIdentificacion })[0]; lblNombre.Text = oneFicha.Nombre_FichaIdentificacion.Trim() + " " + oneFicha.ApPaterno_FichaIdentificacion.Trim() + " " + oneFicha.ApMaterno_FichaIdentificacion.Trim(); NombreCompleto = oneFicha.Nombre_FichaIdentificacion.Trim() + " " + oneFicha.ApPaterno_FichaIdentificacion.Trim() + " " + oneFicha.ApMaterno_FichaIdentificacion.Trim(); }
public void UpdateMetadataValueAsAttributeWithSpecialCharacters(string projectContents, string updatedProject) { ProjectRootElement projectElement = ProjectRootElement.Create(XmlReader.Create( new StringReader(ObjectModelHelpers.CleanupFileContents(projectContents))), ProjectCollection.GlobalProjectCollection, preserveFormatting: true); ProjectItemGroupElement itemGroup = (ProjectItemGroupElement)projectElement.AllChildren.FirstOrDefault(c => c is ProjectItemGroupElement); var project = new Project(projectElement); var items = Helpers.MakeList(itemGroup.Items); Assert.Equal(1, items.Count); Assert.Equal(1, items[0].Metadata.Count); var metadata = items[0].Metadata.First(); Assert.Equal("m1", metadata.Name); Assert.Equal("v1", metadata.Value); Assert.True(metadata.ExpressedAsAttribute); metadata.Value = @"<&>"""; Assert.True(project.IsDirty); Assert.True(metadata.ExpressedAsAttribute); StringWriter writer = new StringWriter(); project.Save(writer); string expected = @"<?xml version=""1.0"" encoding=""utf-16""?>" + ObjectModelHelpers.CleanupFileContents(updatedProject); string actual = writer.ToString(); VerifyAssertLineByLine(expected, actual); }
private void compileC(string outputFile, StandardCompileOutput <Project> output, fileObj[] codeFiles, fileObj[] headerFiles, StandardOutputCallback stdOut) { if (File.Exists(outputFile)) { File.Delete(outputFile); } //collapse the code files and header files into one array but add the header files first. fileObj[] files = new fileObj[0]; Helpers.AddObject(ref files, headerFiles); Helpers.AddObject(ref files, codeFiles); //flatten the files down to a single file string collapsed = collapseFiles(files, ".c"); //perform the compile outputEntry[] errors = new outputEntry[0]; outputEntry[] warnings = new outputEntry[0]; compileC(ref errors, ref warnings, collapsed, outputFile, stdOut); processCompileResults(codeFiles, output, errors, warnings); //clean up File.Delete(collapsed); }
private void ReturnAllRemainigRowsWhenTakeIsTooBigCore(ProviderType provider) { using (var helper = Helpers.CreateDatabase(provider, LimitOffsetInitScripts)) { var expectedData = new List <LimitOffsetTestData>(new[] { new LimitOffsetTestData() { Id = 19, Value = "nineteen" }, new LimitOffsetTestData() { Id = 20, Value = "twenty" }, }); List <LimitOffsetTestData> data = helper.Korm.Query <LimitOffsetTestData>() .OrderBy(item => item.Id) .Skip(18) .Take(100) .ToList(); data.Should().BeEquivalentTo(expectedData); } }
private void UnregisterHandlers() { ConnectionsManager.XenConnections.CollectionChanged -= CollectionChanged; foreach (var xenConnection in ConnectionsManager.XenConnectionsCopy) { var pool = Helpers.GetPool(xenConnection); if (pool == null) { var host = Helpers.GetMaster(xenConnection); if (host != null) { host.PropertyChanged -= PropertyChanged; } } else { pool.PropertyChanged -= PropertyChanged; } xenConnection.ConnectionStateChanged -= xenConnection_ConnectionStateChanged; xenConnection.CachePopulated -= xenConnection_CachePopulated; xenConnection.Cache.DeregisterCollectionChanged <Host>(Host_CollectionChangedWithInvoke); } }
private string GetOutputDirectory() { string directory; switch (Options.OutputLocation) { default: case ThumbnailLocationType.DefaultFolder: directory = Options.DefaultOutputDirectory; break; case ThumbnailLocationType.ParentFolder: directory = Path.GetDirectoryName(MediaPath); break; case ThumbnailLocationType.CustomFolder: directory = Helpers.ExpandFolderVariables(Options.CustomOutputDirectory); break; } Helpers.CreateDirectory(directory); return(directory); }
private void InitializeControls() { InitializeComponent(); foreach (SupportedLanguage language in Helpers.GetEnums <SupportedLanguage>()) { ToolStripMenuItem tsmi = new ToolStripMenuItem(language.GetLocalizedDescription()); tsmi.Image = GetLanguageIcon(language); tsmi.ImageScaling = ToolStripItemImageScaling.None; SupportedLanguage lang = language; tsmi.Click += (sender, e) => ChangeLanguage(lang); cmsLanguages.Items.Add(tsmi); } cbTrayLeftDoubleClickAction.Items.AddRange(Helpers.GetLocalizedEnumDescriptions <HotkeyType>()); cbTrayLeftClickAction.Items.AddRange(Helpers.GetLocalizedEnumDescriptions <HotkeyType>()); cbTrayMiddleClickAction.Items.AddRange(Helpers.GetLocalizedEnumDescriptions <HotkeyType>()); CodeMenu.Create <CodeMenuEntryFilename>(txtSaveImageSubFolderPattern, CodeMenuEntryFilename.t, CodeMenuEntryFilename.pn, CodeMenuEntryFilename.i, CodeMenuEntryFilename.width, CodeMenuEntryFilename.height, CodeMenuEntryFilename.n); cbProxyMethod.Items.AddRange(Helpers.GetLocalizedEnumDescriptions <ProxyMethod>()); UpdateControls(); }
static void createVanishingTrickAndInvisibleBlade() { var invisibility_buff = library.Get <BlueprintBuff>("525f980cb29bc2240b93e953974cb325"); var improved_invisibility_buff = library.Get <BlueprintBuff>("e6b35473a237a6045969253beb09777c"); invisible_blade = Helpers.CreateFeature("NinjaInvisibleBladeFeature", "Invisible Blade", "Whenever a ninja uses the vanishing trick ninja trick, she is treated as if she were under the effects of greater invisibility.", "", improved_invisibility_buff.Icon, FeatureGroup.None); var apply_invisibility = Common.createContextActionApplyBuff(invisibility_buff, Helpers.CreateContextDuration(Helpers.CreateContextValue(AbilityRankType.Default)), dispellable: false); var apply_invisibility_improved = Common.createContextActionApplyBuff(improved_invisibility_buff, Helpers.CreateContextDuration(Helpers.CreateContextValue(AbilityRankType.Default)), dispellable: false); var action = Helpers.CreateConditional(Common.createContextConditionHasFact(invisible_blade), apply_invisibility_improved, apply_invisibility); var ability = Helpers.CreateAbility("NinjaVanishingTrickAbility", "Vanishing Trick", "As a swift action, the ninja can disappear for 1 round per level. This ability functions as invisibility. Using this ability uses up 1 ki point.", "", invisibility_buff.Icon, AbilityType.Supernatural, CommandType.Swift, AbilityRange.Personal, Helpers.roundsPerLevelDuration, "", Helpers.CreateRunActions(action), Helpers.CreateContextRankConfig(ContextRankBaseValueType.ClassLevel, classes: getRogueArray(), progression: ContextRankProgression.AsIs), ki_resource.CreateResourceLogic() ); ability.setMiscAbilityParametersSelfOnly(); vanishing_trick = Common.AbilityToFeature(ability, false); invisible_blade.AddComponent(Helpers.PrerequisiteFeature(vanishing_trick)); }
public static bool IsMinersBins_ALL_Init() { foreach (var filePath in AMD_Miners_Data.ALL_FILES_BINS) { if (!File.Exists(String.Format("AMD_Miners{0}", filePath))) { Helpers.ConsolePrint("MinersExistanceChecker", $"bin{filePath} doesn't exist! Warning"); return(false); } } foreach (var filePath in NVIDIA_Miners_Data.ALL_FILES_BINS) { if (!File.Exists(String.Format("NVIDIA_Miners{0}", filePath))) { Helpers.ConsolePrint("MinersExistanceChecker", $"bin{filePath} doesn't exist! Warning"); return(false); } } foreach (var filePath in AMD_NVIDIA_Miners_Data.ALL_FILES_BINS) { if (!File.Exists(String.Format("AMD_NVIDIA_Miners{0}", filePath))) { Helpers.ConsolePrint("MinersExistanceChecker", $"bin{filePath} doesn't exist! Warning"); return(false); } } foreach (var filePath in CPU_Miners_Data.ALL_FILES_BINS) { if (!File.Exists(String.Format("CPU_Miners{0}", filePath))) { Helpers.ConsolePrint("MinersExistanceChecker", $"bin{filePath} doesn't exist! Warning"); return(false); } } return(true); }
private static bool TryGetExistingTokensFromOtherConnections(IXenConnection currentConnection, out string uploadToken, out string diagnosticToken) { uploadToken = null; diagnosticToken = null; foreach (var connection in ConnectionsManager.XenConnectionsCopy) { if (connection == currentConnection || !connection.IsConnected) { continue; } var poolOfOne = Helpers.GetPoolOfOne(connection); if (poolOfOne != null) { var healthCheckSettings = poolOfOne.HealthCheckSettings(); uploadToken = healthCheckSettings.GetSecretInfo(connection, UPLOAD_TOKEN_SECRET); diagnosticToken = healthCheckSettings.GetSecretInfo(connection, DIAGNOSTIC_TOKEN_SECRET); if (!String.IsNullOrEmpty(uploadToken) && !String.IsNullOrEmpty(diagnosticToken)) { return(true); } } } return(false); }
public static Vector4D Xor_Software(VectorDParam1_3 left, VectorDParam1_3 right) { double x1 = Helpers.X(left); double y1 = Helpers.Y(left); double z1 = Helpers.Z(left); double w1 = Helpers.W(left); double x2 = Helpers.X(right); double y2 = Helpers.Y(right); double z2 = Helpers.Z(right); double w2 = Helpers.W(right); uint xorX = Unsafe.As<double, uint>(ref x1) ^ Unsafe.As<double, uint>(ref x2); uint xorY = Unsafe.As<double, uint>(ref y1) ^ Unsafe.As<double, uint>(ref y2); uint xorZ = Unsafe.As<double, uint>(ref z1) ^ Unsafe.As<double, uint>(ref z2); uint xorW = Unsafe.As<double, uint>(ref w1) ^ Unsafe.As<double, uint>(ref w2); return Vector256.Create( Unsafe.As<uint, double>(ref xorX), Unsafe.As<uint, double>(ref xorY), Unsafe.As<uint, double>(ref xorZ), Unsafe.As<uint, double>(ref xorW) ); }
public static Vector4D And_Software(VectorDParam1_3 left, VectorDParam1_3 right) { double x1 = Helpers.X(left); double y1 = Helpers.Y(left); double z1 = Helpers.Z(left); double w1 = Helpers.W(left); double x2 = Helpers.X(right); double y2 = Helpers.Y(right); double z2 = Helpers.Z(right); double w2 = Helpers.W(right); uint andX = Unsafe.As<double, uint>(ref x1) & Unsafe.As<double, uint>(ref x2); uint andY = Unsafe.As<double, uint>(ref y1) & Unsafe.As<double, uint>(ref y2); uint andZ = Unsafe.As<double, uint>(ref z1) & Unsafe.As<double, uint>(ref z2); uint andW = Unsafe.As<double, uint>(ref w1) & Unsafe.As<double, uint>(ref w2); return Vector256.Create( Unsafe.As<uint, double>(ref andX), Unsafe.As<uint, double>(ref andY), Unsafe.As<uint, double>(ref andZ), Unsafe.As<uint, double>(ref andW) ); }
public override void PageLoaded(PageLoadedDirection direction) { base.PageLoaded(direction); textBoxLog.Clear(); switch (SelectedUpdateType) { case UpdateType.NewRetail: case UpdateType.Existing: textBoxLog.Text = PatchingWizardModeGuidanceBuilder.ModeRetailPatch(SelectedServers, Patch); if (Helpers.MidnightRideOrGreater(SelectedServers[0].Connection)) { AutomaticRadioButton.Enabled = true; AutomaticRadioButton.Checked = true; } else { AutomaticRadioButton.Enabled = false; ManualRadioButton.Checked = true; } break; case UpdateType.NewOem: ManualRadioButton.Checked = true; AutomaticRadioButton.Enabled = false; textBoxLog.Text = PatchingWizardModeGuidanceBuilder.ModeNewOem(SelectedServers); break; case UpdateType.NewSuppPack: AutomaticRadioButton.Enabled = true; AutomaticRadioButton.Checked = true; textBoxLog.Text = PatchingWizardModeGuidanceBuilder.ModeSuppPack(SelectedServers); break; } }
private List<bool> RandomObs() { int randObsNo = Random.Range(0, obstacles.Count); Obstacle obs = obstacles[randObsNo].obstacle; int randomRotation = Random.Range(0, 4); for(int i = 0; i < randomRotation; i++) { obs = Helpers.Rotate90(obs); } if (HelperFunctions.ChanceChecker(negativeChance)) { obs = Helpers.Negative(obs); } if (HelperFunctions.ChanceChecker(mirrorHorizontalChance)) { obs = Helpers.MirrorHorizontal(obs); } if (HelperFunctions.ChanceChecker(mirrorVerticalChange)) { obs = Helpers.MirrorVertical(obs); } return obs.list; }
protected override bool BenchmarkParseLine(string outdata) { Helpers.ConsolePrint("BENCHMARK", outdata); return(false); }
public override APIData GetSummary() { _currentMinerReadStatus = MinerAPIReadStatus.NONE; APIData ad = new APIData(MiningSetup.CurrentAlgorithmType, MiningSetup.CurrentSecondaryAlgorithmType); TcpClient client = null; JsonApiResponse resp = null; try { byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes("{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"miner_getstat1\"}n"); client = new TcpClient("127.0.0.1", APIPort); NetworkStream nwStream = client.GetStream(); nwStream.Write(bytesToSend, 0, bytesToSend.Length); byte[] bytesToRead = new byte[client.ReceiveBufferSize]; int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize); string respStr = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead); resp = JsonConvert.DeserializeObject <JsonApiResponse>(respStr, Globals.JsonSettings); client.Close(); //Helpers.ConsolePrint("ClaymoreZcashMiner API back:", respStr); } catch (Exception ex) { Helpers.ConsolePrint(this.MinerTAG(), "GetSummary exception: " + ex.Message); } if (resp != null && resp.error == null) { //Helpers.ConsolePrint("ClaymoreZcashMiner API back:", "resp != null && resp.error == null"); if (resp.result != null && resp.result.Count > 4) { //Helpers.ConsolePrint("ClaymoreZcashMiner API back:", "resp.result != null && resp.result.Count > 4"); var speeds = resp.result[3].Split(';'); var secondarySpeeds = resp.result[5].Split(';'); ad.Speed = 0; ad.SecondarySpeed = 0; foreach (var speed in speeds) { //Helpers.ConsolePrint("ClaymoreZcashMiner API back:", "foreach (var speed in speeds) {"); double tmpSpeed = 0; try { tmpSpeed = Double.Parse(speed, CultureInfo.InvariantCulture); } catch { tmpSpeed = 0; } ad.Speed += tmpSpeed; } foreach (var speed in secondarySpeeds) { double tmpSpeed = 0; try { tmpSpeed = Double.Parse(speed, CultureInfo.InvariantCulture); } catch { tmpSpeed = 0; } ad.SecondarySpeed += tmpSpeed; } ad.Speed *= api_read_mult; ad.SecondarySpeed *= api_read_mult; _currentMinerReadStatus = MinerAPIReadStatus.GOT_READ; } if (ad.Speed == 0) { _currentMinerReadStatus = MinerAPIReadStatus.READ_SPEED_ZERO; } // some clayomre miners have this issue reporting negative speeds in that case restart miner if (ad.Speed < 0) { Helpers.ConsolePrint(this.MinerTAG(), "Reporting negative speeds will restart..."); this.Restart(); } } return(ad); }
public void poll(int now) { List <Player> playersInArea = new List <Player>(); int attackers = 0; int defenders = 0; Arena.FlagState flag = _flags.FirstOrDefault(f => f == _flag); playersInArea = _arena.getPlayersInRange(posX, posY, _flagCaptureRadius).Where(p => !p.IsDead).ToList(); Team attacker = _arena.ActiveTeams.FirstOrDefault(t => t != flag.team); attackers = playersInArea.Count(p => p._team != flag.team); defenders = playersInArea.Count(p => p._team == flag.team); if (now - tickLastPointer >= 2000) { Helpers.ObjectState state = new Helpers.ObjectState(); Helpers.ObjectState target = new Helpers.ObjectState(); state.positionX = posX; state.positionY = posY; int index = _flags.IndexOf(flag); if (flag.team != null) { if (flag.team._name == "Titan Militia") { if (index + 1 < _flags.Count) { target.positionX = _flags[index + 1].posX; target.positionY = _flags[index + 1].posY; } } if (flag.team._name == "Collective Military") { if (index - 1 >= 0) { target.positionX = _flags[index - 1].posX; target.positionY = _flags[index - 1].posY; } } byte fireAngle = Helpers.computeLeadFireAngle(state, target, 6500 / 1000); Helpers.Player_RouteExplosion(flag.team.ActivePlayers, 1128, posX, posY, 0, fireAngle, 0); tickLastPointer = now; } } if (attackers == 0 && defenders == 0) { tickStartCapture = 0; } if (attackers > defenders) { if (now - tickLastWave >= 2500) { Helpers.Player_RouteExplosion(_arena.Players, 3059, posX, posY, 0, 0, 0); tickLastWave = now; } if (tickStartCapture != 0 && attackers > 0) { int quickCaptureMod = ((attackers - 1) * 1000); tickStartCapture -= quickCaptureMod; } if (tickStartCapture != 0 && now - tickStartCapture >= 10000) { _arena.triggerMessage(0, 500, String.Format("{0} has taken control of the {1} capture point...", attacker._name, name)); _flags.FirstOrDefault(f => f == flag).team = attacker; foreach (Player player in playersInArea.Where(p => p._team == flag.team)) { _baseScript.StatsCurrent(player).flagCaptures++; } //Call our capture event, if it exists if (Captured != null) { Captured(_flag); } tickStartCapture = 0; } else if (tickStartCapture == 0) { tickStartCapture = now; } } if (defenders > attackers) { if (now - tickLastWave >= 2500) { //Helpers.Player_RouteExplosion(_arena.Players, 3059, posX, posY, 0, 0, 0); tickLastWave = now; tickStartCapture = 0; } } else { if (attackers == defenders && attackers > 0 && defenders > 0) { if (now - tickLastWave >= 1500) { Helpers.Player_RouteExplosion(_arena.Players, 3060, posX, posY, 0, 0, 0); tickLastWave = now; } tickStartCapture = 0; } } }
// benchmark stuff protected override void BenchmarkThreadRoutine(object CommandLine) { Thread.Sleep(ConfigManager.GeneralConfig.MinerRestartDelayMS); BenchmarkSignalQuit = false; BenchmarkSignalHanged = false; BenchmarkSignalFinnished = false; BenchmarkException = null; try { Helpers.ConsolePrint("BENCHMARK", "Benchmark starts"); Helpers.ConsolePrint(MinerTAG(), "Benchmark should end in : " + benchmarkTimeWait + " seconds"); BenchmarkHandle = BenchmarkStartProcess((string)CommandLine); BenchmarkHandle.WaitForExit(benchmarkTimeWait + 2); Stopwatch _benchmarkTimer = new Stopwatch(); _benchmarkTimer.Reset(); _benchmarkTimer.Start(); //BenchmarkThreadRoutineStartSettup(); // wait a little longer then the benchmark routine if exit false throw //var timeoutTime = BenchmarkTimeoutInSeconds(BenchmarkTimeInSeconds); //var exitSucces = BenchmarkHandle.WaitForExit(timeoutTime * 1000); // don't use wait for it breaks everything BenchmarkProcessStatus = BenchmarkProcessStatus.Running; bool keepRunning = true; while (keepRunning && IsActiveProcess(BenchmarkHandle.Id)) { //string outdata = BenchmarkHandle.StandardOutput.ReadLine(); //BenchmarkOutputErrorDataReceivedImpl(outdata); // terminate process situations if (_benchmarkTimer.Elapsed.TotalSeconds >= (benchmarkTimeWait + 2) || BenchmarkSignalQuit || BenchmarkSignalFinnished || BenchmarkSignalHanged || BenchmarkSignalTimedout || BenchmarkException != null) { string imageName = MinerExeName.Replace(".exe", ""); // maybe will have to KILL process KillClaymoreMinerBase(imageName); if (BenchmarkSignalTimedout) { throw new Exception("Benchmark timedout"); } if (BenchmarkException != null) { throw BenchmarkException; } if (BenchmarkSignalQuit) { throw new Exception("Termined by user request"); } if (BenchmarkSignalFinnished) { break; } keepRunning = false; break; } else { // wait a second reduce CPU load Thread.Sleep(1000); } } } catch (Exception ex) { BenchmarkThreadRoutineCatch(ex); } finally { BenchmarkAlgorithm.BenchmarkSpeed = 0; // find latest log file string latestLogFile = ""; var dirInfo = new DirectoryInfo(this.WorkingDirectory); foreach (var file in dirInfo.GetFiles("*_log.txt")) { latestLogFile = file.Name; break; } // read file log if (File.Exists(WorkingDirectory + latestLogFile)) { var lines = File.ReadAllLines(WorkingDirectory + latestLogFile); var addBenchLines = bench_lines.Count == 0; foreach (var line in lines) { if (line != null) { bench_lines.Add(line); string lineLowered = line.ToLower(); if (lineLowered.Contains(LOOK_FOR_START)) { if (ignoreZero) { double got = getNumber(lineLowered); if (got != 0) { benchmark_sum += got; ++benchmark_read_count; } } else { benchmark_sum += getNumber(lineLowered); ++benchmark_read_count; } } else if (lineLowered.Contains(SecondaryLookForStart())) { if (ignoreZero) { double got = getNumber(lineLowered, SecondaryLookForStart(), LOOK_FOR_END); if (got != 0) { secondary_benchmark_sum += got; ++secondary_benchmark_read_count; } } else { secondary_benchmark_sum += getNumber(lineLowered); ++secondary_benchmark_read_count; } } } } if (benchmark_read_count > 0) { BenchmarkAlgorithm.BenchmarkSpeed = benchmark_sum / benchmark_read_count; BenchmarkAlgorithm.SecondaryBenchmarkSpeed = secondary_benchmark_sum / secondary_benchmark_read_count; } } BenchmarkThreadRoutineFinish(); } }
public void WriteBackKh1Archive() => OpenKh2File().Using(expected => Helpers.AssertStream(expected, stream => { var actual = new MemoryStream(); ArchiveFactories.Ps4Kh2.Read(stream).Write(actual); return(actual); }));
public string GetFFmpegArgs(bool isCustom = false) { if (IsRecording && !FFmpeg.IsVideoSourceSelected && !FFmpeg.IsAudioSourceSelected) { return(null); } StringBuilder args = new StringBuilder(); args.Append("-rtbufsize 150M "); // default real time buffer size was 3041280 (3M) string fps; if (isCustom) { fps = "$fps$"; } else { fps = FPS.ToString(); } if (IsRecording) { if (FFmpeg.IsVideoSourceSelected) { if (FFmpeg.VideoSource.Equals(FFmpegCLIManager.SourceGDIGrab, StringComparison.InvariantCultureIgnoreCase)) { // http://ffmpeg.org/ffmpeg-devices.html#gdigrab args.AppendFormat("-f gdigrab -framerate {0} -offset_x {1} -offset_y {2} -video_size {3}x{4} -draw_mouse {5} -i desktop ", fps, isCustom ? "$area_x$" : CaptureArea.X.ToString(), isCustom ? "$area_y$" : CaptureArea.Y.ToString(), isCustom ? "$area_width$" : CaptureArea.Width.ToString(), isCustom ? "$area_height$" : CaptureArea.Height.ToString(), isCustom ? "$cursor$" : DrawCursor ? "1" : "0"); if (FFmpeg.IsAudioSourceSelected) { args.AppendFormat("-f dshow -i audio={0} ", Helpers.EscapeCLIText(FFmpeg.AudioSource)); } } else { args.AppendFormat("-f dshow -framerate {0} -i video={1}", fps, Helpers.EscapeCLIText(FFmpeg.VideoSource)); if (FFmpeg.IsAudioSourceSelected) { args.AppendFormat(":audio={0} ", Helpers.EscapeCLIText(FFmpeg.AudioSource)); } else { args.Append(" "); } } } else if (FFmpeg.IsAudioSourceSelected) { args.AppendFormat("-f dshow -i audio={0} ", Helpers.EscapeCLIText(FFmpeg.AudioSource)); } } else { args.Append($"-i \"{InputPath}\" "); } if (!string.IsNullOrEmpty(FFmpeg.UserArgs)) { args.Append(FFmpeg.UserArgs + " "); } if (FFmpeg.IsVideoSourceSelected) { if (IsLossless || FFmpeg.VideoCodec != FFmpegVideoCodec.apng) { string videoCodec; if (IsLossless) { videoCodec = FFmpegVideoCodec.libx264.ToString(); } else if (FFmpeg.VideoCodec == FFmpegVideoCodec.libvpx_vp9) { videoCodec = "libvpx-vp9"; } else { videoCodec = FFmpeg.VideoCodec.ToString(); } args.AppendFormat("-c:v {0} ", videoCodec); args.AppendFormat("-r {0} ", fps); // output FPS } if (IsLossless) { args.AppendFormat("-preset {0} ", FFmpegPreset.ultrafast); args.AppendFormat("-tune {0} ", FFmpegTune.zerolatency); args.AppendFormat("-qp {0} ", 0); } else { switch (FFmpeg.VideoCodec) { case FFmpegVideoCodec.libx264: // https://trac.ffmpeg.org/wiki/Encode/H.264 case FFmpegVideoCodec.libx265: // https://trac.ffmpeg.org/wiki/Encode/H.265 args.AppendFormat("-preset {0} ", FFmpeg.x264_Preset); if (IsRecording) { args.AppendFormat("-tune {0} ", FFmpegTune.zerolatency); } args.AppendFormat("-crf {0} ", FFmpeg.x264_CRF); args.AppendFormat("-pix_fmt {0} ", "yuv420p"); // -pix_fmt yuv420p required otherwise can't stream in Chrome args.AppendFormat("-movflags {0} ", "+faststart"); // This will move some information to the beginning of your file and allow the video to begin playing before it is completely downloaded by the viewer break; case FFmpegVideoCodec.libvpx: // https://trac.ffmpeg.org/wiki/Encode/VP8 case FFmpegVideoCodec.libvpx_vp9: // https://trac.ffmpeg.org/wiki/Encode/VP9 if (IsRecording) { args.AppendFormat("-deadline {0} ", "realtime"); } args.AppendFormat("-b:v {0}k ", FFmpeg.VPx_bitrate); args.AppendFormat("-pix_fmt {0} ", "yuv420p"); // -pix_fmt yuv420p required otherwise causing issues in Chrome related to WebM transparency support break; case FFmpegVideoCodec.libxvid: // https://trac.ffmpeg.org/wiki/Encode/MPEG-4 args.AppendFormat("-qscale:v {0} ", FFmpeg.XviD_qscale); break; case FFmpegVideoCodec.h264_nvenc: // https://trac.ffmpeg.org/wiki/HWAccelIntro#NVENC case FFmpegVideoCodec.hevc_nvenc: args.AppendFormat("-preset {0} ", FFmpeg.NVENC_preset); args.AppendFormat("-b:v {0}k ", FFmpeg.NVENC_bitrate); args.AppendFormat("-pix_fmt {0} ", "yuv420p"); args.AppendFormat("-movflags {0} ", "+faststart"); // This will move some information to the beginning of your file and allow the video to begin playing before it is completely downloaded by the viewer break; case FFmpegVideoCodec.h264_amf: case FFmpegVideoCodec.hevc_amf: args.AppendFormat("-usage {0} ", FFmpeg.AMF_usage); args.AppendFormat("-quality {0} ", FFmpeg.AMF_quality); args.AppendFormat("-pix_fmt {0} ", "yuv420p"); break; case FFmpegVideoCodec.h264_qsv: // https://trac.ffmpeg.org/wiki/Hardware/QuickSync case FFmpegVideoCodec.hevc_qsv: args.AppendFormat("-preset {0} ", FFmpeg.QSV_preset); args.AppendFormat("-b:v {0}k ", FFmpeg.QSV_bitrate); break; case FFmpegVideoCodec.libwebp: // https://www.ffmpeg.org/ffmpeg-codecs.html#libwebp args.AppendFormat("-lossless {0} ", "0"); args.AppendFormat("-preset {0} ", "default"); args.AppendFormat("-loop {0} ", "0"); break; case FFmpegVideoCodec.apng: args.Append("-f apng "); args.AppendFormat("-plays {0} ", "0"); break; } } } if (FFmpeg.IsAudioSourceSelected) { switch (FFmpeg.AudioCodec) { case FFmpegAudioCodec.libvoaacenc: // http://trac.ffmpeg.org/wiki/Encode/AAC args.AppendFormat("-c:a aac -ac 2 -b:a {0}k ", FFmpeg.AAC_bitrate); // -ac 2 required otherwise failing with 7.1 break; case FFmpegAudioCodec.libopus: // https://www.ffmpeg.org/ffmpeg-codecs.html#libopus-1 args.AppendFormat("-c:a libopus -b:a {0}k ", FFmpeg.Opus_bitrate); break; case FFmpegAudioCodec.libvorbis: // http://trac.ffmpeg.org/wiki/TheoraVorbisEncodingGuide args.AppendFormat("-c:a libvorbis -qscale:a {0} ", FFmpeg.Vorbis_qscale); break; case FFmpegAudioCodec.libmp3lame: // http://trac.ffmpeg.org/wiki/Encode/MP3 args.AppendFormat("-c:a libmp3lame -qscale:a {0} ", FFmpeg.MP3_qscale); break; } } if (Duration > 0) { args.AppendFormat("-t {0} ", isCustom ? "$duration$" : Duration.ToString("0.0", CultureInfo.InvariantCulture)); // duration limit } args.Append("-y "); // overwrite file string output; if (isCustom) { output = "$output$"; } else { output = Path.ChangeExtension(OutputPath, IsLossless ? "mp4" : FFmpeg.Extension); } args.AppendFormat("\"{0}\"", output); return(args.ToString()); }
public void UpdateEntertainmentGroupFromImage(MemoryStream image, int width, int height) { try { if (_sendingCommand || _cancelToken.IsCancellationRequested) { return; } if ((DateTime.UtcNow - _lastHueChangeTime).TotalMilliseconds < _frameTimeSpan.TotalMilliseconds) { return; } _sendingCommand = true; var start = DateTime.UtcNow; var(x, y) = (0, 0); Rgb24 c; foreach (var light in _streamBaseLayer) { (x, y) = MapLightLocationToImage(light.LightLocation, width, height); image.Seek(Helpers.GetImageCoordinate(width * 3, x, y), SeekOrigin.Begin); var min = _config.Model.hueSettings.minColorValue; var max = _config.Model.hueSettings.maxColorValue; var r = Math.Floor(image.ReadByte() * _config.Model.hueSettings.colorMultiplier); var g = Math.Floor(image.ReadByte() * _config.Model.hueSettings.colorMultiplier); var b = Math.Floor(image.ReadByte() * _config.Model.hueSettings.colorMultiplier); if (_lastLightColors.ContainsKey(light.Id)) { var lastColor = _lastLightColors[light.Id]; var blendAmount = 1.0f - _config.Model.hueSettings.blendLastColorAmount; if (blendAmount != 0.0f) { r = Math.Sqrt((1 - blendAmount) * Math.Pow(lastColor.R, 2) + blendAmount * Math.Pow(r, 2)); g = Math.Sqrt((1 - blendAmount) * Math.Pow(lastColor.G, 2) + blendAmount * Math.Pow(g, 2)); b = Math.Sqrt((1 - blendAmount) * Math.Pow(lastColor.B, 2) + blendAmount * Math.Pow(b, 2)); } if (lastColor.R >= r - _colorChangeThreshold && lastColor.R <= r + _colorChangeThreshold) { r = lastColor.R; } if (lastColor.G >= g - _colorChangeThreshold && lastColor.G <= g + _colorChangeThreshold) { g = lastColor.G; } if (lastColor.B >= b - _colorChangeThreshold && lastColor.B <= b + _colorChangeThreshold) { b = lastColor.B; } c = new Rgb24((byte)Math.Clamp(r, min, max), (byte)Math.Clamp(g, min, max), (byte)Math.Clamp(b, min, max)); _lastLightColors[light.Id] = c; } else { c = new Rgb24((byte)Math.Clamp(r, min, max), (byte)Math.Clamp(g, min, max), (byte)Math.Clamp(b, min, max)); _lastLightColors.Add(light.Id, c); } light.SetState(_cancelToken, new RGBColor(ColorHelper.ColorToHex(c)), 1.0); } _streamClient.ManualUpdate(_streamGroup); //Console.WriteLine($"UpdateEntertainmentGroupFromImage Time: {(DateTime.UtcNow - start).TotalMilliseconds}"); } catch (Exception ex) { _ = Task.Run(() => _logger?.WriteLog(ex.ToString())); } _lastHueChangeTime = DateTime.UtcNow; _sendingCommand = false; }
/// <summary> /// Parses attribute from data. /// </summary> /// <param name="data">SIP message data.</param> /// <param name="offset">Offset in data.</param> private void ParseAttribute(byte[] data, ref int offset) { /* RFC 3489 11.2. * Each attribute is TLV encoded, with a 16 bit type, 16 bit length, and variable value: * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Value .... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ // Type AttributeType type = (AttributeType)(data[offset++] << 8 | data[offset++]); // Length int length = (data[offset++] << 8 | data[offset++]); // MAPPED-ADDRESS if (type == AttributeType.MappedAddress) { m_pMappedAddress = ParseEndPoint(data, ref offset); } // RESPONSE-ADDRESS else if (type == AttributeType.ResponseAddress) { m_pResponseAddress = ParseEndPoint(data, ref offset); } // CHANGE-REQUEST else if (type == AttributeType.ChangeRequest) { /* * The CHANGE-REQUEST attribute is used by the client to request that * the server use a different address and/or port when sending the * response. The attribute is 32 bits long, although only two bits (A * and B) are used: * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A B 0| +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * The meaning of the flags is: * * A: This is the "change IP" flag. If true, it requests the server * to send the Binding Response with a different IP address than the * one the Binding Request was received on. * * B: This is the "change port" flag. If true, it requests the * server to send the Binding Response with a different port than the * one the Binding Request was received on. */ // Skip 3 bytes offset += 3; m_pChangeRequest = new STUN_t_ChangeRequest((data[offset] & 4) != 0, (data[offset] & 2) != 0); offset++; } // SOURCE-ADDRESS else if (type == AttributeType.SourceAddress) { m_pSourceAddress = ParseEndPoint(data, ref offset); } // CHANGED-ADDRESS else if (type == AttributeType.ChangedAddress) { m_pChangedAddress = ParseEndPoint(data, ref offset); } // USERNAME else if (type == AttributeType.Username) { m_UserName = Helpers.GetDefaultEncoding().GetString(data, offset, length); offset += length; } // PASSWORD else if (type == AttributeType.Password) { m_Password = Helpers.GetDefaultEncoding().GetString(data, offset, length); offset += length; } // MESSAGE-INTEGRITY else if (type == AttributeType.MessageIntegrity) { offset += length; } // ERROR-CODE else if (type == AttributeType.ErrorCode) { /* 3489 11.2.9. * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 0 |Class| Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Reason Phrase (variable) .. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ int errorCode = (data[offset + 2] & 0x7) * 100 + (data[offset + 3] & 0xFF); m_pErrorCode = new STUN_t_ErrorCode(errorCode, Helpers.GetDefaultEncoding().GetString(data, offset + 4, length - 4)); offset += length; } // UNKNOWN-ATTRIBUTES else if (type == AttributeType.UnknownAttribute) { offset += length; } // REFLECTED-FROM else if (type == AttributeType.ReflectedFrom) { m_pReflectedFrom = ParseEndPoint(data, ref offset); } // XorMappedAddress // XorOnly // ServerName else if (type == AttributeType.ServerName) { m_ServerName = Helpers.GetDefaultEncoding().GetString(data, offset, length); offset += length; } // Unknown else { offset += length; } }
/// <summary> /// Sets the state of the various controls based on the progressinfo /// object sent from the downloader service. /// </summary> /// <param name="progress"> /// The progressinfo object sent from the downloader service. /// </param> public void OnDownloadProgress(DownloadProgressInfo progress) { _averageSpeedTextView.Text = string.Format("{0} Kb/s", Helpers.GetSpeedString(progress.CurrentSpeed)); _timeRemainingTextView.Text = string.Format(Resources.GetString(Resource.String.exp_down_time_remaining), Helpers.GetTimeRemaining(progress.TimeRemaining)); _progressBar.Max = (int)(progress.OverallTotal >> 8); _progressBar.Progress = (int)(progress.OverallProgress >> 8); _progressPercentTextView.Text = string.Format("{0}%", progress.OverallProgress * 100 / progress.OverallTotal); _progressFractionTextView.Text = Helpers.GetDownloadProgressString(progress.OverallProgress, progress.OverallTotal); }
/// <summary> /// The download state should trigger changes in the UI. /// It may be useful to show the state as being indeterminate at times. /// </summary> /// <param name="newState"> /// The new state. /// </param> public void OnDownloadStateChanged(DownloaderClientState newState) { #if DEBUG Android.Util.Log.Debug(Tag, "Download state: " + newState); #endif if (_downloaderState != newState) { _downloaderState = newState; _statusTextView.Text = Helpers.GetDownloaderStringFromState(this, newState); } bool showDashboard = true; bool showCellMessage = false; bool paused = false; bool indeterminate = true; switch (newState) { case DownloaderClientState.Idle: case DownloaderClientState.Connecting: case DownloaderClientState.FetchingUrl: break; case DownloaderClientState.Downloading: indeterminate = false; break; case DownloaderClientState.Failed: case DownloaderClientState.FailedCanceled: case DownloaderClientState.FailedFetchingUrl: case DownloaderClientState.FailedUnlicensed: paused = true; showDashboard = false; indeterminate = false; break; case DownloaderClientState.PausedNeedCellularPermission: case DownloaderClientState.PausedWifiDisabledNeedCellularPermission: showDashboard = false; paused = true; indeterminate = false; showCellMessage = true; break; case DownloaderClientState.PausedByRequest: paused = true; indeterminate = false; break; case DownloaderClientState.PausedRoaming: case DownloaderClientState.PausedSdCardUnavailable: paused = true; indeterminate = false; break; default: paused = true; break; } if (newState != DownloaderClientState.Completed) { _dashboardView.Visibility = showDashboard ? ViewStates.Visible : ViewStates.Gone; _useCellDataView.Visibility = showCellMessage ? ViewStates.Visible : ViewStates.Gone; _progressBar.Indeterminate = indeterminate; UpdatePauseButton(paused); } else { ValidateExpansionFiles(); } }
/// <summary> /// <a href="http://math.nist.gov/javanumerics/jama/">Jama</a> [math.nist.gov] style: /// construct a 2D imaginary matrix from a one-dimensional packed array. /// </summary> /// <param name="Name">Array name</param> /// <param name="Real">One-dimensional array of <c>ushort</c> for <i>real</i> values, packed by columns</param> /// <param name="Imag">One-dimensional array of <c>ushort</c> for <i>imaginary</i> values, packed by columns</param> public MLUInt16(string Name, ushort[][] Real, ushort[][] Imag) : this(Name, Helpers.Array2DTo1D <ushort>(Real), Helpers.Array2DTo1D <ushort>(Imag), Real.Length) { }
/// <summary> /// <a href="http://math.nist.gov/javanumerics/jama/">Jama</a> [math.nist.gov] style: /// construct a 2D real matrix from <c>ushort[][]</c>. /// </summary> /// <remarks>Note: Array is converted to <c>ushort[]</c></remarks> /// <param name="Name">Array name</param> /// <param name="vals">Two-dimensional array of values</param> public MLUInt16(string Name, ushort[][] vals) : this(Name, Helpers.Array2DTo1D <ushort>(vals), vals.Length) { }
protected override string ResolveReference(TypeReference reference, object[] args) { if (reference is TypeReference.ConstantTypeReference) { return("string"); } if (reference is TypeReference.TypeModelReference typeModelRef) { return(Helpers.PascalCase(typeModelRef.Model.Name.AsSpan())); } if (reference is TypeReference.ArrayTypeReference arrayTypeRef) { return($"IImmutableList<{ResolveReference(arrayTypeRef.BaseType, args)}>"); } if (reference is TypeReference.DictionaryTypeReference dictTypeRef) { return($"IImmutableDictionary<string, {ResolveReference(dictTypeRef.ValueType, args)}>"); } if (reference == TypeReference.Boolean) { return("bool"); } if (reference == TypeReference.Int32) { return("int"); } if (reference == TypeReference.Int64) { return("long"); } if (reference == TypeReference.Float) { return("float"); } if (reference == TypeReference.Double) { return("double"); } if (reference == TypeReference.String) { return("string"); } if (reference == TypeReference.Date) { return("DateTimeOffset"); } if (reference == TypeReference.DateTime) { return("DateTimeOffset"); } if (reference == TypeReference.Uuid) { return("Guid"); } if (reference == TypeReference.Void) { return("void"); } if (reference == TypeReference.Any) { return("Newtonsoft.Json.Linq.JToken"); } if (reference == TypeReference.File) { return("System.IO.Stream"); } if (reference == TypeReference.Byte) { // TODO: implement this } throw new NotSupportedException(reference.ToString()); }
public CommandParser(string fileName) { commands = Helpers.ReadJsonFile <Command>(fileName); }
public UserServiceTest() { _manager = Helpers.GetMockUserManager(); }
private static string Parse(List<MiningPair> miningPairs, List<MinerOption> options, bool useIfDefaults = true, List<MinerOption> ignoreLogOpions = null, bool ignoreDcri = false) { const string ignoreParam = "Cannot parse \"{0}\", not supported, set to ignore, or wrong extra launch parameter settings"; var optionsOrder = new List<string>(); var cdevOptions = new Dictionary<string, Dictionary<string, string>>(); var isOptionDefaults = new Dictionary<string, bool>(); var isOptionExist = new Dictionary<string, bool>(); // init devs options, and defaults foreach (var pair in miningPairs) { var defaults = new Dictionary<string, string>(); foreach (var option in options) { defaults[option.Type] = option.Default; } cdevOptions[pair.Device.Uuid] = defaults; } // init order and params flags, and params list foreach (var option in options) { var optionType = option.Type; optionsOrder.Add(optionType); isOptionDefaults[optionType] = true; isOptionExist[optionType] = false; } // parse foreach (var pair in miningPairs) { LogParser($"ExtraLaunch params \"{pair.CurrentExtraLaunchParameters}\" for device UUID {pair.Device.Uuid}"); var parameters = pair.CurrentExtraLaunchParameters.Replace("=", "= ").Split(' '); IgnorePrintLogInit(); var currentFlag = MinerOptionTypeNone; var ignoringNextOption = false; foreach (var param in parameters) { if (param.Equals("")) continue; if (currentFlag == MinerOptionTypeNone) { var isIngored = true; foreach (var option in options) { if (param.Equals(option.ShortName) || param.Equals(option.LongName)) { isIngored = false; if (ignoreDcri && option.Type.Equals("ClaymoreDual_dcri")) { Helpers.ConsolePrint("CDTUNING", "Disabling dcri extra launch param"); ignoringNextOption = true; } else { if (option.FlagType == MinerOptionFlagType.Uni) { isOptionExist[option.Type] = true; cdevOptions[pair.Device.Uuid][option.Type] = "notNull"; // if Uni param is null it is not present } else { // Sinlge and Multi param currentFlag = option.Type; } } } } if (isIngored) { if (ignoringNextOption) { // This is a paramater for an ignored option, silently ignore it ignoringNextOption = false; } else { IgnorePrintLog(param, ignoreParam, ignoreLogOpions); } } } else if (currentFlag != MinerOptionTypeNone) { isOptionExist[currentFlag] = true; cdevOptions[pair.Device.Uuid][currentFlag] = param; currentFlag = MinerOptionTypeNone; } else { // problem IgnorePrintLog(param, ignoreParam, ignoreLogOpions); } } } var retVal = ""; // check if is all defaults var isAllDefault = true; foreach (var pair in miningPairs) { foreach (var option in options) { if (option.Default != cdevOptions[pair.Device.Uuid][option.Type]) { isAllDefault = false; isOptionDefaults[option.Type] = false; } } } if (!isAllDefault || useIfDefaults) { foreach (var option in options) { if (isOptionDefaults[option.Type] && !isOptionExist[option.Type] && !useIfDefaults) continue; // if options all default ignore switch (option.FlagType) { case MinerOptionFlagType.Uni: // uni params if one exist use or all must exist? var isOptionInUse = miningPairs.Any(pair => cdevOptions[pair.Device.Uuid][option.Type] != null); if (isOptionInUse) { retVal += $" {option.LongName}"; } break; case MinerOptionFlagType.MultiParam: { var values = miningPairs.Select(pair => cdevOptions[pair.Device.Uuid][option.Type]).ToList(); var mask = " {0} {1}"; if (option.LongName.Contains("=")) { mask = " {0}{1}"; } retVal += string.Format(mask, option.LongName, string.Join(option.Separator, values)); break; } case MinerOptionFlagType.SingleParam: { var values = new HashSet<string>(); foreach (var pair in miningPairs) { values.Add(cdevOptions[pair.Device.Uuid][option.Type]); } var setValue = option.Default; if (values.Count >= 1) { // Always take first setValue = values.First(); } var mask = " {0} {1}"; if (option.LongName.Contains("=")) { mask = " {0}{1}"; } retVal += string.Format(mask, option.LongName, setValue); break; } case MinerOptionFlagType.DuplicateMultiParam: { const string mask = " {0} {1}"; var values = miningPairs.Select(pair => string.Format(mask, option.LongName, cdevOptions[pair.Device.Uuid][option.Type])).ToList(); retVal += " " + string.Join(" ", values); break; } } } } LogParser($"Final extra launch params parse \"{retVal}\""); return retVal; }
private static void SafeDeleteDirectory(string directoryName, string directoryFilter, string fileFilter) { #if DotNetCoreClr // Disable compiling on windows for now. Need to correct when porting FabricDeployer for windows. if (!Directory.Exists(directoryName) || IsDirectorySymbolicLink(directoryName) || string.Equals(directoryName, directoryFilter, StringComparison.OrdinalIgnoreCase)) { return; } // Avoid deleting any file locks var files = Directory.GetFiles(directoryName).Where( (f => !f.EndsWith(FileLock.ReaderLockExtension, StringComparison.OrdinalIgnoreCase) && !f.EndsWith(FileLock.WriterLockExtension, StringComparison.CurrentCultureIgnoreCase))); #else if (!Directory.Exists(directoryName) || IsDirectorySymbolicLink(directoryName) || string.Equals(directoryName, directoryFilter, StringComparison.InvariantCultureIgnoreCase)) { return; } // Avoid deleting any file locks var files = Directory.GetFiles(directoryName).Where( (f => !f.EndsWith(FileLock.ReaderLockExtension, StringComparison.InvariantCultureIgnoreCase) && !f.EndsWith(FileLock.WriterLockExtension, StringComparison.InvariantCultureIgnoreCase))); #endif foreach (var file in files) { if (FabricFile.Exists(file) && !string.Equals(file, fileFilter, StringComparison.OrdinalIgnoreCase)) { try { FabricFile.Delete(file, true); } catch (Exception ex) { DeployerTrace.WriteError("SafeDeleteDirectory failed deleting file: {0}. Exception: {1}.", file, ex); throw; } } } foreach (var subDirectoryName in Directory.GetDirectories(directoryName)) { SafeDeleteDirectory(subDirectoryName, directoryFilter, fileFilter); } if (!Directory.GetDirectories(directoryName).Any() && !Directory.GetFiles(directoryName).Any()) { try { TimeSpan retryInterval = TimeSpan.FromSeconds(5); int retryCount = 12; Type[] exceptionTypes = { typeof(System.IO.FileLoadException) }; Helpers.PerformWithRetry(() => { try { FabricDirectory.Delete(directoryName); } catch (Exception ex) { DeployerTrace.WriteWarning("Directory Delete failed for {0} due to: {1}.", directoryName, ex.Message); throw; } }, exceptionTypes, retryInterval, retryCount); } catch (Exception ex) { DeployerTrace.WriteError("SafeDeleteDirectory failed deleting directory: {0}. Exception: {1}.", directoryName, ex); throw; } } DeployerTrace.WriteInfo("Removed folder: {0}", directoryName); }