Ejemplo n.º 1
0
 /// <summary>
 /// Using a fully specified parameter list: value, name, and type.
 /// </summary>
 private void InitializeParameters(StringBuilder sb, List <ParamTypeInfo> parms)
 {
     parms.ForEachWithIndex((pti, idx) =>
     {
         sb.Append(pti.ParamType + " " + pti.ParamName + " = (" + pti.ParamType + ")paramList[" + idx + "];\r\n");
     });
 }
Ejemplo n.º 2
0
        protected async Task <ICoursesRepository> GetAndInitializeRepository()
        {
            var fakeRepository = new FakeRepository();
            var courses        = new List <Course> {
                new Course(
                    "Data Structures",
                    5000,
                    new DateTime(2021, 01, 26, 10, 30, 00),
                    new DateTime(2021, 01, 28, 15, 00, 00)
                    ),

                new Course(
                    "Math",
                    6000,
                    new DateTime(2021, 01, 26, 10, 30, 00),
                    new DateTime(2021, 01, 28, 15, 00, 00)
                    )
            };

            courses.ForEachWithIndex((x, index) => x.Id = index + 1);
            var tasks = courses.Select(x => fakeRepository.CreateCourse(x));
            await Task.WhenAll(tasks);

            return(fakeRepository);
        }
Ejemplo n.º 3
0
        // ======================================

        static int TaskAwaitGetNextWorkItemBruteForceThrowsException()
        {
            int numProcs = Environment.ProcessorCount;

            totalNumPrimes = 0;
            nextNumber     = 1;
            List <Task> tasks = new List <Task>();

            for (int i = 0; i < numProcs; i++)
            {
                var task = DoWorkAsyncThrowsException(i);
                tasks.Add(task);
            }

            try
            {
                Task.WaitAll(tasks.ToArray());
            }
            catch (AggregateException ex)
            {
                Console.WriteLine(ex.Message);

                tasks.ForEachWithIndex((t, i) =>
                {
                    Console.WriteLine("Task " + i);
                    Console.WriteLine("Is canceled: " + t.IsCanceled);
                    Console.WriteLine("Is completed: " + t.IsCompleted);
                    Console.WriteLine("Is faulted: " + t.IsFaulted);
                });
            }

            return(totalNumPrimes);
        }
Ejemplo n.º 4
0
        public void ConsistencyTest()
        {
            // Start with a tree with 2 leaves:
            MerkleTree tree          = new MerkleTree();
            var        startingNodes = tree.AppendLeaves(new MerkleHash[]
            {
                MerkleHash.Create("1"),
                MerkleHash.Create("2"),
            });

            // startingNodes.ForEachWithIndex((n, i) => n.Text = i.ToString());

            MerkleHash firstRoot = tree.BuildTree();

            List <MerkleHash> oldRoots = new List <MerkleHash>()
            {
                firstRoot
            };

            // Add a new leaf and verify that each time we add a leaf, we can get a consistency check
            // for all the previous leaves.
            for (int i = 2; i < 100; i++)
            {
                tree.AppendLeaf(MerkleHash.Create(i.ToString())); //.Text=i.ToString();
                tree.BuildTree();

                // After adding a leaf, verify that all the old root hashes exist.
                oldRoots.ForEachWithIndex((oldRootHash, n) =>
                {
                    List <MerkleProofHash> proof = tree.ConsistencyProof(n + 2);
                    MerkleHash hash, lhash, rhash;

                    if (proof.Count > 1)
                    {
                        lhash    = proof[proof.Count - 2].Hash;
                        int hidx = proof.Count - 1;
                        hash     = rhash = MerkleTree.ComputeHash(lhash, proof[hidx].Hash);
                        hidx    -= 2;

                        while (hidx >= 0)
                        {
                            lhash = proof[hidx].Hash;
                            hash  = rhash = MerkleTree.ComputeHash(lhash, rhash);

                            --hidx;
                        }
                    }
                    else
                    {
                        hash = proof[0].Hash;
                    }

                    Assert.True(hash == oldRootHash, "Old root hash not found for index " + i + " m = " + (n + 2).ToString());
                });

                // Then we add this root hash as the next old root hash to check.
                oldRoots.Add(tree.RootNode.Hash);
            }
        }
Ejemplo n.º 5
0
        // var trainListForIE = new string[list.Count];
        // list.ForEachWithIndex((item, idx) => {
        //  trainListForIE[idx] = $"{item.queryLeftNewDTO.station_train_code}({item.queryLeftNewDTO.start_time}--{item.queryLeftNewDTO.arrive_time})";
        // });
        // Console.WriteLine(trainListForIE[0]);

        private List <TicketDataModel> transfer(List <string> result, Dictionary <string, string> map)
        {
            List <TicketDataModel> list = new List <TicketDataModel>();
            TicketDataModel        tdm;

            result.ForEachWithIndex((item, idx) =>
            {
                string[] cm         = item.Split('|');
                tdm                 = new TicketDataModel();
                tdm.secretStr       = cm[0];
                tdm.buttonTextInfo  = cm[1];
                tdm.queryLeftNewDTO = new TicketNewModel
                {
                    train_no               = cm[2],
                    station_train_code     = cm[3],
                    start_station_telecode = cm[4],
                    end_station_telecode   = cm[5],
                    from_station_telecode  = cm[6],
                    to_station_telecode    = cm[7],
                    start_time             = cm[8],
                    arrive_time            = cm[9],
                    lishi                 = cm[10],
                    canWebBuy             = cm[11],
                    yp_info               = cm[12],
                    start_train_date      = cm[13],
                    train_seat_feature    = cm[14],
                    location_code         = cm[15],
                    from_station_no       = cm[16],
                    to_station_no         = cm[17],
                    is_support_card       = cm[18],
                    controlled_train_flag = cm[19],
                    gg_num                = !string.IsNullOrEmpty(cm[20]) ? cm[20] : "--",
                    gr_num                = !string.IsNullOrEmpty(cm[21]) ? cm[21] : "--",
                    qt_num                = !string.IsNullOrEmpty(cm[22]) ? cm[22] : "--",
                    rw_num                = !string.IsNullOrEmpty(cm[23]) ? cm[23] : "--",
                    rz_num                = !string.IsNullOrEmpty(cm[24]) ? cm[24] : "--",
                    tz_num                = !string.IsNullOrEmpty(cm[25]) ? cm[25] : "--",
                    wz_num                = !string.IsNullOrEmpty(cm[26]) ? cm[26] : "--",
                    yb_num                = !string.IsNullOrEmpty(cm[27]) ? cm[27] : "--",
                    yw_num                = !string.IsNullOrEmpty(cm[28]) ? cm[28] : "--",
                    yz_num                = !string.IsNullOrEmpty(cm[29]) ? cm[29] : "--",
                    ze_num                = !string.IsNullOrEmpty(cm[30]) ? cm[30] : "--",
                    zy_num                = !string.IsNullOrEmpty(cm[31]) ? cm[31] : "--",
                    swz_num               = !string.IsNullOrEmpty(cm[32]) ? cm[32] : "--",
                    yp_ex                 = cm[33],
                    seat_types            = cm[34],
                    from_station_name     = map[cm[6]],
                    to_station_name       = map[cm[7]]
                };
                list.Add(tdm);
            });
            return(list);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Create the sentence-keyword map (list of keywords in each sentence.)
        /// Create the keyword-sentence map (list of sentence indices for each keyword.)
        /// </summary>
        /// <param name="dvKeywords"></param>
        protected void CreateSentenceKeywordMaps(DataView dvKeywords)
        {
            sentenceKeywordMap.Clear();
            keywordSentenceMap.Clear();

            // For each sentence, get all the keywords in that sentence.
            pageSentences.ForEachWithIndex((s, idx) =>
            {
                List <string> keywordsInSentence = new List <string>();
                sentenceKeywordMap[idx]          = keywordsInSentence;
                string sl = s.ToLower();

                // For each of the returned keywords in the view...
                dvKeywords.ForEach(row =>
                {
                    string keyword = row[0].ToString();

                    if (sl.Contains(keyword.ToLower()))
                    {
                        // Add keyword to sentence-keyword map.
                        keywordsInSentence.Add(keyword);

                        // Add sentence to keyword-sentence map.
                        List <int> sentences;

                        if (!keywordSentenceMap.TryGetValue(keyword, out sentences))
                        {
                            // No entry for this keyword yet, so create the sentence indices list.
                            sentences = new List <int>();
                            keywordSentenceMap[keyword] = sentences;
                        }

                        sentences.AddIfUnique(idx);
                    }
                });
            });
        }
Ejemplo n.º 7
0
        public void PaintTopInGame(ClipState clipState)
        {
            watermark.DrawText(WATERMARK_TEXT, Hud.Window.Size.Width * 0.04f, Hud.Window.Size.Height * 0.966f);
            tableHeadingLayout = tableHeadingFont.GetTextLayout(heading);
            tableHeadingFont.DrawText(tableHeadingLayout, coordX, coordY);

            currentRowIndex = 0;

            var buffs = Hud.Game.Me.Powers.AllBuffs.Where(buff => buff.Active && !excludedBuffs.Contains(buff.SnoPower.Sno))
                        .OrderBy(power => power.SnoPower.Sno).ToList();

            if (initialBuffs.Count == 0)
            {
                initialBuffs.AddRange(buffs);
            }

            var tableEntries = new List <string>();

            buffs.ForEach(buff =>
            {
                if (!initialBuffs.Contains(buff))
                {
                    buffDelta.Add(buff);
                    return;
                }

                if (!(GetBuffRow(buff) is string row))
                {
                    return;
                }
                tableEntries.Add(row);
            });

            var deltaTableEntries = GetDeltaBuffTableEntries();

            background.DrawRectangle(coordX - 10, coordY - 10, Hud.Window.Size.Width * 0.7f,
                                     ((tableEntries.Count + deltaTableEntries.Count + 1) * 19f) + 20);

            tableEntries.ForEachWithIndex((entry, index) =>
            {
                var font = index % 2 == 0 ? tableRow : tableRowB;
                font.DrawText(entry, coordX, coordY + ((index + 1) * 19f));
            });

            deltaTableEntries.ForEachWithIndex((entry, index) =>
            {
                deltaTableRow.DrawText(entry, coordX, coordY + ((tableEntries.Count + index + 1) * 19f));
            });
        }
Ejemplo n.º 8
0
        //Extension methods enable you to "add" methods to
        //existing types without creating a new derived type, recompiling, or
        //otherwise modifying the original type. Extension methods are static methods,
        //but they're called as if they were instance methods on the extended type.
        static void Main(string[] args)
        {
            //String Extension Methods
            string text = "C# Advanced is an awesome subject with great demos and activities!";

            string TextToUpperCase = text.ToUpper();

            string TextToUpperCaseShortenExtensionMethod = TextToUpperCase.Shorten(3);

            string TextToUpperCaseShorten = Shorten(TextToUpperCase, 3);

            Console.WriteLine(TextToUpperCaseShorten);
            Console.WriteLine(TextToUpperCaseShortenExtensionMethod);

            string quotedString = TextToUpperCaseShorten.QuoteString();

            Console.WriteLine(quotedString);

            string newString = text.ToUpper().Shorten(4).QuoteString();

            Console.WriteLine(newString);

            //Generic Extension Method
            List <string> strings = new List <string>()
            {
                "str1", "str2", "str3"
            };
            List <int> ints = new List <int>()
            {
                5, 22, -18
            };
            List <bool> bools = new List <bool> {
                true, false, true
            };

            strings.GoThrough();
            ints.GoThrough();
            bools.GoThrough();

            strings.GetInfoFor();
            ints.GetInfoFor();
            bools.GetInfoFor();

            //Action<string, int> functionBody = (str, index) => Console.WriteLine($"{index + 1}) {str}");
            strings.ForEachWithIndex((str, index) => Console.WriteLine($"{index + 1}) {str}"));

            strings.ForEach(x => Console.WriteLine(x));
        }
Ejemplo n.º 9
0
        protected void ProcessTypeCollection()
        {
            foreach (SemanticTypeInstance typeInstance in Program.SemanticTypeSystem.Instances.Values)
            {
                ISemanticType instance = typeInstance.Instance;
                string        name     = typeInstance.Name;

                if (!ignoreNames.Contains(name))
                {
                    // A distinct type name, used for coloration logic.
                    distinctTypes.AddIfUnique(name);

                    // Also, for each type, we have a specific location to group all instances of that type.
                    if (!typeGroups.ContainsKey(name))
                    {
                        typeGroups[name] = new TypeGroup();
                        AdjustGroupLocations();
                        ResetAllTargets();
                    }

                    VisualSemanticType vst = new VisualSemanticType(instance, name);
                    vtypes.Add(vst);                                    // Only the collections go in this space.

                    // Add all the collection elements.
                    if (name == "PopulationByStateByYear")
                    {
                        // This is a collection.
                        List <ISemanticType> stList = (List <ISemanticType>)((dynamic)vst.SemanticType).Collection.Items;
                        int items = stList.Count;

                        stList.ForEachWithIndex((st, idx2) =>
                        {
                            // Create the collection types.  This is for every item in the collection, so many will be repeated (like year and state)
                            string subname = Program.SemanticTypeSystem.GetSemanticTypeName(st);
                            distinctTypes.AddIfUnique(subname);
                            VisualSemanticType vst2  = new VisualSemanticType(st, subname);
                            CollectionSubtype cs     = new CollectionSubtype(instance, st);
                            typeVisualizationMap[cs] = vst2;
                            // vtypes.Add(vst2);
                        });
                    }
                }
            }
        }
Ejemplo n.º 10
0
        public void UpdateWorldPlaces()
        {
            knownPlaces.ForEach(place =>
            {
                //distance + bearing calculation
                var distance   = Scholar.Distance(deviceLocation, place.Location, 'm');
                var bearing    = Scholar.BearingTo(deviceLocation, place.Location);
                place.Distance = (float)distance;
                place.Bearing  = (float)bearing;
                // TODO: 179 ?
                var bearingRadians = Scholar.Deg2Rad(bearing) + 179;

                // Rotate POI's
                var xRot = -Math.Sin(bearingRadians) * (distance - 0) + 0;
                var zRot = +Math.Cos(bearingRadians) * (distance - 0) + 0;
                place.transform.localPosition = new Vector3((float)-xRot, 0, (float)zRot);
            });
            knownPlaces.Sort((a, b) => a.Distance.CompareTo(b.Distance));
            knownPlaces.ForEachWithIndex((place, index) =>
            {
                SetPlaceSettingsAt(index);
            });
        }
Ejemplo n.º 11
0
        void RecognizeNumber()
        {
            List <int> resultRecognition = new List <int>();

            for (int i = 1; i <= 10; i++)
            {
                string        path    = @"C:\Users\Kamil\source\repos\NumberRecognitionApp\data" + i.ToString();
                List <double> weights = _util.ReadFromFile(path);

                double product = 0;
                for (int j = 0; j < _tab.Length; j++)
                {
                    product += _tab[j] * weights[j];
                    //Console.WriteLine(weights[j]);
                }

                if (product < weights[45])
                {
                    Console.WriteLine(0);
                    resultRecognition.Add(0);
                }
                else
                {
                    Console.WriteLine(1);
                    resultRecognition.Add(1);
                }
            }
            Console.WriteLine("----------------------------------------------------------");
            recognizedNumbersBox.Text = string.Empty;
            resultRecognition.ForEachWithIndex((item, idx) =>
            {
                if (item == 1)
                {
                    recognizedNumbersBox.Text += idx.ToString() + "; ";
                }
            });
        }
Ejemplo n.º 12
0
        protected void DrawDhts()
        {
            WebSocketHelpers.ClearCanvas();
            Application.DoEvents();
            connections = new List<Peer2Peer>();

            if (!ckNodesTopmost.Checked)
            {
                dhtPos.ForEachWithIndex((p, i) => WebSocketHelpers.DropShape("Ellipse", i.ToString(), p, peerColor[dhts[i].ID.Value], ""));
            }

            Application.DoEvents();


            if (ckShowConnections.Checked)
            {
                // First the original connections...
                // dhts.Where(d=>!bucketRefreshPeers.Contains(d)).ForEachWithIndex((d, i) =>
                dhts.ForEachWithIndex((d, i) =>
                {
                    d.Node.BucketList.Buckets.SelectMany(b => b.Contacts).ForEach(c =>
                      {
                          int idx = dhts.FindIndex(target => target.ID == c.ID);
                          var otherDir = new Peer2Peer() { idx1 = idx, idx2 = i };

                      // Don't draw connector going back (idx -> i) because this is a redundant draw.  Speeds things up a little.
                      if (!connections.Contains(otherDir))
                          {
                              Point c1 = dhtPos[i].Center();
                              Point c2 = dhtPos[idx].Center();
                              WebSocketHelpers.DropConnector("DiagonalConnector", "c" + i, c1.X, c1.Y, c2.X, c2.Y, Color.Gray);
                              connections.Add(new Peer2Peer() { idx1 = i, idx2 = idx });
                              Application.DoEvents();
                          }
                      });
                });
            }

            if (ckNodesTopmost.Checked)
            {
                dhtPos.ForEachWithIndex((p, i) => WebSocketHelpers.DropShape("Ellipse", i.ToString(), p, peerColor[dhts[i].ID.Value], ""));
            }

            Application.DoEvents();

            /*
            // Then the bucket refresh connections:
            dhts.Where(d => bucketRefreshPeers.Contains(d)).ForEachWithIndex((d, i) =>
            {
                d.Node.BucketList.Buckets.SelectMany(b => b.Contacts).ForEach(c =>
                {
                    int idx = dhts.FindIndex(target => target.ID == c.ID);
                    var otherDir = new Peer2Peer() { idx1 = idx, idx2 = i };

                    // Don't draw connector going back (idx -> i) because this is a redundant draw.  Speeds things up a little.
                    if (!connections.Contains(otherDir))
                    {
                        Point c1 = dhtPos[i].Center();
                        Point c2 = dhtPos[idx].Center();
                        WebSocketHelpers.DropConnector("DiagonalConnector", "c" + i, c1.X, c1.Y, c2.X, c2.Y, Color.Purple);
                        connections.Add(new Peer2Peer() { idx1 = i, idx2 = idx });
                    }
                });
            });
            */
        }
Ejemplo n.º 13
0
        private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) {
            var selected = new List<object>(TileList.SelectedItems);

            var picker = new FileSavePicker();
            picker.SuggestedFileName = $"export_{DateTime.Now.ToString(DateTimeFormatInfo.CurrentInfo.ShortDatePattern)}";
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeChoices.Add("Tiles file", new List<string>() { ".tiles" });
            var file = await picker.PickSaveFileAsync();
            if (file != null) {
                CachedFileManager.DeferUpdates(file);

                await FileIO.WriteTextAsync(file, "");
                
                using (var stream = await file.OpenStreamForWriteAsync())
                using (var zip = new ZipArchive(stream, ZipArchiveMode.Update)) {

                    while (zip.Entries.Count > 0) {
                        zip.Entries[0].Delete();
                    }

                    using (var metaStream = zip.CreateEntry("tiles.json").Open())
                    using (var writer = new StreamWriter(metaStream)) {
                        var array = new JsonArray();

                        selected.ForEachWithIndex<SecondaryTile>((item, index) => {
                            var objet = new JsonObject();
                            objet.Add("Name", item.DisplayName);
                            objet.Add("Arguments", item.Arguments);
                            objet.Add("TileId", item.TileId);
                            objet.Add("IconNormal", item.VisualElements.ShowNameOnSquare150x150Logo);
                            objet.Add("IconWide", item.VisualElements.ShowNameOnWide310x150Logo);
                            objet.Add("IconBig", item.VisualElements.ShowNameOnSquare310x310Logo);
                            
                            array.Add(objet);

                            if (item.VisualElements.Square150x150Logo.LocalPath != DEFAULT_URI) {
                                var path = ApplicationData.Current.LocalFolder.Path + Uri.UnescapeDataString(item.VisualElements.Square150x150Logo.AbsolutePath.Substring(6));
                                
                                zip.CreateEntryFromFile(path, item.TileId + "/normal");
                            }
                        });
                        writer.WriteLine(array.Stringify());
                        
                    }

                    FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                    if(status == FileUpdateStatus.Complete) {
                        var folder = await file.GetParentAsync();
                        await new MessageDialog("Speichern erfolgreich").ShowAsync();
                    } else {
                        await new MessageDialog("Speichern fehlgeschlagen").ShowAsync();
                    }

                    Debug.WriteLine(status);
                }
            }
        }
Ejemplo n.º 14
0
        public void Query(string from_station, string to_station, string date = null, string types = null, int orderby = 0)
        {
            if (inBreakTime())
            {
                Console.WriteLine("12306.cn网站每日06:00~23:00提供服务!");
                return;
            }

            // 初始化车站映射表
            Dictionary <string, string> stationMaps = StationMaps();

            // 起点站是否开启严格过滤模式
            bool strict_from_station = from_station.StartsWith("^");
            // 到达站是否开启严格过滤模式
            bool strict_to_station = to_station.StartsWith("^");

            if (strict_from_station)
            {
                from_station = from_station.Substring(1, from_station.Length - 1);
            }
            if (strict_to_station)
            {
                to_station = to_station.Substring(1, to_station.Length - 1);
            }

            string from_station_code = stationMaps.ContainsKey(from_station) ? stationMaps[from_station] : null;
            string to_station_code   = stationMaps.ContainsKey(to_station) ? stationMaps[to_station] : null;

            if (string.IsNullOrEmpty(from_station_code))
            {
                throw new Exception("错误的起点站");
            }
            if (string.IsNullOrEmpty(to_station_code))
            {
                throw new Exception("错误的到达站");
            }

            DateTime maxDate    = DateTime.Now.AddDays(29);
            string   minDateStr = DateTime.Now.ToString("yyyy-MM-dd");
            string   maxDateStr = maxDate.ToString("yyyy-MM-dd");

            Console.WriteLine($"预售日期范围:{minDateStr} 至 {maxDateStr}");

            if (!IsDate(date) || date.Equals("now"))
            {
                date = DateTime.Now.ToString("yyyy-MM-dd");
                Console.WriteLine($"本次查询采用默认日期:{date} (今日)");
                // throw new Exception("不正确的日期,日期格式必须为 YYYY-mm-dd");
            }
            else
            {
                if (DateTime.Parse(date) < DateTime.Now.Date)
                {
                    throw new Exception("不正确的日期,日期不能小于今日");
                }
                if (DateTime.Parse(date) > maxDate)
                {
                    throw new Exception("不正确的日期,查询日期不在预售日期范围内");
                }
                date = DateTime.Parse(date).ToString("yyyy-MM-dd");
                Console.WriteLine($"日期:{date}");
            }

            Console.WriteLine($"旅程:{from_station} ({from_station_code}) -> {to_station} ({to_station_code})");

            // 列车类型
            string[] train_types = null;
            if (!string.IsNullOrWhiteSpace(types))
            {
                train_types = types.Split(',');
            }

            Task <string> task;

            while (true)
            {
                var url = $"{basicUrl}?leftTicketDTO.train_date={date}&leftTicketDTO.from_station={from_station_code}&leftTicketDTO.to_station={to_station_code}&purpose_codes=ADULT";
                task = httpUtil.Get(url);
                if (task.Result != null)
                {
                    break;
                }
                else
                {
                    Console.WriteLine("失败,正在重试...");
                }
            }
            TicketModel            tm   = JsonConvert.DeserializeObject <TicketModel>(task.Result);
            List <TicketDataModel> list = tm.GetTickets();

            // 精确筛选车站、车次类型
            list = list.Where(s =>
            {
                bool to         = strict_from_station ? from_station.Equals(s.queryLeftNewDTO.from_station_name) : true;
                bool arrive     = strict_to_station ? to_station.Equals(s.queryLeftNewDTO.to_station_name) : true;
                bool train_type = train_types != null ? train_types.Contains(s.queryLeftNewDTO.station_train_code.Substring(0, 1)) : true;
                return(to && arrive && train_type);
            }).OrderBy(o => {
                switch (orderby)
                {
                case 1:
                    return(o.queryLeftNewDTO.start_time);

                    break;

                case 2:
                    return(o.queryLeftNewDTO.arrive_time);

                    break;

                case 3:
                    return(o.queryLeftNewDTO.lishi);

                    break;

                default:
                    return(null);

                    break;
                }
            }).ToList();

            Console.WriteLine("点击购票: https://kyfw.12306.cn/otn/login/init");
            Console.WriteLine($"根据各筛选条件本次共查询到{list.Count}趟列车,详细列表如下:");
            Console.WriteLine();

            List <string> columns = new List <string> {
                "车次", "出发站", "到达站", "出发时间", "到达时间", "历时", "商务座", "特等座", "一等座", "二等座", "高级软卧", "软卧", "硬卧", "软座", "硬座", "无座", "其他", "是否可预定"
            };

            list.ForEachWithIndex((item, idx) =>
            {
                TicketNewModel model = item.queryLeftNewDTO;
                List <string> values = new List <string> {
                    model.station_train_code,
                    model.from_station_name,
                    model.to_station_name,
                    model.start_time,
                    model.arrive_time,
                    model.lishi,
                    model.swz_num,
                    model.tz_num,
                    model.zy_num,
                    model.ze_num,
                    model.gr_num,
                    model.rw_num,
                    model.yw_num,
                    model.rz_num,
                    model.yz_num,
                    model.wz_num,
                    model.qt_num,
                    string.IsNullOrEmpty(item.secretStr) ? "N" : "Y"
                };
            });
            // draw table
            Console.WriteLine(list.ToStringTable(
                                  columns.ToArray(),
                                  row => row.queryLeftNewDTO.station_train_code,
                                  row => row.queryLeftNewDTO.from_station_name,
                                  row => row.queryLeftNewDTO.to_station_name,
                                  row => row.queryLeftNewDTO.start_time,
                                  row => row.queryLeftNewDTO.arrive_time,
                                  row => row.queryLeftNewDTO.lishi,
                                  row => row.queryLeftNewDTO.swz_num,
                                  row => row.queryLeftNewDTO.tz_num,
                                  row => row.queryLeftNewDTO.zy_num,
                                  row => row.queryLeftNewDTO.ze_num,
                                  row => row.queryLeftNewDTO.gr_num,
                                  row => row.queryLeftNewDTO.rw_num,
                                  row => row.queryLeftNewDTO.yw_num,
                                  row => row.queryLeftNewDTO.rz_num,
                                  row => row.queryLeftNewDTO.yz_num,
                                  row => row.queryLeftNewDTO.wz_num,
                                  row => row.queryLeftNewDTO.qt_num,
                                  row => string.IsNullOrEmpty(row.secretStr) ? "N" : "Y"
                                  ));
        }
Ejemplo n.º 15
0
        protected bool Step()
        {
            bool more = true;

            //  TODO: These 4 lines are duplicate code.  Refactor into a SizeChanged event handler.
            int hw = Visualizer.ClientRectangle.Width / 2;
            int hh = Visualizer.ClientRectangle.Height / 2;
            int n  = (hw < hh ? hw : hh);
            int m  = (n / 5);                                                   // the radius of the group's circle.

            vtypes.ForEachWithIndex((vtype, idx) =>
            {
                more = false;                   // points to plot
                if (vtype.StepNumber == 0)
                {
                    // Initialize the starting location if it's a new entry.

                    //if (targetState == false)
                    //{
                    //	// RANDOM POINT IN SPACE
                    //	vtype.TargetLocation = new Point(rnd.Next(-hw, hw), rnd.Next(-hh, hh));
                    //}
                    //else
                    {
                        if (vtype.Name == "PopulationByStateByYear")
                        {
                            // This is a collection.
                            List <ISemanticType> stList = (List <ISemanticType>)((dynamic)vtype.SemanticType).Collection.Items;
                            int items = stList.Count;

                            if (targetState == false)
                            {
                                // The collection goes somewhere random.
                                vtype.TargetLocation = new Point(rnd.Next(-hw, hw), rnd.Next(-hh, hh));
                            }

                            stList.ForEachWithIndex((st, idx2) =>
                            {
                                if (targetState == false)
                                {
                                    // Set an initial random point for the item in the collection.
                                    CollectionSubtype cs = new CollectionSubtype(vtype.SemanticType, st);
                                    typeVisualizationMap[cs].TargetLocation = new Point(rnd.Next(-hw, hw), rnd.Next(-hh, hh));
                                }
                                else
                                {
                                    // Draw each type on the edge of a small circle surrounding the collection type.
                                    Point p         = vtype.TargetLocation;
                                    Point pOnCircle = GetPointOnCircle(10, idx2, items);
                                    p.Offset(pOnCircle);
                                    // p.Offset(hw, hh);										// translate to LL corner at (0, 0)
                                    // p.Offset(-20, -20);			// UL of the circle offset.
                                    CollectionSubtype cs = new CollectionSubtype(vtype.SemanticType, st);
                                    typeVisualizationMap[cs].TargetLocation = p;
                                }
                            });
                        }
                    }


                    // RANDOM POINT WITHIN A LOCAL GROUP:

                    /*
                     * Point groupPoint = typeGroups[vtype.Name].Location;
                     * // We can figure out a random target within a circle centered here.
                     * double randomAngle = rnd.NextDouble() * 3.14159265 * 2;
                     * Point p = new Point((int)(rnd.Next(-m, m) * Math.Cos(randomAngle)), (int)(rnd.Next(-m, m) * Math.Sin(randomAngle)));
                     * // Center on the group point.
                     * p.Offset(groupPoint);
                     * vtype.TargetLocation = p;
                     */

                    // RANDOM POINT ON A CIRCLE.

                    /*
                     * int l = n - n / 6;
                     * l = (int)(l * (((idx % 3) + 1) / 3.0));		// split each radial into 3 locations along the radial.
                     * double angle = 3.14159265 * 2 * idx / vtypes.Count;
                     * Point p = new Point((int)(l * Math.Cos(angle)), (int)(l * Math.Sin(angle)));
                     * p.Offset(-20, -20);
                     * vtype.TargetLocation = p;
                     */
                }

                if (vtype.StepNumber < RenderTime)
                {
                    more = true;
                    ++vtype.StepNumber;
                    // A quasi acceleration curve:
                    double stepper = Math.Sin(((3.14159265 / 2.0) * ((double)vtype.StepNumber) / (double)RenderTime));

                    // This is the collection.
                    vtype.Location = new Point((int)(vtype.StartLocation.X + (vtype.TargetLocation.X - vtype.StartLocation.X) * stepper), ((int)(vtype.StartLocation.Y + (vtype.TargetLocation.Y - vtype.StartLocation.Y) * stepper)));

                    // These are the collection items.
                    List <ISemanticType> stList = (List <ISemanticType>)((dynamic)vtype.SemanticType).Collection.Items;
                    int items = stList.Count;
                    stList.ForEach((st) =>
                    {
                        CollectionSubtype cs   = new CollectionSubtype(vtype.SemanticType, st);
                        VisualSemanticType vst = typeVisualizationMap[cs];
                        vst.Location           = new Point((int)(vst.StartLocation.X + (vst.TargetLocation.X - vst.StartLocation.X) * stepper), ((int)(vst.StartLocation.Y + (vst.TargetLocation.Y - vst.StartLocation.Y) * stepper)));
                    });
                }
            });

            return(more);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Using a fully specified parameter list: value, name, and type.
 /// </summary>
 private void InitializeParameters(StringBuilder sb, List<ParamTypeInfo> parms)
 {
     parms.ForEachWithIndex((pti, idx) =>
         {
             sb.Append(pti.ParamType + " " + pti.ParamName + " = (" + pti.ParamType+")paramList[" + idx + "];\r\n");
         });
 }
Ejemplo n.º 17
0
        protected void OnVisualizerPaint(object sender, PaintEventArgs e)
        {
            Control ctrl = (Control)sender;
            int     hw   = ctrl.ClientRectangle.Width / 2;
            int     hh   = ctrl.ClientRectangle.Height / 2;

            e.Graphics.FillRectangle(blackBrush, new Rectangle(Location, Size));

/*
 *                      // Plot an "X" where the group coordinates are located.
 *                      foreach (TypeGroup tg in typeGroups.Values)
 *                      {
 *                              Point p = tg.Location;
 *                              p.Offset(hw, hh);
 *                              e.Graphics.DrawString("X", font, whiteBrush, p);
 *                      }
 */
            foreach (VisualSemanticType vtype in vtypes)
            {
                if (vtype.Name == "PopulationByStateByYear")
                {
                    // This is a collection.
                    List <ISemanticType> stList = (List <ISemanticType>)((dynamic)vtype.SemanticType).Collection.Items;
                    int     items   = stList.Count;
                    Point[] objects = new Point[items];

                    stList.ForEachWithIndex((st, idx) =>
                    {
                        // W're going to draw the lines between each item in the collection.
                        CollectionSubtype cs = new CollectionSubtype(vtype.SemanticType, st);
                        Point p = typeVisualizationMap[cs].Location;
                        p.Offset(objectSize.Width / 2, objectSize.Height / 2);          // UL corner of the area for the circle.
                        p.Offset(hw, hh);                                               // translate to LL corner at (0, 0)
                        p.Offset(-20, -20);                                             // UL of the circle offset.
                        objects[idx] = p;

                        // Draw each type on the edge of a small circle surrounding the collection type.
                        //string name = Program.SemanticTypeSystem.GetSemanticTypeName(st);
                        //distinctTypes.AddIfUnique(name);
                        //Pen pen = penColors[distinctTypes.IndexOf(name) % distinctTypes.Count];
                        //Point p = vtype.Location;
                        //Point pOnCircle = GetPointOnCircle(10, idx, items);
                        //p.Offset(pOnCircle);
                        //p.Offset(hw, hh);										// translate to LL corner at (0, 0)
                        //p.Offset(-20, -20);			// UL of the circle offset.
                        //objects[idx] = p;
                        //e.Graphics.DrawEllipse(pen, new Rectangle(p, objectSize));
                    });

                    stList.ForEachWithIndex((st, idx) =>
                    {
                        string subname = Program.SemanticTypeSystem.GetSemanticTypeName(st);

                        int n    = (idx + 1) % items;
                        Point p1 = objects[idx];
                        Point p2 = objects[n];
                        p1.Offset(10, 10);
                        p2.Offset(10, 10);
                        e.Graphics.DrawLine(whitePen, p1, p2);

                        Pen pen = penColors[distinctTypes.IndexOf(subname) % distinctTypes.Count];
                        Point p = objects[idx];
                        e.Graphics.DrawEllipse(pen, new Rectangle(p, objectSize));
                    });
                }

                // else
                {
                    // This is just the collection instance.
                    Pen   pen = penColors[distinctTypes.IndexOf(vtype.Name) % distinctTypes.Count];
                    Point p   = vtype.Location;
                    p.Offset(objectSize.Width / 2, objectSize.Height / 2);      // UL corner of the area for the circle.
                    p.Offset(hw, hh);                                           // translate to LL corner at (0, 0)
                    p.Offset(-20, -20);                                         // UL of the circle offset.
                    e.Graphics.DrawEllipse(pen, new Rectangle(p, objectSize));
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        ///
        /// </summary>
        public int Read(float[] buffer, int offset, int count)
        {
            var numberOfStoredSamples = 0;

            if (count > 0 && this.sourceList.Any())
            {
                // 読み取りバッファを確保
                this.mixerBuffer = this.mixerBuffer.CheckBuffer(count);
                Array.Clear(this.mixerBuffer, 0, count);

                var numberOfReadSamples = new List <int>();
                foreach (var pair in this.sourceList.ToArray())
                {
                    var backend = pair.Key;
                    var source  = pair.Value;

                    // バッファ読み込み時は、すでに読み込んだ部分だけ加算するようにします。
                    var read = source.Read(this.mixerBuffer, 0, count);
                    for (var n = 0; n < read; ++n)
                    {
                        var initial = (numberOfStoredSamples <= n + offset ? 0 : buffer[n + offset]);
                        var add     = this.mixerBuffer[n] * backend.Volume;

                        buffer[n + offset] = (float)(initial + add); // MathEx.Between(-1.0f, +1.0f, (float)(initial + add));
                    }

                    numberOfStoredSamples = Math.Max(numberOfStoredSamples, read);

                    if (read > 0)
                    {
                        numberOfReadSamples.Add(read);
                    }
                    else if (source.Position >= source.Length)
                    {
                        // remove the input to make sure that the event gets only raised once.
                        RemoveSource(backend);
                    }
                }

                if (false)
                {
                    var currentOffset = offset;

                    numberOfReadSamples.Sort();
                    numberOfReadSamples.ForEachWithIndex((readSamples, i) =>
                    {
                        while (currentOffset < offset + readSamples)
                        {
                            buffer[currentOffset] /= numberOfReadSamples.Count - i;
                            buffer[currentOffset]  = MathEx.Between(-1.0f, +1.0f, buffer[currentOffset]);
                            ++currentOffset;
                        }
                    });
                }
            }

            /*if (numberOfStoredSamples != count)
             * {
             *  Array.Clear(
             *      buffer,
             *      Math.Max(offset + numberOfStoredSamples, 0),
             *      count - numberOfStoredSamples);
             *
             *  return count;
             * }*/

            return(numberOfStoredSamples);
        }