コード例 #1
0
ファイル: Program.cs プロジェクト: skovach/acm.timus
        static void Main(string[] args)
        {
            var species = new Dictionary<string, int>()
            {
                {"Emperor Penguin", 0},
                {"Little Penguin", 1},
                {"Macaroni Penguin", 2},
            };
            var result = new int[3];
            int n = int.Parse(Console.ReadLine());
            var notebook = new List<string>();
            for (int i = 0; i < n; i++)
            {
                notebook.Add(Console.ReadLine());
            }

            foreach (var peng in notebook)
            {
                int index = species.SingleOrDefault(p => p.Key == peng).Value;
                result[index]++;
            }

            var maxNotes = Array.FindIndex(result, r => r == result.Max());
            var output = species.SingleOrDefault(s => s.Value == maxNotes).Key;
            Console.WriteLine(output);


        }
コード例 #2
0
        public (List <int>, string) Recognize(string ModelPath, string SetelPath, string TopPath)
        {
            var model = models?.SingleOrDefault(a => a.Key == ModelPath).Value;

            if (model == null)
            {
                return(null, "Error: Model not exist");
            }

            return(model.Recognize(SetelPath), "");
        }
コード例 #3
0
        protected List<TicketAttachment> GetFilesFromForm(ControllerContext controllerContext)
        {
            var request = controllerContext.HttpContext.Request;

            var formElements = new Dictionary<string, object>();
            request.Form.CopyTo(formElements);

            List<TicketAttachment> files = new List<TicketAttachment>();

            var fileIdElements = formElements.Where(fe => fe.Key.StartsWith("fileId_") || fe.Key.StartsWith("newFileId_"));
            foreach (var fileIdElement in fileIdElements)
            {
                string fileId = fileIdElement.Value as string;
                var fileNamePair = formElements.SingleOrDefault(fe => fe.Key == "fileName_" + fileId || fe.Key == "newFileName_" + fileId);
                var fileDescPair = formElements.SingleOrDefault(fe => fe.Key == "fileDescription_" + fileId || fe.Key == "newFileDescription_" + fileId);
                if (!string.IsNullOrEmpty(fileNamePair.Key) && !string.IsNullOrEmpty(fileNamePair.Key))
                {
                    string fileName = fileNamePair.Value as string;
                    string fileDescription = fileDescPair.Value as string;
                    files.Add(new TicketAttachment { FileId = Convert.ToInt32(fileId), FileName = fileName, FileDescription = fileDescription });
                }
            }
            return files;
        }
コード例 #4
0
        public static void StartCLI()
        {
            int    commandReturn = 0;
            string command;

            do
            {
                command = Console.ReadLine();

                if (commands.ContainsKey(command))
                {
                    commandReturn = commands.SingleOrDefault(p => p.Key == command).Value.Run();
                }
                else
                {
                    Printer.Printer.WriteLine($"'{command}' not recognized as command", Printer.Printer.PrintType.Error);
                }
            } while (commandReturn != COMMAND_FATAL_ERROR || commandReturn != COMMAND_EXIT);
        }
コード例 #5
0
 public void Timeout(CustomerRemorsedTimedOut state)
 {
     if (!Data.OrderCancelled)
     {
         Console.WriteLine("Remorse timeout for order: " + state.OrderId);
         var order = _orders.SingleOrDefault(y => y.Key == state.OrderId).Value;
         if (order != null)
         {
             Bus.Publish <OrderAccepted>(m =>
             {
                 m.CustomerId = order.CustomerId;
                 m.ProductId  = order.ProductId;
                 m.OrderValue = order.OrderValue;
                 m.OrderId    = order.OrderId;
             });
             Data.OrderAccepted = true;
         }
     }
 }
コード例 #6
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null)
            {
                return(OrderStatus.Unknown);
            }

            var statusString = reader.Value.ToString();
            var split        = statusString.Split(new[] { " @ " }, StringSplitOptions.RemoveEmptyEntries);
            var result       = mapping.SingleOrDefault(m => m.Key == split[0]);

            if (result.Equals(default(KeyValuePair <string, OrderStatus>)))
            {
                Debug.WriteLine($"Couldn't deserialize order status: {reader.Value}");
                return(OrderStatus.Unknown);
            }

            return(result.Value);
        }
コード例 #7
0
ファイル: DeviceBase.cs プロジェクト: MadhumiPerera/Second
        /// <summary>
        /// Cross synchonize DeviceProperties and ReportedProperties
        /// </summary>
        /// <returns></returns>
        protected void CrossSyncProperties(TwinCollection patch, TwinCollection reported, bool regenerate)
        {
            var devicePropertiesType = DeviceProperties.GetType();
            var reportedPairs        = reported.AsEnumerableFlatten().ToDictionary(pair => pair.Key, pair => pair.Value);

            if (!regenerate)
            {
                // Overwrite regenerated DeviceProperties by current ReportedProperties
                foreach (var pair in reportedPairs)
                {
                    string devicePropertyName = _propertyMapping.SingleOrDefault(p => p.Value == pair.Key).Key;
                    if (string.IsNullOrWhiteSpace(devicePropertyName))
                    {
                        continue;
                    }

                    try
                    {
                        DeviceProperties.SetProperty(devicePropertyName, pair.Value.Value);
                    }
                    catch
                    {
                        // Ignore any failure while overwriting the DeviceProperties
                    }
                }
            }

            // Add missing DeviceProperties to ReportedProperties
            foreach (var property in devicePropertiesType.GetProperties())
            {
                string reportedName;
                if (!_propertyMapping.TryGetValue(property.Name, out reportedName))
                {
                    continue;
                }

                var value = property.GetValue(DeviceProperties);
                if (regenerate || value != null && !reportedPairs.ContainsKey(reportedName))
                {
                    patch.Set(reportedName, value);
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// triggers an event
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool Trigger(string input)
        {
            List <IObservable> inputListeners = listeners.SingleOrDefault(p => p.Key == input).Value;

            if (inputListeners == null || inputListeners.Count == 0)
            {
                return(false);
            }

            foreach (IObservable observable in inputListeners)
            {
                if (!observable.Execute())
                {
                    return(true);
                }
            }

            return(true);
        }
コード例 #9
0
        public (bool isRegistered, bool isModal) StackContainsNavKey(string pageKey)
        {
            bool isUsedModal  = false;
            bool isRegistered = false;

            _lock.Wait();
            try
            {
                isRegistered = _pagesByKey.ContainsKey(pageKey);


                if (isRegistered)
                {
                    var pageType = _pagesByKey.SingleOrDefault(p => p.Key == pageKey).Value;

                    var foundInNavStack   = _navigationPage.Navigation.NavigationStack.Any(p => p.GetType() == pageType);
                    var foundInModalStack = _navigationPage.Navigation.ModalStack.Any(p => p.GetType() == pageType);

                    if (foundInNavStack && !foundInModalStack || !foundInNavStack && !foundInModalStack)
                    {
                        isUsedModal = false;
                    }
                    else if (foundInModalStack && !foundInNavStack)
                    {
                        isUsedModal = true;
                    }
                    else
                    {
                        throw new NotSupportedException("Pages should be used exclusively Modal or for Navigation");
                    }
                }
                else
                {
                    throw new ArgumentException($"No page with key: {pageKey}. Did you forget to call the Configure method?", nameof(pageKey));
                }
            }
            finally
            {
                _lock.Release();
            }

            return(isRegistered, isUsedModal);
        }
コード例 #10
0
        public async Task <Dictionary <long, string> > GetProductNames(List <long> productIds)
        {
            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme, IdentityService.Token);

            var param = "";

            foreach (var id in productIds)
            {
                param = string.Concat(param, $"garmentProductList[]={id}&");
            }
            param = param.Trim('&');

            var httpResponseMessage = await httpClient.GetAsync($@"{APIEndpoint.Core}master/garmentProducts/byId?{param}");

            if (httpResponseMessage.StatusCode.Equals(HttpStatusCode.OK))
            {
                var result = httpResponseMessage.Content.ReadAsStringAsync().Result;
                Dictionary <string, object> resultDict = JsonConvert.DeserializeObject <Dictionary <string, object> >(result);

                var data = resultDict.SingleOrDefault(p => p.Key.Equals("data")).Value;

                List <Dictionary <string, object> > dataDicts = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(data.ToString());

                var productDicts = new Dictionary <long, string>();

                foreach (var dataDict in dataDicts)
                {
                    var Id = dataDict["Id"] != null?Convert.ToInt64(dataDict["Id"].ToString()) : 0;

                    var Name = dataDict["Name"] != null ? dataDict["Name"].ToString() : "";

                    productDicts.Add(Id, Name);
                }

                return(productDicts);
            }
            else
            {
                return(new Dictionary <long, string>());
            }
        }
コード例 #11
0
 private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     try
     {
         string name = e.AddedItems[0].ToString();
         if (!string.IsNullOrEmpty(name))
         {
             if (dct_drivers.ContainsValue(name))
             {
                 string plate = dct_drivers.SingleOrDefault(r => r.Value == name).Key;
                 textBox1.Text = plate;
             }
         }
     }
     catch (System.Exception ex)
     {
         log.Error(ex);
     }
 }
コード例 #12
0
        private void DisplayForecast(string xml)
        {
            XmlDocument xml_doc = new XmlDocument();

            xml_doc.LoadXml(xml);

            XmlNode loc_node = xml_doc.SelectSingleNode("weatherdata/location");

            labelViTri.Text = "Thành phố Hồ Chí Minh, " + loc_node.SelectSingleNode("country").InnerText;


            // lvwForecast.Items.Clear();
            string degrees = (char)176 + "C";



            foreach (XmlNode time_node in xml_doc.SelectNodes("//time"))
            {
                DateTime time =
                    DateTime.Parse(time_node.Attributes["from"].Value,
                                   null, DateTimeStyles.AssumeUniversal);

                if (DateTime.Compare(DateTime.Now, time) == 1)
                {
                    //Lấy nhiệt độ
                    XmlNode temp_node = time_node.SelectSingleNode("temperature");
                    string  temp      = temp_node.Attributes["value"].Value;
                    //chuyển từ độ F sang C
                    double tempC = (Convert.ToDouble(temp) * 1.0 - 32) / 1.8;
                    temp = tempC.ToString();

                    // Lấy biểu tượng thời tiết hiện tại
                    XmlNode sym_node = time_node.SelectSingleNode("symbol");
                    string  var      = sym_node.Attributes["var"].Value;
                    string  path     = var + ".png";
                    string  state    = icon.SingleOrDefault(p => p.Key == var).Value;
                    labelTinhTrang.Text = state;

                    pictureBox1.Image = new Bitmap(Application.StartupPath + "\\iconWeather\\" + path);
                    break;
                }
            }
        }
コード例 #13
0
ファイル: PageFactory.cs プロジェクト: SkyJPark/BMSMonitor
        public static Page GetPage(string name)
        {
            var selectedPage = menuDictionary.SingleOrDefault(r => r.Key == name).Value;

            if (selectedPage == null)
            {
                Page newPage = null;
                switch (name)
                {
                case "Resistance":
                    newPage = new ResistancePage();
                    break;

                case "Bank":
                    newPage = new BankPage();
                    break;

                case "Mode":
                    newPage = new ModePage();
                    break;

                case "TestMeasure":
                    newPage = new TestMeasurePage();
                    break;

                case "OutContact":
                    newPage = new OutContactPage();
                    break;

                case "VoltagePhaseCompensation":
                    newPage = new VoltagePhaseCompensationPage();
                    break;

                default:
                    break;
                }
                menuDictionary.Add(name, newPage);
                selectedPage = newPage;
            }

            return(selectedPage);
        }
コード例 #14
0
        private static string CreateInsertSql(string tableName, DataColumnCollection columns, List <string> columnNames, string[] values, bool isPrimaryKeysHasValue, bool hasPrimaryKey)
        {
            var sql = new StringBuilder();

            if (hasPrimaryKey && isPrimaryKeysHasValue && !IdentityInsertCheckClosedTables.Any(x => x.Equals(tableName, StringComparison.InvariantCultureIgnoreCase)))
            {
                sql.AppendLine($"SET IDENTITY_INSERT {tableName} ON ");
                IdentityInsertCheckClosedTables.Add(tableName);
            }

            string insertSqlHeader;

            if (!InsertSqlCache.Any(x => x.Key.Equals(tableName, StringComparison.InvariantCultureIgnoreCase)))
            {
                insertSqlHeader = $"INSERT INTO {tableName} ( [{string.Join("],[", columnNames)}] ) SELECT ";
                InsertSqlCache.Add(tableName, insertSqlHeader);
            }
            else
            {
                insertSqlHeader = InsertSqlCache.SingleOrDefault(x => x.Key.Equals(tableName, StringComparison.InvariantCultureIgnoreCase)).Value;
            }

            sql.AppendLine(insertSqlHeader);
            var valuesLine = new StringBuilder();

            foreach (DataColumn column in columns)
            {
                if (columnNames.Any(x => x.Equals(column.ColumnName, StringComparison.InvariantCultureIgnoreCase)))
                {
                    var colIndex = columnNames.FindIndex(x => x.Equals(column.ColumnName, StringComparison.InvariantCultureIgnoreCase));
                    valuesLine.Append($"{CreateFieldValueSql(column, values[colIndex])}, ");
                }
                else
                {
                    valuesLine.Append($"{CreateFieldValueSql(column, "NULL")}, ");
                }
            }
            sql.AppendLine(valuesLine.ToString().Remove(valuesLine.Length - 2, 2));


            return(sql.ToString());
        }
コード例 #15
0
        private bool CheckGuidesForDownload(IList <FileMeta> filesMetadata, Dictionary <string, string[]> guidesData)
        {
            var isForDownload = false;

            for (int i = 0; i < filesMetadata.Count; ++i)
            {
                var ftpFile = filesMetadata[i];

                var guide = guidesData.SingleOrDefault(x => x.Value[0] == ftpFile.Name &&
                                                       String.CompareOrdinal(x.Value[1], ftpFile.Date) != 0).Key;

                if (guide != null)
                {
                    ftpFile.IsForUpdate = true;
                    isForDownload       = true;
                }
            }

            return(isForDownload);
        }
コード例 #16
0
            public async Task <IEnumerable <ParameterResource> > Handle(CalculateCommand request, CancellationToken cancellationToken)
            {
                var script = await _scriptRepository.GetAsync(request.ScriptId);

                var parameters = await _parameterRepository.GetAllParametersForScriptAsync(request.ScriptId);

                var equations = new Dictionary <long, string>(parameters.ToDictionary(p => p.Id, p => p.Value));

                var scriptCalculator = new ScriptCalculator(script, parameters.ToList());

                await scriptCalculator.CalculateAsync(request.InputData.Where(v => v.Value != null));

                var calculatedParameters = _mapper.Map <List <Parameter>, List <ParameterResource> >(scriptCalculator.GetResult().ToList());

                calculatedParameters.ForEach(cp => cp.Equation = equations.SingleOrDefault(p => p.Key == cp.Id).Value);

                await _translationService.SetParametersTranslation(request.LanguageCode, calculatedParameters, script.DefaultLanguage);

                return(calculatedParameters);
            }
コード例 #17
0
        // ReSharper disable once SuggestBaseTypeForParameter
        private INZazuWpfField GetFocusedControl(UIElement focusedSubControl)
        {
            if (focusedSubControl == null)
            {
                return(null);
            }

            var field = _fields.SingleOrDefault(x => Equals(x.Value?.ValueControl, focusedSubControl)).Value;

            if (field != null)
            {
                return(field);
            }

            var parent = VisualTreeHelper.GetParent(focusedSubControl);

            return(parent != null
                ? GetFocusedControl(parent as UIElement)
                : null);
        }
コード例 #18
0
        static void Main(string[] args)
        {
            int count = int.Parse(Console.ReadLine());

            Dictionary <int, int> numbers = new Dictionary <int, int>();

            for (int i = 0; i < count; i++)
            {
                int inputNumber = int.Parse(Console.ReadLine());
                if (!numbers.ContainsKey(inputNumber))
                {
                    numbers.Add(inputNumber, 0);
                }
                numbers[inputNumber]++;
            }

            int numberToDisplay = numbers.SingleOrDefault(x => x.Value % 2 == 0).Key;

            Console.WriteLine(numberToDisplay);
        }
コード例 #19
0
        // propertColumnsNamesDict used with Sqlite for @parameter to be save from non valid charaters ('', '!', ...) that are allowed as column Names in Sqlite
        public static string GetCommaSeparatedColumns(List <string> columnsNames, string prefixTable = null, string equalsTable = null, Dictionary <string, string> propertColumnsNamesDict = null)
        {
            prefixTable += (prefixTable != null && prefixTable != "@") ? "." : "";
            equalsTable += (equalsTable != null && equalsTable != "@") ? "." : "";

            string commaSeparatedColumns = "";

            foreach (var columnName in columnsNames)
            {
                var equalsParameter = propertColumnsNamesDict == null ? columnName : propertColumnsNamesDict.SingleOrDefault(a => a.Value == columnName).Key;
                commaSeparatedColumns += prefixTable != "" ? $"{prefixTable}[{columnName}]" : $"[{columnName}]";
                commaSeparatedColumns += equalsTable != "" ? $" = {equalsTable}[{equalsParameter}]" : "";
                commaSeparatedColumns += ", ";
            }
            if (commaSeparatedColumns != "")
            {
                commaSeparatedColumns = commaSeparatedColumns.Remove(commaSeparatedColumns.Length - 2, 2); // removes last excess comma and space: ", "
            }
            return(commaSeparatedColumns);
        }
コード例 #20
0
        public static void Main(string[] args)
        {
            Dictionary <int, int> numbers = new Dictionary <int, int>();
            int count = int.Parse(Console.ReadLine());

            for (int i = 0; i < count; i++)
            {
                int currentNumber = int.Parse(Console.ReadLine());
                if (!numbers.ContainsKey(currentNumber))
                {
                    numbers.Add(currentNumber, 0);
                }
                numbers[currentNumber]++;
            }
            int evenTimesNumber = numbers
                                  .SingleOrDefault(number => number.Value % 2 == 0) // Where
                                  .Key;                                             //ToList()

            Console.WriteLine(evenTimesNumber);
        }
コード例 #21
0
        public int SubarraySum(int[] nums, int k)
        {
            int count = 0, sum = 0;

            Dictionary <int, int> map = new Dictionary <int, int>();

            map.Add(0, 1);
            for (int i = 0; i < nums.Length; i++)
            {
                sum = sum + nums[i];
                int otherPair = sum - k;
                if (map.ContainsKey(otherPair))
                {
                    count += map[otherPair];
                }
                map.Add(sum, map.SingleOrDefault(sum, 0) + 1);
            }

            return(count);
        }
        private async Task <GarmentPurchaseRequestViewModel> GetGarmentPurchaseRequestByRONo(string roNo)
        {
            var httpResponseMessage = await httpClient.GetAsync($@"{APIEndpoint.AzurePurchasing}{GarmentPurchaseRequestUri}/by-rono/{roNo}");

            if (httpResponseMessage.StatusCode.Equals(HttpStatusCode.OK))
            {
                var result = httpResponseMessage.Content.ReadAsStringAsync().Result;
                Dictionary <string, object> resultDict = JsonConvert.DeserializeObject <Dictionary <string, object> >(result);

                var data = resultDict.SingleOrDefault(p => p.Key.Equals("data")).Value;

                GarmentPurchaseRequestViewModel garmentPurchaseRequestViewModel = JsonConvert.DeserializeObject <GarmentPurchaseRequestViewModel>(data.ToString());

                return(garmentPurchaseRequestViewModel);
            }
            else
            {
                return(null);
            }
        }
コード例 #23
0
        private async Task <IAggregateRoot> GetAggregateAsync(Type type, Guid streamId)
        {
            var aggregate = _inMemoryAggregates.SingleOrDefault(x => x.Key == streamId).Value;

            aggregate ??= (await _context.FindAsync(type, streamId)) as IAggregateRoot;

            if (aggregate == null)
            {
                aggregate = GetUninitializedObject(type) as IAggregateRoot;

                _ = _context.Add(aggregate);
            }

            if (!_inMemoryAggregates.Any(x => x.Key == streamId))
            {
                _inMemoryAggregates.Add(streamId, aggregate);
            }

            return(aggregate);
        }
コード例 #24
0
        public SearchResults Search(SearchOptions options)
        {
            // TODO: search logic goes here.
            var optionSizes  = options.Sizes.Count > 0 ? options.Sizes : Size.All;
            var optionColors = options.Colors.Count > 0 ? options.Colors : Color.All;

            var shirts = new List <Shirt>();

            foreach (var size in optionSizes)
            {
                foreach (var color in optionColors)
                {
                    int count = 0;
                    var key   = size.Name + color.Name;


                    var list_shirt = _optionShirts.SingleOrDefault(x => x.Key == key).Value;
                    if (list_shirt != null)
                    {
                        count = list_shirt.Count();
                        shirts.AddRange(list_shirt);
                    }

                    var tempSizeCount = sizeCounts.SingleOrDefault(x => x.Size.Name == size.Name);
                    if (tempSizeCount != null)
                    {
                        tempSizeCount.Count += count;
                    }

                    var tempColorCount = colorCounts.SingleOrDefault(x => x.Color.Name == color.Name);
                    if (tempColorCount != null)
                    {
                        tempColorCount.Count += count;
                    }
                }
            }
            return(new SearchResults
            {
                Shirts = shirts, SizeCounts = sizeCounts, ColorCounts = colorCounts
            });
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: lchoros/AdvancedCSharp
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            Dictionary <int, int> numbers = new Dictionary <int, int>();

            for (int i = 0; i < n; i++)
            {
                int number = int.Parse(Console.ReadLine());

                if (!numbers.ContainsKey(number))
                {
                    numbers.Add(number, 0);
                }
                numbers[number]++;
            }


            int evenNumber = numbers.SingleOrDefault(m => m.Value % 2 == 0).Key;

            Console.WriteLine(evenNumber);
        }
コード例 #26
0
        internal void DoRequest(ERP_DB ctx, ref Dictionary <string, string> holders, int notificationID, string plant)
        {
            var userFromPlaceHolders = holders.SingleOrDefault(holder => holder.Key != null && holder.Key.Equals("user")).Value;
            var phoneNumber          = ctx.SpisPracownikow.FirstOrDefault(user => user.ImieNaziwsko != null && user.ImieNaziwsko.Equals(userFromPlaceHolders)).Telefon;

            var typWezwania = ctx.SpisWezwania.SingleOrDefault(sw => sw.ID == notificationID).TypyWezwanID;
            var voiceType   = 2; //tmp

            if (typWezwania == voiceType)
            {
                var notifVoice = new NotificationVoice();
                notifVoice.GetAndFillTemplate(ctx, holders, notificationID);
                VoiceRequest(phoneNumber, notifVoice.NotificationBody);
            }
            else
            {
                var notifSms = new NotificationSMS();
                notifSms.GetAndFillTemplate(ctx, holders, notificationID);
                SmsRequest(phoneNumber, notifSms.NotificationBody);
            }
        }
コード例 #27
0
        public static void Main(string[] args)
        {
            int numberOfIntegers          = int.Parse(Console.ReadLine());
            Dictionary <int, int> numbers = new Dictionary <int, int>();

            for (int i = 0; i < numberOfIntegers; i++)
            {
                int currentNumber = int.Parse(Console.ReadLine());

                if (!numbers.ContainsKey(currentNumber))
                {
                    numbers.Add(currentNumber, 0);
                }

                numbers[currentNumber]++;
            }

            int evenNumber = numbers.SingleOrDefault(x => x.Value % 2 == 0).Key;

            Console.WriteLine(evenNumber);
        }
コード例 #28
0
        public string Morze2Szöveg(Dictionary <string, string> abc, string morze)
        {
            var roviditettMorze = morze.Replace("   ", " ");
            var splitted        = roviditettMorze.Split(' ');
            var dekodolt        = "";

            foreach (var morzeErtek in splitted)
            {
                if (morzeErtek == "" || morzeErtek == " ")
                {
                    dekodolt += " ";
                }
                else
                {
                    var dekodoltMorze = abc.SingleOrDefault(x => x.Value == morzeErtek).Key;
                    dekodolt += dekodoltMorze;
                }
            }

            return(dekodolt);
        }
コード例 #29
0
        public ITranslation GetCurrentTranslation()
        {
            var culture          = CultureInfo.CurrentUICulture;
            var twoLetterIsoCode = culture.TwoLetterISOLanguageName;

            ITranslation tmp;

            if (_translations.TryGetValue(twoLetterIsoCode, out tmp))
            {
                return(tmp);
            }

            var defaultTranslation = _translations.SingleOrDefault(t => t.Value.IsDefault);

            if (defaultTranslation.Equals(new KeyValuePair <string, ITranslation>()))
            {
                throw new Exception("No default language found. App can't not be translated.");
            }

            return(defaultTranslation.Value);
        }
コード例 #30
0
ファイル: AttributeHelper.cs プロジェクト: Aqnkla/aqnkla-app
        public static T GetLabelEnum <T>(string label) where T : Enum
        {
            var enums      = Enum.GetValues(typeof(T)) as IEnumerable <T>;
            var dictionary = new Dictionary <T, string>();

            foreach (var enumValue in enums)
            {
                var type       = typeof(T);
                var memInfo    = type.GetMember(enumValue.ToString());
                var attributes = memInfo[0].GetCustomAttributes(typeof(LabelEnumAttribute), false);
                var enumLabel  = ((LabelEnumAttribute)attributes[0]).Label;
                dictionary.Add(enumValue, enumLabel);
            }
            var returnValue = dictionary.SingleOrDefault(b => b.Value == label).Key;

            if (returnValue == null)
            {
                throw new UnknownLabelValueException(label);
            }
            return(returnValue);
        }
コード例 #31
0
ファイル: Program.cs プロジェクト: mihaistancu/Dependencies
        private static void ComputeDependencies(Assembly assembly, bool isRecursive)
        {
            var dependencies = assembly.GetReferencedAssemblies();

            foreach (var dependency in dependencies)
            {
                var dependencyPathAndAssembly = Assemblies.SingleOrDefault(x => x.Value.FullName == dependency.FullName);

                if (!string.IsNullOrEmpty(dependencyPathAndAssembly.Key))
                {
                    if (!Dependencies.ContainsKey(dependencyPathAndAssembly.Key))
                    {
                        Dependencies[dependencyPathAndAssembly.Key] = dependencyPathAndAssembly.Value;
                        if (isRecursive)
                        {
                            ComputeDependencies(dependencyPathAndAssembly.Value, true);
                        }
                    }
                }
            }
        }
コード例 #32
0
        private bool LocateSharedWorld()
        {
            Dictionary <long, int> _worlds = new Dictionary <long, int>();

            foreach (var pp in _profiles)
            {
                foreach (var w in pp.m_worldData)
                {
                    if (_worlds.ContainsKey(w.Key))
                    {
                        _worlds[w.Key]++;
                    }
                    else
                    {
                        _worlds.Add(w.Key, 1);
                    }
                }
            }
            _worldId = _worlds.SingleOrDefault(x => x.Value == _profiles.Count()).Key;
            return(_worldId > 0);
        }
コード例 #33
0
        public void DictionaryExtensions_SingleOrDefault_ThrowsExceptionIfDictionaryHasMultipleItems()
        {
            var dictionary = new Dictionary<Int32, String>()
            {
                { 1, "A" },
                { 2, "B" },
            };

            dictionary.SingleOrDefault();
        }
コード例 #34
0
ファイル: PrinterService.cs プロジェクト: neapolis/SambaPOS-3
        private void InternalPrintOrders(PrintJob printJob, Ticket ticket, IEnumerable<Order> orders)
        {
            if (printJob.PrinterMaps.Count == 1
                && printJob.PrinterMaps[0].MenuItemId == 0
                && printJob.PrinterMaps[0].MenuItemGroupCode == null)
            {
                PrintOrderLines(ticket, orders, printJob.PrinterMaps[0]);
                return;
            }

            var ordersCache = new Dictionary<PrinterMap, IList<Order>>();

            foreach (var item in orders)
            {
                var p = GetPrinterMapForItem(printJob.PrinterMaps, item.MenuItemId);
                if (p != null)
                {
                    var lmap = p;
                    var pmap = ordersCache.SingleOrDefault(
                            x => x.Key.PrinterId == lmap.PrinterId && x.Key.PrinterTemplateId == lmap.PrinterTemplateId).Key;
                    if (pmap == null)
                        ordersCache.Add(p, new List<Order>());
                    else p = pmap;
                    ordersCache[p].Add(item);
                }
            }

            foreach (var order in ordersCache)
            {
                PrintOrderLines(ticket, order.Value, order.Key);
            }
        }
コード例 #35
0
        public void DictionaryExtensions_SingleOrDefault_ThrowsExceptionIfDictionaryHasMultipleItems()
        {
            var dictionary = new Dictionary<Int32, String>()
            {
                { 1, "A" },
                { 2, "B" },
            };

            Assert.That(() => dictionary.SingleOrDefault(),
                Throws.TypeOf<InvalidOperationException>());
        }
コード例 #36
0
        /// <summary>
        /// Updating catalogs (only their names, not their fields or records)
        /// </summary>
        /// <param name="entity">The contract-type defining the catalog</param>
        /// <param name="newEntryTexts">Name/Description of the catalog</param>
        /// <param name="CreateNew">true to signal the creation of a new catalog, false for updating existing catalogs</param>
        public void SaveEntityGroup(TopContractsEntities.ContractType entity, Dictionary<string, SysTableEntryText> newEntryTexts, bool CreateNew)
        {
            TopContractsV01Entities context = new TopContractsV01Entities(Utilities.getTestEnvName());
            TopContractsEntities.FieldGroup efFieldGroup = new TopContractsEntities.FieldGroup();

            //efFieldGroup.InitCommonFields(efFieldGroup, entity, efFieldGroup.FieldGroupsLNGs);
            if (CreateNew)
            {
                foreach (var cTypeLng in entity.ContractTypesLNGs)
                {
                    efFieldGroup.FieldGroupsLNGs.Add(new FieldGroupsLNG { OrganizationIdentifier = this.organizationIdentifier, CultureId = cTypeLng.CultureId, DescShort = cTypeLng.DescShort, DescLong = cTypeLng.DescLong });
                }
                efFieldGroup.OrganizationIdentifier = this.organizationIdentifier;
                efFieldGroup.ContractTypeVisibility = (byte)FieldGroupContractTypeVisibility.VisibleToTypes;
                efFieldGroup.RolesVisibility = (byte)FieldGroupRoleVisibility.VisibleToAll;
                efFieldGroup.Inactive = false;
                efFieldGroup.Locked = false;
                efFieldGroup.DisplayOrder = null;
                efFieldGroup.ExternalID = null;
                efFieldGroup.SingleRecord = true;
                efFieldGroup.FieldGroupsContractTypesMAPs.Add(new FieldGroupsContractTypesMAP { OrganizationIdentifier = this.organizationIdentifier, ContractTypeID = entity.ContractTypeID });
                context.FieldGroups.Add(efFieldGroup);
            }
            else
            {
                // code to modify action of the entity field group when action of an entity is changed.
                if (context.FieldGroupsContractTypesMAPs.Any(u => u.ContractTypeID == entity.ContractTypeID))
                {
                    List<FieldGroupsLNG> fgLngs = context.FieldGroupsContractTypesMAPs.SingleOrDefault(u => u.ContractTypeID == entity.ContractTypeID).FieldGroup.FieldGroupsLNGs.ToList();
                    foreach (var fgLng in fgLngs)
                    {
                        fgLng.DescShort = newEntryTexts.SingleOrDefault(l => l.Key == fgLng.CultureId.Trim()).Value.DescShort;
                        fgLng.DescLong = newEntryTexts.SingleOrDefault(l => l.Key == fgLng.CultureId.Trim()).Value.DescLong;
                    }
                }
            }
            context.SaveChanges();
        }
        /// <summary>
        /// Verify file stream information
        /// </summary>
        /// <param name="fileStreamInformations">A list of FileStreamInformation structures</param>
        /// <param name="streamList">A dictionary of streamname and streamsize mapping</param>
        private void VerifyFileStreamInformations(List<FileStreamInformation> fileStreamInformations, Dictionary<string, long> streamList)
        {
            // To verify whether the count of filestreaminformation data elements equals to the actual data streams counts
            BaseTestSite.Assert.AreEqual(streamList.Count, fileStreamInformations.Count,
                "The total number of the returned FILE_STREAM_INFORMATION data elements should be equal the total streams that has been added to the file.");

            // To verify whether each data element of filestreaminformation matches with the actual data streams in name and size
            foreach (FileStreamInformation fileStreamInformation in fileStreamInformations)
            {
                string streamName = Encoding.Unicode.GetString(fileStreamInformation.StreamName);
                KeyValuePair<string, long> streamListElement = streamList.SingleOrDefault(x => x.Key.Equals(streamName));
                BaseTestSite.Assert.IsNotNull(streamListElement, "The stream with name {0} is found.", streamListElement.Key);
                BaseTestSite.Assert.AreEqual(streamListElement.Value, (long)fileStreamInformation.StreamSize,
                    "The StreamSize field of each of the returned FILE_STREAM_INFORMATION data elements should match the size of bytes written to each data stream.");
            }
        }
コード例 #38
0
ファイル: DashboardUpdate.cs プロジェクト: secgoat/Dashboards
        private void DepressionToDashboard(Dictionary<String, IXLRangeRow> providerRows)
        {
            XLWorkbook depressionFile;
            List<XLWorkbook> depressionFiles = new List<XLWorkbook>();
            int[] depressionFileLocations = new int[] { 7, 5, 4, 6 };

            foreach (int fileNum in depressionFileLocations)
            {
                depressionFile = new XLWorkbook(metrics_files[fileNum]);
                depressionFiles.Add(depressionFile);
            }
            foreach (String provider in providers)
            {
                DepressionMetric depression = new DepressionMetric(provider, depressionFiles);
                List<object> metrics = depression.Metrics;
                var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
                var row = kvp.Value; //grap the row out of the value field for the matching KVP entry
                //if Keys do not contain provider name, then row will be null , and no sense in trying to populate!
                if (row != null)
                {
                    for (int x = 1; x <= metrics.Count; x++)
                    {
                        var cell = row.Cell(x);
                        if (x > 7) //do this to up the cell number it x => 7 because in the dashboard cell 7 is a blank line down th middle to seprate the two sides and we want to skip this column
                            cell = row.Cell(x + 1);

                        cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                        if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
                        else if (x == 2 || x == 3 || x == 8) { cell.Style.NumberFormat.Format = "@";}
                        else { cell.Style.NumberFormat.Format = "0.0%"; }
                        //cell.Style.NumberFormat.Format = "@";
                        cell.Style.Font.SetBold(false);
                        cell.SetValue(metrics.ElementAt(x - 1));
                    }
                }

            }
        }
コード例 #39
0
ファイル: DashboardUpdate.cs プロジェクト: secgoat/Dashboards
        private void CardiovascularToDashboard(Dictionary<String, IXLRangeRow> providerRows)
        {
            XLWorkbook cardiovascularFile;
            List<XLWorkbook> cardiovascularFiles = new List<XLWorkbook>();
            int[] cardiovascularFileLocations = new int[] { 13 };

            foreach (int fileNum in cardiovascularFileLocations)
            {
                cardiovascularFile = new XLWorkbook(metrics_files[fileNum]);
                cardiovascularFiles.Add(cardiovascularFile);
            }

            foreach (String provider in providers)
            {
                CardiovascularMetric cardio = new CardiovascularMetric(provider, cardiovascularFiles);
                List<object> metrics = cardio.Metrics;
                var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
                var row = kvp.Value; //grap the row out of the value field for the matching KVP entry
                if (row != null)
                {
                    for (int x = 1; x <= metrics.Count; x++)
                    {
                        var cell = row.Cell(x);
                        cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                        if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
                        else if (x == 2) { cell.Style.NumberFormat.Format = "@";  }
                        else { cell.Style.NumberFormat.Format = "0.0%"; }
                        //cell.Style.NumberFormat.Format = "@";
                        cell.Style.Font.SetBold(false);
                        cell.SetValue(metrics.ElementAt(x - 1));
                    }
                }

            }
        }
コード例 #40
0
        public void DictionaryExtensions_SingleOrDefault_ReturnsDefaultValueIfDictionaryIsEmpty()
        {
            var dictionary = new Dictionary<Int32, String>();

            var result = dictionary.SingleOrDefault();

            TheResultingValue(result).ShouldBe(default(KeyValuePair<Int32, String>));
        }
コード例 #41
0
        public void DictionaryExtensions_SingleOrDefault_ReturnsSingleItemInDictionary()
        {
            var dictionary = new Dictionary<Int32, String>()
            {
                { 4, "A" },
            };

            var result = dictionary.SingleOrDefault();

            TheResultingValue(result).ShouldBe(new KeyValuePair<Int32, String>(4, "A"));
        }
コード例 #42
0
        private async Task Play(TimingMessage playMessage)
        {
            var folders = new Dictionary<string, StorageFolder>
                              {
                                  { "MUSIC:", KnownFolders.MusicLibrary }, 
                                  { "VIDEOS:", KnownFolders.VideosLibrary }, 
                                  { "PICTURES:", KnownFolders.PicturesLibrary }, 
                                  { "CAMERA:", KnownFolders.CameraRoll }, 
                                  { "SAVED:", KnownFolders.SavedPictures }
                              };

            try
            {
                await this.dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal, 
                    async () =>
                        {
                            // force start of whatever is most recently sent
                            if (this.player.CurrentState != MediaElementState.Closed
                                && this.player.CurrentState != MediaElementState.Stopped)
                            {
                                this.player.Stop();
                            }

                            if (this.player.Source != null)
                            {
                                this.player.Source = null;
                            }

                            StorageFile file = null;

                            var url = playMessage.Url;
                            var isWebUrl = false;

                            var colon = url.IndexOf(':');
                            if (colon > -1)
                            {
                                var root = url.Substring(0, colon + 1).ToUpperInvariant();

                                var folder = folders.SingleOrDefault(f => root.StartsWith(f.Key));
                                if (folder.Value != null)
                                {
                                    file = await folder.Value.GetFileAsync(url.Substring(colon + 1));
                                }
                                else
                                {
                                    isWebUrl = true;
                                }
                            }

                            if (isWebUrl)
                            {
                                this.player.Source = new Uri(url);
                            }
                            else
                            {
                                if (file == null)
                                {
                                    await
                                        this.SendResult(
                                            new ResultMessage(playMessage)
                                                {
                                                    ResultId = -3, 
                                                    Result = "file does not exist"
                                                });
                                    return;
                                }

                                var stream = await file.OpenAsync(FileAccessMode.Read);
                                this.player.SetSource(stream, file.ContentType);
                            }

                            this.player.Tag = playMessage;
                            this.player.CurrentStateChanged += this.Player_CurrentStateChanged;

                            this.player.Play();
                        });
            }
            catch (Exception e)
            {
                await this.SendResult(new ResultMessage(playMessage) { ResultId = e.HResult, Result = e.Message });
            }
        }
コード例 #43
0
ファイル: AutorizeUserAttrbute.cs プロジェクト: algola/backup
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            var thisController = ((ProductController)filterContext.Controller);
            IMenuProductRepository prodRepository = thisController.MenuProductRepository;
            string user = thisController.CurrentUser.UserName;

            //Sperimentale
            // first look at routedata then at request parameter:
            var id = (filterContext.RequestContext.RouteData.Values["id"] as string) ?? ("" as string);


            //associazione tra la categoria del prodotto e la Role
            Dictionary<string, string> prodMod = new Dictionary<string, string>();
            prodMod.Add("FogliSingoli", "SmallFormat");
            prodMod.Add("Book", "SmallFormat");
            prodMod.Add("GrandeFormato", "WideFormat");
            prodMod.Add("Rotoli", "Label");
            prodMod.Add("Cliche", "Cliche");
            prodMod.Add("Description", "Description");

            bool redirect = false;

            if (prodRepository != null)
            {
                var product = prodRepository.GetSingle(id);

                Console.WriteLine(product.CodCategory);

                if (product != null)
                {
                   
                    if (!System.Web.Security.Roles.RoleExists(product.CodCategory))
                    {
                        System.Web.Security.Roles.CreateRole(product.CodCategory);
                    }

                    //if is Generico 
                    if (product.CodCategory == "Description")
                    {
                        try
                        {
                            //user that is not in... 
                            var _users = System.Web.Security.Roles.GetUsersInRole(prodMod.SingleOrDefault(k => k.Key == product.CodCategory).Value);
                            if (!_users.Contains(user))
                            {
                                System.Web.Security.Roles.AddUserToRole(user, "Description");
                            }
                        }
                        catch (Exception e)
                        {
                            Console.Write(e.Message);
                            System.Web.Security.Roles.AddUserToRole(user, "Description");
                        }                        
                    }

                    //traduzione e ricerca dal prodotto -> modulo
                    var users = System.Web.Security.Roles.GetUsersInRole(prodMod.SingleOrDefault(k => k.Key == product.CodCategory).Value);
                    redirect = !users.Contains(user);
                }
            }

            if (redirect)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "Account",
                        action = "EditProfile",
                        view = "EditProfileModule",
                        area = "Account"
                    }));
            }

            //sperimentale ----------------------------------------

        }
コード例 #44
0
ファイル: DashboardUpdate.cs プロジェクト: secgoat/Dashboards
        private void DiabetesToDashboard(Dictionary<String, IXLRangeRow> providerRows)
        {
            XLWorkbook diabetesFile;
            List<XLWorkbook> diabetesFiles = new List<XLWorkbook>();
            int[] diabetesFileLocations = new int[] { 8, 10, 11, 12, 9 }; //order is pretty important here, because of the hardcode int he actual Metricsa Class file and the way it is searchinf for values. Just keep the order on all metrics the same as they are no unless osmehitng chnages like file name or what have you that might mess this order up.

            foreach (int fileNum in diabetesFileLocations)
            {
                diabetesFile = new XLWorkbook(metrics_files[fileNum]);
                diabetesFiles.Add(diabetesFile);
            }

            foreach (String provider in providers)
            {
                DiabetesMetric diabetes = new DiabetesMetric(provider, diabetesFiles);
                List<object> metrics = diabetes.Metrics;

                var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
                var row = kvp.Value; //grap the row out of the value field for the matching KVP entry
                if (row != null)
                {

                    for (int x = 1; x <= metrics.Count; x++)
                    {
                        var cell = row.Cell(x);
                        cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                        if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
                        else if (x == 2 || x == 3 ) { cell.Style.NumberFormat.Format = "@"; }
                        else if (x == 5) { cell.Style.NumberFormat.Format = "0.0"; }
                        else { cell.Style.NumberFormat.Format = "0.0%"; }
                        //cell.Style.NumberFormat.Format = "@";
                        cell.Style.Font.SetBold(false);
                        cell.SetValue(metrics.ElementAt(x - 1));
                    }
                }

            }
        }
コード例 #45
0
        internal void CreateSolution(MainViewModel mainViewModel)
        {
            var model = mainViewModel.SelectedTemplate;
            var company = mainViewModel.Company;
            var solutionName = mainViewModel.SolutionName;

            if (model == null)
            {
                return;
            }

            var registryPath = String.Format(Environment.Is64BitOperatingSystem ? @"Software\Wow6432Node\Microsoft\VisualStudio\{0}" : @"Software\Microsoft\VisualStudio\{0}", DTE.Version);
            var registryKey = Registry.LocalMachine.OpenSubKey(registryPath);

            if (registryKey == null)
            {
                return;
            }

            var installDir = registryKey.GetValue("InstallDir");
            var solution = DTE.Solution as Solution4;

            if (solution == null)
            {
                return;
            }

            string solutionFileName;

            if (solution.IsOpen)
            {
                solution.Close();
            }

            var properties = DTE.Properties["Environment", "ProjectsAndSolution"];
            var setting = properties.Item("ProjectsLocation");

            if (setting != null && setting.Value != null)
            {
                var targetDir = Path.Combine(setting.Value.ToString(), solutionName);

                if (!Directory.Exists(targetDir))
                {
                    Directory.CreateDirectory(targetDir);
                }

                solutionFileName = Path.Combine(targetDir, String.Format("{0}.sln", solutionName));
                solution.Create(targetDir, solutionName);
                solution.SaveAs(solutionName);
            }
            else
            {
                return;
            }

            var projects = new Dictionary<Guid, Tuple<Project, string, ICollection<Guid>, ICollection<string>>>();
            DTE.Events.SolutionEvents.ProjectAdded += project =>
            {
                var item = projects.SingleOrDefault(x => x.Value.Item2 == project.Name);

                if (projects.ContainsKey(item.Key))
                {
                    projects[item.Key] = new Tuple<Project, string, ICollection<Guid>, ICollection<string>>(project, item.Value.Item2, item.Value.Item3, item.Value.Item4);
                }
            };

            // Create Folders & Projects
            foreach (var folder in model.Folders)
            {
                var solutionFolder = (SolutionFolder)solution.AddSolutionFolder(folder.Name).Object;

                foreach (var project in folder.Projects)
                {
                    var fullProjectName = String.Format("{0}.{1}.{2}", company, solutionName, project.Name);
                    var projectFolder = Path.Combine(Path.GetDirectoryName(DTE.Solution.FullName), fullProjectName);

                    if (Directory.Exists(projectFolder))
                    {
                        continue;
                    }

                    projects.Add(project.Id, new Tuple<Project, string, ICollection<Guid>, ICollection<string>>(null, fullProjectName, project.References, project.Packages));

                    var csTemplate = project.IsFindTemplate ? solution.GetProjectTemplate(project.TemplatePath, project.Language) : String.Format(project.TemplatePath, installDir);
                    solutionFolder.AddFromTemplate(csTemplate, projectFolder, fullProjectName);
                }
            }

            // Create Projects - without folders
            foreach (var project in model.Projects)
            {
                var fullProjectName = String.Format("{0}.{1}.{2}", company, solutionName, project.Name);
                var projectFolder = Path.Combine(Path.GetDirectoryName(DTE.Solution.FullName), fullProjectName);

                if (Directory.Exists(projectFolder))
                {
                    continue;
                }

                projects.Add(project.Id, new Tuple<Project, string, ICollection<Guid>, ICollection<string>>(null, fullProjectName, project.References, project.Packages));

                var csTemplate = project.IsFindTemplate ? solution.GetProjectTemplate(project.TemplatePath, project.Language) : String.Format(project.TemplatePath, installDir);
                solution.AddFromTemplate(csTemplate, projectFolder, fullProjectName);
            }

            // Reference the Projects
            foreach (var project in projects)
            {
                var vsProject = project.Value.Item1;
                var solutionProject = vsProject.Object as VSProject;

                InstallNugetPackages(vsProject, project.Value.Item4);

                if (solutionProject != null)
                {
                    var references = projects.Where(x => project.Value.Item3.Contains(x.Key)).Select(x => x.Value.Item1);

                    foreach (var reference in references)
                    {
                        solutionProject.References.AddProject(reference);
                    }
                }

                vsProject.Save();
            }

            solution.SaveAs(solutionFileName);
        }
コード例 #46
0
ファイル: DashboardUpdate.cs プロジェクト: secgoat/Dashboards
        private void PreventiveToDashboard(Dictionary<String, IXLRangeRow> providerRows)
        {
            XLWorkbook preventiveFile;
            List<XLWorkbook> preventiveFiles = new List<XLWorkbook>();
            int[] preventivFileLocations = new int[] { 3, 3, 16, 15, 17, 18, 0 };//use 3 twice so we can get the 2 metrics from BMI file
            //this allows the loop in the preventive metrics object to iterate over file 3 2 times with different results

            foreach (int fileNum in preventivFileLocations)
            {
                preventiveFile = new XLWorkbook(metrics_files[fileNum]);
                string name = preventiveFile.Properties.Title;
                preventiveFiles.Add(preventiveFile);
            }

            foreach (String provider in providers)
            {
                PreventiveMetric preventive = new PreventiveMetric(provider, preventiveFiles);
                List<object> metrics = preventive.Metrics;
                var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
                var row = kvp.Value; //grap the row out of the value field for the matching KVP entry
                if (row != null)
                {
                    for (int x = 1; x <= metrics.Count; x++)
                    {
                        var cell = row.Cell(x);
                        cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                        if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
                        else { cell.Style.NumberFormat.Format = "0.0%"; }
                        //cell.Style.NumberFormat.Format = "@";
                        cell.Style.Font.SetBold(false);
                        cell.SetValue(metrics.ElementAt(x - 1));
                    }
                }

            }
        }
コード例 #47
0
        public static FilterNode Parse(string filterStr)
        {
            var tok = new StringTokenizer(filterStr)
                {
                    IgnoreWhiteSpace = true,
                    // the following two should be mutually exclusive
                    // if the following have a mutually shared char, Word char will take precedence
                    // when creating tokens at this time...
                    AdditionalWordChars = new char[] { '*', ' ', '.' },
                    SymbolChars = new[] { '(', ')', '^', '|', ':' }
                };

            var nodeid = 0;
            var nodes = new Dictionary<int, FilterNode>();

            var currentNodeId = ++nodeid;
            nodes.Add(currentNodeId, new FilterNode { ParentNodeId = 0, NodeId = currentNodeId, NodeType = FilterNodeType.Root });
            var currentNode = nodes[nodeid];

            // parse tokens
            Token token;
            do
            {
                token = tok.Next();

                if (token.Kind == TokenKind.Symbol && token.Value == "(")
                {
                    currentNodeId = ++nodeid;
                    nodes.Add(currentNodeId, new FilterNode { ParentNodeId = currentNode.NodeId, NodeId = currentNodeId });
                    currentNode = nodes[nodeid];
                }
                else if (token.Kind == TokenKind.Symbol && token.Value == ")")
                {
                    currentNode = nodes[currentNode.ParentNodeId];
                }
                else if (token.Kind == TokenKind.Symbol && token.Value == "^")
                {
                    currentNode.NodeType = FilterNodeType.AndExpression;
                }
                else if (token.Kind == TokenKind.Symbol && token.Value == "|")
                {
                    currentNode.NodeType = FilterNodeType.OrExpression;
                }
                else if (token.Kind == TokenKind.Symbol && token.Value == ":")
                {
                }
                else if (token.Kind == TokenKind.Word || token.Kind == TokenKind.Number || token.Kind == TokenKind.QuotedString)
                {
                    currentNode.Elements.Add(token.Value);
                }

            } while (token.Kind != TokenKind.EOF);

            // build the tree
            foreach (var node in nodes)
            {
                node.Value.Nodes.AddRange(nodes.Where(n => n.Value.ParentNodeId == node.Key).Select(n => n.Value));
                node.Value.ParentNode = nodes.SingleOrDefault(n => n.Key == node.Value.ParentNodeId).Value;
            }

            // return the root node
            var filterNode = nodes[1];
            return filterNode;
        }
コード例 #48
0
ファイル: DashboardUpdate.cs プロジェクト: secgoat/Dashboards
        private void AsthmaToDashboard(Dictionary<String, IXLRangeRow> providerRows)
        {
            XLWorkbook asthmaFile;
            List<XLWorkbook> asthmaFiles = new List<XLWorkbook>();
            int[] asthmaFileLocations = new int[] {1, 2};

            foreach (int fileNum in asthmaFileLocations)
            {
                asthmaFile = new XLWorkbook(metrics_files[fileNum]);
                asthmaFiles.Add(asthmaFile);
            }
            foreach (String provider in providers)
            {
                AsthmaMetric asthma = new AsthmaMetric(provider, asthmaFiles);
                List<object> metrics = asthma.Metrics;
                var kvp = providerRows.SingleOrDefault(s => s.Key.Contains(provider)); // find matching KVP by using linq
                var row = kvp.Value; //grab the row out of the value field for the matching KVP entry. this ensures the providert names are matched and no missing providers get data for some one who does exist

                if (row != null)
                {
                    for (int x = 1; x <= metrics.Count; x++)
                    {
                        var cell = row.Cell(x);
                        cell.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;
                        if (x == 1) { cell.Style.NumberFormat.NumberFormatId = 17; }//mmm-yy
                        if (x == 2 || x == 4) { cell.Style.NumberFormat.Format = "@"; }
                        else { cell.Style.NumberFormat.Format = "0.0%"; }
                        cell.Style.Font.SetBold(false);
                        cell.SetValue(metrics.ElementAt(x - 1));
                    }
                }

            }
        }
コード例 #49
0
        private IEnumerable<TicketPrintTask> GetPrintTasks(PrintJob printJob, Ticket ticket, IEnumerable<Order> orders)
        {
            var result = new List<TicketPrintTask>();

            if (printJob.PrinterMaps.Count == 1
                && printJob.WhatToPrint != 3
                && printJob.WhatToPrint != 4
                && printJob.PrinterMaps[0].MenuItemId == 0
                && printJob.PrinterMaps[0].MenuItemGroupCode == null)
            {
                result.Add(GetPrintTask(ticket, orders, printJob.PrinterMaps[0]));
                return result;
            }

            var ordersCache = new Dictionary<PrinterMap, IList<Order>>();

            foreach (var item in orders)
            {
                var p = GetPrinterMapForItem(printJob.PrinterMaps, item.MenuItemId);
                if (p != null)
                {
                    var lmap = p;
                    var pmap = ordersCache.SingleOrDefault(
                            x => x.Key.PrinterId == lmap.PrinterId && x.Key.PrinterTemplateId == lmap.PrinterTemplateId).Key;
                    if (pmap == null)
                        ordersCache.Add(p, new List<Order>());
                    else p = pmap;
                    ordersCache[p].Add(item);
                }
            }
            switch (printJob.WhatToPrintType)
            {
                case WhatToPrintTypes.SeparatedByQuantity: result.AddRange(GenerateSeparatedTasks(ticket, ordersCache));
                    break;
                default:
                    result.AddRange(ordersCache.Select(order => GetPrintTask(ticket, order.Value, order.Key)));
                    break;
            }
            return result;
        }
コード例 #50
0
ファイル: TicketPrinter.cs プロジェクト: basio/veropos
        private static void InternalPrintOrders(PrintJob printJob, Ticket ticket, IEnumerable<TicketItem> ticketItems)
        {
            if (printJob.PrinterMaps.Count == 1
                && printJob.PrinterMaps[0].TicketTag == null
                && printJob.PrinterMaps[0].MenuItem == null
                && printJob.PrinterMaps[0].MenuItemGroupCode == null
                && printJob.PrinterMaps[0].Department == null)
            {
                PrintOrderLines(ticket, ticketItems, printJob.PrinterMaps[0]);
                return;
            }

            var ordersCache = new Dictionary<PrinterMap, IList<TicketItem>>();

            foreach (var item in ticketItems)
            {
                var p = GetPrinterMapForItem(printJob.PrinterMaps, ticket, item);
                if (p != null)
                {
                    var lmap = p;
                    var pmap = ordersCache.SingleOrDefault(
                            x => x.Key.Printer == lmap.Printer && x.Key.PrinterTemplate == lmap.PrinterTemplate).Key;
                    if (pmap == null)
                        ordersCache.Add(p, new List<TicketItem>());
                    else p = pmap;
                    ordersCache[p].Add(item);
                }
            }

            foreach (var order in ordersCache)
            {
                PrintOrderLines(ticket, order.Value, order.Key);
            }
        }