Esempio n. 1
0
        public int ExecuteDataPlan(nDumpOptions nDumpOptions, ILogger logger, DataPlan dataPlan)
        {
            if (nDumpOptions.Export)
            {
                var queryExecutor = new QueryExecutor(nDumpOptions.SourceConnectionString);
                ISelectionFilteringStrategy filteringStrategy = nDumpOptions.ApplyFilters ? (ISelectionFilteringStrategy)
                                                                                         new UseFilterIfPresentStrategy(queryExecutor, logger)
                                                                    : new IgnoreFilterStrategy();
                var exporter = new SqlDataExporter(logger, nDumpOptions.CsvDirectory,
                                                   queryExecutor, filteringStrategy);
                try
                {
                    exporter.ExportToCsv(dataPlan.SetupScripts, dataPlan.DataSelects);

                }
                catch (nDumpApplicationException ex)
                {

                    logger.Log("Export To Csv Failed.\n" + ex.StackTrace);
                    return -1;

                }
            }
            if (nDumpOptions.Transform)
            {
                var transformer = new DataTransformer(nDumpOptions.SqlDirectory, nDumpOptions.CsvDirectory,
                                                      logger);
                try
                {

                    transformer.ConvertCsvToSql(dataPlan.DataSelects);

                }
                catch (nDumpApplicationException ex)
                {

                    logger.Log("Export To Csv Failed.\n" + ex.StackTrace);
                    return -1;

                }
            }
            if (nDumpOptions.Import)
            {
                var importer = new SqlDataImporter(logger,
                                                   new QueryExecutor(nDumpOptions.TargetConnectionString), new IncrementingNumberSqlScriptFileStrategy(nDumpOptions.SqlDirectory));
                try
                {
                    importer.RemoveDataAndImportFromSqlFiles(dataPlan.DataSelects);
                }
                catch (nDumpApplicationException ex)
                {

                    logger.Log("Import Of Sql Failed.\n" + ex.Message + "\n" + ex.StackTrace);
                    return -1;

                }

            }
            return 0;
        }
Esempio n. 2
0
        /// <summary>
        /// Implements common data layer setup functionality, and calls
        /// DataLayerSetUp to do special data layer setup for individual layer types.
        /// </summary>
        /// <remarks>
        /// This method may not be overridden except by BasePrefetchingDataLayer.
        /// </remarks>
        /// <param name="colBottom">Specifies the collection of bottom (input) Blobs.</param>
        /// <param name="colTop">Specifies the collection of top (output) Blobs.</param>
        public override void LayerSetUp(BlobCollection <T> colBottom, BlobCollection <T> colTop)
        {
            setupSourceDescriptor();

            if (colTop.Count == 1)
            {
                m_bOutputLabels = false;
            }
            else
            {
                m_bOutputLabels = true;
            }

            int nC = 0;
            int nH = 0;
            int nW = 0;

            if (m_src != null)
            {
                nC = m_src.ImageChannels;
                nH = m_src.ImageHeight;
                nW = m_src.ImageWidth;
            }
            else if (m_imgMean != null)
            {
                nC = m_imgMean.Channels;
                nH = m_imgMean.Height;
                nW = m_imgMean.Width;
            }
            else if (m_param.type == LayerParameter.LayerType.MEMORYDATA)
            {
                nC = (int)m_param.memory_data_param.channels;
                nH = (int)m_param.memory_data_param.height;
                nW = (int)m_param.memory_data_param.width;
            }
            else if (m_param.type == LayerParameter.LayerType.DUMMYDATA)
            {
                nC = (int)m_param.dummy_data_param.channels[0];
                nH = (int)m_param.dummy_data_param.height[0];
                nW = (int)m_param.dummy_data_param.height[0];
            }
            else if (m_param.type == LayerParameter.LayerType.INPUT)
            {
                if (m_param.input_param.shape[0].dim.Count > 1)
                {
                    nC = (int)m_param.input_param.shape[0].dim[1];
                }

                if (m_param.input_param.shape[0].dim.Count > 2)
                {
                    nH = (int)m_param.input_param.shape[0].dim[2];
                }

                if (m_param.input_param.shape[0].dim.Count > 3)
                {
                    nW = (int)m_param.input_param.shape[0].dim[3];
                }
            }
            else if (m_param.type == LayerParameter.LayerType.VIDEO_DATA)
            {
                nC = 3;
                nH = (int)m_param.video_data_param.video_height;
                nW = (int)m_param.video_data_param.video_width;
            }

            if (nC == 0 && nH == 0 && nW == 0)
            {
                throw new Exception("The sizing of C, H, W cannot be zero for all three!");
            }

            if (nC == 0)
            {
                nC = 1;
            }

            if (nH == 0)
            {
                nH = 1;
            }

            if (nW == 0)
            {
                nW = 1;
            }

            m_transformer = new DataTransformer <T>(m_cuda, m_log, m_param.transform_param, m_param.phase, nC, nH, nW, m_imgMean);
            m_transformer.InitRand();

            // The subclasses should setup the size of bottom and top.
            DataLayerSetUp(colBottom, colTop);
        }
Esempio n. 3
0
        /// <summary>
        /// 初始化下拉列表控件关键属性
        /// </summary>
        /// <param name="LkUpContr">下拉列表控件对象</param>
        public void InitLkUp(Control Contr)
        {
            try
            {
                string[] LkUp_Data;
                foreach (Control Control1 in Contr.Controls)
                {
                    if (Control1.Name == "LkUp_Brackets1")
                    {
                        //LkUp_Data = new string[] { "(", "((", "(((" };
                        List <ExpandoObject> ListEObj = new List <ExpandoObject>();
                        dynamic EObj1 = new ExpandoObject();
                        EObj1.FRemark = "(";
                        EObj1.FColNm  = " ( ";
                        ListEObj.Add(EObj1);

                        dynamic EObj2 = new ExpandoObject();
                        EObj2.FRemark = "((";
                        EObj2.FColNm  = " (( ";
                        ListEObj.Add(EObj2);

                        dynamic EObj3 = new ExpandoObject();
                        EObj3.FRemark = "(((";
                        EObj3.FColNm  = " ((( ";
                        ListEObj.Add(EObj3);

                        ((LookUpEdit)Control1).Properties.DisplayMember = "FRemark";
                        ((LookUpEdit)Control1).Properties.ValueMember   = "FColNm";
                        ((LookUpEdit)Control1).Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("FRemark"));
                        ((LookUpEdit)Control1).Properties.DataSource = ListEObj;
                        //清空默认值
                        ((LookUpEdit)Control1).Properties.NullText      = "";
                        ((LookUpEdit)Control1).Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
                    }
                    else if (Control1.Name == "LkUp_Brackets2")
                    {
                        //LkUp_Data = new string[] { ")", "))", ")))" };
                        List <ExpandoObject> ListEObj = new List <ExpandoObject>();
                        dynamic EObj1 = new ExpandoObject();
                        EObj1.FRemark = ")";
                        EObj1.FColNm  = " ) ";
                        ListEObj.Add(EObj1);

                        dynamic EObj2 = new ExpandoObject();
                        EObj2.FRemark = "))";
                        EObj2.FColNm  = " )) ";
                        ListEObj.Add(EObj2);

                        dynamic EObj3 = new ExpandoObject();
                        EObj3.FRemark = ")))";
                        EObj3.FColNm  = " ))) ";
                        ListEObj.Add(EObj3);

                        ((LookUpEdit)Control1).Properties.DisplayMember = "FRemark";
                        ((LookUpEdit)Control1).Properties.ValueMember   = "FColNm";
                        ((LookUpEdit)Control1).Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("FRemark"));
                        ((LookUpEdit)Control1).Properties.DataSource = ListEObj;
                        //清空默认值
                        ((LookUpEdit)Control1).Properties.NullText      = "";
                        ((LookUpEdit)Control1).Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
                    }
                    else if (Control1.Name == "LkUp_Rlt")
                    {
                        List <ExpandoObject> ListEObj = new List <ExpandoObject>();
                        dynamic EObj1 = new ExpandoObject();
                        EObj1.FRemark = "并且";
                        EObj1.FColNm  = " and ";
                        ListEObj.Add(EObj1);

                        dynamic EObj2 = new ExpandoObject();
                        EObj2.FRemark = "或者";
                        EObj2.FColNm  = " or ";
                        ListEObj.Add(EObj2);

                        //LkUp_Data = new string[] { "并且", "或者" };
                        ((LookUpEdit)Control1).Properties.DisplayMember = "FRemark";
                        ((LookUpEdit)Control1).Properties.ValueMember   = "FColNm";
                        ((LookUpEdit)Control1).Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("FRemark"));
                        ((LookUpEdit)Control1).Properties.DataSource = ListEObj;
                        //清空默认值
                        ((LookUpEdit)Control1).Properties.NullText      = "";
                        ((LookUpEdit)Control1).Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
                    }
                    else if (Control1.Name == "SLkUp_ColNams")
                    {
                        LkUp_Data = new string[] { "开始日期", "结束日期", "订单号" };
                        ((SearchLookUpEdit)Control1).Properties.DisplayMember = "FRemark";
                        ((SearchLookUpEdit)Control1).Properties.ValueMember   = "FColNm";
                        List <ExpandoObject> ListEObj = DataTransformer.LoadData(ComClient.GetFltColsByPanelNam("Panel5", FrmNam));
                        //增加一个可见的绑定列
                        ((SearchLookUpEdit)Control1).Properties.View.Columns.AddVisible("FRemark");
                        ((SearchLookUpEdit)Control1).Properties.DataSource    = ListEObj;
                        ((SearchLookUpEdit)Control1).Properties.NullText      = "";
                        ((SearchLookUpEdit)Control1).Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
                    }
                    else if (Control1.Name == "LkUp_Cdt")
                    {
                        List <ExpandoObject> ListEObj = new List <ExpandoObject>();

                        dynamic EObj1 = new ExpandoObject();
                        EObj1.FRemark = "以...开头";
                        EObj1.FColNm  = " like";
                        ListEObj.Add(EObj1);

                        dynamic EObj2 = new ExpandoObject();
                        EObj2.FRemark = "等于";
                        EObj2.FColNm  = " = ";
                        ListEObj.Add(EObj2);

                        dynamic EObj3 = new ExpandoObject();
                        EObj3.FRemark = "包含";
                        EObj3.FColNm  = " like ";
                        ListEObj.Add(EObj3);

                        dynamic EObj4 = new ExpandoObject();
                        EObj4.FRemark = "不包含";
                        EObj4.FColNm  = " not like ";
                        ListEObj.Add(EObj4);

                        dynamic EObj5 = new ExpandoObject();
                        EObj5.FRemark = "大于";
                        EObj5.FColNm  = " > ";
                        ListEObj.Add(EObj5);

                        dynamic EObj6 = new ExpandoObject();
                        EObj6.FRemark = "大于等于";
                        EObj6.FColNm  = " >= ";
                        ListEObj.Add(EObj6);

                        dynamic EObj7 = new ExpandoObject();
                        EObj7.FRemark = "小于";
                        EObj7.FColNm  = " < ";
                        ListEObj.Add(EObj7);

                        dynamic EObj8 = new ExpandoObject();
                        EObj8.FRemark = "小于等于";
                        EObj8.FColNm  = " <= ";
                        ListEObj.Add(EObj8);

                        dynamic EObj9 = new ExpandoObject();
                        EObj9.FRemark = "不等于";
                        EObj9.FColNm  = " != ";
                        ListEObj.Add(EObj9);

                        dynamic EObj10 = new ExpandoObject();
                        EObj10.FRemark = "从...到...";
                        EObj10.FColNm  = " between ";
                        ListEObj.Add(EObj10);

                        dynamic EObj12 = new ExpandoObject();
                        EObj12.FRemark = "为空";
                        EObj12.FColNm  = " = ''";
                        ListEObj.Add(EObj12);

                        dynamic EObj13 = new ExpandoObject();
                        EObj13.FRemark = "不为空";
                        EObj13.FColNm  = " != ''";
                        ListEObj.Add(EObj13);

                        dynamic EObj14 = new ExpandoObject();
                        EObj14.FRemark = "不在...之间";
                        EObj14.FColNm  = " not between ";
                        ListEObj.Add(EObj14);

                        dynamic EObj15 = new ExpandoObject();
                        EObj15.FRemark = "以...结尾";
                        EObj15.FColNm  = "like ";
                        ListEObj.Add(EObj15);

                        dynamic EObj16 = new ExpandoObject();
                        EObj16.FRemark = "在列表中";
                        EObj16.FColNm  = " in ";
                        ListEObj.Add(EObj16);

                        dynamic EObj17 = new ExpandoObject();
                        EObj17.FRemark = "不在列表中";
                        EObj17.FColNm  = " not in ";
                        ListEObj.Add(EObj17);
                        //LkUp_Data = new string[] { "以...开头", "等于", "包含", "不包含", "大于", "大于等于", "小于", "小于等于", "不等于", "从...到...", "为空", "不为空", "不在...之间", "以...结尾", "在列表中", "不在列表中" };

                        ((LookUpEdit)Control1).Properties.DisplayMember = "FRemark";
                        ((LookUpEdit)Control1).Properties.ValueMember   = "FColNm";
                        ((LookUpEdit)Control1).Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("FRemark"));
                        ((LookUpEdit)Control1).Properties.DataSource = ListEObj;

                        //清空默认值
                        ((LookUpEdit)Control1).Properties.NullText      = "";
                        ((LookUpEdit)Control1).Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
                    }
                    else if (Control1.Name == "CBox_CdtValue1" || Control1.Name == "CBox_CdtValue2" || Control1.Name == "CBox_CdtValue3")
                    {
                        ((ComboBoxEdit)Control1).Properties.NullText      = "";
                        ((ComboBoxEdit)Control1).Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
                    }
                    else if (Control1.GetType().ToString() == "DevExpress.XtraEditors.DateEdit")
                    {
                        //清空默认值
                        ((DateEdit)Control1).Properties.NullText      = "";
                        ((DateEdit)Control1).Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
                    }
                }
            }
            catch (Exception Ex)
            {
                Common.ShowMsg(Ex.Message);
            }
        }
Esempio n. 4
0
        public static void Main(string[] args)
        {
            string input = File.ReadAllText("Examples/Input.json");

            string transformer       = File.ReadAllText("Examples/Transformer_valueof.json");
            string transformedString = JsonTransformer.Transform(transformer, input);

            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);


            transformer       = File.ReadAllText("Examples/Transformer_valueofarray.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);


            transformer       = File.ReadAllText("Examples/Transformer_copy.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_replace.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_delete.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);


            transformer       = File.ReadAllText("Examples/Transformer_ifcondition.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_string.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_math.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_aggregate.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_arrayaggregate.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_looping.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_customfunction.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_nestedfunctions.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_xfunctions.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_Existance.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/DataTransformer.xml");
            transformedString = DataTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/DataTransformer.csv");
            transformedString = DataTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(input)));
            Console.WriteLine(transformedString);



            Console.WriteLine("################################################################################################");
            string inputJson   = File.ReadAllText("Examples/ValidationInput.json");
            string schemaJsonX = File.ReadAllText("Examples/SchemaX.json");
            string schemaJsonY = File.ReadAllText("Examples/SchemaY.json");

            string InputToSplit = File.ReadAllText("Examples/InputToSplit.json");

            List <string> outputs = JsonTransformer.SplitJson(InputToSplit, "$.cars.Ford").ToList <string>();

            foreach (string output in outputs)
            {
                Console.WriteLine("-----------------------------------------------------");
                Console.WriteLine(output);
            }

            Console.WriteLine("################################################################################################");

            JsonValidator validator = new JsonValidator(inputJson);

            validator.AddSchema("x", schemaJsonX);
            validator.AddSchema("y", schemaJsonY);

            validator.Validate();

            Console.WriteLine("################################################################################################");
            transformer       = File.ReadAllText("Examples/Transformer_nestedloop.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(input)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");
            transformer       = File.ReadAllText("Examples/Transformer_looptests.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(input)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            string inputSpecial = File.ReadAllText("Examples/InputSpecial.json");

            transformer       = File.ReadAllText("Examples/Transformer_customfunctionspecial.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(inputSpecial)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            string inputUnordered = File.ReadAllText("Examples/Input_Unordered.json");

            transformer       = File.ReadAllText("Examples/Transform_Unordered.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(inputUnordered)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            string inputUnordered2 = File.ReadAllText("Examples/Input_Unordered_2.json");

            transformer       = File.ReadAllText("Examples/Transform_Unordered_2.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(inputUnordered2)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");


            string inputDyn = File.ReadAllText("Examples/InputDynamic.json");

            transformer       = File.ReadAllText("Examples/TransformDynamic.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(inputDyn)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            transformer       = File.ReadAllText("Examples/Transformer_externalmethods.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(input)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            transformer       = File.ReadAllText("Examples/Transformer_array.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(transformer, input));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            transformer       = File.ReadAllText("Examples/Transformer_array.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JArray.Parse(transformer), input));
            Console.WriteLine(transformedString);

            Console.ReadLine();
        }
		public VoteReportContentGenerator( DataTransformer transformer, ISerializer serializer ) : this( transformer.Get, serializer, DocumentFactory.Default ) {}
Esempio n. 6
0
        public static void updatePassword(int USERID, string PASSWORD)
        {
            DateTime now = DateTime.Now;

            try
            {
                ZXPUserData zxpUD       = ZXPUserData.GetZXPUserDataFromCookie();
                string      sql_connStr = new TruckScheduleConfigurationKeysHelper().sql_connStr;
                using (var scope = new TransactionScope())
                {
                    string sqlCmdText;
                    //sql_connStr = new TruckScheduleConfigurationKeysHelper().sql_connStr;

                    ChangeLog cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "Password", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, DataTransformer.PasswordHash(PASSWORD).ToString(), null, "UserID", USERID.ToString());
                    cl.CreateChangeLogEntryIfChanged();

                    sqlCmdText = "UPDATE dbo.Users SET Password = @Password WHERE UserID = @UserID";
                    SqlHelper.ExecuteScalar(sql_connStr, CommandType.Text, sqlCmdText, new SqlParameter("@Password", DataTransformer.PasswordHash(PASSWORD)),
                                            new SqlParameter("@UserID", USERID));
                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                string strErr = " Exception Error in Admin_Users GetPODetailsFromMSID(). Details: " + ex.ToString();
                ErrorLogging.WriteEvent(strErr, EventLogEntryType.Error);
                System.Web.HttpContext.Current.Session["ErrorNum"] = 1;
                ErrorLogging.sendtoErrorPage(1);
                throw ex;
            }
        }
Esempio n. 7
0
 private void FixBoat(Player player)
 {
     player.SetHealth();
     DataTransformer.sendDDA(Time.realtimeSinceStartup, Event.revivePlayer, gameObject.GetComponent <Player>(), 0, 0, GetGameMode());
     DataTransformer.sendDDA(Time.realtimeSinceStartup, Event.revived, ID, transform.position.x, transform.position.y, 0, 0, GetGameMode());
 }
Esempio n. 8
0
        public JsonResult ImportCommisionList(HttpPostedFileBase importCommisionList)
        {
            string fileName = "";
            object ls;
            object retList = null;

            try
            {
                var file = importCommisionList;
                if (file != null)
                {
                    string[] extFile = new string[] { "xlsx" };
                    fileName = string.Format("{0}\\{1}{2}", Server.MapPath("~/Content/Uploads"), DateTime.Now.ToString("yyyyMMddHHmmss"), System.IO.Path.GetExtension(file.FileName));
                    if (fileName.EndsWith(".xlsx", StringComparison.CurrentCultureIgnoreCase))
                    {
                        file.SaveAs(fileName);
                    }

                    Reader           reader = new Reader(fileName);
                    IDataTransformer podata = new DataTransformer();
                    ls = reader.GetData <CPProductImportTempCommisionListModel>(podata);
                    if (ls != null)
                    {
                        int idx = 1;
                        List <CPProductImportCommisionListModel> lsImport  = new List <CPProductImportCommisionListModel>();
                        List <CPProductImportProductModel>       lsProduct = new List <CPProductImportProductModel>();
                        object temp;
                        TheSession.TryGet(_strSectionProduct, out temp);
                        if (temp != null)
                        {
                            lsProduct = (List <CPProductImportProductModel>)temp;
                        }
                        if (lsProduct != null && lsProduct.Any())
                        {
                            foreach (var itx in ls as List <CPProductImportTempCommisionListModel> )
                            {
                                if (!string.IsNullOrEmpty(itx.productCode))
                                {
                                    string strProductCode = itx.productCode.FilterSpecial();
                                    string strMessage     = string.Empty;
                                    bool   isExists       = false;

                                    if (lsProduct != null && lsProduct.Any())
                                    {
                                        lsProduct = lsProduct.Where(x => string.IsNullOrEmpty(x.errorMessage)).ToList();
                                        isExists  = lsProduct.Any(x => x.productCode.ToUpper().Trim().Equals(strProductCode.ToUpper().Trim()));
                                    }
                                    else
                                    {
                                        strMessage += " Không tìm thấy danh sách mã sản phẩm";
                                    }
                                    if (!isExists)
                                    {
                                        strMessage += " Mã sản phẩm không tồn tại";
                                    }

                                    if (itx.effectedFromDate == null)
                                    {
                                        strMessage += " Thiếu trường hiệu lực từ ngày";
                                    }
                                    else
                                    {
                                        if (DateTime.Parse(itx.effectedFromDate.ToString()).Ticks < DateTime.Now.Date.Ticks)
                                        {
                                            strMessage += " Ngày hiệu lực từ ngày phải lớn hơn ngày hiện tại";
                                        }
                                    }
                                    if (itx.effectedToDate == null)
                                    {
                                        strMessage += " Thiếu trường hiệu lực đến ngày";
                                    }
                                    else
                                    {
                                        if (DateTime.Parse(itx.effectedToDate.ToString()).Ticks < DateTime.Now.Date.Ticks)
                                        {
                                            strMessage += " Ngày hiệu lực đến ngày phải lớn hơn ngày hiện tại";
                                        }
                                    }
                                    var item = new CPProductImportCommisionListModel
                                    {
                                        productCode      = strProductCode,
                                        productName      = itx.productName,
                                        effectedFromDate = itx.effectedFromDate != null?DateTime.Parse(itx.effectedFromDate.ToString()) : new DateTime(),
                                                               effectedToDate = itx.effectedToDate != null?DateTime.Parse(itx.effectedToDate.ToString()) : new DateTime(),
                                                                                    totalCommisRate   = (itx.agencyCommisRate ?? 0) + (itx.supportCommisRate ?? 0) + (itx.serviceCostRate ?? 0),
                                                                                    agencyCommisRate  = (itx.agencyCommisRate ?? 0),
                                                                                    supportCommisRate = (itx.supportCommisRate ?? 0),
                                                                                    serviceCostRate   = (itx.serviceCostRate ?? 0),
                                                                                    commisRate        = (itx.commisRate ?? 0),
                                                                                    errorMessage      = strMessage
                                    };
                                    item.remainRate = item.totalCommisRate - item.commisRate;
                                    item.SelectList = new List <SelectListItem>();
                                    item.SelectList = lsProduct;
                                    lsImport.Add(item);
                                    idx++;
                                }
                            }
                            retList = lsImport;
                            TheSession.TrySet(_strSectionCommisionList, retList);
                            return(Json(new { Code = 0, Message = RenderPartialViewToString("~/Areas/CPProduct/Views/Shared/_templateCommissionListImport.cshtml", retList) }));
                        }
                        else
                        {
                            return(Json(new { Code = -1, Message = "Không tìm thấy danh sách sản phẩm" }));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HDBH.Log.WriteLog.Error("ManagerController => ImportCommisionList", ex);
            }
            finally
            {
                if (!string.IsNullOrWhiteSpace(fileName))
                {
                    System.IO.File.Delete(fileName);
                }
            }
            return(Json(new { Code = -1, Message = "Không tìm thấy danh sách sản phẩm" }));
        }
Esempio n. 9
0
        /// <summary>
        /// The constructor.
        /// </summary>
        /// <param name="mycaffe">Specifies the instance of MyCaffe assoiated with the open project - when using more than one Brain, this is the master project.</param>
        /// <param name="properties">Specifies the properties passed into the trainer.</param>
        /// <param name="random">Specifies the random number generator used.</param>
        /// <param name="phase">Specifies the phase under which to run.</param>
        public Brain(MyCaffeControl <T> mycaffe, PropertySet properties, CryptoRandom random, Phase phase)
        {
            m_mycaffe    = mycaffe;
            m_solver     = mycaffe.GetInternalSolver();
            m_netOutput  = mycaffe.GetInternalNet(phase);
            m_netTarget  = new Net <T>(m_mycaffe.Cuda, m_mycaffe.Log, m_netOutput.net_param, m_mycaffe.CancelEvent, null, phase);
            m_properties = properties;
            m_random     = random;

            Blob <T> data = m_netOutput.blob_by_name("data");

            if (data == null)
            {
                m_mycaffe.Log.FAIL("Missing the expected input 'data' blob!");
            }

            m_nBatchSize = data.num;

            Blob <T> logits = m_netOutput.blob_by_name("logits");

            if (logits == null)
            {
                m_mycaffe.Log.FAIL("Missing the expected input 'logits' blob!");
            }

            m_nActionCount = logits.channels;

            m_transformer = m_mycaffe.DataTransformer;
            if (m_transformer == null)
            {
                TransformationParameter trans_param = new TransformationParameter();
                int nC = m_mycaffe.CurrentProject.Dataset.TrainingSource.ImageChannels;
                int nH = m_mycaffe.CurrentProject.Dataset.TrainingSource.ImageHeight;
                int nW = m_mycaffe.CurrentProject.Dataset.TrainingSource.ImageWidth;
                m_transformer = new DataTransformer <T>(m_mycaffe.Cuda, m_mycaffe.Log, trans_param, phase, nC, nH, nW);
            }
            m_blobActions        = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log, false);
            m_blobQValue         = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log);
            m_blobNextQValue     = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log);
            m_blobExpectedQValue = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log);
            m_blobDone           = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log, false);
            m_blobLoss           = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log);
            m_blobWeights        = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log, false);

            m_fGamma = (float)properties.GetPropertyAsDouble("Gamma", m_fGamma);

            m_memLoss = m_netOutput.FindLastLayer(LayerParameter.LayerType.MEMORY_LOSS) as MemoryLossLayer <T>;
            if (m_memLoss == null)
            {
                m_mycaffe.Log.FAIL("Missing the expected MEMORY_LOSS layer!");
            }

            double?dfRate = mycaffe.CurrentProject.GetSolverSettingAsNumeric("base_lr");

            if (dfRate.HasValue)
            {
                m_dfLearningRate = dfRate.Value;
            }

            m_nMiniBatch = m_properties.GetPropertyAsInt("MiniBatch", m_nMiniBatch);
            m_bUseAcceleratedTraining = properties.GetPropertyAsBool("UseAcceleratedTraining", false);

            if (m_nMiniBatch > 1)
            {
                m_colAccumulatedGradients = m_netOutput.learnable_parameters.Clone();
                m_colAccumulatedGradients.SetDiff(0);
            }
        }
Esempio n. 10
0
    public void NotificationDDAUpdate(JSONObject calcs)
    {
        int calcsIndex = (int)calcs.list[0].n;
        int LevelSpawnHeightAndTimer;
        int LevelPrecision;
        int LevelSpeedAndSpawnRate;

        // Since spawn, height, timer, precision and speed are all the same values, we'll store them all in a variable that represents them all
        int LevelGeneral;

        if (Mode == GameMode.Cooperative && calcs.keys[0] == "index" && DDAIndex < calcsIndex)
        {
            // DDAIndex is the latest change to the level that was recieved and updated
            DDAIndex = calcsIndex;
            for (int i = 0; i < NumberOfPlayers; i++)
            {
                // Assuming the enemy factory and the item factory both belong to the corresponding player
                if (EnemyFactories[i].GetID() == ItemFactories[i].GetID() && ItemFactories[i].GetID() == i + 1)
                {
                    // Save difficulty updated from DDA for the specific player
                    LevelSpawnHeightAndTimer = (int)calcs.list[1].list[i].n;
                    LevelPrecision           = (int)calcs.list[1].list[i].n;
                    LevelSpeedAndSpawnRate   = (int)calcs.list[1].list[i].n;
                    LevelGeneral             = LevelPrecision;
                    // Assuming the new change is in range
                    if (!(PlayerDifficIndexes[i] == 1 && LevelGeneral == -1) && !(PlayerDifficIndexes[i] == 6 && LevelGeneral == 1))
                    {
                        // PlayerDifficIndexes is the current index, in a static game it doesn't show what it's supposed to be next
                        if (PlayerDifficIndexes[i] + LevelGeneral > 5)
                        {
                            PlayerDifficIndexes[i] = 5;
                        }
                        else if (PlayerDifficIndexes[i] + LevelGeneral < 1)
                        {
                            PlayerDifficIndexes[i] = 1;
                        }
                        else
                        {
                            PlayerDifficIndexes[i] += LevelGeneral;
                            EnemyFactories[i].SetDDAChanges(LevelGeneral);
                            ItemFactories[i].SetDDAChanges(LevelGeneral);
                            Event evnt = LevelGeneral > 0 ? Event.lvlUp : (LevelGeneral < 0 ? Event.lvlDown : Event.lvlStay);
                            DataTransformer.sendTracker(Time.realtimeSinceStartup, evnt, i + 1, 0, 0, 0, i + 1, (int)Mode);
                        }
                    }
                }
            }
        }

        if (Mode == GameMode.Competitive && calcs.keys[0] == "index" && DDAIndex < calcsIndex)
        {
            DDAIndex = calcsIndex;
            for (int i = 0; i < NumberOfPlayers; i++)
            {
                LevelSpawnHeightAndTimer = (int)calcs.list[1].list[i].n;
                LevelPrecision           = (int)calcs.list[1].list[i].n;
                LevelSpeedAndSpawnRate   = (int)calcs.list[1].list[i].n;
                LevelGeneral             = LevelPrecision;
                // Save difficulty updated from DDA
                if (!(PlayerDifficIndexes[i] == 1 && LevelGeneral == -1) && !(PlayerDifficIndexes[i] == 6 && LevelGeneral == 1))
                {
                    if (PlayerDifficIndexes[i] + LevelGeneral > 5)
                    {
                        PlayerDifficIndexes[i] = 5;
                    }
                    else if (PlayerDifficIndexes[i] + LevelGeneral < 1)
                    {
                        PlayerDifficIndexes[i] = 1;
                    }
                    else
                    {
                        PlayerDifficIndexes[i] += LevelGeneral;
                        EnemyFactories[i].SetDDAChanges(LevelGeneral);
                        ItemFactories[i].SetDDAChanges(LevelGeneral);
                        Event evnt = LevelGeneral > 0 ? Event.lvlUp : (LevelGeneral < 0 ? Event.lvlDown : Event.lvlStay);
                        DataTransformer.sendTracker(Time.realtimeSinceStartup, evnt, i + 1, 0, 0, 0, -1, (int)Mode);
                    }
                }
            }
        }
    }
Esempio n. 11
0
 // Start is called before the first frame update
 void Start()
 {
     DataTransformer.SetTimeSpent(Time.realtimeSinceStartup);
     InvokeRepeating("TrackObjLocation", 5.0f, 5.0f);
 }
Esempio n. 12
0
 private string GetAssemblyName(DataTransformer transformer)
 {
     return(transformer.Method.Module.Assembly.CustomAttributes.First(a => a.AttributeType.Name == "AssemblyTitleAttribute").ConstructorArguments[0].Value as string);
 }
Esempio n. 13
0
 private void ResponseIdentified()
 {
     DataTransformer.sendTracker(Time.realtimeSinceStartup, Event.playerResponseTime, GetID(), 0, 0, (int)(ResponseTime * 1000), 0, GetGameMode());
     ResponseTime = -1;
 }
Esempio n. 14
0
        /// <summary>
        /// Run teaching epoch.
        /// </summary>
        /// <returns></returns>
        public override double RunEpoch()
        {
            var data = DataTransformer.Transform(Path(Config.Train.Data));

            int[] permutation = null;

            switch (Config.Batch)
            {
            case NetworkConfig.BatchType.Full:
            {
                permutation = Combinatorics.GeneratePermutation(data.RowCount);
                break;
            }

            case NetworkConfig.BatchType.Mini:
            {
                var batchSize = data.RowCount;

                if (Config.BatchSize > 0 && Config.BatchSize <= data.RowCount)
                {
                    batchSize = Config.BatchSize;
                }

                permutation = Combinatorics.GenerateVariation(data.RowCount, batchSize);
                break;
            }

            default:
            {
                permutation = new int[] { DiscreteUniform.Sample(0, data.RowCount - 1) };
                break;
            }
            }

            if (data.ColumnCount != Config.Inputs)
            {
                throw new Exception("Invalid data format.");
            }

            accumulatedCost = 0;

            accumulatedGradient = new Matrix <double> [layers.Count];

            var tasks = new Task[permutation.Length];

            for (int i = 0; i < permutation.Length; i++)
            {
                var index = permutation[i];

                tasks[i] = Task.Factory.StartNew((object trainState) =>
                {
                    var state = trainState as TrainState;

                    Train(
                        state.input,
                        state.target,
                        out double cost,
                        out List <Matrix <double> > gradient
                        );

                    // Console.WriteLine("\nTask cost {0} + {1}", cost, accumulatedCost);

                    accumulatedCost += cost;

                    for (int g = 0; g < gradient.Count; g++)
                    {
                        if (accumulatedGradient[g] == null)
                        {
                            accumulatedGradient[g] = Matrix <double> .Build.Dense(gradient[g].RowCount, gradient[g].ColumnCount);
                        }
                        accumulatedGradient[g] += gradient[g];
                    }
                }, new TrainState
                {
                    input  = data.Row(index),
                    target = LabelTransformer.TransformLabels().Row(index)
                }, TaskCreationOptions.LongRunning);

                //tasks[i].Wait(1);

                /*
                 * Train(
                 *  data.Row(index),
                 *  LabelTransformer.TransformLabels().Row(index),
                 *  out double cost,
                 *  out List<Matrix<double>> gradient
                 * );
                 *
                 * accumulatedCost += cost;
                 *
                 * for (int g = 0; g < gradient.Count; g++)
                 * {
                 *  if (accumulatedGradient[g] == null)
                 *  {
                 *      accumulatedGradient[g] = Matrix<double>.Build.Dense(gradient[g].RowCount, gradient[g].ColumnCount);
                 *  }
                 *  accumulatedGradient[g] += gradient[g];
                 * }
                 */
            }

            Task.WaitAll(tasks, Timeout.Infinite, CancellationToken.None);

            // Go through each layer of the network in opposite direction.
            for (int i = layers.Count - 1; i >= 0; i--)
            {
                var layer         = layers[i];
                var layerGradient = accumulatedGradient[layers.Count - 1 - i];

                if (Program.Debug)
                {
                    Console.WriteLine("accumulated gradient for layer {0}: {1}", i, layerGradient);
                }

                for (int j = 0; j < layer.Size; j++)
                {
                    for (int k = 0; k < layer.Neurons[j].InputCount; k++)
                    {
                        var v = layerGradient.Row(j);
                        layer.Neurons[j].Weights[k] += layerGradient.Row(j).At(k + 1);
                    }
                    layer.Neurons[j].Bias += layerGradient.Row(j).At(0);
                }
            }

            return(accumulatedCost / permutation.Length);
        }
Esempio n. 15
0
        /// <summary>
        /// The constructor.
        /// </summary>
        /// <param name="mycaffe">Specifies the instance of MyCaffe assoiated with the open project - when using more than one Brain, this is the master project.</param>
        /// <param name="properties">Specifies the properties passed into the trainer.</param>
        /// <param name="random">Specifies the random number generator used.</param>
        /// <param name="phase">Specifies the phase under which to run.</param>
        public Brain(MyCaffeControl <T> mycaffe, PropertySet properties, CryptoRandom random, Phase phase)
        {
            m_mycaffe    = mycaffe;
            m_solver     = mycaffe.GetInternalSolver();
            m_netOutput  = mycaffe.GetInternalNet(phase);
            m_netTarget  = new Net <T>(m_mycaffe.Cuda, m_mycaffe.Log, m_netOutput.net_param, m_mycaffe.CancelEvent, null, phase);
            m_properties = properties;
            m_random     = random;

            Blob <T> data = m_netOutput.blob_by_name("data");

            if (data == null)
            {
                m_mycaffe.Log.FAIL("Missing the expected input 'data' blob!");
            }

            m_nFramesPerX = data.channels;
            m_nBatchSize  = data.num;

            Blob <T> logits = m_netOutput.blob_by_name("logits");

            if (logits == null)
            {
                m_mycaffe.Log.FAIL("Missing the expected input 'logits' blob!");
            }

            m_nActionCount = logits.channels;

            m_transformer = m_mycaffe.DataTransformer;

            for (int i = 0; i < m_nFramesPerX; i++)
            {
                m_transformer.param.mean_value.Add(255 / 2); // center each frame
            }

            m_transformer.param.scale = 1.0 / 255; // normalize
            m_transformer.Update();

            m_blobActions        = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log, false);
            m_blobQValue         = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log);
            m_blobNextQValue     = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log);
            m_blobExpectedQValue = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log);
            m_blobDone           = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log, false);
            m_blobLoss           = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log);
            m_blobWeights        = new Blob <T>(m_mycaffe.Cuda, m_mycaffe.Log, false);

            m_fGamma = (float)properties.GetPropertyAsDouble("Gamma", m_fGamma);

            m_memLoss = m_netOutput.FindLastLayer(LayerParameter.LayerType.MEMORY_LOSS) as MemoryLossLayer <T>;
            if (m_memLoss == null)
            {
                m_mycaffe.Log.FAIL("Missing the expected MEMORY_LOSS layer!");
            }

            double?dfRate = mycaffe.CurrentProject.GetSolverSettingAsNumeric("base_lr");

            if (dfRate.HasValue)
            {
                m_dfLearningRate = dfRate.Value;
            }

            m_nMiniBatch = m_properties.GetPropertyAsInt("MiniBatch", m_nMiniBatch);
            m_bUseAcceleratedTraining = properties.GetPropertyAsBool("UseAcceleratedTraining", false);

            if (m_nMiniBatch > 1)
            {
                m_colAccumulatedGradients = m_netOutput.learnable_parameters.Clone();
                m_colAccumulatedGradients.SetDiff(0);
            }
        }
Esempio n. 16
0
        public JsonResult ImportProduct(HttpPostedFileBase importProduct)
        {
            string fileName = "";
            object ls;
            object retList = null;

            try
            {
                var file = importProduct;
                if (file != null)
                {
                    string[] extFile = new string[] { "xlsx" };
                    fileName = string.Format("{0}\\{1}{2}", Server.MapPath("~/Content/Uploads"), DateTime.Now.ToString("yyyyMMddHHmmss"), System.IO.Path.GetExtension(file.FileName));
                    if (fileName.EndsWith(".xlsx", StringComparison.CurrentCultureIgnoreCase))
                    {
                        file.SaveAs(fileName);
                    }

                    Reader           reader = new Reader(fileName);
                    IDataTransformer podata = new DataTransformer();
                    ls = reader.GetData <CPProductImportTempProductModel>(podata);
                    if (ls != null)
                    {
                        int idx = 1;
                        List <CPProductImportProductModel> lsImport = new List <CPProductImportProductModel>();
                        foreach (var itx in ls as List <CPProductImportTempProductModel> )
                        {
                            if (!string.IsNullOrEmpty(itx.productCode))
                            {
                                string strProductCode = itx.productCode.FilterSpecial();
                                string strProductName = itx.productName.FilterSpecial();
                                string strMessage     = string.Empty;

                                if (string.IsNullOrEmpty(strProductCode))
                                {
                                    strMessage += " Chưa nhập Product Code";
                                }
                                else
                                {
                                    if (HasSpecialChars(strProductCode))
                                    {
                                        strMessage += " Lỗi ký tự đặc biệt";
                                    }
                                    if (HasUnicode(strProductCode))
                                    {
                                        strMessage += " Lỗi ký unicode";
                                    }
                                    if (HasSpace(strProductCode))
                                    {
                                        strMessage += " Lỗi khoảng trắng";
                                    }
                                }

                                var item = new CPProductImportProductModel
                                {
                                    productCode  = strProductCode,
                                    productName  = strProductName,
                                    errorMessage = strMessage
                                };

                                lsImport.Add(item);
                                idx++;
                            }
                        }
                        retList = lsImport;
                    }
                    TheSession.TrySet(_strSectionProduct, retList);
                }
            }
            catch (Exception ex)
            {
                HDBH.Log.WriteLog.Error("ManagerController => ImportProduct", ex);
            }
            finally
            {
                if (!string.IsNullOrWhiteSpace(fileName))
                {
                    System.IO.File.Delete(fileName);
                }
            }
            return(Json(RenderPartialViewToString("~/Areas/CPProduct/Views/Shared/_templateProductImport.cshtml", retList)));
        }
        //-----------------------------------------------------------------------
        public void DoTransform()
        {
            var preview = new TransformPreview();

            var projectDir = Path.GetDirectoryName(Workspace.ProjectRoot);
            var files      = Directory.EnumerateFiles(projectDir, "*", SearchOption.AllDirectories).ToList();

            foreach (var file in files)
            {
                var ext = Path.GetExtension(file);

                if (ext == ".xml" || ext == ".json" || ext == ".yaml" || Workspace.SupportedExtensionMap.ContainsKey(ext))
                {
                    try
                    {
                        var doc         = XDocument.Load(file);
                        var transformed = DataTransformer.TransformDocument(doc.Root);
                        var asString    = new StringBuilder();

                        XmlWriterSettings settings = new XmlWriterSettings
                        {
                            Indent             = true,
                            IndentChars        = "\t",
                            NewLineChars       = "\r\n",
                            NewLineHandling    = NewLineHandling.Replace,
                            OmitXmlDeclaration = true,
                            Encoding           = new UTF8Encoding(false)
                        };

                        using (XmlWriter writer = XmlTextWriter.Create(asString, settings))
                        {
                            doc.Save(writer);
                        }

                        var original    = File.ReadAllText(file);
                        var newContents = asString.ToString();

                        if (transformed && original != newContents)
                        {
                            var builder = new SideBySideDiffBuilder(new Differ());
                            var diff    = builder.BuildDiffModel(original, newContents);

                            if (diff.NewText.Lines.Any(e => e.Type != ChangeType.Unchanged) || diff.OldText.Lines.Any(e => e.Type != ChangeType.Unchanged))
                            {
                                preview.Files.Add(new Tuple <string, string, string, SideBySideDiffModel>(file, Path.GetFileNameWithoutExtension(file), newContents, diff));
                            }
                        }
                    }
                    catch (Exception) { }
                }
            }

            if (preview.Files.Count == 0)
            {
                Message.Show("No matching files found in project", "Completed transform");
            }
            else
            {
                Preview = preview;
                RaisePropertyChangedEvent(nameof(Preview));
            }
        }
Esempio n. 18
0
    private void OnTriggerEnter2D(Collider2D collider)
    {
        const int itemLayer            = 10;
        const int enemyLayer           = 11;
        const int sinkLayer            = 12;
        const int playerCollisionLayer = 13;
        const int dontCollideLayer     = 14;
        const int powerupLayer         = 15;

        Player playerObj = gameObject.GetComponent <Player>();
        int    gameMode  = GetGameMode();

        switch (collider.gameObject.layer)
        {
        // Check collistion with treasures
        case itemLayer:
            Treasure treasure = collider.GetComponent <Treasure>();
            // Untaken treasure
            if (!treasure.GetIsPickedUp())
            {
                TakeTreasure(collider.gameObject);
                DataTransformer.sendDDA(Time.realtimeSinceStartup, Event.pickup, playerObj, treasure.GetID(), 0, gameMode);
            }
            break;

        // Check collistion with enemies
        case enemyLayer:
            int enemyID = collider.GetComponent <Enemy>().GetID();
            collider.gameObject.layer = dontCollideLayer;
            if (enemyID == ID || enemyID == -1)
            {
                SetEnemyHit(collider.GetComponent <Enemy>());
            }
            else
            {
                DataTransformer.sendDDA(Time.realtimeSinceStartup, Event.blockDamage, playerObj, 0, enemyID, gameMode);
            }
            break;

        case sinkLayer:
            if (!IsInventoryEmpty(MyItemInventory))
            {
                for (int i = 0; i < MyItemInventory.Length; i++)
                {
                    int itemID = MyItemInventory[i].GetID();
                    if (RemoveItem(MyItemInventory[i]))
                    {
                        collider.GetComponent <ItemSink>().SetScore(playerObj);
                        DataTransformer.sendDDA(Time.realtimeSinceStartup, Event.dropitem, playerObj, itemID, 0, gameMode);
                        break;
                    }
                }
            }
            break;

        case playerCollisionLayer:
            Player otherPlayer = collider.transform.parent.gameObject.GetComponent <Player>();
            if (!IsInventoryEmpty(OthersItemInventory))
            {
                if (!otherPlayer.IsInventoryFull(otherPlayer.GetMyItemInventory()))
                {
                    for (int i = 0; i < OthersItemInventory.Length; i++)
                    {
                        if (OthersItemInventory[i].GetID() == otherPlayer.GetID())
                        {
                            // Give item to other player
                            OthersItemInventory[i].SetDisown();
                            OrderCarriedItems();
                            otherPlayer.TakeTreasure(OthersItemInventory[i].gameObject);
                            RemoveItem(OthersItemInventory[i]);
                            DataTransformer.sendDDA(Time.realtimeSinceStartup, Event.giveItem, playerObj, otherPlayer.GetID(), 0, gameMode);
                        }
                    }
                }
            }
            // If it's a cooperative mode AND if the other player needs revival
            if (OthersItemInventory.Length != 0 && otherPlayer.GetComponent <Player>().GetHealth() == 0)
            {
                FixBoatTime = 0;
            }
            break;

        case powerupLayer:

            if (gameMode == 1)
            {
                // Competitive mode
                immuneTimer = 5;
                collider.GetComponent <Powerup>().SetPickedUp();
                gameObject.GetComponentsInChildren <Animator>()[1].SetBool("Aura", true);
                Destroy(collider.gameObject);
                StartCoroutine(Countdown());
            }
            else
            {
                // Cooperative mode
                collider.GetComponent <Powerup>().SetPickedUp();
                Destroy(collider.gameObject);
                GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("Player");
                foreach (var g in gameObjects)
                {
                    g.GetComponent <Player>().SetHealth();
                }
            }
            DataTransformer.sendDDA(Time.realtimeSinceStartup, Event.powerupTaken, playerObj, 0, 0, gameMode);
            break;

        default:
            break;
        }
    }
Esempio n. 19
0
        public static void Main(string[] args)
        {
            string input = File.ReadAllText("Examples/Input.json");

            string transformer       = File.ReadAllText("Examples/Transformer_valueof.json");
            string transformedString = JsonTransformer.Transform(transformer, input);

            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);


            transformer       = File.ReadAllText("Examples/Transformer_valueofarray.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);


            transformer       = File.ReadAllText("Examples/Transformer_copy.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_replace.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_delete.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);


            transformer       = File.ReadAllText("Examples/Transformer_ifcondition.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_string.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_math.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_aggregate.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_arrayaggregate.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_looping.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_customfunction.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_nestedfunctions.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_xfunctions.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer_Existance.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/DataTransformer.xml");
            transformedString = DataTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/DataTransformer.csv");
            transformedString = DataTransformer.Transform(transformer, input);
            Console.WriteLine("################################################################################################");
            Console.WriteLine(transformedString);

            transformer       = File.ReadAllText("Examples/Transformer.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(input)));
            Console.WriteLine(transformedString);



            Console.WriteLine("################################################################################################");
            string inputJson   = File.ReadAllText("Examples/ValidationInput.json");
            string schemaJsonX = File.ReadAllText("Examples/SchemaX.json");
            string schemaJsonY = File.ReadAllText("Examples/SchemaY.json");

            string InputToSplit = File.ReadAllText("Examples/InputToSplit.json");

            List <string> outputs = JsonTransformer.SplitJson(InputToSplit, "$.cars.Ford").ToList <string>();

            foreach (string output in outputs)
            {
                Console.WriteLine("-----------------------------------------------------");
                Console.WriteLine(output);
            }

            Console.WriteLine("################################################################################################");

            JsonValidator validator = new JsonValidator(inputJson);

            validator.AddSchema("x", schemaJsonX);
            validator.AddSchema("y", schemaJsonY);

            validator.Validate();

            Console.WriteLine("################################################################################################");
            transformer       = File.ReadAllText("Examples/Transformer_nestedloop.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(input)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");
            transformer       = File.ReadAllText("Examples/Transformer_looptests.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(input)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            string inputSpecial = File.ReadAllText("Examples/InputSpecial.json");

            transformer       = File.ReadAllText("Examples/Transformer_customfunctionspecial.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(inputSpecial)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            string inputUnordered = File.ReadAllText("Examples/Input_Unordered.json");

            transformer       = File.ReadAllText("Examples/Transform_Unordered.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(inputUnordered)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            string inputUnordered2 = File.ReadAllText("Examples/Input_Unordered_2.json");

            transformer       = File.ReadAllText("Examples/Transform_Unordered_2.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(inputUnordered2)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");


            string inputDyn = File.ReadAllText("Examples/InputDynamic.json");

            transformer       = File.ReadAllText("Examples/TransformDynamic.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(inputDyn)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            transformer       = File.ReadAllText("Examples/Transformer_externalmethods.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(input)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            transformer       = File.ReadAllText("Examples/Transformer_array.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(transformer, input));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            transformer       = File.ReadAllText("Examples/Transformer_array.json");
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JArray.Parse(transformer), input));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            transformer = File.ReadAllText("Examples/Transformer_registeredmethods.json");
            var context = new JUSTContext();

            context.RegisterCustomFunction("ExternalMethods", "ExternalMethods.ExternalClass", "StaticMethod", "External_StaticMethod");
            context.RegisterCustomFunction("ExternalMethods", "ExternalMethods.ExternalClass", "StaticTypedParameters", "External_StaticTypedParameters");
            context.RegisterCustomFunction("ExternalMethods", "ExternalMethods.ExternalClass", "InstanceMethod", "External_InstanceMethod");
            context.RegisterCustomFunction("ExternalMethods", "ExternalMethods.ExternalClass", "TypedParameters", "External_TypedParameters");
            context.RegisterCustomFunction("ExternalMethods", "ExternalMethods.ExternalClass", "NavigateTypedParameters", "External_NavigateTypedParameters");

            context.RegisterCustomFunction(null, "InternalMethods.InternalClass", "StaticMethod");
            context.RegisterCustomFunction(null, "InternalMethods.InternalClass", "StaticTypedParameters");
            context.RegisterCustomFunction(null, "InternalMethods.InternalClass", "InstanceMethod");
            context.RegisterCustomFunction(null, "InternalMethods.InternalClass", "TypedParameters");
            context.RegisterCustomFunction(null, "InternalMethods.InternalClass", "NavigateTypedParameters");

            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(input), context));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            transformer = File.ReadAllText("Examples/Transformer_registeredmethods.json");
            JsonTransformer.GlobalContext.RegisterCustomFunction("ExternalMethods", "ExternalMethods.ExternalClass", "StaticMethod", "External_StaticMethod");
            JsonTransformer.GlobalContext.RegisterCustomFunction("ExternalMethods", "ExternalMethods.ExternalClass", "StaticTypedParameters", "External_StaticTypedParameters");
            JsonTransformer.GlobalContext.RegisterCustomFunction("ExternalMethods", "ExternalMethods.ExternalClass", "InstanceMethod", "External_InstanceMethod");
            JsonTransformer.GlobalContext.RegisterCustomFunction("ExternalMethods", "ExternalMethods.ExternalClass", "TypedParameters", "External_TypedParameters");
            JsonTransformer.GlobalContext.RegisterCustomFunction("ExternalMethods", "ExternalMethods.ExternalClass", "NavigateTypedParameters", "External_NavigateTypedParameters");

            JsonTransformer.GlobalContext.RegisterCustomFunction(null, "InternalMethods.InternalClass", "StaticMethod");
            JsonTransformer.GlobalContext.RegisterCustomFunction(null, "InternalMethods.InternalClass", "StaticTypedParameters");
            JsonTransformer.GlobalContext.RegisterCustomFunction(null, "InternalMethods.InternalClass", "InstanceMethod");
            JsonTransformer.GlobalContext.RegisterCustomFunction(null, "InternalMethods.InternalClass", "TypedParameters");
            JsonTransformer.GlobalContext.RegisterCustomFunction(null, "InternalMethods.InternalClass", "NavigateTypedParameters");

            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(input)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            JsonTransformer.GlobalContext.EvaluationMode = EvaluationMode.Strict;

            inputDyn          = File.ReadAllText("Examples/InputDynamic.json");
            transformer       = "{ \"Result\": { \"Header\": \"JsonTransform\", \"#eval(#valueof($.Tree.Flower))\": \"x\", \"#ifgroup(#exists($.Tree.Flower))\": { \"Comment\": { \"Statement\": \"Flower Exists\" } } }}";
            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(inputDyn)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            JsonTransformer.GlobalContext.EvaluationMode = EvaluationMode.FallbackToDefault;

            inputDyn    = File.ReadAllText("Examples/InputDynamic.json");
            transformer = "{ \"Result\": { \"Header\": \"JsonTransform\", \"#ifgroup(1)\": { \"State\": { \"Value1\": \"#valueof($.Tree.Branch)\", \"Value2\": \"#valueof($.Tree.Flower)\" }} } }";

            transformedString = JsonConvert.SerializeObject
                                    (JsonTransformer.Transform(JObject.Parse(transformer), JObject.Parse(inputDyn)));
            Console.WriteLine(transformedString);

            Console.WriteLine("################################################################################################");

            input             = File.ReadAllText("Examples/Input.json");
            transformer       = File.ReadAllText("Examples/Transformer_typeconversion.json");
            transformedString = JsonTransformer.Transform(transformer, input);
            Console.WriteLine(transformedString);

            Console.ReadLine();
        }
Esempio n. 20
0
        /// <summary>
        /// Setup the layer.
        /// </summary>
        /// <param name="colBottom">Specifies the collection of bottom (input) Blobs.</param>
        /// <param name="colTop">Specifies the collection of top (output) Blobs.</param>
        public override void LayerSetUp(BlobCollection <T> colBottom, BlobCollection <T> colTop)
        {
            m_log.CHECK_GT(m_param.detection_output_param.num_classes, 0, "There must be at least one class specified.");
            m_nNumClasses = (int)m_param.detection_output_param.num_classes;

            m_bShareLocations          = m_param.detection_output_param.share_location;
            m_nNumLocClasses           = (m_bShareLocations) ? 1 : m_nNumClasses;
            m_nBackgroundLabelId       = m_param.detection_output_param.background_label_id;
            m_codeType                 = m_param.detection_output_param.code_type;
            m_bVarianceEncodedInTarget = m_param.detection_output_param.variance_encoded_in_target;
            m_nKeepTopK                = m_param.detection_output_param.keep_top_k;
            m_fConfidenceThreshold     = m_param.detection_output_param.confidence_threshold.GetValueOrDefault(-float.MaxValue);

            // Parameters used in nms.
            m_fNmsThreshold = m_param.detection_output_param.nms_param.nms_threshold;
            m_log.CHECK_GE(m_fNmsThreshold, 0, "The nms_threshold must be non negative.");
            m_fEta = m_param.detection_output_param.nms_param.eta;
            m_log.CHECK_GT(m_fEta, 0, "The nms_param.eta must be > 0.");
            m_log.CHECK_LE(m_fEta, 1, "The nms_param.eta must be < 0.");

            m_nTopK = m_param.detection_output_param.nms_param.top_k.GetValueOrDefault(-1);

            m_strOutputDir = m_param.detection_output_param.save_output_param.output_directory;
            m_bNeedSave    = !string.IsNullOrEmpty(m_strOutputDir);
            if (m_bNeedSave && !Directory.Exists(m_strOutputDir))
            {
                Directory.CreateDirectory(m_strOutputDir);
            }

            m_strOutputNamePrefix = m_param.detection_output_param.save_output_param.output_name_prefix;
            m_outputFormat        = m_param.detection_output_param.save_output_param.output_format;

            if (!string.IsNullOrEmpty(m_param.detection_output_param.save_output_param.label_map_file))
            {
                string strLabelMapFile = m_param.detection_output_param.save_output_param.label_map_file;
                if (!File.Exists(strLabelMapFile))
                {
                    // Ignore saving if there is no label map file.
                    m_log.WriteLine("WARNING: Could not find the label_map_file '" + strLabelMapFile + "'!");
                    m_bNeedSave = false;
                }
                else
                {
                    LabelMap label_map;

                    try
                    {
                        RawProto proto = RawProto.FromFile(strLabelMapFile);
                        label_map = LabelMap.FromProto(proto);
                    }
                    catch (Exception excpt)
                    {
                        throw new Exception("Failed to read label map file!", excpt);
                    }

                    try
                    {
                        m_rgLabelToName = label_map.MapToName(m_log, true, false);
                    }
                    catch (Exception excpt)
                    {
                        throw new Exception("Failed to convert the label to name!", excpt);
                    }

                    try
                    {
                        m_rgLabelToDisplayName = label_map.MapToName(m_log, true, true);
                    }
                    catch (Exception excpt)
                    {
                        throw new Exception("Failed to convert the label to display name!", excpt);
                    }
                }
            }
            else
            {
                m_bNeedSave = false;
            }

            if (!string.IsNullOrEmpty(m_param.detection_output_param.save_output_param.name_size_file))
            {
                string strNameSizeFile = m_param.detection_output_param.save_output_param.name_size_file;
                if (!File.Exists(strNameSizeFile))
                {
                    // Ignore saving if there is no name size file.
                    m_log.WriteLine("WARNING: Could not find the name_size_file '" + strNameSizeFile + "'!");
                    m_bNeedSave = false;
                }
                else
                {
                    using (StreamReader sr = new StreamReader(strNameSizeFile))
                    {
                        string strName;
                        int    nHeight;
                        int    nWidth;

                        string strLine = sr.ReadLine();
                        while (strLine != null)
                        {
                            string[] rgstr = strLine.Split(' ');
                            if (rgstr.Length != 3 && rgstr.Length != 4)
                            {
                                throw new Exception("Invalid name_size_file format, expected 'name' 'height' 'width'");
                            }

                            int nNameIdx = (rgstr.Length == 4) ? 1 : 0;
                            strName = rgstr[nNameIdx].Trim(',');
                            nHeight = int.Parse(rgstr[nNameIdx + 1].Trim(','));
                            nWidth  = int.Parse(rgstr[nNameIdx + 2].Trim(','));

                            m_rgstrNames.Add(strName);
                            m_rgSizes.Add(new SizeF(nWidth, nHeight));

                            strLine = sr.ReadLine();
                        }
                    }

                    if (m_param.detection_output_param.save_output_param.num_test_image.HasValue)
                    {
                        m_nNumTestImage = (int)m_param.detection_output_param.save_output_param.num_test_image.Value;
                    }
                    else
                    {
                        m_nNumTestImage = m_rgstrNames.Count;
                    }

                    m_log.CHECK_LE(m_nNumTestImage, m_rgstrNames.Count, "The number of test images cannot exceed the number of names.");
                }
            }
            else
            {
                m_bNeedSave = false;
            }

            if (m_param.detection_output_param.save_output_param.resize_param != null && m_param.detection_output_param.save_output_param.resize_param.Active)
            {
                m_resizeParam = m_param.detection_output_param.save_output_param.resize_param;
            }

            m_nNameCount = 0;

            m_bVisualize = m_param.detection_output_param.visualize;
            if (m_bVisualize)
            {
                m_fVisualizeThreshold = m_param.detection_output_param.visualize_threshold.GetValueOrDefault(0.6f);
                m_transformer         = new DataTransformer <T>(m_cuda, m_log, m_param.transform_param, m_phase, 0, 0, 0);
                m_transformer.InitRand();
                m_strSaveFile = m_param.detection_output_param.save_file;
            }

            m_blobBboxPreds.ReshapeLike(colBottom[0]);

            if (!m_bShareLocations)
            {
                m_blobBboxPermute.ReshapeLike(colBottom[0]);
            }

            m_blobConfPermute.ReshapeLike(colBottom[1]);
        }
Esempio n. 21
0
        public static void updateUser(int USERID, string USERNAME, string FIRSTNAME, string LASTNAME, string EMAIL, string CELLPHONENUMBER, int?CELLPHONEPROVIDER, bool ADMIN, bool DOCKMANAGER, bool INSPECTOR, bool GUARD, bool LABPERSONEL, bool LOADER, bool YARDMULE, bool LABADMIN, bool REPORTER, bool ACCTMANAGER)
        {
            DateTime now = DateTime.Now;

            try
            {
                ZXPUserData zxpUD       = ZXPUserData.GetZXPUserDataFromCookie();
                string      sql_connStr = new TruckScheduleConfigurationKeysHelper().sql_connStr;
                using (var scope = new TransactionScope())
                {
                    string sqlCmdText;

                    if (CELLPHONENUMBER == null && CELLPHONEPROVIDER == null)
                    {
                        ChangeLog cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "UserName", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, USERNAME.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "FirstName", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, FIRSTNAME.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "LastName", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, LASTNAME.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "EmailAddress", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, EMAIL.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isAdmin", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, ADMIN.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isDockManager", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, DOCKMANAGER.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isInspector", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, INSPECTOR.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isGuard", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, GUARD.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isLabPersonel", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, LABPERSONEL.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isLoader", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, LOADER.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isYardMule", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, YARDMULE.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "canViewReports", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, REPORTER.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isLabAdmin", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, LABADMIN.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.INSERT, "Users", "isAccountManager", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, ACCTMANAGER.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "Phone", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, "NULL", null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "CellProviderID", now, zxpUD._uid, ChangeLog.ChangeLogDataType.INT, "NULL", null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();

                        sqlCmdText = "UPDATE dbo.Users SET UserName = @UserName, FirstName = @FirstName, LastName = @LastName, EmailAddress = @EmailAddress, isAdmin = @isAdmin, isDockManager = @isDockManager, isInspector = @isInspector, " +
                                     "isGuard = @isGuard, isLabPersonel = @isLabPersonel, isLoader = @isLoader, isYardMule = @isYardMule, isLabAdmin = @isLabAdmin, canViewReports = @canViewReports, isAccountManager = @isAccountManager, " +
                                     "Phone = null, CellProviderID = null WHERE UserID = @UserID";
                        SqlHelper.ExecuteScalar(sql_connStr, CommandType.Text, sqlCmdText, new SqlParameter("@UserName", USERNAME),
                                                new SqlParameter("@FirstName", FIRSTNAME),
                                                new SqlParameter("@LastName", LASTNAME),
                                                new SqlParameter("@EmailAddress", EMAIL),
                                                new SqlParameter("@Password", DataTransformer.PasswordHash("ZXPpassword1!")),
                                                new SqlParameter("@isAdmin", ADMIN),
                                                new SqlParameter("@isDockManager", DOCKMANAGER),
                                                new SqlParameter("@isInspector", INSPECTOR),
                                                new SqlParameter("@isGuard", GUARD),
                                                new SqlParameter("@isLabPersonel", LABPERSONEL),
                                                new SqlParameter("@isLoader", LOADER),
                                                new SqlParameter("@isYardMule", YARDMULE),
                                                new SqlParameter("@canViewReports", REPORTER),
                                                new SqlParameter("@isLabAdmin", LABADMIN),
                                                new SqlParameter("@isAccountManager", ACCTMANAGER),
                                                new SqlParameter("@UserID", USERID));
                    }
                    else if (CELLPHONEPROVIDER != null && CELLPHONENUMBER != null)
                    {
                        ChangeLog cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "UserName", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, USERNAME.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "FirstName", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, FIRSTNAME.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "LastName", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, LASTNAME.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "EmailAddress", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, EMAIL.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isAdmin", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, ADMIN.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isDockManager", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, DOCKMANAGER.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isInspector", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, INSPECTOR.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isGuard", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, GUARD.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isLabPersonel", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, LABPERSONEL.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isLoader", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, LOADER.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isYardMule", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, YARDMULE.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "canViewReports", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, REPORTER.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "isLabAdmin", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, LABADMIN.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.INSERT, "Users", "isAccountManager", now, zxpUD._uid, ChangeLog.ChangeLogDataType.BIT, ACCTMANAGER.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "Phone", now, zxpUD._uid, ChangeLog.ChangeLogDataType.NVARCHAR, CELLPHONENUMBER.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();
                        cl = new ChangeLog(ChangeLog.ChangeLogChangeType.UPDATE, "Users", "CellProviderID", now, zxpUD._uid, ChangeLog.ChangeLogDataType.INT, CELLPHONEPROVIDER.ToString(), null, "UserID", USERID.ToString());
                        cl.CreateChangeLogEntryIfChanged();

                        sqlCmdText = "UPDATE dbo.Users SET UserName = @UserName, FirstName = @FirstName, LastName = @LastName, EmailAddress = @EmailAddress, Phone = @Phone, CellProviderID = @CellProviderID, " +
                                     "isAdmin = @isAdmin, isDockManager = @isDockManager, isInspector = @isInspector, isGuard = @isGuard, isLabPersonel = @isLabPersonel, isLoader = @isLoader, isYardMule = @isYardMule, " +
                                     "isLabAdmin = @isLabAdmin, canViewReports = @canViewReports, isAccountManager = @isAccountManager WHERE UserID = @UserID";
                        SqlHelper.ExecuteScalar(sql_connStr, CommandType.Text, sqlCmdText, new SqlParameter("@UserName", USERNAME),
                                                new SqlParameter("@FirstName", FIRSTNAME),
                                                new SqlParameter("@LastName", LASTNAME),
                                                new SqlParameter("@EmailAddress", EMAIL),
                                                new SqlParameter("@Phone", CELLPHONENUMBER),
                                                new SqlParameter("@CellProviderID", CELLPHONEPROVIDER),
                                                new SqlParameter("@Password", DataTransformer.PasswordHash("ZXPpassword1!")),
                                                new SqlParameter("@isAdmin", ADMIN),
                                                new SqlParameter("@isDockManager", DOCKMANAGER),
                                                new SqlParameter("@isInspector", INSPECTOR),
                                                new SqlParameter("@isGuard", GUARD),
                                                new SqlParameter("@isLabPersonel", LABPERSONEL),
                                                new SqlParameter("@isLoader", LOADER),
                                                new SqlParameter("@isYardMule", YARDMULE),
                                                new SqlParameter("@canViewReports", REPORTER),
                                                new SqlParameter("@isLabAdmin", LABADMIN),
                                                new SqlParameter("@isAccountManager", ACCTMANAGER),
                                                new SqlParameter("@UserID", USERID));
                    }
                    else if (CELLPHONEPROVIDER == null && CELLPHONENUMBER != null)
                    {
                        throw new Exception("Trying to add a cell phone provider without a cell phone number to a user.");
                    }
                    else if (CELLPHONEPROVIDER != null && CELLPHONENUMBER == null)
                    {
                        throw new Exception("Trying to add a cell phone number without a cell phone provider to a user.");
                    }
                    else
                    {
                        throw new Exception("Username already exists");
                    }
                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                string strErr = " Exception Error in Admin_Users updateUser(). Details: " + ex.ToString();
                ErrorLogging.WriteEvent(strErr, EventLogEntryType.Error);
                System.Web.HttpContext.Current.Session["ErrorNum"] = 1;
                ErrorLogging.sendtoErrorPage(1);
                throw ex;
            }
        }