示例#1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        AWSAuthConnection conn = new AWSAuthConnection(accessKey, secretKey);

          XmlTextReader r = new XmlTextReader(Request.InputStream);
          r.MoveToContent();
          string xml = r.ReadOuterXml();

          XmlDocument documentToSave = new XmlDocument();
          documentToSave.LoadXml(xml);

          SortedList metadata = new SortedList();
          metadata.Add("title", bucket);
          metadata.Add("Content-Type", "application/xml");
          S3Object titledObject =
           new S3Object(documentToSave.OuterXml, metadata);

          SortedList headers = new SortedList();
          headers.Add("Content-Type", "application/xml");
          headers.Add("x-amz-acl", "public-read");

          conn.put(bucket, documentKey, titledObject, headers);

          Response.Write("saved: " + documentToSave.OuterXml);
    }
示例#2
0
        static void Main(string[] args)
        {
            var books = new SortedList<string, string>();
            books.Add("C# 2008 Wrox Box", "978–0–470–047205–7");
            books.Add("Professional ASP.NET MVC 1.0", "978–0–470–38461–9");

            books["Beginning Visual C# 2008"] = "978–0–470-19135-4";
            books["Professional C# 2008"] = "978–0–470–19137–6";

            foreach (KeyValuePair<string, string> book in books)
            {
                Console.WriteLine("{0}, {1}", book.Key, book.Value);
            }

            foreach (string isbn in books.Values)
            {
                Console.WriteLine(isbn);
            }

            foreach (string title in books.Keys)
            {
                Console.WriteLine(title);
            }

            {
                string isbn;
                string title = "Professional C# 7.0";
                if (!books.TryGetValue(title, out isbn))
                {
                    Console.WriteLine("{0} not found", title);
                }
            }
            Console.ReadKey();
        }
示例#3
0
        public Form1()
        {
            InitializeComponent();

            for (int i = 0; i < table.Columns.Count; ++i)
            {
                contextMenuStrip2.Items.Add(table.Columns[i].HeaderText);

                contextMenuStrip2.Items[i].Name = table.Columns[i].Name;

                ((ToolStripMenuItem)contextMenuStrip2.Items[i]).Checked = table.Columns[i].Visible;
            }

            prevCat = new SortedList<string, int>();

            prevCat.Add(mensCategories.DropDownItems[0].Text, 0);
            for (int i = 1; i < mensCategories.DropDownItems.Count; ++i)
                prevCat.Add(mensCategories.DropDownItems[i].Text, Convert.ToInt32(mensCategories.DropDownItems[i - 1].Text));

            prevCat.Add(womensCategories.DropDownItems[0].Text, 0);
            for (int i = 1; i < womensCategories.DropDownItems.Count; ++i)
                prevCat.Add(womensCategories.DropDownItems[i].Text, Convert.ToInt32(womensCategories.DropDownItems[i - 1].Text));

            changed = false;
        }
示例#4
0
文件: Add.cs 项目: GTuritto/ngenerics
        public void StressTestList()
        {
            var sortedList = new SortedList<int>();

            for (var i = 1000; i > 0; i--)
            {
                sortedList.Add(i);
            }

            for (var i = 1000; i > 0; i--)
            {
                sortedList.Add(i);
            }

            var counter = 0;
            var val = 1;

            while (counter <= 1000)
            {
                Assert.AreEqual(sortedList[counter], val);
                counter++;

                Assert.AreEqual(sortedList[counter], val);
                counter++;
                val++;
            }
        }
        public static SortedList<string, Either<TreeTreeReference, TreeBlobReference>> ComputeChildList(IEnumerable<TreeTreeReference> treeRefs, IEnumerable<TreeBlobReference> blobRefs)
        {
            // Sort refs by name:
            var namedRefs = new SortedList<string, Either<TreeTreeReference, TreeBlobReference>>(treeRefs.Count() + blobRefs.Count(), StringComparer.Ordinal);

            // Add tree refs:
            foreach (var tr in treeRefs)
            {
                if (namedRefs.ContainsKey(tr.Name))
                    throw new InvalidOperationException();

                namedRefs.Add(tr.Name, tr);
            }

            // Add blob refs:
            foreach (var bl in blobRefs)
            {
                if (namedRefs.ContainsKey(bl.Name))
                    throw new InvalidOperationException();

                namedRefs.Add(bl.Name, bl);
            }

            return namedRefs;
        }
示例#6
0
        public void Simple()
        {
            var sortedList = new SortedList<int> { 5 };

            Assert.AreEqual(sortedList.Count, 1);

            sortedList.RemoveAt(0);

            Assert.AreEqual(sortedList.Count, 0);

            sortedList.Add(5);
            sortedList.Add(2);

            Assert.AreEqual(sortedList.Count, 2);
            sortedList.RemoveAt(1);

            Assert.AreEqual(sortedList.Count, 1);

            sortedList.Add(2);

            Assert.AreEqual(sortedList.Count, 2);
            sortedList.RemoveAt(0);

            Assert.AreEqual(sortedList.Count, 1);
        }
示例#7
0
 private void ListProc()
 {
     listView1.Items.Clear();
     Process[] proc = System.Diagnostics.Process.GetProcesses();
     List<Process> l = proc.ToList<Process>();
     SortedList<String, Process> sl = new SortedList<string, Process>();
     int it = 0;
     foreach (Process p in proc)
     {
         if (sl.ContainsKey(p.ProcessName))
             sl.Add(p.ProcessName + it.ToString(), p);
         else sl.Add(p.ProcessName, p);
         it++;
     }
     foreach (KeyValuePair<String, Process> pr in sl.ToList<KeyValuePair<String, Process>>())
     {
         ListViewItem lvi = new ListViewItem(pr.Value.ProcessName);
         lvi.SubItems.Add(pr.Value.BasePriority.ToString());
         lvi.SubItems.Add(pr.Value.Id.ToString());
         lvi.SubItems.Add(pr.Value.WorkingSet64.ToString());
         listView1.Items.Add(lvi);
     }
     toolStripStatusLabel1.Text = "Процессов: " + proc.Count<Process>().ToString();
     int count = 0;
     foreach (Process p in proc)
     {
         count += p.Threads.Count;
     }
     toolStripStatusLabel2.Text = "Потоков: " + count.ToString();
 }
        public ClassHierarchyTreeView(Type typeRoot)
        {
            // Make sure PresentationCore is loaded.
            UIElement dummy = new UIElement();

            // Put all the referenced assemblies in a List.
            List<Assembly> assemblies = new List<Assembly>();

            // Get all referenced assemblies.
            AssemblyName[] anames =
                    Assembly.GetExecutingAssembly().GetReferencedAssemblies();

            // Add to assemblies list.
            foreach (AssemblyName aname in anames)
                assemblies.Add(Assembly.Load(aname));

            // Store descendants of typeRoot in a sorted list.
            SortedList<string, Type> classes = new SortedList<string, Type>();
            classes.Add(typeRoot.Name, typeRoot);

            // Get all the types in the assembly.
            foreach (Assembly assembly in assemblies)
                foreach (Type typ in assembly.GetTypes())
                    if (typ.IsPublic && typ.IsSubclassOf(typeRoot))
                        classes.Add(typ.Name, typ);

            // Create root item.
            TypeTreeViewItem item = new TypeTreeViewItem(typeRoot);
            Items.Add(item);

            // Call recursive method.
            CreateLinkedItems(item, classes);
        }
 public static void Run()
 {
     string[] line = Console.ReadLine().Split(' ');
     long r = Convert.ToInt32(line[0]),
         g = Convert.ToInt32(line[1]),
         b = Convert.ToInt32(line[2]);
     SortedList<long, long> list = new SortedList<long, long>();
     list.Add(r, r);
     list.Add(g, g);
     list.Add(b, b);
     long t = list[2] / 2;
     long result = 0;
     if (list[0] + list[1] <= t)
     {
         result = (list[0] + list[1]) * 2;
     }
     else
     {
         result = t * 2;
         long last = list[2] - t * 2;
         if (list[0] - t >= 0) {
             list[0] -= t; // 0 - n
             list[2] = last; // 0 - 1
             
         }
         else {
             t -= list[0];
             list[0] = 0;
             list[1] -= t;
             list[2] = last;
             if (last == 1) result++;
         }
     }
 }
示例#10
0
        static void Main()
        {
            var books = new SortedList<string, string>();
              books.Add("Professional WPF Programming", "978–0–470–04180–2");
              books.Add("Professional ASP.NET MVC 3", "978–1–1180–7658–3");

              books["Beginning Visual C# 2010"] = "978–0–470-50226-6";
              books["Professional C# 4 and .NET 4"] = "978–0–470–50225–9";

              foreach (KeyValuePair<string, string> book in books)
              {
            Console.WriteLine("{0}, {1}", book.Key, book.Value);
              }

              foreach (string isbn in books.Values)
              {
            Console.WriteLine(isbn);
              }

              foreach (string title in books.Keys)
              {
            Console.WriteLine(title);
              }

              {
            string isbn;
            string title = "Professional C# 7.0";
            if (!books.TryGetValue(title, out isbn))
            {
              Console.WriteLine("{0} not found", title);
            }
              }
        }
        public void SortBehavior(string sortBy, bool sortAsc)
        {
            SortedList<string, User> list = new SortedList<string, User>();
            IList<User> userList = new List<User>();
            foreach (User user in User.FindAll())
            {
                if (sortBy == "Email")
                    list.Add(user.Email, user);
                else
                    list.Add(user.Name, user);
            }

            if (!sortAsc)
            {
                for (int x = list.Count - 1; x >= 0; x--)
                {
                    userList.Add(list[list.Keys[x]]);
                }
            }
            else
            {
                foreach (KeyValuePair<string, User> pair in list)
                {
                    userList.Add(pair.Value);
                }
            }

            PropertyBag["users"] = userList;
            PropertyBag["sortBy"] = sortBy;
            PropertyBag["sortAsc"] = sortAsc;
        }
示例#12
0
 private void lb_mvtypes_SelectedIndexChanged(object sender, EventArgs e)
 {
     String t = lb_mvtypes.SelectedItem.ToString();
     PythonReader pr = null;
     if (t == "common") { pr = StaticDataHolder.Header_Common; }
     else if (t == "operations") { pr = StaticDataHolder.Header_Operations; }
     else if (t == "triggers") { pr = StaticDataHolder.Header_Triggers; }
     lb_mvnames.Items.Clear();
     SortedList<String, byte> tempsort = new SortedList<string, byte>();
     for (int j = 0; j < pr.Items.Length; ++j)
     {
         if (tempsort.ContainsKey(pr.Items[j].Name))
         {
             for (int k = 0; k < 100; ++k)
             {
                 if (!tempsort.ContainsKey(pr.Items[j].Name + "(" + k.ToString() + ")"))
                 {
                     tempsort.Add(pr.Items[j].Name + "(" + k.ToString() + ")", 0);
                     k = 100;
                 }
             }
         }
         else { tempsort.Add(pr.Items[j].Name, 0); }
     }
     foreach (KeyValuePair<String, byte> kvp in tempsort) { lb_mvnames.Items.Add(kvp.Key); }
 }
示例#13
0
 private void Frm_Main_Load(object sender, EventArgs e)
 {
     //构造泛型排序列表
     SortedList<int, UserInfo> uses = new SortedList<int, UserInfo>();
     //为泛型排序列表添加元素
     uses.Add(2, new UserInfo(2, "User02", "02"));
     uses.Add(1, new UserInfo(3, "User03", "03"));
     uses.Add(3, new UserInfo(1, "User01", "01"));
    label1.Text="未按用户名排序前的查询结果:\n";
     foreach (var item in uses)//泛型排序列表按键自动进行排序
     {
         label1.Text+=string.Format("({0},{1})", item.Key, item.Value.UserName);
         label1.Text += "\n";
     }
     //按用户名对泛型排序列表进行排序
     var query = from item in uses
                 orderby item.Value.UserName
                 select item;
     label1.Text += "按用户名排序后的查询结果:\n";
     foreach (var item in query)//遍历查询结果
     {
         label1.Text+=string.Format("({0},{1})", item.Key, item.Value.UserName);
         label1.Text += "\n";
     }
 }
示例#14
0
 public static void CovertChatLogsToDialogue(ref SortedList<DateTime, List<ChatWord>> chatLogs, ref SortedList<DateTime, List<ChatDialogue>> chatDialogues, int timeSpan = 60)
 {
     DateTime currentDate = DateTime.Today;
     DateTime currentDateTime = DateTime.Today;
     foreach (var dialogue in chatLogs)
     {
         if (currentDateTime.Equals(DateTime.Today) || (dialogue.Value.First().timeStamp - currentDateTime).TotalMinutes > timeSpan)
         {
             chatDialogues.Add(dialogue.Key, new List<ChatDialogue>());
             currentDate = dialogue.Key;
         }
         foreach (var log in dialogue.Value)
         {
             if (currentDateTime.Equals(DateTime.Today) || (log.timeStamp - currentDateTime).TotalMinutes > timeSpan)
             {
                 if (!currentDate.Date.Equals(log.timeStamp.Date))
                 {
                     chatDialogues.Add(dialogue.Key, new List<ChatDialogue>());
                     currentDate = dialogue.Key;
                 }
                 chatDialogues[currentDate].Add(new ChatDialogue(log.timeStamp));
             }
             chatDialogues[currentDate].Last().chatWords.Add(log);
             currentDateTime = log.timeStamp;
         }
     }
 }
    private void LoadData()
    {
        // Create sorted list for drop down values
        var items = new SortedList<string, string>()
        {
            { GetString("smartsearch.indextype." + TreeNode.OBJECT_TYPE), TreeNode.OBJECT_TYPE },
            { GetString("smartsearch.indextype." + UserInfo.OBJECT_TYPE), UserInfo.OBJECT_TYPE },
            { GetString("smartsearch.indextype." + CustomTableInfo.OBJECT_TYPE_CUSTOMTABLE), CustomTableInfo.OBJECT_TYPE_CUSTOMTABLE },
            { GetString("smartsearch.indextype." + SearchHelper.CUSTOM_SEARCH_INDEX), SearchHelper.CUSTOM_SEARCH_INDEX },
            { GetString("smartsearch.indextype." + SearchHelper.DOCUMENTS_CRAWLER_INDEX), SearchHelper.DOCUMENTS_CRAWLER_INDEX },
            { GetString("smartsearch.indextype." + SearchHelper.GENERALINDEX), SearchHelper.GENERALINDEX },
        };

        // Allow forum only if forums module is available
        if ((ModuleManager.IsModuleLoaded(ModuleName.FORUMS)))
        {
            items.Add(GetString("smartsearch.indextype." + PredefinedObjectType.FORUM), PredefinedObjectType.FORUM);
        }

        // Allow on-line forms only if the module is available
        if ((ModuleManager.IsModuleLoaded(ModuleName.BIZFORM)))
        {
            items.Add(GetString("smartsearch.indextype." + SearchHelper.ONLINEFORMINDEX), SearchHelper.ONLINEFORMINDEX);
        }

        // Data bind DDL
        drpIndexType.DataSource = items;
        drpIndexType.DataValueField = "value";
        drpIndexType.DataTextField = "key";
        drpIndexType.DataBind();

        // Pre-select documents
        drpIndexType.SelectedValue = TreeNode.OBJECT_TYPE;
    }
 public IDictionary<int, XenUSB> GetUSB()
 {
     var list = new SortedList<int, XenUSB>();
     list.Add(1, new XenUSB() { State = USBState.Assigned, Name = "Mouse", Description = "Mousey", AssignedVM = "TestVM1" });
     list.Add(2, new XenUSB() { State = USBState.Unassigned, Name = "Camera", Description = "Flashy", AssignedVM = "TestVM2" });
     list.Add(3, new XenUSB() { State = USBState.Unavailable, Name = "Memory Stick", Description = "Sticky", AssignedVM = "TestVM3" });
     return list;
 }
示例#17
0
 static UnaryExpression()
 {
     _stringMap = new SortedList<TokenId, string>();
     _stringMap.Add(TokenId.Minus, @"-");
     _stringMap.Add(TokenId.Not, @"!");
     _stringMap.Add(TokenId.Plus, @"+");
     _stringMap.Add(TokenId.PlusPlus, @"++");
     _stringMap.Add(TokenId.MinusMinus, @"--");
 }
示例#18
0
 private void LoadModVars()
 {
     lb_mvtypes.Items.Clear();
     SortedList<String, byte> tempsort = new SortedList<string, byte>();
     tempsort.Add("common", 0);
     tempsort.Add("operations", 0);
     tempsort.Add("triggers", 0);
     foreach (KeyValuePair<String, byte> kvp in tempsort) { lb_mvtypes.Items.Add(kvp.Key); }
 }
        public void Save( string filename )
        {
            double[,] mesh = SlopeMap.GetInstance().GetSlopeMap();
            int width = mesh.GetUpperBound(0) + 1;
            int height = mesh.GetUpperBound(1) + 1;

            double maxslopetoexport = Config.GetInstance().SlopemapExportMaxSlope;

            Image image = new Image(width, height);
            //Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            //Graphics g = Graphics.FromImage(bitmap);
            // cache pencolors;
            List<MovementAreaConfig> movementareas = Config.GetInstance().movementareas;
            SortedList<double, Color> sortedcolorbymaxslope = new SortedList<double, Color>();
            foreach (MovementAreaConfig movementarea in movementareas)
            {
                if (movementarea.MaxSlope >= 0)
                {
                    sortedcolorbymaxslope.Add(movementarea.MaxSlope, movementarea.color);
                }
                else
                {
                    sortedcolorbymaxslope.Add(double.PositiveInfinity, movementarea.color);
                }
            }
            for (int area = 0; area < sortedcolorbymaxslope.Count; area++)
            {
                LogFile.GetInstance().WriteLine(sortedcolorbymaxslope.Keys[area] + " " + sortedcolorbymaxslope.Values[area].ToString());
            }
            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    Color colortouse = new Color(1, 1, 1);
                    for (int area = 0; area < sortedcolorbymaxslope.Count; area++)
                    {
                        if (mesh[i, j] < sortedcolorbymaxslope.Keys[area])
                        {
                            colortouse = sortedcolorbymaxslope.Values[area];
                            break;
                        }
                    }
                    int valuetowrite = (int)(mesh[i, j] * 255 / maxslopetoexport);
                    valuetowrite = Math.Max(0, valuetowrite);
                    valuetowrite = Math.Min(255, valuetowrite);
                    image.SetPixel(i, j, (byte)(colortouse.r * 255 * valuetowrite),
                        (byte)( colortouse.g * 255 * valuetowrite ),
                        (byte)( colortouse.b * 255 * valuetowrite ),
                        255
                    );
                }
            }
            image.Save(filename);
            exportheightmapfilename = filename;
            MainUI.GetInstance().uiwindow.InfoMessage("Slopemap exported");
        }
        public void AppendConfigSegment(StringBuilder bd)
        {
            SortedList<ushort, bool> watch_port = new SortedList<ushort, bool>();
            SortedList<string, IPAddress> watch_ip = new SortedList<string, IPAddress>();
            SortedList<string, IPPair> watch_scope = new SortedList<string, IPPair>();
            SortedList<string, bool> added_scope = new SortedList<string, bool>();
            foreach (VirtualSite site in virtualSites_)
            {
                foreach (IPPair p in site.IPPairs)
                {
                    if (!watch_port.ContainsKey(p.Port))
                        watch_port.Add(p.Port, true);
                    if (p.IPAddress != null && !watch_ip.ContainsKey(p.IPAddress.ToString()))
                        watch_ip.Add(p.IPAddress.ToString(), p.IPAddress);
                    if (!watch_scope.ContainsKey(p.ToString()))
                        watch_scope.Add(p.ToString(), p);
                }
            }
            foreach (ushort port in watch_port.Keys)
            {
                bd.AppendFormat(@"Listen {0}", port);
                bd.AppendLine();
            }
            if (watch_ip.Count == 0)
                watch_ip.Add("127.0.0.1", new IPAddress(new byte[] { 127, 0, 0, 1 }));

            foreach (KeyValuePair<string, IPPair> pair in watch_scope)
            {
                IPPair p = pair.Value;
                if (p.IPAddress == null)
                {
                    foreach (IPAddress add in watch_ip.Values)
                    {
                        if (!added_scope.ContainsKey(String.Format("{0}:{1}", add, p.Port)))
                        {
                            bd.AppendFormat(@"NameVirtualHost {0}:{1}", add, p.Port);
                            bd.AppendLine();
                            added_scope.Add(String.Format("{0}:{1}", add, p.Port), true);
                        }
                    }
                }
                else
                {
                    if (!added_scope.ContainsKey(String.Format("{0}:{1}", p.IPAddress, p.Port)))
                    {
                        bd.AppendFormat(@"NameVirtualHost {0}:{1}", p.IPAddress, p.Port);
                        bd.AppendLine();
                        String.Format("{0}:{1}", p.IPAddress, p.Port);
                    }
                }
            }
            foreach (VirtualSite site in virtualSites_)
            {
                site.AppendConfigSegment(bd, watch_ip.Values);
            }
        }
 public IDictionary<int, XenVM> GetVMs()
 {
     var list = new SortedList<int, XenVM>();
     list.Add(5, new XenVM() { Hidden = false, Image = (Bitmap)Properties.Resources.Blue_VM.Clone(), Name = "WinVista", Slot = 1, UUID = "1" });
     list.Add(2, new XenVM() { Hidden = false, Image = (Bitmap)Properties.Resources.Blue_VM.Clone(), Name = "Test Win 7", Slot = 2, UUID = "12" });
     list.Add(3, new XenVM() { Hidden = false, Image = (Bitmap)Properties.Resources.Blue_VM.Clone(), Name = "Windows 7", Slot = 3, UUID = "123" });
     list.Add(4, new XenVM() { Hidden = false, Image = (Bitmap)Properties.Resources.Blue_VM.Clone(), Name = "Windows XP with SP2", Slot = 4, UUID = "1234" });
     list.Add(1, new XenVM() { Hidden = false, Image = (Bitmap)Properties.Resources.Blue_VM.Clone(), Name = "A really long name to see what happens", Slot = 5, UUID = "12345" });
     return list;
 }
        /// <summary> Constructor for a new instance of the Source_Element class </summary>
        public Source_Element()
            : base("Source Institution", "source")
        {
            Repeatable = false;
            possible_select_items.Add("");

            clear_textbox_on_combobox_change = true;

            // Get the codes to display in the source
            codeToNameDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            if (UI_ApplicationCache_Gateway.Aggregations != null )
            {
                SortedList<string, string> tempItemList = new SortedList<string, string>();
                foreach (string thisType in UI_ApplicationCache_Gateway.Aggregations.All_Types)
                {
                    if (thisType.IndexOf("Institution") >= 0)
                    {
                        ReadOnlyCollection<Item_Aggregation_Related_Aggregations> matchingAggr = UI_ApplicationCache_Gateway.Aggregations.Aggregations_By_Type(thisType);
                        foreach (Item_Aggregation_Related_Aggregations thisAggr in matchingAggr)
                        {
                            if (thisAggr.Code.Length > 1)
                            {
                                if ((thisAggr.Code[0] == 'i') || (thisAggr.Code[0] == 'I'))
                                {
                                    if (!tempItemList.ContainsKey(thisAggr.Code.Substring(1)))
                                    {
                                        codeToNameDictionary[thisAggr.Code.Substring(1).ToUpper()] = thisAggr.Name;
                                        tempItemList.Add(thisAggr.Code.Substring(1), thisAggr.Code.Substring(1));
                                    }
                                }
                                else
                                {
                                    if (!tempItemList.ContainsKey(thisAggr.Code))
                                    {
                                        codeToNameDictionary[thisAggr.Code.ToUpper()] = thisAggr.Name;
                                        tempItemList.Add(thisAggr.Code, thisAggr.Code);
                                    }
                                }
                            }
                        }
                    }
                }

                IList<string> keys = tempItemList.Keys;
                foreach (string thisKey in keys)
                {
                    possible_select_items.Add(tempItemList[thisKey].ToUpper());
                    if (codeToNameDictionary.ContainsKey(thisKey))
                    {
                        Add_Code_Statement_Link(thisKey, codeToNameDictionary[thisKey]);
                    }
                }
            }
        }
示例#23
0
        public static SortedList<string, string> LoadTasks(string configPath, string cliCommandName)
        {
            var list = new SortedList<string, string>();

            try
            {
                string document = File.ReadAllText(configPath);
                JObject root = JObject.Parse(document);
                JToken scripts = root["scripts"];

                if (scripts != null)
                {
                    var children = scripts.Children<JProperty>();

                    foreach (var child in children)
                    {
                        if (!list.ContainsKey(child.Name))
                            list.Add(child.Name, $"{cliCommandName} run {child.Name}");
                    }
                }

                bool isNpm = (cliCommandName == Constants.NPM_CLI_COMMAND);
                string[] alwaysTasks = (isNpm
                    ? Constants.NPM_ALWAYS_TASKS
                    : Constants.YARN_ALWAYS_TASKS);

                // Only fill default tasks if any scripts are found
                foreach (var reserved in alwaysTasks)
                {
                    if (!list.ContainsKey(reserved))
                        list.Add(reserved, $"{cliCommandName} {reserved}");
                }

                AddMissingDefaultParents(list, cliCommandName, isNpm);

                if (isNpm)
                {
                    bool hasMatch = (from l in list
                                     from t in Constants.RESTART_SCRIPT_TASKS
                                     where l.Key == t
                                     select l).Any();

                    // Add "restart" node if RESTART_SCRIPT_TASKS contains anything in list
                    if (hasMatch)
                        list.Add("restart", $"{cliCommandName} restart");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
            }

            return list;
        }
示例#24
0
		private SortedList<int, int> SetUpTestList(IComparer<int> comparer)
		{
			var list = new SortedList<int, int>(comparer);
			list.Add(1, 1);
			list.Add(3, 3);
			list.Add(4, 4);
			list.Add(5, 5);
			list.Add(7, 7);

			return list;
		}
        /// <summary>
        /// Creates a payment request for this payment provider
        /// </summary>
        /// <param name="orderInfo"> </param>
        /// <returns>Payment request</returns>
        public PaymentRequest CreatePaymentRequest(OrderInfo orderInfo)
        {
            var paymentProvider = PaymentProvider.GetPaymentProvider(orderInfo.PaymentInfo.Id, orderInfo.StoreInfo.Alias);

            #region build urls

            var returnUrl = paymentProvider.SuccessUrl();

            var reportUrl = paymentProvider.ReportUrl();

            var testMode = paymentProvider.TestMode;  //currently we don't have a testmode for easy-ideal this var is unused

            #endregion

            #region config helper

            var merchantId = paymentProvider.GetSetting("merchantId");

            var merchantKey = paymentProvider.GetSetting("merchantKey");

            var merchantSecret = paymentProvider.GetSetting("merchantSecret");

            var url = paymentProvider.GetSetting("url");

            #endregion

            var args = new SortedList<string, string>();
            var ci = new CultureInfo("en-US");
            args.Add("Amount", orderInfo.ChargedAmount.ToString("G", ci));
            args.Add("Currency", "EUR");
            args.Add("Bank", orderInfo.PaymentInfo.MethodId);
            args.Add("Description", orderInfo.OrderNumber);
            args.Add("Return", reportUrl);

            var xmlRequest = GetXml(IDEAL_EXECUTE, args, merchantId, merchantKey, merchantSecret);

            XDocument xmlResponse = XDocument.Parse(PostXml(xmlRequest, url));

            var responseStatus = xmlResponse.Element("Response").Element("Status").FirstNode.ToString();

            var transactionId = xmlResponse.Element("Response").Element("Response").Element("TransactionID").FirstNode.ToString();
            var transactionCode = xmlResponse.Element("Response").Element("Response").Element("Code").FirstNode.ToString();
            var bankUrl = HttpUtility.HtmlDecode(xmlResponse.Element("Response").Element("Response").Element("BankURL").FirstNode.ToString());

            orderInfo.PaymentInfo.Url = bankUrl;

            PaymentProviderHelper.SetTransactionId(orderInfo, transactionId); //transactionCode hierin verwerken??

            //IO.Container.Resolve<IOrderUpdatingService>().AddCustomerFields(order, new Dictionary<string, string>({ "extraBilling", value }), CustomerDatatypes.Extra);
            orderInfo.AddCustomerFields(new Dictionary<string, string> { { "extraTransactionCode", transactionCode } }, Common.CustomerDatatypes.Extra);
            orderInfo.Save();

            return new PaymentRequest();
        }
        public void TestAdd()
        {
            var list = new SortedList<int>();
            list.Add(1);
            list.Add(3);
            list.Add(5);
            list.Add(4);
            list.Add(8);

            Assert.AreEqual("1,3,4,5,8", string.Join(",", list));
            Assert.AreEqual(5, list.Count);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies.AllKeys.Contains(".ASPXAUTH"))
        //if (!Request.Cookies.AllKeys.Contains(".ASPXAUTH"))
        {
            NotLoggedIn.Visible = false;

            if (!IsPostBack)
            {
                string strGetRolesJSON = @"{""Script"":""select * from Role"",""Args"":{""PageNumber"":1,""PageSize"":10000,""Limit"":10000,""SortBy"":"""",""direction"":""False"",""Caching"":-1}}";
                Centrify_API_Interface centGetRoles = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentQueryURL, strGetRolesJSON);
                var jssGetRoles = new JavaScriptSerializer();
                Dictionary<string, dynamic> centGetRoles_Dict = jssGetRoles.Deserialize<Dictionary<string, dynamic>>(centGetRoles.returnedResponse);

                SortedList<string, string> RolesList = new SortedList<string, string>();

                ArrayList centGetRoles_Roles = centGetRoles_Dict["Result"]["Results"];
                foreach (Dictionary<string, object> dRoles in centGetRoles_Roles)
                {
                    dynamic dRole = dRoles["Row"];
                    if (dRole["Name"] != null)
                    {
                        RolesList.Add(dRole["Name"], dRole["ID"]);
                    }
                    else
                    {
                        RolesList.Add(dRole["ID"], dRole["ID"]);
                    }
                }

                Roles_Dropdown.DataTextField = "Key";
                Roles_Dropdown.DataValueField = "Value";
                Roles_Dropdown.DataSource = RolesList;
                Roles_Dropdown.DataBind();
            }
        }
        else
        {
            Manage.Visible = false;           
        }

        ResultMessage.Visible = false;

        SetPassword.Visible = false;
        SetPassword_Label.Visible = false;
        Account_Enabled.Visible = false;
        Account_Enabled_Label.Visible = false;
        Account_Locked.Visible = false;
        Account_Locked_Label.Visible = false;
        ModifyUser_Button.Visible = false;


    }
        /// <summary>
        /// Constructor Metabolism: fills the list of available implementations of metabolism
        /// </summary>
        public Metabolism(string globalModelTimeStepUnit)
        {
            // Initialise the list of metabolism implementations
            Implementations = new SortedList<string, IMetabolismImplementation>();

            // Add the basic endotherm metabolism implementation to the list of implementations
            MetabolismEndotherm MetabolismEndothermImplementation = new MetabolismEndotherm(globalModelTimeStepUnit);
            Implementations.Add("basic endotherm", MetabolismEndothermImplementation);

            // Add the basic ectotherm metabolism implementation to the list of implementations
            MetabolismEctotherm MetabolismEctothermImplementation = new MetabolismEctotherm(globalModelTimeStepUnit);
            Implementations.Add("basic ectotherm", MetabolismEctothermImplementation);
        }
        /// <summary>
        /// Constructor for Eating: fills the list of available implementations of eating
        /// </summary>
        public Eating(double cellArea, string globalModelTimeStepUnit)
        {
            // Initialize the list of eating implementations
            Implementations = new SortedList<string, IEatingImplementation>();

            // Add the revised herbivory implementation to the list of implementations
            RevisedHerbivory RevisedHerbivoryImplementation = new RevisedHerbivory(cellArea, globalModelTimeStepUnit);
            Implementations.Add("revised herbivory", RevisedHerbivoryImplementation);

            //Add the revised predation implementation to the list of implementations
            RevisedPredation RevisedPredationImplementation = new RevisedPredation(cellArea, globalModelTimeStepUnit);
            Implementations.Add("revised predation", RevisedPredationImplementation);
        }
        public void Test_ExpenseSplitter_FiveParties()
        {
            Person p1 = new Person("John Debtor");
            Person p2 = new Person("Sally Debtor");
            Person p3 = new Person("Mark Creditor");
            Person p4 = new Person("Brock Debtor");
            Person p5 = new Person("Kane Creditor");

            //john owes the most and will pay mark, the biggest creditor
            p1.AddExpense(9m);
            p1.AddExpense(1m);

            //sally doesn't owe anything
            p2.AddExpense(10m);
            p2.AddExpense(10m);

            //mark is the biggest creditor
            p3.AddExpense(30m);

            //Brock owes the second-most and will pay Kane, the second creditor
            p4.AddExpense(10m);
            p4.AddExpense(5.5m);

            //Kane is the second biggest creditor
            p5.AddExpense(8m);
            p5.AddExpense(14.5m);
            p5.AddExpense(2m);

            SortedList<string, Person> persons = new SortedList<string, Person>();
            persons.Add(p1.PersonName, p1);
            persons.Add(p2.PersonName, p2);
            persons.Add(p3.PersonName, p3);
            persons.Add(p4.PersonName, p4);
            persons.Add(p5.PersonName, p5);

            ExpenseSplitter.SplitExpenses(persons);

            Assert.AreEqual(1, p1.PayoutObligations.Count);
            Assert.AreEqual("Mark Creditor", p1.PayoutObligations[0].Key);
            Assert.AreEqual(10m, p1.PayoutObligations[0].Value);

            Assert.AreEqual(0, p2.PayoutObligations.Count);

            Assert.AreEqual(0, p3.PayoutObligations.Count);

            Assert.AreEqual(1, p4.PayoutObligations.Count);
            Assert.AreEqual("Kane Creditor", p4.PayoutObligations[0].Key);
            Assert.AreEqual(4.5m, p4.PayoutObligations[0].Value);

            Assert.AreEqual(0, p5.PayoutObligations.Count);
        }
示例#31
0
        internal static void BuildResourceCap(SPList list, string field, SortedList resourceCaps)
        {
            var resultList = new SortedList();

            foreach (SPListItem listItem in list.Items)
            {
                var itemValue = string.Empty;

                try
                {
                    itemValue = listItem[field].ToString();
                }
                catch (Exception ex)
                {
                    TraceError("Exception Suppressed {0}", ex);
                }

                if (itemValue != string.Empty)
                {
                    if (resultList.Contains(itemValue))
                    {
                        var i = (int)resultList[itemValue];
                        i++;
                        resultList[itemValue] = i;
                    }
                    else
                    {
                        resultList.Add(itemValue, 1);
                    }
                }
            }

            foreach (DictionaryEntry de in resultList)
            {
                resourceCaps?.Add(string.Format("{0}\n{1}", field, de.Key), de.Value);
            }
        }
示例#32
0
        public void TestEnum(IDictionary <String, String> idic)
        {
            SortedList <String, String> _dic;
            IComparer <String>          comparer;

            String[] keys = new String[idic.Count];
            idic.Keys.CopyTo(keys, 0);
            String[] values = new String[idic.Count];
            idic.Values.CopyTo(values, 0);
            IComparer <String>[] predefinedComparers = new IComparer <String>[] {
                StringComparer.CurrentCulture,
                StringComparer.CurrentCultureIgnoreCase,
                StringComparer.OrdinalIgnoreCase,
                StringComparer.Ordinal
            };

            foreach (IComparer <String> predefinedComparer in predefinedComparers)
            {
                _dic = new SortedList <String, String>(idic, predefinedComparer);
                m_test.Eval(_dic.Comparer == predefinedComparer, String.Format("Err_4568aijueud! Comparer differ expected: {0} actual: {1}", predefinedComparer, _dic.Comparer));
                m_test.Eval(_dic.Count == idic.Count, String.Format("Err_23497sg! Count different: {0}", _dic.Count));
                m_test.Eval(_dic.Keys.Count == idic.Count, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count));
                m_test.Eval(_dic.Values.Count == idic.Count, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count));
                for (int i = 0; i < idic.Keys.Count; i++)
                {
                    m_test.Eval(_dic.ContainsKey(keys[i]), String.Format("Err_234afs! key not found: {0}", keys[i]));
                    m_test.Eval(_dic.ContainsValue(values[i]), String.Format("Err_3497sg! value not found: {0}", values[i]));
                }
            }


            //Current culture
            CultureInfo.DefaultThreadCurrentCulture = s_english;
            comparer = StringComparer.CurrentCulture;
            _dic     = new SortedList <String, String>(idic, comparer);
            m_test.Eval(_dic.Comparer == comparer, String.Format("Err_58484aheued! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
            _dic.Add(strAE, value);
            m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_235rdag! Wrong result returned: {0}", _dic.ContainsKey(strUC4)));

            //bug #11263 in NDPWhidbey
            CultureInfo.DefaultThreadCurrentCulture = s_german;
            comparer = StringComparer.CurrentCulture;
            _dic     = new SortedList <String, String>(idic, comparer);
            m_test.Eval(_dic.Comparer == comparer, String.Format("Err_5468ahiede! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
            _dic.Add(strAE, value);
            // same result in Desktop
            m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_23r7ag! Wrong result returned: {0}", _dic.ContainsKey(strUC4)));

            //CurrentCultureIgnoreCase
            CultureInfo.DefaultThreadCurrentCulture = s_english;
            comparer = StringComparer.CurrentCultureIgnoreCase;
            _dic     = new SortedList <String, String>(idic, comparer);
            m_test.Eval(_dic.Comparer == comparer, String.Format("Err_4488ajede! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
            _dic.Add(straA, value);
            m_test.Eval(_dic.ContainsKey(strAa), String.Format("Err_237g! Wrong result returned: {0}", _dic.ContainsKey(strAa)));

            CultureInfo.DefaultThreadCurrentCulture = s_danish;
            comparer = StringComparer.CurrentCultureIgnoreCase;
            _dic     = new SortedList <String, String>(idic, comparer);
            m_test.Eval(_dic.Comparer == comparer, String.Format("Err_6884ahnjed! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
            _dic.Add(straA, value);
            m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0723f! Wrong result returned: {0}", _dic.ContainsKey(strAa)));

            //OrdinalIgnoreCase
            CultureInfo.DefaultThreadCurrentCulture = s_english;
            comparer = StringComparer.OrdinalIgnoreCase;
            _dic     = new SortedList <String, String>(idic, comparer);
            m_test.Eval(_dic.Comparer == comparer, String.Format("Err_95877ahiez! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
            _dic.Add(strI, value);
            m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234qf! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI)));

            CultureInfo.DefaultThreadCurrentCulture = s_turkish;
            comparer = StringComparer.OrdinalIgnoreCase;
            _dic     = new SortedList <String, String>(idic, comparer);
            m_test.Eval(_dic.Comparer == comparer, String.Format("Err_50548haied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
            _dic.Add(strI, value);
            m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234ra7g! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI)));

            //Ordinal - not that many meaningful test
            CultureInfo.DefaultThreadCurrentCulture = s_english;
            comparer = StringComparer.Ordinal;
            _dic     = new SortedList <String, String>(idic, comparer);
            m_test.Eval(_dic.Comparer == comparer, String.Format("Err_1407hizbd! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
            _dic.Add(strBB, value);
            m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_1244sd! Wrong result returned: {0}", _dic.ContainsKey(strbb)));

            CultureInfo.DefaultThreadCurrentCulture = s_danish;
            comparer = StringComparer.Ordinal;
            _dic     = new SortedList <String, String>(idic, comparer);
            m_test.Eval(_dic.Comparer == comparer, String.Format("Err_5088aied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer));
            _dic.Add(strBB, value);
            m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_235aeg! Wrong result returned: {0}", _dic.ContainsKey(strbb)));
        }
示例#33
0
文件: Astar.cs 项目: tayyl/TSP
        public Tuple <int, string> TSP(ICollection <City> VisitedCities, ICollection <Edge> CurrentEdges, ICollection <Edge> FinalEdges)
        {
            int  bestDistance = 0;
            City startingCity = cities.First();
            SortedList <double, List <City> > paths = new SortedList <double, List <City> >(new DuplicateKeyComparer <double>());
            List <City> currentBestDistancePath;

            paths.Add(0, new List <City>()
            {
                startingCity
            });
            do
            {
                currentBestDistancePath = paths.First().Value;
                paths.RemoveAt(0);

                foreach (City city in cities)
                {
                    if (!currentBestDistancePath.Contains(city))
                    {
                        if (neighbourMatrix[currentBestDistancePath.Last().Number, city.Number] != 0)
                        {
                            double F = pathDistance(currentBestDistancePath) + heuristic(startingCity, city);
                            paths.Add(F, new List <City>(currentBestDistancePath)
                            {
                                city
                            });
                            if (CurrentEdges.Count < cities.Count * 30)
                            {
                                App.Current.Dispatcher.BeginInvoke((Action) delegate
                                {
                                    CurrentEdges.Add(new Edge(currentBestDistancePath.Last(), city, neighbourMatrix[currentBestDistancePath.Last().Number, city.Number]));
                                });
                                System.Threading.Thread.Sleep(delay);
                            }
                        }
                    }
                }
                if (paths.First().Value.Count == cities.Count)
                {
                    double      F   = pathDistance(paths.First().Value) + heuristic(paths.First().Value.Last(), startingCity);
                    List <City> tmp = paths.First().Value;

                    paths.RemoveAt(0);
                    paths.Add(F, new List <City>(tmp)
                    {
                        startingCity
                    });
                }
            } while (paths.First().Value.Count != cities.Count + 1);
            currentBestDistancePath = paths.First().Value;
            App.Current.Dispatcher.BeginInvoke((Action) delegate {
                for (int i = 0; i < currentBestDistancePath.Count - 1; i++)
                {
                    FinalEdges.Add(new Edge(currentBestDistancePath[i], currentBestDistancePath[i + 1], neighbourMatrix[currentBestDistancePath[i].Number, currentBestDistancePath[i + 1].Number]));
                    VisitedCities.Add(currentBestDistancePath[i]);
                }
            });
            System.Threading.Thread.Sleep(delay);
            currentBestDistancePath.RemoveAt(cities.Count);
            bestDistance = pathDistance(currentBestDistancePath);
            return(new Tuple <int, string>(bestDistance, CreatePath(FinalEdges)));
        }
        public string GetRtf(Range r)
        {
            this.tb = r.tb;
            var styles         = new Dictionary <StyleIndex, object>();
            var sb             = new StringBuilder();
            var tempSB         = new StringBuilder();
            var currentStyleId = StyleIndex.None;

            r.Normalize();
            int currentLine = r.Start.iLine;

            styles[currentStyleId] = null;
            colourTable.Clear();
            //
            var lineNumberColor = GetColourTableNumber(r.tb.LineNumberColour);

            if (IncludeLineNumbers)
            {
                tempSB.AppendFormat(@"{{\cf{1} {0}}}\tab", currentLine + 1, lineNumberColor);
            }
            //
            foreach (Place p in r)
            {
                Char c = r.tb[p.iLine][p.iChar];
                if (c.style != currentStyleId)
                {
                    Flush(sb, tempSB, currentStyleId);
                    currentStyleId         = c.style;
                    styles[currentStyleId] = null;
                }

                if (p.iLine != currentLine)
                {
                    for (int i = currentLine; i < p.iLine; i++)
                    {
                        tempSB.AppendLine(@"\line");
                        if (IncludeLineNumbers)
                        {
                            tempSB.AppendFormat(@"{{\cf{1} {0}}}\tab", i + 2, lineNumberColor);
                        }
                    }
                    currentLine = p.iLine;
                }
                switch (c.c)
                {
                case '\\':
                    tempSB.Append(@"\\");
                    break;

                case '{':
                    tempSB.Append(@"\{");
                    break;

                case '}':
                    tempSB.Append(@"\}");
                    break;

                default:
                    var ch   = c.c;
                    var code = (int)ch;
                    if (code < 128)
                    {
                        tempSB.Append(c.c);
                    }
                    else
                    {
                        tempSB.AppendFormat(@"{{\u{0}}}", code);
                    }
                    break;
                }
            }
            Flush(sb, tempSB, currentStyleId);

            //build color table
            var list = new SortedList <int, Color>();

            foreach (var pair in colourTable)
            {
                list.Add(pair.Value, pair.Key);
            }

            tempSB.Length = 0;
            tempSB.AppendFormat(@"{{\colortbl;");

            foreach (var pair in list)
            {
                tempSB.Append(GetColourAsString(pair.Value) + ";");
            }
            tempSB.AppendLine("}");

            //
            if (UseOriginalFont)
            {
                sb.Insert(0, string.Format(@"{{\fonttbl{{\f0\fmodern {0};}}}}{{\fs{1} ",
                                           tb.Font.Name, (int)(2 * tb.Font.SizeInPoints), tb.CharHeight));
                sb.AppendLine(@"}");
            }

            sb.Insert(0, tempSB.ToString());

            sb.Insert(0, @"{\rtf1\ud\deff0");
            sb.AppendLine(@"}");

            return(sb.ToString());
        }
示例#35
0
    void OnEnable()
    {
        // Cache reference to transform to increase performance
        _transform = transform;

        // Calculate the actual spawn
        _distanceToSpawn = range * distanceSpawn;

        // Populate the material list based on probabilty of materials
        if (_materialList.Count == 0)
        {
            if (materialVeryRare.Length > 0)
            {
                _materialList.Add(5, "VeryRare");
            }
            if (materialRare.Length > 0)
            {
                _materialList.Add(5 + 15, "Rare");
            }
            if (materialCommon.Length > 0)
            {
                _materialList.Add(5 + 15 + 30, "Common");
            }
            if (materialVeryCommon.Length != 0)
            {
                _materialList.Add(5 + 15 + 30 + 50, "VeryCommon");
            }
            else
            {
                Debug.LogError("Asteroid Field must have at least one Material in the 'Material Very Common' Array.");
            }
        }


        // Check if there are any asteroid objects that was spawned prior to this script being disabled
        // If there are asteroids in the list, activate the gameObject again.
        for (int i = 0; i < _asteroidsTransforms.Count; i++)
        {
            _asteroidsTransforms[i].gameObject.SetActive(true);
        }

        // Spawn new asteroids in the entire sphere (not just at spawn range, hence the "false" parameter)
        SpawnAsteroids(false);

        // Use transform as origin (center) of asteroid field. If null, use this transform.
        if (asteroidFieldOriginTransform == null)
        {
            asteroidFieldOriginTransform = transform;
        }

        // Set the parameters for each asteroid for fading/scaling
        for (int i = 0; i < _asteroidsTransforms.Count; i++)
        {
            SU_Asteroid _a = _asteroidsTransforms[i].GetComponent <SU_Asteroid>();
            if (_a != null)
            {
                // When spawning asteroids, set the parameters for the shader based on parameters of this asteroid field
                _a.fadeAsteroids = fadeAsteroids;
                _a.fadeAsteroidsFalloffExponent = 1f; // fadeAsteroidsFalloffExponent;
                _a.distanceFade    = distanceFade;
                _a.visibilityRange = range;
            }
        }
    }
示例#36
0
        /// <summary>
        /// This is raised by _world once per frame (this is raised, then it requests forces for bodies)
        /// </summary>
        private void World_Updating(object sender, WorldUpdatingArgs e)
        {
            try
            {
                if (_hasSetVelocities && _setVelocityArgs != null)
                {
                    _hasSetVelocities = false;
                    _setVelocityArgs  = null;
                }

                Vector3D shipPosition = _ship.PositionWorld.ToVector();

                _ship.WorldUpdating(e.ElapsedTime);

                #region Minerals

                foreach (Mineral mineral in _map.GetMinerals())
                {
                    mineral.WorldUpdating();
                }

                #endregion

                #region Space Stations

                SpaceStation currentlyOverStation = null;

                foreach (SpaceStation station in _spaceStations)
                {
                    station.WorldUpdating();

                    // See if the ship is over the station
                    Vector3D stationPosition = station.PositionWorld.ToVector();
                    stationPosition.Z = 0;

                    if ((stationPosition - shipPosition).LengthSquared < station.Radius * station.Radius)
                    {
                        currentlyOverStation = station;
                    }
                }

                // Store the station that the ship is over
                if (currentlyOverStation == null)
                {
                    statusMessage.Content = "";
                }
                else
                {
                    statusMessage.Content = "Press space to enter station";

                    //TODO:  Play a sound if this is the first time they entered the station's range
                }

                _currentlyOverStation = currentlyOverStation;

                #endregion

                // Camera
                UpdateCameraPosition();

                #region Asteroid Gravity

                //TODO:  It's too expensive for every small item to examine every other object each frame, and it's choppy when the calculations are
                // intermitent (should do threads).  Set up a vector field for the minerals and bots to be attracted to
                //
                // On second thought, I don't think this will work.  It would be more efficient for the map to return objects in range, but that requires
                // the map to store things different (I think for 2D it's a quad tree, and 3D is an oct tree?)

                // Only doing asteroids - the ship does gravity calculation against the asteroids in it's apply force event
                if (_hasGravity)
                {
                    _asteroidGravityForces.Clear();

                    if (StaticRandom.NextDouble() < .05d)               // I don't want to do this every frame
                    {
                        // Init my forces list
                        for (int cntr = 0; cntr < _asteroids.Count; cntr++)
                        {
                            _asteroidGravityForces.Add(_asteroids[cntr].PhysicsBody, new Vector3D());
                        }

                        // Apply Gravity
                        for (int outerCntr = 0; outerCntr < _asteroids.Count - 1; outerCntr++)
                        {
                            Point3D centerMass1 = _asteroids[outerCntr].PositionWorld;

                            for (int innerCntr = outerCntr + 1; innerCntr < _asteroids.Count; innerCntr++)
                            {
                                #region Apply Gravity

                                Point3D centerMass2 = _asteroids[innerCntr].PositionWorld;

                                Vector3D gravityLink = centerMass1 - centerMass2;

                                double force = GRAVITATIONALCONSTANT * (_asteroids[outerCntr].Mass * _asteroids[innerCntr].Mass) / gravityLink.LengthSquared;

                                gravityLink.Normalize();
                                gravityLink *= force;

                                _asteroidGravityForces[_asteroids[innerCntr].PhysicsBody] += gravityLink;
                                _asteroidGravityForces[_asteroids[outerCntr].PhysicsBody] -= gravityLink;

                                #endregion
                            }
                        }

                        // I also need to attract to the ship, because it's attracted to the asteroids
                        // I can't because the ship is attracted every frame, so the forces are unbalanced
                        Point3D shipPos  = _ship.PositionWorld;
                        double  shipMass = _ship.PhysicsBody.Mass;

                        for (int cntr = 0; cntr < _asteroids.Count; cntr++)
                        {
                            #region Apply Gravity

                            Vector3D gravityLink = shipPos - _asteroids[cntr].PositionWorld;

                            double force = GRAVITATIONALCONSTANT * (_asteroids[cntr].Mass * shipMass) / gravityLink.LengthSquared;

                            gravityLink.Normalize();
                            gravityLink *= force;

                            _asteroidGravityForces[_asteroids[cntr].PhysicsBody] -= gravityLink;

                            #endregion
                        }
                    }
                }

                #endregion

                _map.WorldUpdating();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        static void Main()
        {
            // Join Unicode
            Console.OutputEncoding = Encoding.Unicode;

            // set size of console
            Console.SetWindowSize(80, 60);
            Console.SetBufferSize(80, 60);

            #region Hashtable
#if false
            Hashtable ht = new Hashtable();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    // на випадок повторень ключа
                    try
                    {
                        keys.Add(GetFullName());
                        ht.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, (string)ht[i]);
                }
            }
#endif
            #endregion

            #region ListDictionary
#if false
            ListDictionary ld = new ListDictionary();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    // на випадок повторень ключа
                    try
                    {
                        keys.Add(GetFullName());
                        ld.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, (string)ld[i]);
                }
            }
#endif
            #endregion

            #region HybridDictionary
#if false
            HybridDictionary hd = new HybridDictionary();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    // на випадок повторень ключа
                    try
                    {
                        keys.Add(GetFullName());
                        hd.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, (string)hd[i]);
                }
            }
#endif
            #endregion

            #region SortedList
#if false
            SortedList <string, string> sl = new SortedList <string, string>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                try
                {
                    sl.Add(GetFullName(), GetProduct());
                }
                catch (ArgumentException)
                {
                    i--;
                }
            }

            // виведення
            foreach (var i in sl)
            {
                GetRes(i.Key, i.Value);
            }
#endif
            #endregion

            #region OrderedDictionary
#if false
            OrderedDictionary od = new OrderedDictionary();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    try
                    {
                        keys.Add(GetFullName());
                        od.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, (string)od[i]);
                }
            }
#endif
            #endregion

            #region StringDictionary
#if false
            StringDictionary sd = new StringDictionary();
            {
                List <string> keys = new List <string>();
                for (int i = 0; i < rnd.Next(10, 28); i++)
                {
                    try
                    {
                        keys.Add(GetFullName());
                        sd.Add(keys.Last(), GetProduct());
                    }
                    catch (ArgumentException)
                    {
                        keys.RemoveAt(i--);
                    }
                }

                // виведення
                foreach (var i in keys)
                {
                    GetRes(i, sd[i]);
                }
            }
#endif
            #endregion

            #region NameValueCollection
#if false
            NameValueCollection nvc = new NameValueCollection();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                nvc.Add(GetFullName(), GetProduct());
            }

            // виведення
            foreach (var i in nvc.AllKeys)
            {
                GetRes(i, nvc[i]);
            }
#endif
            #endregion

            #region List
#if false
            List <Customer> list = new List <Customer>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                list.Add(GetCustomer());
            }

            // виведення
            foreach (var i in list)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
            #endregion

            #region Dictionary
#if false
            Dictionary <string, string> d = new Dictionary <string, string>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                try
                {
                    d.Add(GetFullName(), GetProduct());
                }
                catch (ArgumentException)
                {
                    i--;
                }
            }

            // виведення
            foreach (var i in d)
            {
                GetRes(i.Key, i.Value);
            }
#endif
            #endregion

            #region SortedDictionary
#if false
            SortedDictionary <string, string> sd = new SortedDictionary <string, string>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                try
                {
                    sd.Add(GetFullName(), GetProduct());
                }
                catch (ArgumentException)
                {
                    i--;
                }
            }

            // виведення
            foreach (var i in sd)
            {
                GetRes(i.Key, i.Value);
            }
#endif
            #endregion

            #region LinkedList
#if false
            LinkedList <Customer> ll = new LinkedList <Customer>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                ll.AddLast(GetCustomer());
            }

            // виведення
            foreach (var i in ll)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
            #endregion

            #region ArrayList
#if false
            ArrayList al = new ArrayList();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                al.Add(GetCustomer());
            }

            // виведення
            foreach (var i in al)
            {
                GetRes(((Customer)i).FullName, ((Customer)i).CategoryProdact);
            }
#endif
            #endregion

            #region Queue
#if false
            Queue <Customer> q = new Queue <Customer>();
            List <Customer>  l = new List <Customer>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                l.Add(GetCustomer());
                q.Enqueue(l.Last());
            }

            // виведення
            foreach (var i in l)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
            Console.WriteLine();
#if false
            foreach (var i in q)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
#if false    // можна отримати доступ і після проходження всього перебору
            {
                Customer i = q.Dequeue();
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
#endif
#if true
            while (q.Count > 0)
            {
                Customer i = q.Dequeue();
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
#endif
            #endregion

            #region Stack
#if true
            Stack <Customer> s = new Stack <Customer>();
            List <Customer>  l = new List <Customer>();
            for (int i = 0; i < rnd.Next(10, 28); i++)
            {
                l.Add(GetCustomer());
                s.Push(l.Last());
            }

            // виведення
            foreach (var i in l)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
            Console.WriteLine();
#if false
            foreach (var i in s)
            {
                GetRes(i.FullName, i.CategoryProdact);
            }
#if true    // можна отримати доступ і після проходження всього перебору
            {
                Customer i = s.Pop();
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
#endif
#if true
            while (s.Count > 0)
            {
                Customer i = s.Pop();
                GetRes(i.FullName, i.CategoryProdact);
            }
#endif
#endif
            #endregion

            // repeat
            DoExitOrRepeat();
        }
示例#38
0
        //修改
        private void but_edit_Click(object sender, EventArgs e)
        {
            if (dgv_01.SelectedRows.Count == 0)
            {
                MessageBox.Show(PromptMessageXmlHelper.Instance.GetPromptMessage("choicechange", EnumPromptMessage.warning, new string[] { "修改", "存储点" }), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            int        selectedIndex = dgv_01.Rows.IndexOf(dgv_01.SelectedRows[0]);
            SortedList slindata      = new SortedList();//存取和传递dgv某一行数据

            try
            {
                slindata.Add("id", dgv_01.SelectedRows[0].Cells["id"].Value);
                slindata.Add("s_name", dgv_01.SelectedRows[0].Cells["s_name"].Value);
                slindata.Add("s_barcode", dgv_01.SelectedRows[0].Cells["s_barcode"].Value);
                slindata.Add("s_type", dgv_01.SelectedRows[0].Cells["s_type"].Value);
                slindata.Add("s_room", dgv_01.SelectedRows[0].Cells["s_room"].Value);
                slindata.Add("s_customer", sl_customer.GetKey(sl_customer.IndexOfValue(dgv_01.SelectedRows[0].Cells["s_customer"].Value)));
                slindata.Add("s_uselocation", sl_uselocation.GetKey(sl_uselocation.IndexOfValue(dgv_01.SelectedRows[0].Cells["s_uselocation"].Value)));
                Costcenter(sl_customer.GetKey(sl_customer.IndexOfValue(dgv_01.SelectedRows[0].Cells["s_customer"].Value)).ToString());
                slindata.Add("s_costcenter", sl_costcenter2.GetKey(sl_costcenter2.IndexOfValue(dgv_01.SelectedRows[0].Cells["s_costcenter"].Value)));
                slindata.Add("s_basket", dgv_01.SelectedRows[0].Cells["s_basket"].Value);
                slindata.Add("s_remarks", dgv_01.SelectedRows[0].Cells["s_remarks"].Value);
                slindata.Add("s_cabinet", dgv_01.SelectedRows[0].Cells["s_cabinet"].Value);
                HCSCM_storage_manage_new hcsm = new HCSCM_storage_manage_new(slindata);
                hcsm.ShowDialog();
                if (tb_sel.Text == string.Empty)
                {
                    if (rb_base.Checked == false && rb_ins.Checked == false)
                    {
                        if (this.cb_customer.Text == "----所有----")
                        {
                            Loaddata(null);
                        }
                        else
                        {
                            Loaddata(sl_customer.GetKey(sl_customer.IndexOfValue(this.cb_customer.Text)).ToString());
                        }
                    }
                    else
                    {
                        if (rb_ins.Checked == true)
                        {
                            rb_CheckedChanged(null, null);
                        }
                        if (rb_base.Checked == true)
                        {
                            rb_base_CheckedChanged(null, null);
                        }
                    }
                }
                else
                {
                    GetData();
                }
                if (dgv_01.Rows.Count > selectedIndex)
                {
                    dgv_01.CurrentRow = dgv_01.Rows[selectedIndex];
                }
            }
            catch
            {
                MessageBox.Show(PromptMessageXmlHelper.Instance.GetPromptMessage("choicechange", EnumPromptMessage.warning, new string[] { "修改", "存储点" }), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
示例#39
0
        private void but_eliminar_materia_Click(object sender, EventArgs e)
        {
            StringBuilder errorMessages = new StringBuilder();
            Materia       mat           = new Materia();

            if (tex_nombre.Text.Length == 0)
            {
                this.inicializarDatos();
                MessageBox.Show("Debe ingresar un Nombre",
                                "Eliminar Materia",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
            }
            else
            {
                try
                {
                    mat.v_nombre    = tex_nombre.Text;
                    mat.v_usuario_m = this.usuario;

                    if ((mat.ConsultarMateria(mat)).v_nombre.Length != 0)
                    {
                        tex_nombre.Text      = mat.v_nombre;
                        tex_clave.Text       = mat.v_clave;
                        tex_descripcion.Text = mat.v_descripcion;

                        SLfacultad.Add(mat.v_Dfacultad, mat.v_Dfacultad);
                        com_facultad.DataSource = SLfacultad.GetValueList();
                        com_facultad.Show();
                        com_facultad.Enabled = false;
                        SLfacultad.Clear();

                        if ((MessageBox.Show("¿Desea eliminar la Materia con Nombre: " + mat.v_nombre + " ?", "Eliminar Materia", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes))
                        {
                            try
                            {
                                if (mat.EliminarMateria(mat) != 0)
                                {
                                    this.inicializarDatos();
                                    com_facultad.DataSource = null;
                                    com_facultad.Show();
                                    MessageBox.Show("Materia eliminada correctamente",
                                                    "Eliminar Materia",
                                                    MessageBoxButtons.OK,
                                                    MessageBoxIcon.Information);
                                }
                            }
                            catch (SqlException ex)
                            {
                                for (int i = 0; i < ex.Errors.Count; i++)
                                {
                                    errorMessages.Append("Index #" + i + "\n" +
                                                         "Message: " + ex.Errors[i].Message + "\n" +
                                                         "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                                                         "Source: " + ex.Errors[i].Source + "\n" +
                                                         "Procedure: " + ex.Errors[i].Procedure + "\n");
                                }
                                Console.WriteLine(errorMessages.ToString());
                                this.inicializarDatos();
                                MessageBox.Show(ex.Errors[0].Message.ToString(),
                                                "Eliminar Materia",
                                                MessageBoxButtons.OK,
                                                MessageBoxIcon.Warning);
                            }
                        }
                    }
                }
                catch (SqlException ex)
                {
                    for (int i = 0; i < ex.Errors.Count; i++)
                    {
                        errorMessages.Append("Index #" + i + "\n" +
                                             "Message: " + ex.Errors[i].Message + "\n" +
                                             "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                                             "Source: " + ex.Errors[i].Source + "\n" +
                                             "Procedure: " + ex.Errors[i].Procedure + "\n");
                    }
                    Console.WriteLine(errorMessages.ToString());
                    this.inicializarDatos();
                    MessageBox.Show(ex.Errors[0].Message.ToString(),
                                    "Eliminar Materia",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                }
            }
        }
示例#40
0
        static void Main(string[] args)
        {
            //https://msdn.microsoft.com/es-es/library/ybcx56wz(v=vs.110).aspx
            // Lista de strings.
            List <string> sieteMares = new List <string>();

            // Agrego items de a uno
            sieteMares.Add("Golfo Pérsico");
            sieteMares.Add("Negro");
            sieteMares.Add("Caspio");
            sieteMares.Add("Rojo");
            sieteMares.Add("Mediterráneo");
            sieteMares.Add("Adriático");
            sieteMares.Add("de Arabia");
            // Itero la lista y muestro los 7 mares
            Console.WriteLine("Los 7 mares:");
            for (int i = 0; i < sieteMares.Count; i++)
            {
                Console.Write(sieteMares[i] + ", ");
            }
            // Freno y luego limpio la pantalla
            Console.ReadKey();
            Console.Clear();

            // Ordeno la Lista y vuelvo a mostrarla
            Console.WriteLine("Orden Ascendente");
            sieteMares.Sort();
            // Itero la lista y muestro los mares
            foreach (var mar in sieteMares)
            {
                Console.Write(mar + ", ");
            }

            Console.WriteLine("");
            Console.WriteLine("Orden Descendente");
            // Ordeno la Lista inversa y vuelvo a mostrarla
            sieteMares.Sort(Program.OrdenarDescendente);
            // Itero la lista y muestro los mares
            foreach (var mar in sieteMares)
            {
                Console.Write(mar + ", ");
            }
            // Freno y luego limpio la pantalla
            Console.ReadKey();
            Console.Clear();

            // Creo una lista, utilizando el inicializador de Colecciones.
            List <string> oceanos = new List <string> {
                "Ártico", "Antártico", "Pacífico", "Atlántico", "Índico"
            };

            // Itero la lista y muestro los oceanos
            foreach (var oceano in oceanos)
            {
                Console.Write(oceano);
                Console.Write((oceanos.IndexOf(oceano) == oceanos.Count - 1) ? "." : ", "); // (condición) ? true : false
            }
            // Shorthand IF https://msdn.microsoft.com/es-ar/library/ty67wk28.aspx
            // Freno y luego limpio la pantalla
            Console.ReadKey();
            Console.Clear();

            // Quito el primer elemento que coincida
            oceanos.Remove("Antártico");
            // Itero la lista y muestro los oceanos que quedaron
            foreach (var oceano in oceanos)
            {
                Console.WriteLine("{1} {0}", oceano, oceanos.IndexOf(oceano) + 1);
            }
            // Freno y luego limpio la pantalla
            Console.ReadKey();
            Console.Clear();

            // Quito el elemento en una posición especifica
            oceanos.RemoveAt(2); //Atlántico
            // Itero la lista y muestro los oceanos que quedaron
            foreach (var oceano in oceanos)
            {
                Console.Write("{0}, ", oceano);
            }
            // Freno y luego limpio la pantalla
            Console.ReadKey();
            Console.Clear();

            //---------------OTRAS COLECCIONES GENERICAS---------------------------
            // Diccionario
            Dictionary <string, string> miDiccionario = new Dictionary <string, string>();

            miDiccionario.Add("1ra", "Boca Juniors");
            miDiccionario.Add("2da", "Boca Unidos");
            miDiccionario.Add("3ra", "Boca Río Gallegos");
            miDiccionario.Add("4ta", "Huracán San Rafael");
            miDiccionario.Add("5ta", "Leandro N. Alem");

            // Itero y muestro el Diccionario
            foreach (KeyValuePair <string, string> entrada in miDiccionario)
            {
                Console.WriteLine("{0}. {1}", entrada.Key, entrada.Value);
            }
            // Pregundo si contiene cierta Clave
            if (miDiccionario.ContainsKey("2da"))
            {
                Console.WriteLine("El Key '2da' es {0}", miDiccionario["2da"]);
            }

            // Quito un ítem
            miDiccionario.Remove("3ra");
            // Itero y muestro las claves
            foreach (string entrada in miDiccionario.Keys)
            {
                Console.WriteLine("Claves: {0}", entrada);
            }
            // Itero y muestro los valores
            foreach (string entrada in miDiccionario.Values)
            {
                Console.WriteLine("Valor: {0}", entrada);
            }

            // Freno y luego limpio la pantalla
            Console.ReadKey();
            Console.Clear();

            // Cola
            Console.WriteLine("COLA");
            Queue <Cliente> clientesCola = new Queue <Cliente>();

            clientesCola.Enqueue(new Cliente("Jorge"));
            clientesCola.Enqueue(new Cliente("Alberto"));
            clientesCola.Enqueue(new Cliente("Luis"));
            clientesCola.Enqueue(new Cliente("María"));

            Random r = new Random();

            while (clientesCola.Count > 0)
            {
                Console.WriteLine("Atender a: {0}. Quedan {1} cliente/s en espera.", clientesCola.Dequeue(), clientesCola.Count);
                // Demoro la iteración entre 1 y 3 segundos
                System.Threading.Thread.Sleep(r.Next(1000, 3000));
            }

            Console.WriteLine("");

            // Pila
            Console.WriteLine("PILA");
            Stack <Cliente> clientesPila = new Stack <Cliente>();

            clientesPila.Push(new Cliente("Jorge"));
            clientesPila.Push(new Cliente("Alberto"));
            clientesPila.Push(new Cliente("Luis"));
            clientesPila.Push(new Cliente("María"));

            while (clientesPila.Count > 0)
            {
                Console.WriteLine("Atender a: {0}. Quedan {1} cliente/s en espera.", clientesPila.Pop(), clientesPila.Count);
                // Demoro la iteración entre 1 y 3 segundos
                System.Threading.Thread.Sleep(r.Next(1000, 3000));
            }

            // Freno y luego limpio la pantalla
            Console.ReadKey();
            Console.Clear();

            SortedList <int, Cliente> listaOrdenada = new SortedList <int, Cliente>();

            listaOrdenada.Add(3, new Cliente("Miguel"));
            listaOrdenada.Add(2, new Cliente("Alejandra"));
            listaOrdenada.Add(8, new Cliente("Agostina"));
            listaOrdenada.Add(1, new Cliente("Valentino"));

            foreach (KeyValuePair <int, Cliente> entrada in listaOrdenada)
            {
                Console.WriteLine("{0}. {1}", entrada.Key, entrada.Value);
            }
            // Freno y luego limpio la pantalla
            Console.ReadKey();
            Console.Clear();

            Console.WriteLine("PILA GENERICA");
            System.Collections.Stack clientesPilaGenerica = new System.Collections.Stack();
            clientesPilaGenerica.Push(new Cliente("Jorge"));
            clientesPilaGenerica.Push(new Cliente("Alberto"));
            clientesPilaGenerica.Push(new Cliente("Luis"));
            clientesPilaGenerica.Push(new Cliente("María"));

            while (clientesPilaGenerica.Count > 0)
            {
                // Debo castear el contenido de la pila, ya que es del tipo Object
                Cliente c = (Cliente)clientesPilaGenerica.Pop();
                Console.WriteLine("Atender a: {0}. Quedan {1} cliente/s en espera.", c, clientesPilaGenerica.Count);
            }

            // Freno y luego limpio la pantalla
            Console.ReadKey();
            Console.Clear();
        }
示例#41
0
        //删除
        private void but_remove_Click(object sender, EventArgs e)
        {
            if (dgv_01.SelectedRows.Count == 0)
            {
                MessageBox.Show(PromptMessageXmlHelper.Instance.GetPromptMessage("choicechange", EnumPromptMessage.warning, new string[] { "删除", "存储点" }), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            try
            {
                int           selectedIndex   = dgv_01.Rows.IndexOf(dgv_01.SelectedRows[0]);
                CnasRemotCall reCnasRemotCall = new CnasRemotCall();
                SortedList    sttemp01        = new SortedList();
                sttemp01.Add(1, CnasBaseData.SystemID);
                #region 判断存储点是否被实体包占用

                DataTable getdt = reCnasRemotCall.RemotInterface.SelectData("HCS-set-sec004", sttemp01);//137
                if (getdt != null)
                {
                    int ii = getdt.Rows.Count;
                    if (ii <= 0)
                    {
                        return;
                    }
                    for (int i = 0; i < ii; i++)
                    {
                        if (dgv_01.SelectedRows[0].Cells["id"].Value.ToString() == getdt.Rows[i]["storage_id_02"].ToString().Trim() || dgv_01.SelectedRows[0].Cells["id"].Value.ToString() == getdt.Rows[i]["storage_id"].ToString().Trim())
                        {
                            MessageBox.Show(PromptMessageXmlHelper.Instance.GetPromptMessage("relation", EnumPromptMessage.warning, new string[] { "存储点", "实体包", "实体包" }), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                    }
                }
                #endregion
                if (MessageBox.Show(PromptMessageXmlHelper.Instance.GetPromptMessage("choicedelete", EnumPromptMessage.warning, new string[] { dgv_01.SelectedRows[0].Cells["s_name"].Value.ToString(), "存储点" }), ConfigurationManager.AppSettings["SystemName"] + "--删除存储点", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }

                SortedList sltmp   = new SortedList();
                SortedList sltmp01 = new SortedList();
                sltmp01.Add(1, dgv_01.SelectedRows[0].Cells["id"].Value);
                sltmp.Add(1, sltmp01);
                CnasRemotCall reCnasremotCall = new CnasRemotCall();
                string        gg     = reCnasremotCall.RemotInterface.CheckUPData(1, "HCS-storage-del001", sltmp, null);
                int           recint = reCnasremotCall.RemotInterface.UPData(1, "HCS-storage-del001", sltmp, null);
                if (recint > -1)
                {
                    MessageBox.Show(PromptMessageXmlHelper.Instance.GetPromptMessage("deletesuccessful", EnumPromptMessage.warning, new string[] { "存储点" }), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dgv_01.Rows.RemoveAt(selectedIndex);//移除选择的dgv的数据
                    if (dgv_01.Rows.Count > 0)
                    {
                        if (selectedIndex == 0)//删除后判断是否为0
                        {
                            dgv_01.CurrentRow = dgv_01.Rows[0];
                        }
                        else
                        {
                            dgv_01.CurrentRow = dgv_01.Rows[selectedIndex - 1];
                        }
                    }
                }
            }



            catch
            {
                MessageBox.Show(PromptMessageXmlHelper.Instance.GetPromptMessage("choicechange", EnumPromptMessage.warning, new string[] { "删除", "存储点" }), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
示例#42
0
 void AddTimeout(TimeSpan time, Timeout timeout)
 {
     timeouts.Add((DateTime.UtcNow + time).Ticks, timeout);
 }
示例#43
0
        public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
        {
            Hashtable    nsLocallyDeclared = new Hashtable();
            SortedList   nsListToRender    = new SortedList(new NamespaceSortOrder());
            SortedList   attrListToRender  = new SortedList(new AttributeSortOrder());
            UTF8Encoding utf8 = new UTF8Encoding(false);

            byte[] rgbData;

            XmlAttributeCollection attrList = this.Attributes;

            if (attrList != null)
            {
                foreach (XmlAttribute attr in attrList)
                {
                    if (((CanonicalXmlAttribute)attr).IsInNodeSet || Utils.IsNamespaceNode(attr) || Utils.IsXmlNamespaceNode(attr))
                    {
                        if (Utils.IsNamespaceNode(attr))
                        {
                            anc.TrackNamespaceNode(attr, nsListToRender, nsLocallyDeclared);
                        }
                        else if (Utils.IsXmlNamespaceNode(attr))
                        {
                            anc.TrackXmlNamespaceNode(attr, nsListToRender, attrListToRender, nsLocallyDeclared);
                        }
                        else if (IsInNodeSet)
                        {
                            attrListToRender.Add(attr, null);
                        }
                    }
                }
            }

            if (!Utils.IsCommittedNamespace(this, this.Prefix, this.NamespaceURI))
            {
                string       name     = ((this.Prefix.Length > 0) ? "xmlns" + ":" + this.Prefix : "xmlns");
                XmlAttribute nsattrib = (XmlAttribute)this.OwnerDocument.CreateAttribute(name);
                nsattrib.Value = this.NamespaceURI;
                anc.TrackNamespaceNode(nsattrib, nsListToRender, nsLocallyDeclared);
            }

            if (IsInNodeSet)
            {
                anc.GetNamespacesToRender(this, attrListToRender, nsListToRender, nsLocallyDeclared);
                rgbData = utf8.GetBytes("<" + this.Name);
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
                foreach (object attr in nsListToRender.GetKeyList())
                {
                    (attr as CanonicalXmlAttribute).WriteHash(hash, docPos, anc);
                }
                foreach (object attr in attrListToRender.GetKeyList())
                {
                    (attr as CanonicalXmlAttribute).WriteHash(hash, docPos, anc);
                }
                rgbData = utf8.GetBytes(">");
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            }

            anc.EnterElementContext();
            anc.LoadUnrenderedNamespaces(nsLocallyDeclared);
            anc.LoadRenderedNamespaces(nsListToRender);

            XmlNodeList childNodes = this.ChildNodes;

            foreach (XmlNode childNode in childNodes)
            {
                CanonicalizationDispatcher.WriteHash(childNode, hash, docPos, anc);
            }

            anc.ExitElementContext();

            if (IsInNodeSet)
            {
                rgbData = utf8.GetBytes("</" + this.Name + ">");
                hash.TransformBlock(rgbData, 0, rgbData.Length, rgbData, 0);
            }
        }
示例#44
0
    public bool ReadUnicodeData()
    {
        FileStream   dataFile    = null;
        StreamReader inputStream = null;
        string       strCurLine;

        string[] strLineFields;
        CharInfo curCharInfo;

        try
        {
            dataFile =
                new FileStream(DATA_FILENAME, FileMode.Open, FileAccess.Read);
            inputStream = new StreamReader(dataFile, Encoding.ASCII);
        }
        catch (Exception exc)
        {
            Console.WriteLine("TestCase blocked",
                              UNABLE_TO_OPEN_FILE + " '" + DATA_FILENAME + "'.", exc);
            if (inputStream != null)
            {
                inputStream.Close();
            }
            if (dataFile != null)
            {
                dataFile.Close();
            }
            return(false);
        }
        try
        {
            m_uCharsRead = 0;
            while ((strCurLine = inputStream.ReadLine()) != null)
            {
                strLineFields = strCurLine.Split(FIELD_SEP);
                curCharInfo   = new CharInfo();
                if (strLineFields[0].Length > 4)
                {
                    continue;
                }
                else
                {
                    curCharInfo.chChar =
                        Convert.ToChar(Convert.ToInt32(strLineFields[0], 16));
                }
                curCharInfo.eCategory =
                    TranslateUnicodeCategory(strLineFields[2]);
                if (strLineFields[8].Length > 0)
                {
                    curCharInfo.dNumericValue =
                        ConvertToDouble(strLineFields[8]);
                }
                m_CharData.Add(curCharInfo.chChar, curCharInfo);
                m_uCharsRead++;
            }
        }
        catch (Exception exc)
        {
            Console.WriteLine("Testcase blocked",
                              BAD_DATA_FILE + " '" + DATA_FILENAME +
                              "', Line " + (m_uCharsRead + 1) + ".",
                              exc);
            if (inputStream != null)
            {
                inputStream.Close();
            }
            if (dataFile != null)
            {
                dataFile.Close();
            }
            return(false);
        }
        inputStream.Close();
        dataFile.Close();
        return(true);
    }
示例#45
0
        // only works for PW !!!
        public eList[] Load(string elFile, ref ColorProgressBar.ColorProgressBar cpb2)
        {
            eList[] Li = new eList[0];
            addonIndex = new Dictionary <int, int>();

            Listcnts  = null;
            ListOsets = null;
            Listver   = -1;
            SStat     = new int[5] {
                0, 0, 0, 0, 0
            };

            string fileStream = Path.GetDirectoryName(elFile) + "\\elements.list.count";

            if (File.Exists(fileStream))
            {
                Listcnts  = new SortedList();
                ListOsets = new SortedList();
                using (StreamReader reader = new StreamReader(fileStream))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        string[] val = line.Split('=');
                        if (val[0] == "ver")
                        {
                            Listver = Convert.ToInt16(val[1]);
                        }
                        else if (val[0] == "offset")
                        {
                            ListOsets.Add(val[1], val[2]);
                        }
                        else
                        {
                            Listcnts.Add(val[0], val[1]);
                        }
                    }
                }
            }

            // open the element file
            FileStream   fs = File.OpenRead(elFile);
            BinaryReader br = new BinaryReader(fs);

            Version = br.ReadInt16();
            if (Listver > -1)
            {
                Version = Listver;
            }
            Signature = br.ReadInt16();

            // check if a corresponding configuration file exists
            string[] configFiles = Directory.GetFiles(Application.StartupPath + "\\configs", "PW_*_v" + Version + ".cfg");
            if (configFiles.Length > 0)
            {
                // configure an eList array with the configuration file
                ConfigFile   = configFiles[0];
                Li           = loadConfiguration(ConfigFile);
                cpb2.Maximum = Li.Length;
                cpb2.Value   = 0;

                // read the element file
                for (int l = 0; l < Li.Length; l++)
                {
                    SStat[0] = l;
                    Application.DoEvents();

                    // read offset
                    if (Li[l].listOffset != null)
                    {
                        // offset > 0
                        if (Li[l].listOffset.Length > 0)
                        {
                            Li[l].listOffset = br.ReadBytes(Li[l].listOffset.Length);
                        }
                    }
                    // autodetect offset (for list 20 & 100)
                    else
                    {
                        if (l == 0)
                        {
                            byte[] t      = br.ReadBytes(4);
                            byte[] len    = br.ReadBytes(4);
                            byte[] buffer = br.ReadBytes(BitConverter.ToInt32(len, 0));
                            Li[l].listOffset = new byte[t.Length + len.Length + buffer.Length];
                            Array.Copy(t, 0, Li[l].listOffset, 0, t.Length);
                            Array.Copy(len, 0, Li[l].listOffset, 4, len.Length);
                            Array.Copy(buffer, 0, Li[l].listOffset, 8, buffer.Length);
                        }
                        if (l == 20)
                        {
                            byte[] tag    = br.ReadBytes(4);
                            byte[] len    = br.ReadBytes(4);
                            byte[] buffer = br.ReadBytes(BitConverter.ToInt32(len, 0));
                            byte[] t      = br.ReadBytes(4);
                            Li[l].listOffset = new byte[tag.Length + len.Length + buffer.Length + t.Length];
                            Array.Copy(tag, 0, Li[l].listOffset, 0, tag.Length);
                            Array.Copy(len, 0, Li[l].listOffset, 4, len.Length);
                            Array.Copy(buffer, 0, Li[l].listOffset, 8, buffer.Length);
                            Array.Copy(t, 0, Li[l].listOffset, 8 + buffer.Length, t.Length);
                        }
                        int NPC_WAR_TOWERBUILD_SERVICE_index = 100;
                        if (Version >= 191)
                        {
                            NPC_WAR_TOWERBUILD_SERVICE_index = 99;
                        }
                        if (l == NPC_WAR_TOWERBUILD_SERVICE_index)
                        {
                            byte[] tag    = br.ReadBytes(4);
                            byte[] len    = br.ReadBytes(4);
                            byte[] buffer = br.ReadBytes(BitConverter.ToInt32(len, 0));
                            Li[l].listOffset = new byte[tag.Length + len.Length + buffer.Length];
                            Array.Copy(tag, 0, Li[l].listOffset, 0, tag.Length);
                            Array.Copy(len, 0, Li[l].listOffset, 4, len.Length);
                            Array.Copy(buffer, 0, Li[l].listOffset, 8, buffer.Length);
                        }
                    }

                    // read conversation list
                    if (l == ConversationListIndex)
                    {
                        if (Version >= 191)
                        {
                            long sourcePosition = br.BaseStream.Position;
                            int  listLength     = 0;
                            bool run            = true;
                            while (run)
                            {
                                run = false;
                                try
                                {
                                    br.ReadByte();
                                    listLength++;
                                    run = true;
                                }
                                catch
                                { }
                            }
                            br.BaseStream.Position = sourcePosition;
                            Li[l].elementTypes[0]  = "byte:" + listLength;
                        }
                        else
                        {
                            // Auto detect only works for Perfect World elements.data !!!
                            if (Li[l].elementTypes[0].Contains("AUTO"))
                            {
                                byte[] pattern        = (Encoding.GetEncoding("GBK")).GetBytes("facedata\\");
                                long   sourcePosition = br.BaseStream.Position;
                                int    listLength     = -72 - pattern.Length;
                                bool   run            = true;
                                while (run)
                                {
                                    run = false;
                                    for (int i = 0; i < pattern.Length; i++)
                                    {
                                        listLength++;
                                        if (br.ReadByte() != pattern[i])
                                        {
                                            run = true;
                                            break;
                                        }
                                    }
                                }
                                br.BaseStream.Position = sourcePosition;
                                Li[l].elementTypes[0]  = "byte:" + listLength;
                            }
                        }

                        Li[l].elementValues       = new object[1][];
                        Li[l].elementValues[0]    = new object[Li[l].elementTypes.Length];
                        Li[l].elementValues[0][0] = readValue(br, Li[l].elementTypes[0]);
                    }
                    // read lists
                    else
                    {
                        if (Version >= 191)
                        {
                            Li[l].listType = br.ReadInt32();
                        }
                        if (Listver > -1 && Listcnts[l.ToString()] != null)
                        {
                            int num = Convert.ToInt32(Listcnts[l.ToString()]);
                            Li[l].elementValues = new object[num][];
                            br.ReadBytes(4);
                        }
                        else
                        {
                            Li[l].elementValues = new object[br.ReadInt32()][];
                        }

                        SStat[1] = Li[l].elementValues.Length;

                        if (Version >= 191)
                        {
                            Li[l].elementSize = br.ReadInt32();
                        }

                        // go through all elements of a list
                        for (int e = 0; e < Li[l].elementValues.Length; e++)
                        {
                            Li[l].elementValues[e] = new object[Li[l].elementTypes.Length];

                            // go through all fields of an element
                            int idtest = -1;
                            for (int f = 0; f < Li[l].elementValues[e].Length; f++)
                            {
                                Li[l].elementValues[e][f] = readValue(br, Li[l].elementTypes[f]);
                                if (Li[l].elementFields[f] == "ID")
                                {
                                    idtest   = Int32.Parse(Li[l].GetValue(e, f));
                                    SStat[2] = idtest;
                                    if (l == 0)
                                    {
                                        if (!addonIndex.ContainsKey(idtest))
                                        {
                                            addonIndex.Add(idtest, e);
                                        }
                                        else
                                        {
                                            MessageBox.Show("Error: Found duplicate Addon id:" + idtest);
                                            addonIndex[idtest] = e;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    cpb2.Value++;
                }
            }
            else
            {
                MessageBox.Show("No corressponding configuration file found!\nVersion: " + Version + "\nPattern: " + "configs\\PW_*_v" + Version + ".cfg");
            }

            br.Close();
            fs.Close();

            return(Li);
        }
示例#46
0
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbtnSave_Click(object sender, EventArgs e)
        {
            //this.axFramerControl.Dispose();
            //this.axFramerControl.Close();

            //模版名称为空则提示
            if (string.IsNullOrEmpty(rtxtTem_name.Text))
            {
                MessageBox.Show(PromptMessageXmlHelper.Instance.GetPromptMessage("customtemplatename", EnumPromptMessage.warning), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            //模版上传辅助类
            TemFileUploadHelper temFileUploadHelper = new TemFileUploadHelper();


            //新建报表
            if (custom_tem_id != 0 && id == 0)
            {
                if (dtTemRowDate.Rows.Count > 0)
                {
                    string file = temFileUploadHelper.GetTemFilePath(@"Template\", dtTemRowDate.Rows[0]["guidname"].ToString());


                    //检测是否存在目录,不存在则先创建
                    if (!Directory.Exists(temFileUploadHelper.GetTemFilePath(@"Report\")))
                    {
                        Directory.CreateDirectory(temFileUploadHelper.GetTemFilePath(@"Report\"));
                    }

                    string newGuid    = Guid.NewGuid().ToString();
                    string reportFile = temFileUploadHelper.GetTemFilePath(@"Report\") + newGuid + Path.GetExtension(file);


                    //生成一个临时的文件
                    string tem_fileName = dtTemRowDate.Rows[0]["guidname"].ToString().Replace(Path.GetExtension(file), "");

                    string tem_file = temFileUploadHelper.GetTemFilePath(@"Template\", dtTemRowDate.Rows[0]["guidname"].ToString()).Replace(tem_fileName, tem_fileName + "_tem");


                    this.axFramerControl.Save();
                    this.axFramerControl.Save(tem_file, true, "", "");
                    this.axFramerControl.Close();


                    //把数据存放到临时文件
                    File.Copy(file, reportFile);

                    FileStream fileStream = File.Open(reportFile, FileMode.Open);
                    temFileUploadHelper.UploadTemFile(@"Report\", newGuid + Path.GetExtension(file), fileStream);
                    fileStream.Dispose();
                    fileStream.Close();

                    SortedList addlist   = new SortedList();
                    SortedList addlist01 = new SortedList();
                    addlist.Add(1, custom_tem_id);
                    addlist.Add(2, rtxtTem_name.Text);
                    addlist.Add(3, newGuid + Path.GetExtension(file));
                    addlist.Add(4, DateTime.Now);
                    addlist01.Add(1, addlist);

                    string ss             = reCnasRemotCall.RemotInterface.CheckUPData(1, "HCS-custom-template-report-add001", addlist01, null);
                    int    addDataService = reCnasRemotCall.RemotInterface.UPData(1, "HCS-custom-template-report-add001", addlist01, null);

                    if (addDataService > -1)
                    {
                        MessageBox.Show(PromptMessageXmlHelper.Instance.GetPromptMessage("succeed", EnumPromptMessage.warning), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Close();
                        HCSRM_custom_template_report01.DataBindReport();
                    }
                }
            }

            //修改报表
            if (custom_tem_id == 0 && id != 0)
            {
                string file = temFileUploadHelper.GetTemFilePath(@"Report\", dtRowDate.Rows[0]["file_name"].ToString());

                //获取打开文档的句柄(文件类型)
                //Microsoft.Office.Interop.Excel.Workbook workbook = (Microsoft.Office.Interop.Excel.Workbook)this.axFramerControl.ActiveDocument;
                //workbook.Saved = true;
                //workbook.Save();

                //Microsoft.Office.Interop.Word.Words words = (Microsoft.Office.Interop.Word.Words)this.axFramerControl.ActiveDocument;

                string tem_fileName = dtRowDate.Rows[0]["file_name"].ToString().Replace(Path.GetExtension(file), "");

                string tem_file = temFileUploadHelper.GetTemFilePath(@"Report\", dtRowDate.Rows[0]["file_name"].ToString()).Replace(tem_fileName, tem_fileName + "_tem");


                this.axFramerControl.Save();
                this.axFramerControl.Save(tem_file, true, "", "");
                this.axFramerControl.Close();

                //return;

                //如果是修改,但是未返回数据,则直接关闭窗体
                if (dtRowDate.Rows.Count <= 0)
                {
                    this.Close();
                }
                SortedList uplist   = new SortedList();
                SortedList uplist01 = new SortedList();
                uplist.Add(1, rtxtTem_name.Text);
                uplist.Add(2, id);
                uplist01.Add(1, uplist);

                //string ss = reCnasRemotCall.RemotInterface.CheckUPData(1, "HCS-custom-template-report-up001", uplist01, null);
                int UpDataService = reCnasRemotCall.RemotInterface.UPData(1, "HCS-custom-template-report-up001", uplist01, null);

                //先删除服务器文件
                temFileUploadHelper.DeleteTemFile(@"Report\", dtRowDate.Rows[0]["file_name"].ToString());

                FileStream fileStream = File.Open(file, FileMode.Open);
                temFileUploadHelper.UploadTemFile(@"Report\", dtRowDate.Rows[0]["file_name"].ToString(), fileStream);
                fileStream.Dispose();
                fileStream.Close();

                if (UpDataService > -1)
                {
                    MessageBox.Show(PromptMessageXmlHelper.Instance.GetPromptMessage("editsucceed", EnumPromptMessage.warning), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();

                    HCSRM_custom_template_report01.DataBindReport();
                }
            }
        }
示例#47
0
        static bool WriteAnnotations(IndexerState state, SymbolFile file, StreamWriter sw)
        {
            SortedList <string, SourceProvider> providers = new SortedList <string, SourceProvider>();
            int itemCount = 1;

            foreach (SourceFile sf in file.SourceFiles)
            {
                if (!sf.IsResolved || sf.NoSourceAvailable)
                {
                    continue;
                }

                SourceReference sr       = sf.SourceReference;
                SourceProvider  provider = sr.SourceProvider;

                if (providers.ContainsKey(provider.Id))
                {
                    continue;
                }

                providers.Add(provider.Id, provider);

                if (provider.SourceEntryVariableCount > itemCount)
                {
                    itemCount = provider.SourceEntryVariableCount;
                }
            }

            if (providers.Count == 0)
            {
                return(false);
            }

            sw.WriteLine("SRCSRV: ini ------------------------------------------------");
            sw.WriteLine("VERSION=1");
            sw.Write("VERCTRL=SharpSvn.PdbAnnotate");
            foreach (SourceProvider sp in providers.Values)
            {
                if (!string.IsNullOrEmpty(sp.Name))
                {
                    sw.Write('+');
                    sw.Write(sp.Name);
                }
            }
            sw.WriteLine();
            sw.WriteLine("SRCSRV: variables ------------------------------------------");
            sw.WriteLine("DATETIME=" + DateTime.Now.ToUniversalTime().ToString("u"));
            sw.WriteLine("SRCSRVTRG=%fnvar%(%VAR2%__TRG)");
            sw.WriteLine("SRCSRVCMD=%fnvar%(%VAR2%__CMD)");
            //sw.WriteLine("SRCSRVENV=PATH=%PATH%\\bSystemDrive=%SystemDrive%\\bSystemRoot=%SystemRoot%\\bProgramFiles=%ProgramFiles%\\bProgramData=%ProgramData%\\b%fnvar%(%VAR2%__ENV)");
            foreach (SourceProvider sp in providers.Values)
            {
                sp.WriteEnvironment(sw);
            }
            sw.WriteLine("SRCSRV: source files ---------------------------------------");

            // Note: the sourcefile block must be written in the order they are found by the PdbReader
            //	otherwise SrcTool skips all sourcefiles which don't exist locally and are out of order
            foreach (SourceFile sf in file.SourceFiles)
            {
                if (!sf.IsResolved || sf.NoSourceAvailable)
                {
                    continue;
                }

                sw.Write(sf.FullName);
                sw.Write('*');

                SourceReference sr       = sf.SourceReference;
                SourceProvider  provider = sr.SourceProvider;

                sw.Write(provider.Id);
                sw.Write('*');

                string[] strings = sr.GetSourceEntries();

                if (strings != null)
                {
                    for (int i = 0; i < itemCount; i++)
                    {
                        if (i < strings.Length)
                        {
                            sw.Write(strings[i]);
                        }

                        sw.Write('*');
                    }
                }
                else
                {
                    for (int i = 0; i < itemCount; i++)
                    {
                        sw.Write('*');
                    }
                }

                // Note: We defined the variables upto itemCount+2 (filename, type, itemcount),
                // All variables above this index are reserved for future extensions

                sw.WriteLine();
            }

            sw.WriteLine("SRCSRV: end ------------------------------------------------");

            return(true);
        }
示例#48
0
 private void pridejSoupravu(Souprava s)
 {
     seznamSouprav.Add(s.id, s);
     pocetSouprav[s.pismeno]++;
 }
示例#49
0
        protected DataTable BindData()
        {
            SortedList sParams = new SortedList();
            DataTable  dtPELs  = new DataTable();

            int iSessionID = 0;

            int.TryParse(Session["CampaignID"].ToString(), out iSessionID);
            sParams.Add("@CampaignID", iSessionID);

            dtPELs = Classes.cUtilities.LoadDataTable("uspGetPELsToApprove", sParams, "LARPortal", Session["UserName"].ToString(), "PELApprovalList.Page_PreRender");

            string sSelectedChar      = "";
            string sSelectedEventDate = "";
            string sSelectedEventName = "";
            string sSelectedPELStatus = "";

            foreach (DataRow dRow in dtPELs.Rows)
            {
                if (dRow["RoleAlignment"].ToString() != "PC")
                {
                    dRow["CharacterAKA"] = dRow["RoleAlignment"].ToString();
                }
            }

            // While creating the filter am also saving the selected values so we can go back and have the drop down list use them.
            string sRowFilter = "(1 = 1)";      // This is so it's easier to build the filter string. Now can always say 'and ....'

            if (ddlCharacterName.SelectedIndex > 0)
            {
                sRowFilter   += " and (CharacterAKA = '" + ddlCharacterName.SelectedValue.Replace("'", "''") + "')";
                sSelectedChar = ddlCharacterName.SelectedValue;
            }

            if (ddlEventDate.SelectedIndex > 0)
            {
                sRowFilter        += " and (EventStartDate = '" + ddlEventDate.SelectedValue + "')";
                sSelectedEventDate = ddlEventDate.SelectedValue;
            }

            if (ddlEventName.SelectedIndex > 0)
            {
                sRowFilter        += " and (EventName = '" + ddlEventName.SelectedValue.Replace("'", "''") + "')";
                sSelectedEventName = ddlEventName.SelectedValue;
            }

            if (ddlStatus.SelectedIndex > 0)
            {
                sRowFilter        += " and (PELStatus = '" + ddlStatus.SelectedValue.Replace("'", "''") + "')";
                sSelectedPELStatus = ddlStatus.SelectedValue;
            }

            DataView dvPELs = new DataView(dtPELs, sRowFilter, "PELStatus desc, DateSubmitted", DataViewRowState.CurrentRows);

            gvPELList.DataSource = dvPELs;
            gvPELList.DataBind();

            DataView  view             = new DataView(dtPELs, sRowFilter, "EventName", DataViewRowState.CurrentRows);
            DataTable dtDistinctEvents = view.ToTable(true, "EventName");

            ddlEventName.DataSource     = dtDistinctEvents;
            ddlEventName.DataTextField  = "EventName";
            ddlEventName.DataValueField = "EventName";
            ddlEventName.DataBind();
            ddlEventName.Items.Insert(0, new ListItem("No Filter", ""));
            ddlEventName.SelectedIndex = -1;
            if (sSelectedEventName != "")
            {
                foreach (ListItem li in ddlEventName.Items)
                {
                    if (li.Value == sSelectedEventName)
                    {
                        li.Selected = true;
                    }
                    else
                    {
                        li.Selected = false;
                    }
                }
            }
            if (ddlEventName.SelectedIndex == -1)     // Didn't find what was selected.
            {
                ddlEventName.SelectedIndex = 0;
            }

            view = new DataView(dtPELs, sRowFilter, "CharacterAKA", DataViewRowState.CurrentRows);
            DataTable dtDistinctChars = view.ToTable(true, "CharacterAKA");

            ddlCharacterName.DataSource     = dtDistinctChars;
            ddlCharacterName.DataTextField  = "CharacterAKA";
            ddlCharacterName.DataValueField = "CharacterAKA";
            ddlCharacterName.DataBind();
            ddlCharacterName.Items.Insert(0, new ListItem("No Filter", ""));
            ddlCharacterName.SelectedIndex = -1;
            if (sSelectedChar != "")
            {
                foreach (ListItem li in ddlCharacterName.Items)
                {
                    if (li.Value == sSelectedChar)
                    {
                        li.Selected = true;
                    }
                    else
                    {
                        li.Selected = false;
                    }
                }
            }
            if (ddlCharacterName.SelectedIndex == -1)     // Didn't find what was selected.
            {
                ddlCharacterName.SelectedIndex = 0;
            }

            view = new DataView(dtPELs, sRowFilter, "EventStartDate", DataViewRowState.CurrentRows);
            DataTable dtDistinctDates = view.ToTable(true, "EventStartDateStr");

            ddlEventDate.DataSource     = dtDistinctDates;
            ddlEventDate.DataTextField  = "EventStartDateStr";
            ddlEventDate.DataValueField = "EventStartDateStr";
            ddlEventDate.DataBind();
            ddlEventDate.Items.Insert(0, new ListItem("No Filter", ""));
            ddlEventDate.SelectedIndex = -1;
            if (sSelectedEventDate != "")
            {
                foreach (ListItem li in ddlEventDate.Items)
                {
                    if (li.Value == sSelectedEventDate)
                    {
                        li.Selected = true;
                    }
                    else
                    {
                        li.Selected = false;
                    }
                }
            }
            if (ddlEventDate.SelectedIndex == -1)     // Didn't find what was selected.
            {
                ddlEventDate.SelectedIndex = 0;
            }

            view = new DataView(dtPELs, sRowFilter, "PELStatus desc", DataViewRowState.CurrentRows);
            DataTable dtDistinctStatus = view.ToTable(true, "PELStatus");

            ddlStatus.DataSource     = dtDistinctStatus;
            ddlStatus.DataTextField  = "PELStatus";
            ddlStatus.DataValueField = "PELStatus";
            ddlStatus.DataBind();
            ddlStatus.Items.Insert(0, new ListItem("No Filter", ""));
            ddlStatus.SelectedIndex = -1;
            if (sSelectedPELStatus != "")
            {
                foreach (ListItem li in ddlStatus.Items)
                {
                    if (li.Value == sSelectedPELStatus)
                    {
                        li.Selected = true;
                    }
                    else
                    {
                        li.Selected = false;
                    }
                }
            }
            if (ddlStatus.SelectedIndex == -1)     // Didn't find what was selected.
            {
                ddlStatus.SelectedIndex = 0;
            }

            return(dtPELs);
        }
示例#50
0
文件: Help.cs 项目: tamsky/duplicati
        public static void PrintUsage(string topic, IDictionary <string, string> options)
        {
            try
            {
                //Force translation off
                System.Threading.Thread.CurrentThread.CurrentCulture   = System.Globalization.CultureInfo.InvariantCulture;
                System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
            }
            catch
            {
            }

            if (string.IsNullOrWhiteSpace(topic))
            {
                topic = "help";
            }

            if (string.Equals("help", topic, StringComparison.InvariantCultureIgnoreCase))
            {
                if (options.Count == 1)
                {
                    topic = new List <string>(options.Keys)[0];
                }
                else if (System.Environment.CommandLine.IndexOf("--exclude", StringComparison.InvariantCultureIgnoreCase) >= 0)
                {
                    topic = "exclude";
                }
                else if (System.Environment.CommandLine.IndexOf("--include", StringComparison.InvariantCultureIgnoreCase) >= 0)
                {
                    topic = "include";
                }
            }


            if (_document.ContainsKey(topic))
            {
                string tp = _document[topic];
                Library.Main.Options opts = new Library.Main.Options(new Dictionary <string, string>());

                tp = tp.Replace("%VERSION%", License.VersionNumbers.Version);
                tp = tp.Replace("%BACKENDS%", string.Join(", ", Library.DynamicLoader.BackendLoader.Keys));
                tp = tp.Replace("%MONO%", Library.Utility.Utility.IsMono ? "mono " : "");
                tp = tp.Replace("%APP_PATH%", System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location));
                tp = tp.Replace("%EXAMPLE_SOURCE_PATH%", Library.Utility.Utility.IsClientLinux ? "/source" : "D:\\source");
                tp = tp.Replace("%EXAMPLE_SOURCE_FILE%", Library.Utility.Utility.IsClientLinux ? "/source/myfile.txt" : "D:\\source\\file.txt");
                tp = tp.Replace("%EXAMPLE_RESTORE_PATH%", Library.Utility.Utility.IsClientLinux ? "/restore" : "D:\\restore");
                tp = tp.Replace("%ENCRYPTIONMODULES%", string.Join(", ", Library.DynamicLoader.EncryptionLoader.Keys));
                tp = tp.Replace("%COMPRESSIONMODULES%", string.Join(", ", Library.DynamicLoader.CompressionLoader.Keys));
                tp = tp.Replace("%DEFAULTENCRYPTIONMODULE%", opts.EncryptionModule);
                tp = tp.Replace("%DEFAULTCOMPRESSIONMODULE%", opts.CompressionModule);
                tp = tp.Replace("%GENERICMODULES%", string.Join(", ", Library.DynamicLoader.GenericLoader.Keys));

                if (tp.Contains("%MAINOPTIONS%"))
                {
                    List <string> lines = new List <string>();
                    SortedList <string, Library.Interface.ICommandLineArgument> sorted = new SortedList <string, Library.Interface.ICommandLineArgument>();
                    foreach (Library.Interface.ICommandLineArgument arg in opts.SupportedCommands)
                    {
                        sorted.Add(arg.Name, arg);
                    }

                    foreach (Library.Interface.ICommandLineArgument arg in Program.SupportedCommands)
                    {
                        sorted[arg.Name] = arg;
                    }

                    foreach (Library.Interface.ICommandLineArgument arg in sorted.Values)
                    {
                        lines.Add(PrintArgSimple(arg, arg.Name));
                    }

                    tp = tp.Replace("%MAINOPTIONS%", string.Join(Environment.NewLine, lines.ToArray()));
                }

                if (tp.Contains("%ALLOPTIONS%"))
                {
                    List <string> lines = new List <string>();
                    foreach (Library.Interface.ICommandLineArgument arg in opts.SupportedCommands)
                    {
                        Library.Interface.CommandLineArgument.PrintArgument(lines, arg, "  ");
                    }


                    foreach (Library.Interface.ICommandLineArgument arg in Program.SupportedCommands)
                    {
                        Library.Interface.CommandLineArgument.PrintArgument(lines, arg, "  ");
                    }

                    lines.Add("");
                    lines.Add("");
                    lines.Add(Strings.Program.SupportedBackendsHeader);
                    foreach (Duplicati.Library.Interface.IBackend back in Library.DynamicLoader.BackendLoader.Backends)
                    {
                        PrintBackend(back, lines);
                    }

                    lines.Add("");
                    lines.Add("");
                    lines.Add(Strings.Program.SupportedEncryptionModulesHeader);
                    foreach (Duplicati.Library.Interface.IEncryption mod in Library.DynamicLoader.EncryptionLoader.Modules)
                    {
                        PrintEncryptionModule(mod, lines);
                    }

                    lines.Add("");
                    lines.Add("");
                    lines.Add(Strings.Program.SupportedCompressionModulesHeader);
                    foreach (Duplicati.Library.Interface.ICompression mod in Library.DynamicLoader.CompressionLoader.Modules)
                    {
                        PrintCompressionModule(mod, lines);
                    }

                    lines.Add("");

                    lines.Add("");
                    lines.Add("");
                    lines.Add(Strings.Program.GenericModulesHeader);
                    foreach (Duplicati.Library.Interface.IGenericModule mod in Library.DynamicLoader.GenericLoader.Modules)
                    {
                        PrintGenericModule(mod, lines);
                    }

                    lines.Add("");

                    tp = tp.Replace("%ALLOPTIONS%", string.Join(Environment.NewLine, lines.ToArray()));
                }

                if (tp.Contains("%MODULEOPTIONS%"))
                {
                    //Figure out which module we are in
                    IList <Library.Interface.ICommandLineArgument> args = null;
                    bool found = false;
                    foreach (Duplicati.Library.Interface.IBackend backend in Library.DynamicLoader.BackendLoader.Backends)
                    {
                        if (string.Equals(backend.ProtocolKey, topic, StringComparison.InvariantCultureIgnoreCase))
                        {
                            args  = backend.SupportedCommands;
                            found = true;
                            break;
                        }
                    }

                    if (args == null)
                    {
                        foreach (Duplicati.Library.Interface.IEncryption module in Library.DynamicLoader.EncryptionLoader.Modules)
                        {
                            if (string.Equals(module.FilenameExtension, topic, StringComparison.InvariantCultureIgnoreCase))
                            {
                                args  = module.SupportedCommands;
                                found = true;
                                break;
                            }
                        }
                    }

                    if (args == null)
                    {
                        foreach (Duplicati.Library.Interface.ICompression module in Library.DynamicLoader.CompressionLoader.Modules)
                        {
                            if (string.Equals(module.FilenameExtension, topic, StringComparison.InvariantCultureIgnoreCase))
                            {
                                args  = module.SupportedCommands;
                                found = true;
                                break;
                            }
                        }
                    }

                    if (args == null)
                    {
                        foreach (Duplicati.Library.Interface.IGenericModule module in Library.DynamicLoader.GenericLoader.Modules)
                        {
                            if (string.Equals(module.Key, topic, StringComparison.InvariantCultureIgnoreCase))
                            {
                                args  = module.SupportedCommands;
                                found = true;
                                break;
                            }
                        }
                    }

                    //If the module is not found, we do not display the description
                    if (found)
                    {
                        tp = tp.Replace("%MODULEOPTIONS%", PrintArgsSimple(args));
                    }
                    else
                    {
                        Console.WriteLine("Topic not found: {0}", topic);
                        Console.WriteLine();
                        //Prevent recursive lookups
                        if (topic != "help")
                        {
                            PrintUsage("help", new Dictionary <string, string>());
                        }
                        return;
                    }
                }

                if (NAMEDOPTION_REGEX.IsMatch(tp))
                {
                    tp = NAMEDOPTION_REGEX.Replace(tp, new Matcher().MathEvaluator);
                }

                PrintFormatted(tp.Split(new string[] { Environment.NewLine }, StringSplitOptions.None));
            }
            else
            {
                List <string> lines = new List <string>();

                foreach (Duplicati.Library.Interface.IBackend backend in Library.DynamicLoader.BackendLoader.Backends)
                {
                    if (string.Equals(backend.ProtocolKey, topic, StringComparison.InvariantCultureIgnoreCase))
                    {
                        PrintBackend(backend, lines);
                        break;
                    }
                }

                if (lines.Count == 0)
                {
                    foreach (Duplicati.Library.Interface.IEncryption mod in Library.DynamicLoader.EncryptionLoader.Modules)
                    {
                        if (string.Equals(mod.FilenameExtension, topic, StringComparison.InvariantCultureIgnoreCase))
                        {
                            PrintEncryptionModule(mod, lines);
                            break;
                        }
                    }
                }

                if (lines.Count == 0)
                {
                    foreach (Duplicati.Library.Interface.ICompression mod in Library.DynamicLoader.CompressionLoader.Modules)
                    {
                        if (string.Equals(mod.FilenameExtension, topic, StringComparison.InvariantCultureIgnoreCase))
                        {
                            PrintCompressionModule(mod, lines);
                            break;
                        }
                    }
                }

                if (lines.Count == 0)
                {
                    foreach (Duplicati.Library.Interface.IGenericModule mod in Library.DynamicLoader.GenericLoader.Modules)
                    {
                        if (string.Equals(mod.Key, topic, StringComparison.InvariantCultureIgnoreCase))
                        {
                            PrintGenericModule(mod, lines);
                            break;
                        }
                    }
                }


                if (lines.Count == 0)
                {
                    PrintArgumentIfFound(new Matcher().Values, topic, lines);
                }

                if (lines.Count != 0)
                {
                    PrintFormatted(lines);
                }
                else
                {
                    Console.WriteLine("Topic not found: {0}", topic);
                    Console.WriteLine();
                    PrintUsage("help", new Dictionary <string, string>());
                }
            }
        }
        static void Main(string[] args)
        {
            // collection implementation

            //implementation of list.It can have duplicate elements
            var nam = new List <string>();

            //to add the data in the list(one way to add data)
            nam.Add("vivek kumar");
            nam.Add("rakesh kumar");
            Console.WriteLine("...............List Implementation..............");

            //other way declaration with initialization
            var name = new List <string>()
            {
                "raju", "shyam"
            };

            // for accessing data
            foreach (var names in name)
            {
                Console.WriteLine(names);
            }


            //SortedList<TKey, TValue> implementation
            SortedList <string, string> SortedListData = new SortedList <string, string>();

            Console.WriteLine("...............SortedList<TKey, TValue> Implementation..............");
            SortedListData.Add("1", "Ravish");
            SortedListData.Add("12", "David");
            SortedListData.Add("13", "kailesh");
            SortedListData.Add("11", "Mona");
            foreach (var sortData in SortedListData)
            {
                Console.WriteLine(sortData);
            }

            //  HashSet<T> implementation
            var hashdata = new HashSet <string>()
            {
                "first", "second", "third"
            };

            Console.WriteLine("...............HashSet Implementation..............");
            foreach (var hashdataAccess in hashdata)
            {
                Console.WriteLine(hashdataAccess);
            }

            // SortedSet<T> implementation
            var SortedSetData = new SortedSet <string>()
            {
                "vivek", "kumar", "Abhishek", "Kamal"
            };

            Console.WriteLine("...............SortedSet<T> Implementation..............");
            foreach (var sortedsetdata in SortedSetData)
            {
                Console.WriteLine(sortedsetdata);
            }

            // Stack<T> implementation
            var stackData = new Stack <string>();

            Console.WriteLine("...............Stack<T> Implementation..............");
            stackData.Push("vivek");
            stackData.Push("kumar");
            stackData.Push("Neha");

            Console.WriteLine("Element which is in first position" + stackData.Peek());
            Console.WriteLine("Get Type" + stackData.GetType());



            //Queue<T> implementation

            Console.WriteLine("...............Queue<T> Implementation..............");
            var QueueData = new Queue <string>();

            QueueData.Enqueue("data1");
            QueueData.Enqueue("data2");
            QueueData.Enqueue("data3");
            QueueData.Dequeue();

            foreach (var data in QueueData)
            {
                Console.WriteLine(data);
            }
            //LinkedList<T> implementation
            var LinkedListData = new LinkedList <string>();

            Console.WriteLine("...............LinkedList<T> Implementation..............");
            LinkedListData.AddFirst("sonu");
            LinkedListData.AddLast("Monu");
            foreach (var linkdata in LinkedListData)
            {
                Console.WriteLine(linkdata);
            }
            // Dictionary<TKey, TValue> Implementation
            Dictionary <int, string> Dictdata = new Dictionary <int, string>();

            Console.WriteLine("...............Dictionary<TKey, TValue> Implementation ..............");
            Dictdata.Add(1, "shyam");
            Dictdata.Add(2, "Ravi");
            foreach (var dictdata in Dictdata)
            {
                Console.WriteLine(dictdata);
            }

            //SortedDictionary<TKey, TValue> implementation
            SortedDictionary <string, string> SortedDictData = new SortedDictionary <string, string>();

            Console.WriteLine("...............SortedDictionary<TKey, TValue> Implementation ..............");
            SortedDictData.Add("1", "Shyam");
            SortedDictData.Add("2", "ARUN");
            SortedDictData.Add("3", "rahul");
            foreach (var data in SortedDictData)
            {
                Console.WriteLine(data);
            }
            Console.ReadLine();
        }
示例#52
0
        public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t)
        {
            if (nums == null)
            {
                return(false);
            }

            if (nums.Length <= 1)
            {
                return(false);
            }

            if (k <= 0)
            {
                return(false);
            }

            if (t < 0)
            {
                return(false);
            }

            var intervals = new SortedList <int, int>();

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

                if (i > k)
                {
                    var removeVal = nums[i - k - 1];

                    var count = intervals[removeVal];

                    if (count == 1)
                    {
                        intervals.Remove(removeVal);
                    }
                    else
                    {
                        --intervals[removeVal];
                    }
                }

                if (FindInInterval(intervals, val, t, 0, intervals.Keys.Count - 1))
                {
                    return(true);
                }

                if (intervals.ContainsKey(val))
                {
                    intervals[val]++;
                }
                else
                {
                    intervals.Add(val, 1);
                }
            }

            return(false);
        }
示例#53
0
        private void rb_base_CheckedChanged(object sender, EventArgs e)
        {
            dgv_01.Rows.Clear();
            dgv_01.ClearSelection();
            CnasRemotCall reCnasRemotCall = new CnasRemotCall();
            SortedList    sltmp           = new SortedList();
            SortedList    sltmp01         = new SortedList();
            SortedList    sltmp02         = new SortedList();
            DataTable     getdt           = null;

            if (cb_customer.Text.Trim() == "----所有----")
            {
                sltmp.Add(1, 1);
                getdt = reCnasRemotCall.RemotInterface.SelectData("HCS-storage-sec004", sltmp);
            }
            else
            {
                string customer = sl_customer.GetKey(sl_customer.IndexOfValue(this.cb_customer.Text)).ToString();
                sltmp01.Add(1, Convert.ToInt32(customer));
                sltmp01.Add(2, 1);
                sltmp02.Add(1, sltmp01);
                string gg = reCnasRemotCall.RemotInterface.CheckSelectData("HCS-storage-sec003", sltmp01);
                getdt = reCnasRemotCall.RemotInterface.SelectData("HCS-storage-sec003", sltmp01);
            }

            if (getdt != null)
            {
                int ii = getdt.Rows.Count;
                if (ii <= 0)
                {
                    return;
                }
                dgv_01.RowCount = ii;
                for (int i = 0; i < ii; i++)
                {
                    if (getdt.Columns.Contains("s_type") && getdt.Columns.Contains("s_type") && getdt.Rows[i]["s_type"] != null)
                    {
                        dgv_01.Rows[i].Cells["s_type"].Value = sl_type[getdt.Rows[i]["s_type"].ToString()].ToString();
                    }
                    if (getdt.Columns.Contains("id") && getdt.Rows[i]["id"] != null)
                    {
                        dgv_01.Rows[i].Cells["id"].Value = getdt.Rows[i]["id"].ToString();
                    }
                    if (getdt.Columns.Contains("s_barcode") && getdt.Rows[i]["s_barcode"] != null)
                    {
                        dgv_01.Rows[i].Cells["s_barcode"].Value = getdt.Rows[i]["s_barcode"].ToString();
                    }
                    if (getdt.Columns.Contains("s_name") && getdt.Rows[i]["s_name"] != null)
                    {
                        dgv_01.Rows[i].Cells["s_name"].Value = getdt.Rows[i]["s_name"].ToString();
                    }
                    if (getdt.Columns.Contains("s_customer") && getdt.Rows[i]["s_customer"] != null)
                    {
                        dgv_01.Rows[i].Cells["s_customer"].Value = sl_customer[getdt.Rows[i]["s_customer"].ToString()].ToString();
                    }
                    if (getdt.Columns.Contains("s_room") && getdt.Rows[i]["s_room"] != null)
                    {
                        dgv_01.Rows[i].Cells["s_room"].Value = getdt.Rows[i]["s_room"].ToString();
                    }
                    if (getdt.Columns.Contains("s_basket") && getdt.Rows[i]["s_basket"] != null)
                    {
                        dgv_01.Rows[i].Cells["s_basket"].Value = getdt.Rows[i]["s_basket"].ToString();
                    }
                    if (getdt.Columns.Contains("s_costcenter") && getdt.Rows[i]["s_costcenter"] != null)
                    {
                        dgv_01.Rows[i].Cells["s_costcenter"].Value = sl_costcenter[getdt.Rows[i]["s_costcenter"].ToString()].ToString();
                    }
                    if (getdt.Columns.Contains("s_cabinet") && getdt.Rows[i]["s_cabinet"] != null)
                    {
                        dgv_01.Rows[i].Cells["s_cabinet"].Value = getdt.Rows[i]["s_cabinet"].ToString();
                    }
                    if (getdt.Columns.Contains("s_remarks") && getdt.Rows[i]["s_remarks"] != null)
                    {
                        dgv_01.Rows[i].Cells["s_remarks"].Value = getdt.Rows[i]["s_remarks"].ToString();
                    }
                    if (getdt.Columns.Contains("s_uselocation") && getdt.Rows[i]["s_uselocation"] != null)
                    {
                        dgv_01.Rows[i].Cells["s_uselocation"].Value = sl_uselocation[getdt.Rows[i]["s_uselocation"].ToString()].ToString();
                    }
                }
                if (dgv_01.Rows.Count > 0)
                {
                    dgv_01.CurrentRow = dgv_01.Rows[0];
                }
            }
            bt_ins.Enabled = false;
            bt_set.Enabled = true;
        }
示例#54
0
        public static SortedList <uint, DedimaniaRanking> GetRankingsToShow(DedimaniaRanking[] rankings, string login, uint maxRecordsToShow, uint maxRecordsToReport)
        {
            // show at least the top 3
            maxRecordsToShow   = (uint)Math.Max(Math.Min(Math.Min(maxRecordsToShow, maxRecordsToReport), rankings.Length), 3);
            maxRecordsToReport = (uint)Math.Min(rankings.Length, maxRecordsToReport);

            // set maxRecordsToShow to amount of existing rankings when the amoutn of rankings is less than the value of maxRecordsToShow
            if (rankings.Length < maxRecordsToShow && rankings.Length > 3)
            {
                maxRecordsToShow = Convert.ToUInt32(rankings.Length);
            }

            int currentPlayerRankIndex = Array.FindIndex(rankings, ranking => ranking.Login == login);

            SortedList <uint, DedimaniaRanking> result = new SortedList <uint, DedimaniaRanking>();

            // always add the first 3 records, replace non existing records with empty ones
            for (uint i = 1; i <= 3; i++)
            {
                DedimaniaRanking currentRank = rankings.Length >= i ? rankings[i - 1] : new DedimaniaRanking(string.Empty, string.Empty, 0, DateTime.MinValue);
                result.Add(i, currentRank);
            }

            // leave if no more records left
            if (maxRecordsToShow <= 3)
            {
                return(result);
            }

            uint amountOfRecordsLeft = maxRecordsToShow - 3;
            uint upperLimitLeft      = 4 + ((maxRecordsToReport - 3) / 2) + ((maxRecordsToReport - 3) % 2);
            uint lowerLimitRight     = upperLimitLeft;

            if (currentPlayerRankIndex != -1 && currentPlayerRankIndex > 2 && currentPlayerRankIndex < maxRecordsToReport)
            {
                result.Add((uint)(currentPlayerRankIndex + 1), rankings[currentPlayerRankIndex]);
                amountOfRecordsLeft--;

                upperLimitLeft  = (uint)currentPlayerRankIndex + 1;
                lowerLimitRight = (uint)(currentPlayerRankIndex + 2);
            }

            List <uint> ranksBeforePlayerRank = new List <uint>();

            for (uint i = 4; i < upperLimitLeft; i++)
            {
                ranksBeforePlayerRank.Add(i);
            }

            List <uint> ranksAfterPlayerRank = new List <uint>();

            for (uint i = lowerLimitRight; i <= maxRecordsToReport; i++)
            {
                ranksAfterPlayerRank.Add(i);
            }

            uint leftAmount  = (amountOfRecordsLeft / 2) + (amountOfRecordsLeft % 2);
            uint rightAmount = (amountOfRecordsLeft / 2);

            if (leftAmount > ranksBeforePlayerRank.Count)
            {
                uint diff = leftAmount - (uint)ranksBeforePlayerRank.Count;
                leftAmount   = (uint)ranksBeforePlayerRank.Count;
                rightAmount += diff;
            }

            if (rightAmount > ranksAfterPlayerRank.Count)
            {
                uint diff = rightAmount - (uint)ranksAfterPlayerRank.Count;
                rightAmount = (uint)ranksAfterPlayerRank.Count;
                leftAmount += diff;
            }

            uint leftAmountStart = leftAmount, leftAmountEnd = 0;
            uint rightAmountStart = 0, rightAmountEnd = rightAmount;

            if (currentPlayerRankIndex != -1 && currentPlayerRankIndex > 2)
            {
                leftAmountStart  = (leftAmount / 2);
                leftAmountEnd    = (leftAmount / 2) + (leftAmount % 2);
                rightAmountStart = (rightAmount / 2);
                rightAmountEnd   = (rightAmount / 2) + (rightAmount % 2);
            }

            for (int i = 0; i < leftAmountStart; i++)
            {
                result.Add(ranksBeforePlayerRank[i], rankings[ranksBeforePlayerRank[i] - 1]);
            }

            for (int i = ranksBeforePlayerRank.Count - 1; i > (ranksBeforePlayerRank.Count - 1) - leftAmountEnd; i--)
            {
                result.Add(ranksBeforePlayerRank[i], rankings[ranksBeforePlayerRank[i] - 1]);
            }

            for (int i = 0; i < rightAmountStart; i++)
            {
                result.Add(ranksAfterPlayerRank[i], rankings[ranksAfterPlayerRank[i] - 1]);
            }

            for (int i = ranksAfterPlayerRank.Count - 1; i > (ranksAfterPlayerRank.Count - 1) - rightAmountEnd; i--)
            {
                result.Add(ranksAfterPlayerRank[i], rankings[ranksAfterPlayerRank[i] - 1]);
            }

            return(result);
        }
示例#55
0
        private string strbarcodexml = "";               // 条码打印BarCodeXML数据
        public HCSCM_storage_manage()
        {
            InitializeComponent();
            #region  钮图片加载

            this.but_new.Image       = ResourcesImageHelper.Instance.GetResourcesImage("Common.Buttom", "new", EnumImageType.PNG);
            this.but_edit.Image      = ResourcesImageHelper.Instance.GetResourcesImage("Common.Buttom", "edit", EnumImageType.PNG);
            this.but_remove.Image    = ResourcesImageHelper.Instance.GetResourcesImage("Common.Buttom", "delete", EnumImageType.PNG);
            this.but_printlist.Image = ResourcesImageHelper.Instance.GetResourcesImage("Common.Buttom", "printList", EnumImageType.PNG);
            this.but_print.Image     = ResourcesImageHelper.Instance.GetResourcesImage("Common.Buttom", "printCode", EnumImageType.PNG);
            this.bt_ins.Image        = ResourcesImageHelper.Instance.GetResourcesImage("Common.Buttom", "configureSterilizer", EnumImageType.PNG);
            this.bt_set.Image        = ResourcesImageHelper.Instance.GetResourcesImage("Common.Buttom", "configureSet", EnumImageType.PNG);
            this.but_import.Image    = ResourcesImageHelper.Instance.GetResourcesImage("Common.Buttom", "export", EnumImageType.PNG);
            #endregion
            //this.Font = new Font(this.Font.FontFamily, 11);
            CnasRemotCall reCnasRemotCall = new CnasRemotCall();
            //获取存储点类型
            DataRow[] type = CnasBaseData.SystemBaseData.Select("type_code='HCS-storage-type'");
            if (type.Length > 0)
            {
                foreach (DataRow dr in type)
                {
                    sl_type.Add(dr["key_code"].ToString().Trim(), dr["value_code"].ToString().Trim());
                }
            }

            //获取使用地点数据
            DTlocation = reCnasRemotCall.RemotInterface.SelectData("HCS-use-location-sec001", null);
            if (DTlocation != null)
            {
                int ii = DTlocation.Rows.Count;
                if (ii <= 0)
                {
                    return;
                }
                for (int i = 0; i < ii; i++)
                {
                    if (DTlocation.Rows[i]["id"].ToString() != null && DTlocation.Rows[i]["u_uname"].ToString().Trim() != null)
                    {
                        sl_uselocation.Add(DTlocation.Rows[i]["id"].ToString(), DTlocation.Rows[i]["u_uname"].ToString().Trim());
                    }
                }
            }
            //获取成本中心数据
            DTcostcenter = reCnasRemotCall.RemotInterface.SelectData("HCS-costcenter-sec003", null);
            if (DTcostcenter != null)
            {
                int ii = DTcostcenter.Rows.Count;
                if (ii <= 0)
                {
                    return;
                }
                for (int i = 0; i < ii; i++)
                {
                    if (DTcostcenter.Rows[i]["id"].ToString() != null && DTcostcenter.Rows[i]["ca_name"].ToString().Trim() != null)
                    {
                        sl_costcenter.Add(DTcostcenter.Rows[i]["id"].ToString(), DTcostcenter.Rows[i]["ca_name"].ToString().Trim());
                    }
                }
            }
            //获取客户数据
            DTcustomer = reCnasRemotCall.RemotInterface.SelectData("HCS-customer-sec002", null);
            if (DTcustomer != null)
            {
                this.cb_customer.Items.Add("----所有----");
                sl_customer.Add("0", "----所有----");
                int ii = DTcustomer.Rows.Count;
                if (ii <= 0)
                {
                    return;
                }
                for (int i = 0; i < ii; i++)
                {
                    if (DTcustomer.Rows[i]["id"].ToString() != null && DTcustomer.Rows[i]["cu_name"].ToString().Trim() != null)
                    {
                        sl_customer.Add(DTcustomer.Rows[i]["id"].ToString(), DTcustomer.Rows[i]["cu_name"].ToString().Trim());
                        sl_customer01.Add(DTcustomer.Rows[i]["bar_code"].ToString(), DTcustomer.Rows[i]["cu_name"].ToString().Trim());
                        cb_customer.Items.Add(DTcustomer.Rows[i]["cu_name"].ToString().Trim());
                    }
                }
                cb_customer.Text = "----所有----";
            }
            Loaddata(null);
            if (dgv_01.RowCount > 0)//初次加载,如果dgv_01有数据,则默认选中第一行
            {
                dgv_01.Rows[0].IsSelected = true;
            }
            //获取打印条码的 XML 数据信息
            DataRow[] arrayDR02 = CnasBaseData.SystemBaseData.Select("type_code='HCS_barcode_type' and key_code='BCS'");
            strbarcodexml = arrayDR02[0]["other_code"].ToString().Trim();
        }
示例#56
0
        /// <summary>
        /// 加载数据
        /// </summary>
        public void DataBind()
        {
            //模版上传辅助类
            TemFileUploadHelper temFileUploadHelper = new TemFileUploadHelper();


            //新建报表
            if (custom_tem_id != 0 && id == 0)
            {
                SortedList sellist = new SortedList();
                sellist.Add(1, custom_tem_id);
                //string ss = reCnasRemotCall.RemotInterface.CheckSelectData("HCS-custom-template-sec002", sellist);
                dtTemRowDate = reCnasRemotCall.RemotInterface.SelectData("HCS-custom-template-sec002", sellist);

                if (dtTemRowDate == null)
                {
                    dtTemRowDate = new DataTable();
                }

                if (dtTemRowDate.Rows.Count > 0)
                {
                    //先下载模版文件
                    temFileUploadHelper.DownloadTemFile(@"Template\", dtTemRowDate.Rows[0]["guidname"].ToString());
                    string file = temFileUploadHelper.GetTemFilePath(@"Template\", dtTemRowDate.Rows[0]["guidname"].ToString());

                    //生成一个临时文件,用于存储数据
                    string tem_fileName = dtTemRowDate.Rows[0]["guidname"].ToString().Replace(Path.GetExtension(file), "");

                    string tem_file = temFileUploadHelper.GetTemFilePath(@"Template\", dtTemRowDate.Rows[0]["guidname"].ToString()).Replace(tem_fileName, tem_fileName + "_tem");

                    //如果有则先删除
                    if (File.Exists(tem_file))
                    {
                        File.Delete(tem_file);
                    }

                    try
                    {
                        this.axFramerControl.Open(@file);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }
            }


            //修改报表
            if (custom_tem_id == 0 && id != 0)
            {
                SortedList sellist1 = new SortedList();
                sellist1.Add(1, id);
                //string ss = reCnasRemotCall.RemotInterface.CheckSelectData("HCS-custom-template-sec002", sellist);
                dtRowDate = reCnasRemotCall.RemotInterface.SelectData("HCS-custom-template-report-sec002", sellist1);

                if (dtRowDate == null)
                {
                    dtRowDate = new DataTable();
                }


                //this.Text = SystemName + "--模版修改";

                //如果是修改,但是未返回数据,则直接关闭窗体
                if (dtRowDate.Rows.Count <= 0)
                {
                    this.Close();
                }

                rtxtTem_name.Text = dtRowDate.Rows[0]["report_name"].ToString();

                //先下载模版文件
                temFileUploadHelper.DownloadTemFile(@"Report\", dtRowDate.Rows[0]["file_name"].ToString());
                string file = temFileUploadHelper.GetTemFilePath(@"Report\", dtRowDate.Rows[0]["file_name"].ToString());

                string tem_fileName = dtRowDate.Rows[0]["file_name"].ToString().Replace(Path.GetExtension(file), "");

                string tem_file = temFileUploadHelper.GetTemFilePath(@"Report\", dtRowDate.Rows[0]["file_name"].ToString()).Replace(tem_fileName, tem_fileName + "_tem");


                if (File.Exists(tem_file))
                {
                    File.Delete(tem_file);
                }


                //把数据存放到临时文件
                File.Copy(file, tem_file, true);

                try
                {
                    this.axFramerControl.Open(@file);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
        }
示例#57
0
        static void Main(string[] args)
        {
            string sourcedirectory = string.Empty;
            string dbdirectory     = Directory.GetCurrentDirectory();
            string fileextension   = "asc";

            for (int i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                case "-s":
                    sourcedirectory = args[i + 1];
                    break;

                case "-o":
                    dbdirectory = args[i + 1];
                    break;
                }
            }

            if (string.IsNullOrEmpty(sourcedirectory) || string.IsNullOrEmpty(dbdirectory))
            {
                Console.WriteLine("USAGE: TimeSeriesDB.exe -s sourcedirectory [-o output directory]");
                return;
            }

            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss.fff"));
            SortedList <string, List <string> > FilesSortedByMarket = new SortedList <string, List <string> >();

            foreach (string file in System.IO.Directory.GetFiles(sourcedirectory, "*." + fileextension, SearchOption.AllDirectories))
            {
                string   fname      = Path.GetFileNameWithoutExtension(file);
                string[] fnameelems = fname.Split(new char[] { '_' });
                string   market     = fnameelems[0];
                if (FilesSortedByMarket.ContainsKey(market))
                {
                    FilesSortedByMarket[market].Add(file);
                }
                else
                {
                    FilesSortedByMarket.Add(market, new List <string>()
                    {
                        file
                    });
                }
            }

            // get quote files by market and process to build
            // stream of best bid-offer
            foreach (string markets in FilesSortedByMarket.Keys)
            {
                #region Process Ticker Files
                if (NameToMarketId.ContainsKey(markets))
                {
                    if (MarketName != markets)
                    {
                        MarketName = markets;
                        MarketId   = NameToMarketId[MarketName];
                        Console.WriteLine("Processing {0}", MarketName);
                        Console.WriteLine("\tQuotes");
                    }
                    List <string> files = FilesSortedByMarket[MarketName];

                    // loop over all quotes files for the market and insert each quote into sortedquotedata
                    #region Process Ticker Quote Files
                    Parallel.ForEach(files.Where(x => x.Contains("_Q")), new ParallelOptions()
                    {
                        MaxDegreeOfParallelism = Environment.ProcessorCount * 2
                    }, quotedatafile =>
                    {
                        Console.WriteLine("\t\t{0}", quotedatafile);

                        // list that contains sorted time series of trades and quotes for all markets
                        var sortedalltimeseries = CreateList(new { TimeSeriesRecord = (TSRecord)null });

                        string tradedatafile = quotedatafile.Replace("X_Q", "X_T");
                        if (!File.Exists(tradedatafile))
                        {
                            Console.WriteLine("\t\t\tTrade data file does not exist: {0}", tradedatafile);
                            return;
                        }

                        Dictionary <DateTime, uint> markettodt = new Dictionary <DateTime, uint>();
                        var sortedquotedata = CreateList(new { Key = (TSDateTime)null, Value = (QuoteData)null });                         // new[] { new { Key = (TSDateTime)null, Value = (QuoteData)null } }.ToList();
                        using (StreamReader sr = new StreamReader(quotedatafile))
                        {
                            String line = null;
                            while ((line = sr.ReadLine()) != null)
                            {
                                QuoteData qd = new QuoteData(line);
                                if (qd.Dt.TimeOfDay >= WhenTimeIsBefore && qd.Dt.TimeOfDay <= WhenTimeIsAfter && qd.Bid != 0.0 && qd.Ask != 0.0 && qd.BidSz != 0 && qd.AskSz != 0 && qd.Bid <= qd.Ask && ExchangeInclusionList.Contains(qd.Exch))
                                {
                                    uint seqno = 1;
                                    if (markettodt.ContainsKey(qd.Dt))
                                    {
                                        seqno             = markettodt[qd.Dt];
                                        markettodt[qd.Dt] = seqno + 1;
                                    }
                                    else
                                    {
                                        markettodt[qd.Dt] = 1;
                                    }
                                    TSDateTime tsdt = new TSDateTime(qd.Dt, MarketId, seqno);                                     //GetSeqNo(qd.Dt, MarketId));
                                    sortedquotedata.Add(new { Key = new TSDateTime(qd.Dt, MarketId, seqno), Value = qd });
                                }
                            }
                        }
//						List<QuoteData> quotedata = ParseQuoteData(item, sortedquotedata);
                        Console.WriteLine("\t\t\tSorting quotes for {0}", quotedatafile);
                        sortedquotedata.Sort((p1, p2) => p1.Key.Timestamp.CompareTo(p2.Key.Timestamp));
                        markettodt.Clear();

                        #region Build Inside Quotes For Ticker
                        // we have sorted quotes for a market. now build stream of best bid-offer
                        var sortedbiddata = CreateList(new { Exch = string.Empty, Price = 0.0, Size = (uint)0 });
                        var sortedaskdata = CreateList(new { Exch = string.Empty, Price = 0.0, Size = (uint)0 });
                        var sortedquotes  = CreateList(new { Dt = (ulong)0, Exch = string.Empty, Bid = 0.0, BidSz = (uint)0, Ask = 0.0, AskSz = (uint)0 });

                        string prevbidexch  = string.Empty;
                        string prevaskexch  = string.Empty;
                        double prevbidprice = 0.0;
                        double prevaskprice = 0.0;
                        uint prevbidsize    = 0;
                        uint prevasksize    = 0;
                        DateTime prevdt     = DateTime.Now;

                        // walk sortedquotedata to compute inside market
                        // insert inside market records into sortedquotes
                        Console.WriteLine("\t\t\tBuilding inside market for {0}", quotedatafile);
                        foreach (var qd in sortedquotedata)
                        {
                            bool newbiddata = true;
                            bool newaskdata = true;

                            var mqqs = sortedbiddata.FirstOrDefault(x => x.Exch == qd.Value.BidExch);
                            if (mqqs == null)
                            {
                                sortedbiddata.Add(new { Exch = qd.Value.BidExch, Price = qd.Value.Bid, Size = qd.Value.BidSz });
                            }
                            else if (mqqs != null && (mqqs.Price != qd.Value.Bid || mqqs.Size != qd.Value.BidSz))
                            {
                                sortedbiddata.Remove(mqqs);
                                sortedbiddata.Add(new { Exch = qd.Value.BidExch, Price = qd.Value.Bid, Size = qd.Value.BidSz });
                            }
                            else
                            {
                                newbiddata = false;
                            }

                            mqqs = sortedaskdata.FirstOrDefault(x => x.Exch == qd.Value.AskExch);
                            if (mqqs == null)
                            {
                                sortedaskdata.Add(new { Exch = qd.Value.AskExch, Price = qd.Value.Ask, Size = qd.Value.AskSz });
                            }
                            else if (mqqs != null && (mqqs.Price != qd.Value.Ask || mqqs.Size != qd.Value.AskSz))
                            {
                                sortedaskdata.Remove(mqqs);
                                sortedaskdata.Add(new { Exch = qd.Value.AskExch, Price = qd.Value.Ask, Size = qd.Value.AskSz });
                            }
                            else
                            {
                                newaskdata = false;
                            }

                            if (newbiddata)
                            {
                                sortedbiddata = sortedbiddata.OrderByDescending(x => x.Price).ThenByDescending(y => y.Size).ToList();
                            }
                            if (newaskdata)
                            {
                                sortedaskdata = sortedaskdata.OrderBy(x => x.Price).ThenByDescending(y => y.Size).ToList();
                            }

                            if (
                                ((prevbidprice != sortedbiddata[0].Price) || (prevbidsize != sortedbiddata[0].Size) ||
                                 (prevaskprice != sortedaskdata[0].Price) || (prevasksize != sortedaskdata[0].Size)
                                 //						|| (prevbidexch != sortedbiddata[0].Exch) || (prevaskexch != sortedaskdata[0].Exch)
                                )
                                &&
                                (prevdt != qd.Value.Dt)
                                )
                            {
                                sortedquotes.Add(new { Dt = (ulong)new TSDateTime(qd.Key.Dt, qd.Key.MarketId, 0).Timestamp, Exch = sortedbiddata[0].Exch, Bid = (double)sortedbiddata[0].Price, BidSz = (uint)sortedbiddata[0].Size, Ask = (double)sortedaskdata[0].Price, AskSz = (uint)sortedaskdata[0].Size });
                                //						Console.WriteLine(string.Format("{0} {1}:{2}:{3} {4}:{5}:{6}", qd.Value.Dt.Ticks, sortedbiddata[0].Exch, sortedbiddata[0].Price, sortedbiddata[0].Size, sortedaskdata[0].Exch, sortedaskdata[0].Price, sortedaskdata[0].Size));
                                prevbidexch  = sortedbiddata[0].Exch;
                                prevbidprice = sortedbiddata[0].Price;
                                prevbidsize  = sortedbiddata[0].Size;
                                prevaskexch  = sortedaskdata[0].Exch;
                                prevaskprice = sortedaskdata[0].Price;
                                prevasksize  = sortedaskdata[0].Size;
                                prevdt       = qd.Value.Dt;
                            }
                        }
                        Console.WriteLine("\t\t\tSorting inside market for {0}", quotedatafile);
                        sortedquotes.Sort((p1, p2) => p1.Dt.CompareTo(p2.Dt));
                        sortedbiddata.Clear();
                        sortedaskdata.Clear();
                        sortedquotedata.Clear();
                        #endregion

                        #region Process Ticker Trades Files
                        var sortedtrades = CreateList(new { Key = (TSDateTime)null, Value = (TradeData)null });
                        if (sortedquotes.Count > 0)
                        {
                            using (StreamReader sr = new StreamReader(tradedatafile))
                            {
                                String line = null;
                                while ((line = sr.ReadLine()) != null)
                                {
                                    try
                                    {
                                        TradeData td = new TradeData(line);
                                        uint seqno   = 1;
                                        if (markettodt.ContainsKey(td.Dt))
                                        {
                                            seqno             = markettodt[td.Dt];
                                            markettodt[td.Dt] = seqno + 1;
                                        }
                                        else
                                        {
                                            markettodt[td.Dt] = 1;
                                        }
                                        if (td.Dt.TimeOfDay >= WhenTimeIsBefore && td.Dt.TimeOfDay <= WhenTimeIsAfter && td.Price > 0.0 && td.Volume > 0 && ExchangeInclusionList.Contains(td.Exch))
                                        {
                                            sortedtrades.Add(new { Key = new TSDateTime(td.Dt, TimeSeriesDB.MarketId, seqno), Value = td });
                                        }
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                            // need to process all trades files and create a sorted list of trades
                            Console.WriteLine("\t\t{0}", tradedatafile);
                        }
                        #endregion
                        Console.WriteLine("\tSorting trades");
                        sortedtrades.Sort((p1, p2) => p1.Key.Timestamp.CompareTo(p2.Key.Timestamp));

                        #region Build Interleaved Timeseries
                        var sortedtimeseries = CreateList(new { TimeSeriesRecord = (TSRecord)null });

                        ulong timestamp_msecs = 0;
                        ulong timestamp_quote = 0;
                        // loop over sortedtrades and create time series record
                        Console.WriteLine("\tBuilding interleaved timeseries");
                        foreach (var x in sortedtrades)
                        {
                            if (10 * ((ulong)x.Key.Dt.Ticks) > timestamp_msecs)
                            {
                                // find nearest quote by timestamp
                                int index       = BinarySearchForMatch(sortedquotes, (y) => { return(y.Dt.CompareTo(x.Key.Timestamp)); });
                                int idx         = index == 0 ? 0 : index - 1;
                                var quote       = sortedquotes[idx];
                                timestamp_quote = quote.Dt;
                                timestamp_msecs = 10 * ((ulong)x.Key.Dt.Ticks);
                            }
                            sortedtimeseries.Add(new { TimeSeriesRecord = new TSRecord(x.Key.Timestamp, x.Value.Exch, x.Value.Price, x.Value.Volume)
                                                       {
                                                           QuoteIdx = timestamp_quote
                                                       } });
                        }
                        sortedtrades.Clear();
                        foreach (var x in sortedquotes)
                        {
                            sortedtimeseries.Add(new { TimeSeriesRecord = new TSRecord(x.Dt, x.Exch, x.Bid, x.BidSz, x.Ask, x.AskSz) });
                        }
                        sortedquotes.Clear();

                        Console.WriteLine("\tSorting timeseries");
                        sortedtimeseries.Sort((p1, p2) => p1.TimeSeriesRecord.Idx.CompareTo(p2.TimeSeriesRecord.Idx));
                        #endregion

                        Console.WriteLine("\tAdding {0} timeseries to master timeseries", TimeSeriesDB.MarketName);
                        sortedalltimeseries.AddRange(sortedtimeseries);

                        Console.WriteLine("\tSorting master timeseries");
                        sortedalltimeseries.Sort((p1, p2) => p1.TimeSeriesRecord.Idx.CompareTo(p2.TimeSeriesRecord.Idx));

                        #region Write To Timeseries DB
                        if (sortedalltimeseries.Count > 0)
                        {
                            string filename = string.Format(@"{0}\{1}", dbdirectory, Path.GetFileName(quotedatafile).Replace("_Q", "_TSDB").Replace(fileextension, "dts"));                             //new TSDateTime(sortedalltimeseries[0].TimeSeriesRecord.Idx).Dt.ToString("yyyyMMddHHmmssfff"), new TSDateTime(sortedalltimeseries[sortedalltimeseries.Count - 1].TimeSeriesRecord.Idx).Dt.ToString("yyyyMMddHHmmssfff"));

                            if (File.Exists(filename))
                            {
                                File.Delete(filename);
                            }

                            using (var file = new BinCompressedSeriesFile <ulong, TSRecord>(filename))
                            {
                                var root = (ComplexField)file.RootField;
                                ((ScaledDeltaFloatField)root["Bid"].Field).Multiplier = 1000;
                                ((ScaledDeltaFloatField)root["Ask"].Field).Multiplier = 1000;

                                file.UniqueIndexes = false;                               // enforces index uniqueness
                                file.InitializeNewFile();                                 // create file and write header

                                List <TSRecord> tsrlist = new List <TSRecord>();
                                foreach (var tsr in sortedalltimeseries)
                                {
                                    tsrlist.Add(tsr.TimeSeriesRecord);
                                }

                                ArraySegment <TSRecord> arr = new ArraySegment <TSRecord>(tsrlist.ToArray());
                                file.AppendData(new ArraySegment <TSRecord>[] { arr });
                            }
                        }
                        #endregion
                    });
                    #endregion
                }
                #endregion

                // merge files together
                #region merge per day per tick ts files into a single per tick file
                string mergedfilename = string.Format(@"{0}\{1}", dbdirectory, markets + ".dts");                 //new TSDateTime(sortedalltimeseries[0].TimeSeriesRecord.Idx).Dt.ToString("yyyyMMddHHmmssfff"), new TSDateTime(sortedalltimeseries[sortedalltimeseries.Count - 1].TimeSeriesRecord.Idx).Dt.ToString("yyyyMMddHHmmssfff"));
                if (File.Exists(mergedfilename))
                {
                    File.Delete(mergedfilename);
                }

                List <string> filestobemerged = Directory.GetFiles(dbdirectory, markets + "*.dts").ToList();
                do
                {
                    var pairs = filestobemerged.Where((x, i) => i % 2 == 0).Zip(filestobemerged.Where((x, i) => i % 2 == 1), (second, first) => new[] { first, second }).ToList();
                    Parallel.ForEach(pairs, new ParallelOptions()
                    {
                        MaxDegreeOfParallelism = Environment.ProcessorCount * 2
                    }, pair =>
                    {
                        string mergedfile = Path.GetTempFileName();
                        File.Copy(mergedfile, mergedfile = dbdirectory + "\\" + Path.GetFileName(mergedfile));
                        File.Delete(mergedfile);
                        string mergefile1 = pair[0];
                        string mergefile2 = pair[1];

                        List <TSDBEnumerator> sortedtsdbenumerators = new List <TSDBEnumerator>();
                        List <TSDBEnumerator> TSDBEnumerators       = pair.Select(x => new TSDBEnumerator(new TSStreamer(x), new TSDateTime(DateTime.MinValue, 0, 0).Timestamp, new TSDateTime(DateTime.MaxValue, 999, 99).Timestamp)).ToList();                  //.TimeSeriesDB.Stream(new TSDateTime(DateTime.MinValue, 0, 0).Timestamp, new TSDateTime(DateTime.MaxValue, 999, 99).Timestamp).GetEnumerator())).ToList();
                        using (var file = new BinCompressedSeriesFile <ulong, TSRecord>(mergedfile))
                        {
                            List <TSRecord> tsrlist = new List <TSRecord>();

                            var root = (ComplexField)file.RootField;
                            ((ScaledDeltaFloatField)root["Bid"].Field).Multiplier = 1000;
                            ((ScaledDeltaFloatField)root["Ask"].Field).Multiplier = 1000;

                            file.UniqueIndexes = false;                           // enforces index uniqueness
                            file.InitializeNewFile();                             // create file and write header

                            sortedtsdbenumerators.AddRange(TSDBEnumerators.Select(x => x));
                            do
                            {
                                foreach (var tsdbenumerator in TSDBEnumerators.Where(x => x.GetNext == true && x.TSEnumerator != null))
                                {
                                    tsdbenumerator.GetNext = false;
                                    if (true == tsdbenumerator.TSEnumerator.MoveNext())
                                    {
                                        tsdbenumerator.TSRecord = tsdbenumerator.TSEnumerator.Current;
                                    }
                                    else
                                    {
                                        tsdbenumerator.Dispose();
                                        tsdbenumerator.TSEnumerator = null;
                                        tsdbenumerator.TSRecord     = null;
                                        sortedtsdbenumerators.Remove(tsdbenumerator);
                                    }
                                }
                                if (sortedtsdbenumerators.Count > 0)
                                {
                                    sortedtsdbenumerators.Sort((item1, item2) => item1.TSRecord.Idx.CompareTo(item2.TSRecord.Idx));
                                    sortedtsdbenumerators[0].GetNext = true;
                                    tsrlist.Add(sortedtsdbenumerators[0].TSRecord);
                                }
                                if (tsrlist.Count == 10000000)
                                {
                                    ArraySegment <TSRecord> arr = new ArraySegment <TSRecord>(tsrlist.ToArray());
                                    file.AppendData(new ArraySegment <TSRecord>[] { arr });
                                    tsrlist.Clear();
                                }
                            } while (sortedtsdbenumerators.Count > 0);
                            if (tsrlist.Count > 0)
                            {
                                ArraySegment <TSRecord> arr = new ArraySegment <TSRecord>(tsrlist.ToArray());
                                file.AppendData(new ArraySegment <TSRecord>[] { arr });
                            }
                        }
                        filestobemerged.Remove(mergefile1);
                        if (mergefile1.Contains(".tmp"))
                        {
                            File.Delete(mergefile1);
                        }
                        filestobemerged.Remove(mergefile2);
                        if (mergefile2.Contains(".tmp"))
                        {
                            File.Delete(mergefile2);
                        }
                        filestobemerged.Add(mergedfile);
                    });
                } while (filestobemerged.Count > 1);
                if (filestobemerged.Count == 1)
                {
                    File.Move(filestobemerged[0], dbdirectory + "\\" + markets + ".dts");
                }
                #endregion
            }

            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss.fff"));
        }
示例#58
0
 /// <summary>
 /// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.
 /// </summary>
 /// <param name="key">The object to use as the key of the element to add.</param>
 /// <param name="value">The object to use as the value of the element to add.</param>
 /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"></see> is read-only.</exception>
 /// <exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.</exception>
 /// <exception cref="T:System.ArgumentNullException">key is null.</exception>
 public void Add(TKey key, TValue value)
 {
     _table.Add(key, new KeyValuePair <int, TValue> (_index.Count, value));
     _index.Add(new KeyValuePair <TKey, TValue> (key, value));
 }
示例#59
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            string a = "  sdsad     dasdas  ";

xuly:
            {
                a = a.Trim();

                Console.WriteLine(a);

                a = a.Replace("  ", " ");

                Console.WriteLine(a);
                bool dem = a.Contains(" ");
                if (dem == true)
                {
                    Console.WriteLine(a);
                }
                else
                {
                    goto xuly;
                }
            }



            var now = DayMontYear();

            Console.WriteLine($"Day: {now.Item1} , Month: {now.Item2}, Year: {now.Item3} Gio: {now.Item4} Phut: {now.Item5} Giay:{now.Item6} Khac:{now.Item7}");

            ArrayList arrPerson = new ArrayList();
            Hashtable hash      = new Hashtable();

            Console.WriteLine(hash[""]);

            SortedList sortedList  = new SortedList(new SortPerson());
            SortedList sortedList1 = new SortedList(sortedList, new SortPerson());



            sortedList.Add(new Person("quan1", 15), "quan15");
            sortedList.Add(new Person("quan2", 17), "quan17");
            sortedList.Add(new Person("quan4", 13), "quan13");

            foreach (DictionaryEntry item in sortedList)
            {
                Console.WriteLine("key: " + item.Key + " value: " + item.Value);
            }

            for (int i = 0; i < 3; i++)
            {
                Person person = new Person();
                Console.Write("Ho va Ten: ");
                person.Name = Console.ReadLine();
                Console.Write("Tuoi: ");
                person.Age = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine();

                arrPerson.Add(person);
            }

            //arrPerson.Add(new Person("mai bai quan", 19));
            //arrPerson.Add(new Person("mai bai quan", 22));
            //arrPerson.Add(new Person("mai bai quan", 17));
            //arrPerson.Add(new Person("mai bai quan", 25));


            Console.WriteLine("Danh sach Person ban dau");
            foreach (Person item in arrPerson)
            {
                item.ShowData();
            }

            arrPerson.Sort(new SortPerson());

            Console.WriteLine();
            Console.WriteLine("danh sach tanwg dan:");
            foreach (Person item in arrPerson)
            {
                item.ShowData();
            }
        }
示例#60
0
        public override bool VisitASTContext(ASTContext context)
        {
            SortedList <string, TranslationUnit> missingTranslationUnits = new SortedList <string, TranslationUnit>();

            // Get list of generated units
            List <TranslationUnit> units = Context.ASTContext.TranslationUnits.GetGenerated().ToList();

            foreach (TranslationUnit unit in units)
            {
                NodeJSTypeReferenceCollector typeReferenceCollector = new NodeJSTypeReferenceCollector(Context.ConfigurationContext, Context.TypeMaps, Context.Options);
                typeReferenceCollector.Process(unit);

                IEnumerable <NodeJSTypeReference> classToWrapTypeReferences = typeReferenceCollector.TypeReferences
                                                                              .Where(item => item.Declaration is Class);

                // Check if no class reference where found
                if (classToWrapTypeReferences.Count() > 0)
                {
                    foreach (NodeJSTypeReference currentReference in classToWrapTypeReferences)
                    {
                        // Check if missing unit was already added
                        if (missingTranslationUnits.ContainsKey(currentReference.Declaration.Name))
                        {
                            continue;
                        }

                        // Check if missing unit exists with trimmed name
                        if (units.Exists(u => NamingHelper.GenerateTrimmedClassName(u.FileNameWithoutExtension).ToLower().Contains(NamingHelper.GenerateTrimmedClassName(currentReference.Declaration.Name).ToLower())))
                        {
                            continue;
                        }

                        // Make deep copy of current unit
                        TranslationUnit missingTranslationUnit = unit.Copy();

                        // Change names of copy
                        missingTranslationUnit.Name         = currentReference.Declaration.Name;
                        missingTranslationUnit.OriginalName = currentReference.Declaration.Name;

                        // Change public fields
                        string missingTranslationUnitFileName         = NamingHelper.GenerateTrimmedClassName(currentReference.Declaration.Name).ToLower() + ".gen";
                        string missingTranslationUnitFileRelativePath = unit.FileRelativePath;

                        // Update public fields
                        missingTranslationUnit.FilePath = Path.Combine(Path.GetDirectoryName(unit.FilePath), missingTranslationUnitFileName);

                        // Update private fields with reflection
                        FieldInfo fileNameFieldInfo = missingTranslationUnit.GetType().GetField("fileName", BindingFlags.NonPublic | BindingFlags.Instance);
                        fileNameFieldInfo.SetValue(missingTranslationUnit, missingTranslationUnitFileName);

                        FieldInfo fileNameWithoutExtensionFieldInfo = missingTranslationUnit.GetType().GetField("fileNameWithoutExtension", BindingFlags.NonPublic | BindingFlags.Instance);
                        fileNameWithoutExtensionFieldInfo.SetValue(missingTranslationUnit, Path.GetFileNameWithoutExtension(missingTranslationUnitFileName));

                        FieldInfo fileRelativeDirectoryFieldInfo = missingTranslationUnit.GetType().GetField("fileRelativeDirectory", BindingFlags.NonPublic | BindingFlags.Instance);
                        fileRelativeDirectoryFieldInfo.SetValue(missingTranslationUnit, Path.GetDirectoryName(missingTranslationUnitFileRelativePath));

                        FieldInfo fileRelativePathFieldInfo = missingTranslationUnit.GetType().GetField("fileRelativePath", BindingFlags.NonPublic | BindingFlags.Instance);
                        fileRelativePathFieldInfo.SetValue(missingTranslationUnit, Path.Combine(Path.GetDirectoryName(missingTranslationUnitFileRelativePath), missingTranslationUnitFileName));

                        // Add to collection for later processing
                        missingTranslationUnits.Add(currentReference.Declaration.Name, missingTranslationUnit);
                    }
                }
            }

            // Insert missing items
            Context.ASTContext.TranslationUnits.AddRange(missingTranslationUnits.Values);

            return(true);
        }