private static void _addRptParams(IDbConnection conn, String rptUID, Params prms, String userUID, String remoteIP) { var v_prms = new Params(); v_prms.SetValue("p_rpt_uid", rptUID); var v_sql = "begin xlr.clear_rparams(:p_rpt_uid); end;"; SQLCmd.ExecuteScript(conn, v_sql, v_prms, 120); v_sql = "begin xlr.add_rparam(:p_rpt_uid, :p_prm_name, :p_prm_type, :p_prm_val, :p_usr_uid, :p_remote_ip); end;"; foreach (var v_prm in prms) { v_prms.SetValue("p_prm_name", v_prm.Name); String v_prmValue; var v_prmTypeStr = "A"; if (v_prm.Value != null) { var v_prmType = v_prm.ParamType ?? v_prm.Value.GetType(); if (Utl.TypeIsNumeric(v_prmType)) { v_prmTypeStr = "N"; v_prmValue = "" + v_prm.Value; v_prmValue = v_prmValue.Replace(",", "."); } else if (v_prmType == typeof(DateTime)) { v_prmTypeStr = "D"; v_prmValue = ((DateTime)v_prm.Value).ToString("yyyy.MM.dd HH:mm:ss"); } else v_prmValue = "" + v_prm.Value; } else continue; v_prms.SetValue("p_prm_type", v_prmTypeStr); v_prms.SetValue("p_prm_val", v_prmValue); v_prms.SetValue("p_usr_uid", userUID); v_prms.SetValue("p_remote_ip", remoteIP); SQLCmd.ExecuteScript(conn, v_sql, v_prms, 120); } }
static void DeleteFile(RxMessageBrokerMinimod bus, Params @params) { var file = @params.File.FileName; bus.Send(new AdvanceToNextFile()); bus.Send(new DeleteFile(file, @params.Command.WhatIf)); }
public static void Generate(IMapGrid map, Params param) { m_params = param; map.Init(); // round block for (int x = 0; x < map.Width; x++) for (int y = 0; y < map.Height; y++) if (x == 0 || y == 0 || x == (map.Width - 1) || y == (map.Height - 1)) map.SetID (x, y, MapGridTypes.ID.Blocked); else map.SetID (x, y, MapGridTypes.ID.Empty); // create rooms PlaceRooms(map); // create corridors PlaceCorridors(map); // place stairs PlaceStairs(map); // remove dead ends if (m_params.RemoveDeadEnd) RemoveDeadEnds(map); // final cleanup Cleanup(map); }
private static String _prepareParamValue(Params inParams, String paramText) { if (String.IsNullOrEmpty(paramText)) return paramText; foreach (var t in inParams) paramText = paramText.Replace("#" + t.Name + "#", t.ValueAsString()); return paramText; }
/// <summary> /// Inits this instance. /// </summary> /// <returns></returns> private bool Init() { this.Graph = this.Model as IGraph; if (Graph == null) throw new InconsistencyException("The model has not been set and the Graph property is hence 'null'"); this.LayoutRoot = this.Controller.Model.LayoutRoot;//could be null if not set in the GUI Graph.ClearSpanningTree(); Graph.MakeSpanningTree(LayoutRoot as INode); Pars = new Dictionary<string, Params>(); if (Graph.Nodes.Count == 0) return false; if (Graph.Edges.Count == 0) //this layout is base on embedded springs in the connections return false; Params par; foreach (INode node in Graph.Nodes) { par = new Params(); Pars.Add(node.Uid.ToString(), par); } return true; }
protected internal OCRCharacterResult run(Params params1) { double d = 4.9406564584124654E-324D; int[] ai = { -1, -1 }; ReferenceCharacter referencecharacter = ReferenceCharacter.INVALID; IEnumerator iterator = params1.references.GetEnumerator(); do { if (!iterator.MoveNext()) break; ReferenceCharacter referencecharacter1 = (ReferenceCharacter)iterator.Current; double[] ad = calculateMatch(params1.symbol, referencecharacter1.image); double d1 = ad[0]; if (d1 > d) { d = d1; ai[0] = (int)ad[1]; ai[1] = (int)ad[2]; referencecharacter = referencecharacter1; } } while (true); if (referencecharacter == ReferenceCharacter.INVALID) return OCRCharacterResult.INVALID; else return new OCRCharacterResult(referencecharacter, d); }
private void _exec(Params bioPrms, AjaxRequestDelegate callback, SQLTransactionCmd cmd, Boolean silent) { if (this.AjaxMng == null) throw new EBioException("Свойство \"ajaxMng\" должно быть определено!"); if (String.IsNullOrEmpty(this.BioCode)) throw new EBioException("Свойство \"bioCode\" должно быть определено!"); this.BioParams = Params.PrepareToUse(this.BioParams, bioPrms); this._lastRequestedBioCode = this.BioCode; this.AjaxMng.Request(new BioSQLRequest { RequestType = RequestType.SQLR, BioCode = this.BioCode, BioParams = this.BioParams, transactionCmd = cmd, transactionID = this.TransactionID, Prms = null, Silent = silent, Callback = (sndr, args) => { if (args.Response.Success) { var rsp = args.Response as BioResponse; if (rsp != null){ this._lastReturnedParams = (rsp.BioParams != null) ? rsp.BioParams.Clone() as Params : null; this.TransactionID = rsp.TransactionID; } } if (callback != null) callback(this, args); } }); }
public ExternalMonitorAdder(IRequestSender<SimpleResponse> requestSender, ILog log ) { RequestSender = requestSender; Log = log; LocationIds = new List<int>(); Params = new Params(); }
/// <summary> /// Конструктор /// </summary> /// <param name="connStr"></param> /// <param name="workSpaceSchema"></param> public DBSession(String connStr, String workSpaceSchema) { this._connStrItems = new Params(); this._storedTrans = new Dictionary<String, IDbTransaction>(); this._connStr = connStr; this._parsConnectionStr(this._connStr); this._workSpaceSchema = workSpaceSchema; }
public void OpenModal(Params bioPrms, HtmlPopupWindowOptions opts) { if (this.AjaxMng == null) throw new EBioException("Свойство \"ajaxMng\" должно быть определено!"); if (String.IsNullOrEmpty(this.BioCode)) throw new EBioException("Свойство \"bioCode\" должно быть определено!"); this.BioParams = Params.PrepareToUse(this.BioParams, bioPrms); var v_cli = new SQLRClient(); v_cli.AjaxMng = this.AjaxMng; v_cli.BioCode = "iod.ping_webdb"; //http://localhost/ekb8/srv.aspx?rqtp=FileSrv&rqbc=ios.givc.mailer.getAttchmntFile&hf=1216 var urlBody = this._bldBodyUrl(); const string c_url = "sys/HTMLShowPage.htm"; var v_opts = opts ?? new HtmlPopupWindowOptions { Width = 600, Height = 500 }; v_cli.Exec(null, (s, a) => { var v_opts_line = ""; Utl.AppendStr(ref v_opts_line, "resizable:" + ((v_opts.Resizeable) ? "yes" : "no"), ";"); Utl.AppendStr(ref v_opts_line, "menubar:no;status:no;center:yes;help:no;minimize:no;maximize:no;border:think;statusbar:no", ";"); Utl.AppendStr(ref v_opts_line, "dialogWidth:" + v_opts.Width + "px", ";"); Utl.AppendStr(ref v_opts_line, "dialogHeight:" + v_opts.Height + "px", ";"); //var v_rsp = a.response as BioResponse; var v_html = "Сообщение" + "||" + urlBody; var v_js = String.Format("self.showModalDialog('{0}', '{1}', '{2}');", c_url, v_html, v_opts_line); HtmlPage.Window.Eval(v_js); }); }
/// <summary> /// Calculates the attraction or tension on the given edge. /// </summary> /// <param name="edge">The edge.</param> public void CalculateAttraction(IEdge edge) { INode n1, n2; Params n1p = new Params(); Params n2p = new Params(); if (edge.SourceNode != null) { n2 = edge.SourceNode; n2p = Pars[n2.Uid.ToString()]; }; if (edge.TargetNode != null) { n1 = edge.TargetNode; n1p = Pars[n1.Uid.ToString()]; }; double xDelta = n1p.loc[0] - n2p.loc[0]; double yDelta = n1p.loc[1] - n2p.loc[1]; double deltaLength = Math.Max(EPSILON, Math.Sqrt(xDelta * xDelta + yDelta * yDelta)); double force = (deltaLength * deltaLength) / forceConstant; if (Double.IsNaN(force)) { System.Diagnostics.Trace.WriteLine("Oops, the layout resulted in a NaN problem."); return; } double xDisp = (xDelta / deltaLength) * force; double yDisp = (yDelta / deltaLength) * force; n1p.disp[0] -= xDisp; n1p.disp[1] -= yDisp; n2p.disp[0] += xDisp; n2p.disp[1] += yDisp; }
public static async Task<bool> Execute(Params @params) { var arguments = string.Join(" ", string.Format("\"{0}\"", @params.SolutionPath), @params.Args, string.Format(MsBuildArgs, @params.Configuration, @params.Platform, @params.Verbosity)); var process = new Process { StartInfo = new ProcessStartInfo(MsBuildPath) { Arguments = arguments, CreateNoWindow = true, RedirectStandardOutput = true, UseShellExecute = false } }; process.OutputDataReceived += (sender, args) => @params.Callback(args.Data); process.Start(); process.BeginOutputReadLine(); while (!process.HasExited) { if (@params.CancellationToken.IsCancellationRequested) { process.Kill(); return false; } await Task.Delay(50, @params.CancellationToken); } return process.ExitCode == 0; }
public static void LoadItems(AjaxResponse prevResponse, IAjaxMng ajaxMng, ComboBox cbx, String bioCode, Params bioParams, Action<ComboBox, AjaxResponse> callback, Boolean addNullItem, Boolean useCache) { if ((prevResponse != null) && (!prevResponse.Success)) { if (callback != null) callback(cbx, prevResponse); return; } var v_cli = new JsonStoreClient { AjaxMng = ajaxMng, BioCode = bioCode }; CbxItems storedItems = null; if (useCache) storedItems = _restoreItems(bioCode); if (storedItems != null) { _loadItems(cbx, storedItems, addNullItem); if (callback != null) callback(cbx, new AjaxResponse { Success = true }); } else { v_cli.Load(bioParams, (s, a) => { if (a.Response.Success) { var cbxitems = new CbxItems {metadata = v_cli.JSMetadata, ds = v_cli.DS}; if (useCache) _storeItems(bioCode, cbxitems); _loadItems(cbx, cbxitems, addNullItem); } if (callback != null) callback(cbx, a.Response); }); } }
static Params ParseCmdLine(string[] args) { if (args.Length == 0) return null; var res = new Params(); var s = args[0].ToLower(); switch (s) { case "-gen": res.ActionToPerform = Params.Action.Generate; break; case "-encr": res.ActionToPerform = Params.Action.Encrypt; break; case "-decr": res.ActionToPerform = Params.Action.Decrypt; break; default: return null; } if (res.ActionToPerform == Params.Action.Generate) { if (args.Length != 3) return null; res.KeyFile = args[1]; res.Pwd = args[2]; } else { if (args.Length != 4) return null; res.InFile = args[1]; res.OutFile = args[2]; res.KeyFile = args[3]; } return res; }
public virtual void Init(Params pBioParams) { this.Init(new JsonStoreRequestGet { BioParams = pBioParams, Packet = this._creJSData(), Sort = null, //nav = null }); }
public static void Main() { Params p1=new Params(),p2=new Params(); p1.x=p2.x=100; modify(ref p1); modify1(p2); System.Console.WriteLine(p1.x + " " + p2.x); }
public TcpConnection(Params.Connection param) { EndPoint = param.EndPoint; ReceiveBufferSettings = param.ReceiveBuffer; SendBufferSettings = param.SendBuffer; Logger.Network.Debug("New TCP connection created for host " + EndPoint.Address.ToString() + " on port " + EndPoint.Port.ToString()); }
public object Create(Params prms) { return new ServerConfiguration() { Port = prms.GetValue<int>(ServerParams.Port), SendBigDataDelay = prms.GetValue<int>(ServerParams.SendBigDataDelay) }; }
public void TestParseArgs() { Params parameters = new Params(); string[] testargs; //test basic parameter testargs = new string[2] { "-c", "C:\test.txt" }; parameters = ParseArgs(testargs); Assert.Equal("C:\test.txt", parameters.configFile); Assert.Equal(false, parameters.validate); Assert.Equal(false, parameters.showHelp); //config file and validate param testargs = new string[3] { "-c", "C:\test.txt", "--validate" }; parameters = ParseArgs(testargs); Assert.Equal("C:\test.txt", parameters.configFile); Assert.Equal(true, parameters.validate); Assert.Equal(false, parameters.showHelp); //config file and logLevelOverride testargs = new string[4] { "-c", "C:\test.txt", "-l", "Debug" }; parameters = ParseArgs(testargs); Assert.Equal("C:\test.txt", parameters.configFile); Assert.Equal(false, parameters.validate); Assert.Equal(false, parameters.showHelp); //help param testargs = new string[1] { "--help" }; parameters = ParseArgs(testargs); Assert.True(String.IsNullOrEmpty(parameters.configFile)); Assert.Equal(false, parameters.validate); Assert.Equal(true, parameters.showHelp); //help param with another param testargs = new string[3] { "-c", "C:\test.txt", "-h" }; parameters = ParseArgs(testargs); Assert.Equal(false, parameters.validate); Assert.Equal(true, parameters.showHelp); //add the more param testargs = new string[5] { "-c", "C:\test.txt", "--validate", "--more", "30" }; parameters = ParseArgs(testargs); Assert.Equal("C:\test.txt", parameters.configFile); Assert.Equal(true, parameters.validate); Assert.Equal(false, parameters.showHelp); Assert.Equal(30, parameters.more); //add logLevel testargs = new string[7] { "-c", "C:\test.txt", "--validate", "-m", "30", "--loglevel", "Warn" }; parameters = ParseArgs(testargs); Assert.Equal("C:\test.txt", parameters.configFile); Assert.Equal(true, parameters.validate); Assert.Equal(false, parameters.showHelp); Assert.Equal(30, parameters.more); //invalid --more param should throw an OptionException testargs = new string[5] { "-c", "C:\test.txt", "--validate", "--more", "notanint" }; Assert.Throws<OptionException>(delegate { ParseArgs(testargs); }); }
public void SetRequest(IRequest request, IResponse response, Session session, Params parameters, Client client) { Request = request; Response = response; Session = session; Params = parameters; Client = client; Library = Library.Instance; }
private string GetJsonProperties() { var settings = new Params { tracker_error_ratio = TrackerErrorRatio, maps = Maps.ToArray() }; return JsonUtility.ToJson(settings); }
private IDbCommand _prepareCmdDelegate(IDbConnection conn, ref String currentSQL, ref Params currentParams) { IDbCommand stmt = null; XmlElement vDS = this.FBioDesc.DocumentElement; if (vDS != null) { CJSCursor vCursor = new CJSCursor(conn, vDS, this.bioCode); currentParams = (Params)this.bioParams.Clone(); stmt = vCursor.DoPrepareCommand(currentParams, ref currentSQL, 0); } return stmt; }
public object Create(Params prms) { return new ClientConfiguration() { Port = prms.GetValue<int>(ClientParams.Port), RegistrationTimeout = prms.GetValue<int>(ClientParams.ServerRegistrationTimeout), ServerIP = prms.GetValue<string>(ClientParams.ServerIP), ServerPort = prms.GetValue<int>(ClientParams.ServerPort) }; }
public static Params Parse(string[] args, IEnumerable<string> gitBranches) { var errors = new List<string>(); var branches = new List<string>(); var p = new Params(); foreach(var o in args) { if (o.Equals("--console-output")) p.UseConsole = true; else if (o.Equals("--caps-lock")) p.UseCapsLock = true; else if (o.Equals("--skip-empty-commits")) p.SkipEmptyCommits = true; else if (o.Equals("--ignore-labels")) p.IgnoreLabels = true; else if (o.Equals("--help")) { errors.Add("Usage: vault2git [options]"); errors.Add("options:"); errors.Add(" --help This screen"); errors.Add(" --console-output Use console output (default=no output)"); errors.Add(" --caps-lock Use caps lock to stop at the end of the cycle with proper finalizers (default=no caps-lock)"); errors.Add(" --branch=<branch> Process only one branch from config. Branch name should be in git terms. Default=all branches from config"); errors.Add(" --limit=<n> Max number of versions to take from Vault for each branch"); errors.Add(" --skip-empty-commits Do not create empty commits in Git"); errors.Add(" --ignore-labels Do not create Git tags from Vault labels"); } else if (o.StartsWith(_limitParam)) { var l = o.Substring(_limitParam.Length); var max = 0; if (int.TryParse(l, out max)) p.Limit = max; else errors.Add(string.Format("Incorrect limit ({0}). Use integer.", l)); } else if (o.StartsWith(_branchParam)) { var b = o.Substring(_limitParam.Length); if (gitBranches.Contains(b)) branches.Add(b); else errors.Add(string.Format("Unknown branch {0}. Use one specified in .config", b)); } else errors.Add(string.Format("Unknown option {0}", o)); } p.Branches = 0 == branches.Count() ? gitBranches : branches; p.Errors = errors; return p; }
/// <summary> /// Parse cli args using the NDesk library /// </summary> /// <param name="args">Array of arguments</param> /// <returns>Params struct represnting the options</returns> protected static Params ParseArgs(string[] args) { Params parameters = new Params(); //Create a list of possible values of LogLevels to include in the help info string logLevels = ""; foreach (var value in Enum.GetValues(typeof(LogLevel))) { if (logLevels != "") { logLevels += ", "; } logLevels += Convert.ToString((LogLevel)value); } /* * Initialize NDesk.OptionSet object. * For each block the first value represents the parameter name and whether it takes a value or is a switch. * Arguments that take values have an = sign at the end, the others are switches. * The second element is the help info to print. * The third is a lambra expression that NDesk executes if that argument is passed in. */ var p = new OptionSet() { { "c|configfile=" , "The config file {PATH}." , v => parameters.configFile = v }, { "v|validate" , "Validate configuration file, print the parsed contents " + "to the console and exit." , v => parameters.validate = true }, { "m|more=" , "Used with --validate, emulates the unix more utility. Prints {NUM} lines" + " and then waits for input before continuing." , ( int v) => parameters.more = v }, { "h|help" , "show this message and exit" , v => parameters.showHelp = v != null }, { "f|logfile=", "The log file {PATH}.", v => parameters.logFile = v }, { "p|datamappingfile=", "The data type mappings file {PATH} used by Slave agents.", v => parameters.dataMappingFile = v}, { "n|log4netfile=", "The log4net configuration file {PATH}.", v => parameters.log4NetConfigPath = v}, { "a|agent=", "The agent type that you wish to run. Valid options are 'Master', 'Slave', 'ShardCoordinator', 'MasterMaintenance', 'RelayMaintenance', 'SlaveMaintenance', 'Notifier'", v => parameters.agentType = (AgentType)Enum.Parse(typeof(AgentType),v)} }; //Save the option set object to the params struct. This is required to run ShowHelp if --help is passed in. parameters.optionSet = p; //parse the arguments against the OptionSet //extra will hold a list of unprocessed/unsupported args, which we will ignore. List<string> extra = p.Parse(args); foreach (string s in extra) { //can't use Logger class because LogLevel wouldn't have been loaded into config yet. //just warn the user via cli about this Console.WriteLine("Warning: unprocessed CLI arg: " + s); } return parameters; }
public void Open(Params bioPrms, HtmlPopupWindowOptions opts) { var v_url_body = this._bldBodyUrl(); this.BioParams = Params.PrepareToUse(this.BioParams, bioPrms); var v_cli = new SQLRClient(); v_cli.AjaxMng = this.AjaxMng; v_cli.BioCode = "iod.ping_webdb"; v_cli.Exec(null, (s, a) => HtmlPage.Window.Navigate(new Uri(v_url_body, UriKind.Relative), "myTarget")); }
/// <summary> /// Добавляет в очередь новый процесс создания отчета. Возвращает UID просесса. /// </summary> /// <param name="rptCode">Код содаваемого отчета</param> /// <param name="sessionID">ID сессии в которой создается процесс</param> /// <param name="userUID">UID пользователя, который запускает процесс</param> /// <param name="remoteIP">IP адрес с котороко запускается процесс</param> /// <param name="prms">Параметры отчета</param> /// <param name="priority">Уроверь приоритетности</param> /// <returns>UID просесса</returns> public String Add(String rptCode, String sessionID, String userUID, String remoteIP, Params prms, ThreadPriority priority) { String err_json = null; int v_priority = (int)priority; String v_prms = prms.Encode(); String rslt = this._remoteObject.Add(rptCode, sessionID, userUID, remoteIP, v_prms, v_priority, ref err_json); if (!String.IsNullOrEmpty(err_json)) { EBioException ex = EBioException.Decode(err_json); throw ex; } return rslt; }
static void Send(Params @params) { var copyDataMem = IntPtr.Zero; var dataPointer = IntPtr.Zero; try { var dataSize = 0; dataPointer = IntPtr.Zero; if (@params.Send.Data != null) { // Same algorithm to determine size as in Marshal.StringToHGlobalUni. dataSize = (@params.Send.Data.Length + 1) * 2; dataPointer = Marshal.StringToHGlobalUni(@params.Send.Data); } var copyData = new COPYDATASTRUCT { dwData = new UIntPtr(@params.Send.Message), cbData = dataSize, lpData = dataPointer }; copyDataMem = Marshal.AllocHGlobal(Marshal.SizeOf(copyData)); Marshal.StructureToPtr(copyData, copyDataMem, true); var result = NativeMethods.SendMessage(@params.Connection.Handle, NativeConstants.WM_COPYDATA, @params.Receiver.Handle, copyDataMem); if (result == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error()); } RxMessageBrokerMinimod.Default.Send(new Log("Sent message {0} to MPC", @params.Send.Info())); } catch (Exception ex) { RxMessageBrokerMinimod.Default.Send(new Log("Failed to send message {0} to MPC: {1}", @params.Send.Info(), ex.Message)); } finally { if (copyDataMem != IntPtr.Zero) { Marshal.FreeHGlobal(copyDataMem); } if (dataPointer != IntPtr.Zero) { Marshal.FreeHGlobal(dataPointer); } } }
private static void _applayParams(SqlCommand cmd, Params prms) { cmd.Parameters.Clear(); foreach (var v_p in prms) { var v_type = v_p.Value == null ? typeof(String) : v_p.Value.GetType(); if (v_p.ParamType != null) v_type = v_p.ParamType; long v_size = 0; if(v_type == typeof(String)) v_size = v_p.ParamSize; cmd.Parameters.Add(v_p.Name, detectSqlTypeByType(v_type, v_size)).Value = v_p.Value; } }
//public //constructor public CXLRMacro(XmlElement definition){ this.FParams = new Params(); if (definition != null) { Boolean v_enabled = Xml.getAttribute<Boolean>(definition, "enabled", true); if (v_enabled) { this.FName = Xml.getAttribute<String>(definition, "name", null); XmlNodeList vParams = definition.SelectNodes("param"); foreach (XmlElement e in vParams) this.FParams.Add(e.GetAttribute("name"), e.InnerText); } } }
/// <summary> /// <para> /// Returns a list of air traffic reports based on the number of searches. /// </para> /// /// <pre> /// amadeus.travel.analytics.airTraffic.searched.get(Params /// .with("originCityCode", "MAD") /// .and("searchPeriod", "2017-08") /// .and("marketCountryCode", "ES"));</pre> /// </summary> /// <param name="params"> the parameters to send to the API </param> /// <returns> an API response object </returns> /// <exception cref="ResponseException"> when an exception occurs </exception> public virtual Search[] Get(Params @params) { Response response = client.Get("/v1/travel/analytics/air-traffic/searched", @params); return((Search[])Resource.FromArray(response, typeof(Search[]))); }
// GET: api/DocDomesticExpenseTabs public async Task <IHttpActionResult> GetDocDomesticExpenseTabs(HttpRequestMessage request) { try { #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции //Получаем Куку System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"]; // Проверяем Логин и Пароль Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true)); if (!field.Access) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10))); } //Изменяем строку соединения db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true)); //Права (1 - Write, 2 - Read, 3 - No Access) int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocDomesticExpenses")); if (iRight == 3) { return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)))); } //Разные Функции function.NumberDecimalSeparator(); //Получам настройки Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1); #endregion #region Параметры Params _params = new Params(); //paramList -список параметров var paramList = request.GetQueryNameValuePairs(); //Параметры _params.DocDomesticExpenseID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocDomesticExpenseID", true) == 0).Value); //_params.DocDate = Convert.ToDateTime(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocDate", true) == 0).Value); _params.DateS = Convert.ToDateTime(Convert.ToDateTime(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocDateS", true) == 0).Value).ToString("yyyy-MM-dd 23:59:59")); if (_params.DateS < Convert.ToDateTime("01.01.1800")) { _params.DateS = Convert.ToDateTime(sysSetting.JurDateS.ToString("yyyy-MM-dd 00:00:00")).AddDays(-1); } else { _params.DateS = _params.DateS.Value.AddDays(-1); } _params.DatePo = Convert.ToDateTime(Convert.ToDateTime(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocDatePo", true) == 0).Value).ToString("yyyy-MM-dd 23:59:59")); if (_params.DatePo < Convert.ToDateTime("01.01.1800")) { _params.DatePo = Convert.ToDateTime(sysSetting.JurDatePo.ToString("yyyy-MM-dd 23:59:59")); } _params.DirWarehouseID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirWarehouseID", true) == 0).Value); _params.UO_GridIndex = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "UO_GridIndex", true) == 0).Value); #endregion #region Основной запрос *** *** *** var query = ( from y in db.DocDomesticExpenseTabs where //y.FieldID == y.DocRetailTabID && y.docDomesticExpense.doc.DocDate >= _params.DateS && y.docDomesticExpense.doc.DocDate <= _params.DatePo && //y.docDomesticExpense.doc.ListObjectID == 56 && y.docDomesticExpense.DirWarehouseID == _params.DirWarehouseID #region select select new { DocID = y.docDomesticExpense.DocID, DirPaymentTypeName = y.docDomesticExpense.doc.dirPaymentType.DirPaymentTypeName, DocDate = y.docDomesticExpense.doc.DocDate, Held = y.docDomesticExpense.doc.Held, Discount = y.docDomesticExpense.doc.Discount, DocDomesticExpenseID = y.DocDomesticExpenseID, DocDomesticExpenseReturnID = y.DocDomesticExpenseID, DirWarehouseID = y.docDomesticExpense.DirWarehouseID, ListObjectID = y.docDomesticExpense.doc.listObject.ListObjectID, ListObjectNameRu = y.docDomesticExpense.doc.listObject.ListObjectNameRu, DirDomesticExpenseID = y.DirDomesticExpenseID, DirDomesticExpenseName = y.dirDomesticExpense.DirDomesticExpenseName, PriceVAT = y.PriceVAT, DirCurrencyID = y.DirCurrencyID, DirCurrencyRate = y.DirCurrencyRate, DirCurrencyMultiplicity = y.DirCurrencyMultiplicity, DirCurrencyName = y.dirCurrency.DirCurrencyName + " (" + y.DirCurrencyRate + ", " + y.DirCurrencyMultiplicity + ")", //Цена в т.в. PriceCurrency = y.PriceCurrency, DirEmployeeName = y.docDomesticExpense.doc.dirEmployee.DirEmployeeName, DirEmployeeNameSpisat = y.docDomesticExpense.dirEmployeeSpisat.DirEmployeeName, } #endregion ); if (_params.UO_GridIndex == 2) { query = query.Where(x => x.DirDomesticExpenseID == 3); } else { query = query.Where(x => x.DirDomesticExpenseID != 3); } #endregion #region Отправка JSON dynamic collectionWrapper = new { sucess = true, total = query.Count(), DocDomesticExpenseTab = query }; return(await Task.Run(() => Ok(collectionWrapper))); #endregion } catch (Exception ex) { return(Ok(returnServer.Return(false, exceptionEntry.Return(ex)))); } }
void render(GraphicsDevice device, LayoutSystem ls, Params parameters, GameTime gameTime) { parameters.MaxParticles = lay.ParticleCount; parameters.edgeOpacity = Config.EdgeOpacity; parameters.nodeScale = Config.NodeScale; parameters.highNodeColor = HighlightNodeColor; parameters.highEdgeColor = HighlightEdgeColor; device.ResetStates(); device.ClearBackbuffer(BackgroundColor); device.SetTargets(null, device.BackbufferColor); paramsCB.SetData(parameters); device.ComputeShaderConstants [0] = paramsCB; device.VertexShaderConstants [0] = paramsCB; device.GeometryShaderConstants [0] = paramsCB; device.PixelShaderConstants [0] = paramsCB; device.PixelShaderSamplers [0] = SamplerState.LinearWrap; int anchorFlag = (AnchorToNodes ? (int)RenderFlags.RELATIVE_POS : (int)RenderFlags.ABSOLUTE_POS); // draw points: --------------------------------------------------------------------------- device.PipelineState = factory[(int)RenderFlags.DRAW | (int)RenderFlags.POINT | anchorFlag]; device.SetCSRWBuffer(0, null); device.GeometryShaderResources [2] = ls.CurrentStateBuffer; // device.PixelShaderResources [0] = particleTex; device.PixelShaderResources [0] = atlas.Texture; device.Draw(nodeList.Count, 0); // draw lines: ---------------------------------------------------------------------------- device.PipelineState = factory[(int)RenderFlags.DRAW | (int)RenderFlags.LINE | anchorFlag]; device.GeometryShaderResources [2] = ls.CurrentStateBuffer; device.GeometryShaderResources [3] = ls.LinksBuffer; device.Draw(edgeList.Count, 0); // draw highlighted points: --------------------------------------------------------------- device.PipelineState = factory[(int)RenderFlags.DRAW | (int)RenderFlags.SELECTION | anchorFlag]; device.PixelShaderResources [0] = highlightTex; foreach (var high in highlightNodesList) { device.GeometryShaderResources[4] = high.Item1; parameters.highNodeColor = high.Item2.color.ToVector4(); paramsCB.SetData(parameters); int num = high.Item2.number; device.Draw(num, 0); } // draw highlighted lines: ---------------------------------------------------------------- // device.PipelineState = factory[(int)RenderFlags.DRAW | (int)RenderFlags.HIGH_LINE|anchorFlag]; // device.GeometryShaderResources [5] = highlightedEdgesBuffer; // device.Draw(highlightedEdgesBuffer.GetStructureCount(), 0); // draw sparks: --------------------------------------------------------------------------- List <Spark> updSparks = new List <Spark>(); foreach (var sp in sparkList) { Spark updSp = sp; updSp.Parameter = sp.Parameter + gameTime.Elapsed.Milliseconds / sp.Time; if (updSp.Parameter < 1.0f) { updSparks.Add(updSp); } } sparkList = updSparks; if (sparkBuffer != null && updSparks.Count > 0) { sparkBuffer.SetData(updSparks.ToArray()); device.PipelineState = factory[(int)RenderFlags.DRAW | (int)RenderFlags.SPARKS | anchorFlag]; device.PixelShaderResources [0] = sparkTex; device.GeometryShaderResources [2] = ls.CurrentStateBuffer; device.GeometryShaderResources [6] = sparkBuffer; device.Draw(sparkList.Count, 0); } }
public IEnumerable <SerializedObject> Primary(int cultureId, int memberId, int objectId, Params @params) { IQueryable <SerializedObject> results = this.dbSet.FromSql( this.GetSortedSelectQuerySql("SerializedObjects.ObjectId IN (SELECT PrimaryId FROM Relations WHERE MemberId = {1} AND ForeignId = {2})", @params), cultureId, memberId, objectId ); return(this.ApplyPaging(results, @params)); }
public override void Read() { Params.Read(_worldPacket); }
internal void processToScreen() { toolTip1.RemoveAll(); Params.Items.Clear(); Params.Objects.ForEach(x => { Params.RemoveObject(x); }); Params.CellEditActivation = ObjectListView.CellEditActivateMode.SingleClick; Params.CanExpandGetter = delegate(object x) { var y = (data)x; if (y.children != null && y.children.Count > 0) { return(true); } return(false); }; Params.ChildrenGetter = delegate(object x) { var y = (data)x; return(new ArrayList(y.children)); }; //Params.Sort(Params.Columns[0], ListSortDirection.Ascending); var sorted = new List <string>(); foreach (string item in MainV2.comPort.MAV.param.Keys) { sorted.Add(item); } sorted.Sort(); var roots = new List <data>(); var lastroot = new data(); // process hashdefines and update display foreach (var value in sorted) { if (value == null || value == "") { continue; } //System.Diagnostics.Debug.WriteLine("Doing: " + value); var data = new data(); var split = value.Split('_'); data.root = split[0]; data.paramname = value; data.Value = ((float)MainV2.comPort.MAV.param[value]).ToString(); try { var metaDataDescription = ParameterMetaDataRepository.GetParameterMetaData(value, ParameterMetaDataConstants.Description, MainV2.comPort.MAV.cs.firmware.ToString()); if (!string.IsNullOrEmpty(metaDataDescription)) { var range = ParameterMetaDataRepository.GetParameterMetaData(value, ParameterMetaDataConstants.Range, MainV2.comPort.MAV.cs.firmware.ToString()); var options = ParameterMetaDataRepository.GetParameterMetaData(value, ParameterMetaDataConstants.Values, MainV2.comPort.MAV.cs.firmware.ToString()); var units = ParameterMetaDataRepository.GetParameterMetaData(value, ParameterMetaDataConstants.Units, MainV2.comPort.MAV.cs.firmware.ToString()); data.unit = (units); data.range = (range + options.Replace(",", " ")); data.desc = (metaDataDescription); } if (lastroot.root == split[0]) { lastroot.children.Add(data); } else { var newroot = new data { root = split[0], paramname = split[0] }; newroot.children.Add(data); roots.Add(newroot); lastroot = newroot; } } catch (Exception ex) { log.Error(ex); } } foreach (var item in roots) { // if the child has no children, we dont need the root. if (item.children.Count == 1) { Params.AddObject(item.children[0]); continue; } Params.AddObject(item); } }
private void button2_Click(object sender, EventArgs e) { String result = parseResult(textBox1.Text); if (result.Replace(" ", "") == "" && check_showLabel.Checked) { MessageBox.Show(Rekod.Properties.Resources.LabelControl_NotEmpty, Properties.Resources.AWT_EditLabel, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (result.Contains("SELECT") || result.Contains("DROP") || result.Contains("INSERT") || result.Contains("UPDATE") || result.Contains("DELETE")) { MessageBox.Show(Rekod.Properties.Resources.LabelControl_InvalidExpression, Properties.Resources.AWT_EditLabel, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } SqlWork sqlCmd = new SqlWork(true); if (result.Replace(" ", "") != "") { tablesInfo ti = classesOfMetods.getTableInfo(_idT); sqlCmd.sql = string.Format("SELECT {0} FROM \"{1}\".\"{2}\" LIMIT 1", result, ti.nameSheme, ti.nameDB); try { sqlCmd.ExecuteNonQuery(null); } catch { MessageBox.Show(Rekod.Properties.Resources.LabelControl_InvalidExpression, Properties.Resources.AWT_EditLabel, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } finally { sqlCmd.Close(); } } _rezult = result; if (!userStyle) { Params par = new Params(); par.paramName = "@labelexpr"; par.typeData = NpgsqlDbType.Varchar; par.value = (!String.IsNullOrEmpty(result.Replace(" ", ""))) ? result : null; sqlCmd = new SqlWork(); if (!Program.WorkSets.CurrentWorkSet.IsDefault) { sqlCmd.sql = String.Format("UPDATE sys_scheme.table_info_sets SET lablefiled=@labelexpr, label_showlabel={1} WHERE id_table={0} AND id_set = {2}", _idT, check_showLabel.Checked, Program.WorkSets.CurrentWorkSet.Id); } else { sqlCmd.sql = String.Format("UPDATE sys_scheme.table_info SET lablefiled=@labelexpr, label_showlabel={1} WHERE id={0}", _idT, check_showLabel.Checked); } sqlCmd.ExecuteNonQuery(new IParams[] { par }); sqlCmd.Close(); sqlCmd = new SqlWork(); sqlCmd.sql = String.Format("SELECT sys_scheme.create_view_for_table({0})", _idT); sqlCmd.ExecuteNonQuery(); sqlCmd.Close(); classesOfMetods.reloadLayer(_idT); SyncController.ReloadStyle(_idT); } if (_parent != null) { _parent.CloseElemsAfter(this, true); } Program.mainFrm1.axMapLIb1.mapRepaint(); }
public ResultSet Search(Params ps) { return(Snap.Search2.Search.Do <Relocation>(ps)); }
public override Syntax GetSyntax(Params args) { return(Syntax.Begin()); }
private string GetSortedByDateTimeValueSelectQuerySql(Params @params) { return("Members.Id = " + @params.Sorting.MemberId + " ORDER BY datetime(Properties.DateTimeValue) " + @params.Sorting.Direction); }
private IEnumerable <SerializedObject> ApplyPaging(IQueryable <SerializedObject> results, Params @params) { if (@params.Paging == null) { return(results); } if (@params.Paging.Skip != null) { results = results.Skip((int)@params.Paging.Skip); } if (@params.Paging.Take != null) { results = results.Take((int)@params.Paging.Take); } return(results); }
/// <summary> /// Constructor /// </summary> /// <param name="parameters">KCF parameters TrackerKCF::Params</param> /// <returns></returns> public static TrackerKCF Create(Params parameters) { NativeMethods.HandleException( NativeMethods.tracking_TrackerKCF_create2(parameters, out var p)); return(new TrackerKCF(p)); }
/// <summary> /// Make an HTTP request. /// </summary> /// <param name="Route">URL route of API</param> /// <param name="Method">Method of HTTP request</param> /// <param name="Params">Additional paramerters</param> /// <returns>Varies according to API endpoint</returns> private dynamic Request(string Route, string Method, Dictionary <string, dynamic> Params = null) { string url = _root + _routes[Route]; if (Params == null) { Params = new Dictionary <string, dynamic>(); } if (url.Contains("{")) { var urlparams = Params.ToDictionary(entry => entry.Key, entry => entry.Value); foreach (KeyValuePair <string, dynamic> item in urlparams) { if (url.Contains("{" + item.Key + "}")) { url = url.Replace("{" + item.Key + "}", (string)item.Value); Params.Remove(item.Key); } } } //if (!Params.ContainsKey("api_key")) // Params.Add("api_key", _apiKey); //if (!Params.ContainsKey("access_token") && !String.IsNullOrEmpty(_accessToken)) // Params.Add("access_token", _accessToken); HttpWebRequest request; string paramString = String.Join("&", Params.Select(x => Utils.BuildParam(x.Key, x.Value))); if (Method == "POST" || Method == "PUT") { request = (HttpWebRequest)WebRequest.Create(url); request.AllowAutoRedirect = true; request.Method = Method; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = paramString.Length; AddExtraHeaders(ref request); using (Stream webStream = request.GetRequestStream()) using (StreamWriter requestWriter = new StreamWriter(webStream)) requestWriter.Write(paramString); } else { request = (HttpWebRequest)WebRequest.Create(url + "?" + paramString); request.AllowAutoRedirect = true; request.Method = Method; AddExtraHeaders(ref request); } WebResponse webResponse; try { webResponse = request.GetResponse(); } catch (WebException e) { if (e.Response.Equals(null)) { throw e; } webResponse = e.Response; } using (Stream webStream = webResponse.GetResponseStream()) { using (StreamReader responseReader = new StreamReader(webStream)) { string response = responseReader.ReadToEnd(); HttpStatusCode status = ((HttpWebResponse)webResponse).StatusCode; if (webResponse.ContentType == "application/json") { JObject responseDictionary = Utils.JsonDeserialize(response); if (status != HttpStatusCode.OK) { string errorType = "GeneralException"; string message = ""; if (responseDictionary["error_type"] != null) { errorType = (string)responseDictionary["error_type"]; } if (responseDictionary["message"] != null) { message = (string)responseDictionary["message"]; } switch (errorType) { case "GeneralException": throw new GeneralException(message, status); case "TokenException": { _sessionHook?.Invoke(); throw new TokenException(message, status); } case "PermissionException": throw new PermissionException(message, status); case "OrderException": throw new OrderException(message, status); case "InputException": throw new InputException(message, status); case "DataException": throw new DataException(message, status); case "NetworkException": throw new NetworkException(message, status); default: throw new GeneralException(message, status); } } return(responseDictionary); } else if (webResponse.ContentType == "text/csv") { //return Utils.ParseCSV(response); CsvConfiguration configuration = new CsvConfiguration(CultureInfo.InvariantCulture) { HasHeaderRecord = true, }; var reader = new StringReader(response); var csv = new CsvReader(reader, configuration); var csvRecords = csv.GetRecords <CsvInstrument>().ToList(); return(csvRecords); } else { throw new DataException("Unexpected content type " + webResponse.ContentType + " " + response); } } } }
internal void processToScreen() { toolTip1.RemoveAll(); Params.Rows.Clear(); log.Info("processToScreen"); var list = new List <string>(); foreach (string item in _paramlist.Select(a => ASCIIEncoding.ASCII.GetString(a.name, 0, a.name_len))) { list.Add(item); } var rowlist = new List <DataGridViewRow>(); // process hashdefines and update display Parallel.ForEach(list, value => { if (value == null || value == "") { return; } var row = new DataGridViewRow(); lock (rowlist) rowlist.Add(row); row.CreateCells(Params); row.Cells[Command.Index].Value = value; row.Cells[Value.Index].Value = _paramlist .First(a => ASCIIEncoding.ASCII.GetString(a.name, 0, a.name_len) == value).value.GetValue(); row.Cells[Min.Index].Value = _paramlist .First(a => ASCIIEncoding.ASCII.GetString(a.name, 0, a.name_len) == value).min_value.GetValue(); row.Cells[Max.Index].Value = _paramlist .First(a => ASCIIEncoding.ASCII.GetString(a.name, 0, a.name_len) == value).max_value.GetValue(); row.Cells[Default.Index].Value = _paramlist .First(a => ASCIIEncoding.ASCII.GetString(a.name, 0, a.name_len) == value).default_value.GetValue(); var fav_params = Settings.Instance.GetList("fav_params"); row.Cells[Fav.Index].Value = fav_params.Contains(value); }); log.Info("about to add all"); Params.SuspendLayout(); Params.Visible = false; Params.Enabled = false; Params.Rows.AddRange(rowlist.ToArray()); log.Info("about to sort"); Params.SortCompare += OnParamsOnSortCompare; Params.Sort(Params.Columns[Command.Index], ListSortDirection.Ascending); Params.Enabled = true; Params.Visible = true; Params.ResumeLayout(); log.Info("Done"); }
/// <summary> /// 获取过滤参数(数组) /// </summary> /// <returns></returns> public SqlParameter[] GetParams() { return(Params.ToArray()); }
public IEnumerable <SerializedObject> FilteredByCultureIdAndClassIdAndObjectId(int cultureId, int classId, int objectId, Params @params) { IQueryable <SerializedObject> results = this.dbSet.FromSql( this.GetSortedSelectQuerySql("SerializedObjects.ClassId = {1} AND SerializedObjects.ObjectId IN (SELECT ForeignId FROM Relations WHERE PrimaryId = {2})", @params), cultureId, classId, objectId ); return(this.ApplyPaging(results, @params)); }
/* * Copyright 2009-2010 Jon Klein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <exception cref="System.Exception"/> public static void Main(string[] args) { if (args.Length != 1) { Console.Out.WriteLine("Usage: PshEquationBuilder inputfile"); System.Environment.Exit(0); } // FilePath inFile = new FilePath(args[0]); // Read fileString string fileString = Params.ReadFileString(args[0]); // Get programString string programString; int indexNewline = fileString.IndexOf("\n"); if (indexNewline == -1) { programString = fileString; } else { programString = SharpenMinimal.Extensions.Trim(SharpenMinimal.Runtime.Substring(fileString, 0, indexNewline)); } //Get rid of parentheses programString = programString.Replace('(', ' '); programString = SharpenMinimal.Extensions.Trim(programString.Replace(')', ' ')); string[] instructions = programString.Split("\\s+"); List <string> stringStack = new List <string>(); stringStack.Add("x"); foreach (string instruction in instructions) { // (input.in0 float.+ float.- float.* float./ float.exp float.sin float.cos float.2pi) if (instruction.Equals("input.in0")) { stringStack.Add("x"); } else { if (instruction.Equals("float.+")) { if (stringStack.Count > 1) { string top = stringStack.Remove(stringStack.Count - 1); string next = stringStack.Remove(stringStack.Count - 1); string result = "(" + top + " + " + next + ")"; stringStack.Add(result); } } else { if (instruction.Equals("float.-")) { if (stringStack.Count > 1) { string top = stringStack.Remove(stringStack.Count - 1); string next = stringStack.Remove(stringStack.Count - 1); string result = "(" + top + " - " + next + ")"; stringStack.Add(result); } } else { if (instruction.Equals("float.*")) { if (stringStack.Count > 1) { string top = stringStack.Remove(stringStack.Count - 1); string next = stringStack.Remove(stringStack.Count - 1); string result = "(" + top + " * " + next + ")"; stringStack.Add(result); } } else { if (instruction.Equals("float./")) { if (stringStack.Count > 1) { string top = stringStack.Remove(stringStack.Count - 1); string next = stringStack.Remove(stringStack.Count - 1); string result = "(" + top + " / " + next + ")"; stringStack.Add(result); } } else { if (instruction.Equals("float.exp")) { if (stringStack.Count > 0) { string top = stringStack.Remove(stringStack.Count - 1); string result = "(e^" + top + ")"; stringStack.Add(result); } } else { if (instruction.Equals("float.sin")) { if (stringStack.Count > 0) { string top = stringStack.Remove(stringStack.Count - 1); string result = "sin(" + top + ")"; stringStack.Add(result); } } else { if (instruction.Equals("float.cos")) { if (stringStack.Count > 0) { string top = stringStack.Remove(stringStack.Count - 1); string result = "cos(" + top + ")"; stringStack.Add(result); } } else { if (instruction.Equals("float.2pi")) { stringStack.Add("2 * pi"); } else { throw new Exception("Unrecognized Psh instruction " + instruction + " in program."); } } } } } } } } } } Console.Out.WriteLine(stringStack[stringStack.Count - 1]); }
public static async Task Generate(GeneratorConfig config) { if (config == null) { throw new ArgumentNullException(nameof(config)); } using (var tokenSource = new CancellationTokenSource()) { Console.CancelKeyPress += (s, e) => { if (!tokenSource.IsCancellationRequested) { tokenSource.Cancel(); } e.Cancel = true; }; try { ConsoleExecutor.WriteInfo("Start all generations.", ConsoleColor.Cyan); _logger.Info("Start all generations"); var result = await new GeneratorClient() .GenerateAll(config, tokenSource.Token) .ConfigureAwait(false); LogLevel resultLevel; if (result.AllSucceeded) { ConsoleExecutor.WriteInfo("All generations completed successfully.", ConsoleColor.Green); _logger.Info("All generations completed successfully."); resultLevel = LogLevel.Info; } else { resultLevel = LogLevel.Error; if (result.AllFailed) { ConsoleExecutor.WriteInfo("All generations completed unsuccessfully.", ConsoleColor.Red); _logger.Error("All generations completed unsuccessfully"); } else { ConsoleExecutor.WriteInfo("Some generations completed unsuccessfully.", ConsoleColor.Yellow); _logger.Warn("Some generations completed unsuccessfully"); } var errorResults = result .GenerationResults .SelectMany(g => g.GenerationResults) .Where(g => !g.Success) .ToList(); foreach (var item in errorResults) { ConsoleExecutor.WriteInfo($"Generation {item.Id} - {item.GenerationType} failed.", ConsoleColor.Red, item.Exception.Message); } _logger.Warn("All results with errors: {@results}", errorResults); } var title = resultLevel == LogLevel.Info ? "Data generation completed succesfully" : "Data generation failed"; LogHelper.MailLogger.LogWithEventParams( resultLevel, "Config:\r\n{config}\r\n\r\nResult:\r\n{results}", args: Params.ToArray( JsonConvert.SerializeObject(config, Formatting.Indented), JsonConvert.SerializeObject(result, Formatting.Indented)), eventParams: Params.ToArray <(object, object)>(("ResultTitle", title))); } catch (ValidationException ve) { ConsoleExecutor.WriteInfo("Validation failed.", ConsoleColor.Red, ve); _logger.Fatal(ve, "Validation failed"); } catch (OperationCanceledException oce) { ConsoleExecutor.WriteInfo("Operation was canceled", ConsoleColor.Red, oce); _logger.Error(oce, "Operation was canceled"); } } }
protected override void TrySolveInstance(IGH_DataAccess DA) { Types.GraphicalElement element = null; if (!DA.GetData("Element", ref element)) { return; } var _Level_ = Params.IndexOfOutputParam("Level"); if (_Level_ >= 0) { DA.SetData(_Level_, element.Level); } var _Box_ = Params.IndexOfOutputParam("Box"); if (_Box_ >= 0) { var box = element.Box; if (box.IsValid) { DA.SetData(_Box_, box); } } var _Location_ = Params.IndexOfOutputParam("Location"); if (_Location_ >= 0) { var location = element.Location; if (location.IsValid) { DA.SetData(_Location_, element.Location); } } var _Orientation_ = Params.IndexOfOutputParam("Facing Orientation"); if (_Orientation_ >= 0) { var orientation = element.FacingOrientation; if (orientation.IsValid && !orientation.IsZero) { DA.SetData(_Orientation_, orientation); } } var _Handing_ = Params.IndexOfOutputParam("Hand Orientation"); if (_Handing_ >= 0) { var handing = element.HandOrientation; if (handing.IsValid && !handing.IsZero) { DA.SetData(_Handing_, handing); } } var _Curve_ = Params.IndexOfOutputParam("Curve"); if (_Curve_ >= 0) { DA.SetData(_Curve_, element.Curve); } }
public GpuJob(Params @params) : base(@params) { workSize = @params.WorkSize; platformIndex = @params.PlatformIndex; }
public override string ToString() { return(string.Format("{0} {1} T:{2},{3}", Method.ToUpper(), Url, Tid, string.Join(",", Params.Select(x => string.Format("{0}={1}", x.Key, x.Value)).ToArray()))); }
public ResultSet Search(Params ps) { return(Snap.Search2.Search.Do <AgingAndDisabilityResourceCenter>(ps)); }
public void AddParam(string Name, object Value) { Params.Add(Name, Value); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="dataAccess"> /// The DA object is used to retrieve from inputs and store in outputs. /// </param> protected override void SolveInstance(IGH_DataAccess dataAccess) { int index = -1; bool run = false; index = Params.IndexOfInputParam("_run"); if (index != -1) { if (!dataAccess.GetData(index, ref run) || !run) { return; } } GH_ObjectWrapper objectWrapper = null; index = Params.IndexOfInputParam("revitLinkInstance_"); if (index != -1) { dataAccess.GetData(index, ref objectWrapper); } Transform tranform = null; Document document = null; if (objectWrapper != null && Core.Grasshopper.Revit.Query.TryGetElement(objectWrapper, out RevitLinkInstance revitLinkInstance) && revitLinkInstance != null) { document = revitLinkInstance.GetLinkDocument(); tranform = revitLinkInstance.GetTotalTransform(); } else if (objectWrapper?.Value is RhinoInside.Revit.GH.Types.ProjectDocument) { document = ((RhinoInside.Revit.GH.Types.ProjectDocument)objectWrapper.Value).Value; } if (document == null) { document = RhinoInside.Revit.Revit.ActiveDBDocument; } if (document == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data"); return; } if (tranform == null) { tranform = Transform.Identity; } index = Params.IndexOfInputParam("_view"); if (index == -1 || !dataAccess.GetData(index, ref objectWrapper) || objectWrapper.Value == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data"); return; } IEnumerable <ElementId> elementIds = null; if (Core.Grasshopper.Revit.Query.TryGetElement(objectWrapper, out ViewPlan viewPlan)) { Outline outline = Core.Revit.Query.Outline(viewPlan, tranform); if (outline != null) { //LogicalOrFilter logicalOrFilter = new LogicalOrFilter(new BoundingBoxIsInsideFilter(outline), new BoundingBoxIntersectsFilter(outline)); //elementIds = new FilteredElementCollector(document_Linked).WherePasses(logicalOrFilter)?.ToElementIds(); BoundingBoxIsInsideFilter boundingBoxIsInsideFilter = new BoundingBoxIsInsideFilter(outline, Core.Tolerance.MacroDistance); elementIds = new FilteredElementCollector(document).WherePasses(boundingBoxIsInsideFilter).ToElementIds(); } } if (elementIds == null || elementIds.Count() == 0) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data"); return; } ConvertSettings convertSettings = new ConvertSettings(true, true, true); IEnumerable <Core.ISAMObject> sAMObjects = null; List <Panel> panels = Analytical.Revit.Convert.ToSAM_Panels(document, elementIds, convertSettings); if (panels != null) { sAMObjects = panels.Cast <Core.ISAMObject>(); } dataAccess.SetDataList(0, sAMObjects); }
public override void TickTest() { // check repeated args Params MultiArgs1 = new Params(new[] { "foo=one", "foo=two" }); List <string> MultiArgs1Result = MultiArgs1.ParseValues("foo"); CheckResult(MultiArgs1Result.Count == 2, "Incorrect result count"); CheckResult(MultiArgs1Result[0] == "one" && MultiArgs1Result[1] == "two", "Incorrect result count"); // check comma-separated Params MultiArgs2 = new Params(new[] { "foo=one,two" }); List <string> MultiArgs2Result = MultiArgs2.ParseValues("foo", true); CheckResult(MultiArgs2Result.Count == 2, "Incorrect result count"); CheckResult(MultiArgs2Result[0] == "one" && MultiArgs2Result[1] == "two", "Incorrect result count"); // check comma-separated with spaces (on cmdline these would be quote-wrapped) Params MultiArgs3 = new Params(new[] { "foo=one, two" }); List <string> MultiArgs3Result = MultiArgs3.ParseValues("foo", true); CheckResult(MultiArgs3Result.Count == 2, "Incorrect result count"); CheckResult(MultiArgs3Result[0] == "one" && MultiArgs3Result[1] == "two", "Incorrect result count"); // simple comma-separated list with no subparams string TestCase1 = "Test1, Test2"; var Results1 = ArgumentWithParams.CreateFromString(TestCase1); CheckResult(Results1.Count == 2, "Incorrect result count"); CheckResult(Results1[0].Argument == "Test1", "Incorrect Test Result"); CheckResult(Results1[0].AllArguments.Length == 0, "Incorrect Test Result"); CheckResult(Results1[1].Argument == "Test2", "Incorrect Test Result"); CheckResult(Results1[1].AllArguments.Length == 0, "Incorrect Test Result"); // comma-separated list with params string TestCase2 = "Test1,Test2(p1,p2=foo)"; var Results2 = ArgumentWithParams.CreateFromString(TestCase2); CheckResult(Results2.Count == 2, "Incorrect result count"); CheckResult(Results2[0].Argument == "Test1", "Incorrect Test Result"); CheckResult(Results2[0].AllArguments.Length == 0, "Incorrect Test Result"); CheckResult(Results2[1].Argument == "Test2", "Incorrect Test Result"); CheckResult(Results2[1].AllArguments.Length == 2, "Failed to parse correct param count"); CheckResult(Results2[1].ParseParam("p1"), "Failed to parse p1 from params"); CheckResult(Results2[1].ParseValue("p2", null) == "foo", "Failed to parse p2 from params"); // comma-separated list with params that are what we'd get if the user encloses them in quotes string TestCase3 = "Test3(p1,p2=foo bar,p3)"; var Results3 = ArgumentWithParams.CreateFromString(TestCase3); CheckResult(Results3.Count == 1, "Incorrect result count"); CheckResult(Results3[0].Argument == "Test3", "Incorrect Test Result"); CheckResult(Results3[0].AllArguments.Length == 3, "Failed to parse correct param count"); CheckResult(Results3[0].ParseParam("p1"), "Failed to parse p1 from params"); CheckResult(Results3[0].ParseValue("p2", null) == "foo bar", "Failed to parse p2 from params"); CheckResult(Results3[0].ParseParam("p3"), "Failed to parse p3 from params"); // One day... //string TestCase4 = "Test4(p1,p2(foo,bar),p3)"; //var Results4 = SubParams.CreateFromString(TestCase4); //CheckResult(Results4.Count == 1, "Incorrect result count"); MarkComplete(); }
protected override void Executed(Params args, IConsoleOutput target) { Globals.PrimaryTimer.Paused = !Globals.PrimaryTimer.Paused; target.WriteLine(Globals.PrimaryTimer.Paused ? "Frozen" : "Unfrozen"); }
public Function Resolve(string Name, params Expression[] Params) { return(Resolve(Name, Params.AsEnumerable())); }
private string GetSortedByDecimalValueSelectQuerySql(Params @params) { return("Members.Id = " + @params.Sorting.MemberId + " ORDER BY Properties.DecimalValue " + @params.Sorting.Direction); }
public override Params getParameters(bool includeServiceAndAction) { Params kparams = base.getParameters(includeServiceAndAction); return(kparams); }
public IEnumerable <SerializedObject> FilteredByCultureIdAndClassId(int cultureId, int classId, Params @params) { IQueryable <SerializedObject> results = this.dbSet.FromSql( this.GetSortedSelectQuerySql("SerializedObjects.ClassId = {1}", @params), cultureId, classId ); return(this.ApplyPaging(results, @params)); }