Ejemplo n.º 1
0
        public static void ShowParsedCommand(ConsoleCommand consoleCommand, TextWriter consoleOut)
        {
            if (!consoleCommand.TraceCommandAfterParse)
            {
                return;
            }

            string[] skippedProperties = new []{
                "Command",
                "OneLineDescription",
                "Options",
                "TraceCommandAfterParse",
                "RemainingArgumentsCount",
                "RemainingArgumentsHelpText",
                "RequiredOptions"
            };

            var properties = consoleCommand.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(p => !skippedProperties.Contains(p.Name));

            var fields = consoleCommand.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)
                .Where(p => !skippedProperties.Contains(p.Name));

            Dictionary<string,string> allValuesToTrace = new Dictionary<string, string>();

            foreach (var property in properties)
            {
                object value = property.GetValue(consoleCommand, new object[0]);
                allValuesToTrace[property.Name] = value != null ? value.ToString() : "null";
            }

            foreach (var field in fields)
            {
                allValuesToTrace[field.Name] = MakeObjectReadable(field.GetValue(consoleCommand));
            }

            consoleOut.WriteLine();

            string introLine = String.Format("Executing {0}", consoleCommand.Command);

            if (string.IsNullOrEmpty(consoleCommand.OneLineDescription))
                introLine = introLine + ":";
            else
                introLine = introLine + " (" + consoleCommand.OneLineDescription + "):";

            consoleOut.WriteLine(introLine);

            foreach(var value in allValuesToTrace.OrderBy(k => k.Key))
                consoleOut.WriteLine("    " + value.Key + " : " + value.Value);

            consoleOut.WriteLine();
        }
Ejemplo n.º 2
0
        public void Initialize(bool blockUnrated)
        {
            if (_ratings != null) return;  //already intitialized

            //We get our ratings from the server
            _ratings = new Dictionary<string, int>();
            try
            {
                foreach (var rating in Kernel.ApiClient.GetParentalRatings())
                {
                    _ratings.Add(rating.Name, rating.Value);
                }
            }
            catch (Exception e)
            {
                Logging.Logger.ReportException("Error retrieving ratings from server",e);
                return;
            }

            try
            {
                _ratings.Add("", blockUnrated ? 1000 : 0);
            }
            catch (Exception e)
            {
                Logging.Logger.ReportException("Error adding blank value to ratings", e);
            }
            //and rating reverse lookup dictionary (non-redundant ones)
            ratingsStrings.Clear();
            int lastLevel = -10;
            ratingsStrings.Add(-1,LocalizedStrings.Instance.GetString("Any"));
            foreach (var pair in _ratings.OrderBy(p => p.Value))
            {
                if (pair.Value > lastLevel)
                {
                    lastLevel = pair.Value;
                    try
                    {
                        ratingsStrings.Add(pair.Value, pair.Key);
                    }
                    catch (Exception e)
                    {
                        Logging.Logger.ReportException("Error adding "+pair.Value+" to ratings strings", e);
                    }
                }
            }

        }
        private IEnumerable<string> GetColumns()
        {
            var columns = new Dictionary<int, string>();

            foreach (PropertyInfo propertyInfo in _type.GetProperties())
            {
                var attribute = Attributes.GetAttribute<UserDefinedTableTypeColumnAttribute>(propertyInfo);

                if (attribute != null)
                    columns.Add(attribute.Order, propertyInfo.Name);
            }

            var sortedColumns = columns.OrderBy(kvp => kvp.Key);

            return sortedColumns.Select(kvp => kvp.Value);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Returns the string for the Authorisation header to be used for OAuth authentication.
        /// Parameters other than OAuth ones are ignored.
        /// </summary>
        /// <param name="parameters">OAuth and other parameters.</param>
        /// <returns></returns>
        public static string OAuthCalculateAuthHeader(Dictionary<string, string> parameters)
        {
            StringBuilder sb = new StringBuilder("OAuth ");

            var sorted = parameters.OrderBy(x => x.Key);

            foreach (KeyValuePair<string, string> pair in sorted)
            {
                if (pair.Key.StartsWith("oauth"))
                {
                    sb.Append(pair.Key + "=\"" + Uri.EscapeDataString(pair.Value) + "\",");
                }
            }

            return sb.Remove(sb.Length - 1, 1).ToString();
        }
Ejemplo n.º 5
0
        public override IEnumerable GetDistribution(Release[] releases)
        {
            Dictionary<string, int> result = new Dictionary<string, int>();

            foreach (Release release in releases)
            {
                if (!string.IsNullOrEmpty(release.Country))
                {
                    if (!result.ContainsKey(release.Country))
                    {
                        result[release.Country] = 0;
                    }

                    ++result[release.Country];
                }
            }

            var allItems = result.OrderBy(i => -i.Value);
            var topItems = allItems.Take(6);
            var otherItems = allItems.Skip(6);
            int otherItemsSum = otherItems.Sum(i => i.Value);

            foreach (var topItem in topItems)
            {
                yield return new Item()
                {
                    Key = topItem.Key + " (" + topItem.Value + ")",
                    Value = topItem.Value,
                    Countries = new string[] { topItem.Key },
                };
            }

            if (otherItemsSum != 0)
            {
                yield return new Item()
                {
                    Key = "Other (" + otherItemsSum + ")",
                    Value = otherItemsSum,
                    Countries = otherItems.Select(i => i.Key).ToArray()
                };
            }
        }
Ejemplo n.º 6
0
        public static void SortChildren(this IDomObject node)
        {
            if (node.ChildNodes.Count == 0)
                return;

            var buffer = new Dictionary<string, IDomObject>();

            foreach (var child in node.ChildNodes)
            {
                var value = GetValueBasedOnNode(child);
                if (!string.IsNullOrWhiteSpace(value))
                {
                    buffer.Add(value, child);
                }
            }

            node.ChildNodes.Clear();

            var sorted = buffer.OrderBy(x => x.Key);
            foreach (var kvp in sorted)
            {
                node.ChildNodes.Add(kvp.Value);
            }
        }
        public static string ProcessUniqueTerms(Index index)
        {
            _index = index;

            // initialize the rank dictionary
            Dictionary<int, double> rank = new Dictionary<int, double>();
            foreach (KeyValuePair<int, string> document in _index.documents)
                rank.Add(document.Key, 0.0);

            // loop though all of the documents in the index
            foreach (KeyValuePair<int, string> document in _index.documents)
            {
                rank[document.Key] = ((double)UniqueTermsCount(document.Value) / _index.GetDocumentLength(document.Key));
            }

            // calculate the results
            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<int, double> result in rank.OrderBy(z => z.Value))
            {
                sb.AppendLine(result.Key.ToString() + " " + result.Value.ToString());
            }

            return sb.ToString();
        }
        /// <summary>
        /// Determine popularity of classes for the selection process using the lists
        /// </summary>
        public void verifyPopularity()
        {
            AllClasses = new Dictionary<String, int>();

            ThirdClasses = new Dictionary<String, int>();
            SecondClasses = new Dictionary<String, int>();
            FirstClasses = new Dictionary<String, int>();

            foreach(Presenter currentPresenter in presenterList)
            {
                AllClasses.Add(currentPresenter.PresenterTitle, 0);

                #region Loop over all requests and populate dictionaries
                foreach (Request currentRequest in requestList)
                {
                    string presenterName = currentPresenter.PresenterTitle;
                    if (currentRequest.RequestOne.Equals(presenterName) || currentRequest.RequestTwo.Equals(presenterName) || currentRequest.RequestThree.Equals(presenterName) || currentRequest.RequestFour.Equals(presenterName) || currentRequest.RequestFive.Equals(presenterName))
                    {
                        if (AllClasses.ContainsKey(presenterName))
                        {
                            int currentCount = AllClasses[presenterName];
                            ++currentCount;
                            AllClasses[presenterName] = currentCount;
                        }
                        else
                        {
                            AllClasses.Add(presenterName, 1);
                        }
                    }

                    if (currentRequest.RequestThree.Equals(presenterName) )
                    {
                        if (ThirdClasses.ContainsKey(presenterName))
                        {
                            int currentCount = ThirdClasses[presenterName];
                            ++currentCount;
                            ThirdClasses[presenterName] = currentCount;
                        }
                        else
                        {
                            ThirdClasses.Add(presenterName, 1);
                        }
                    }

                    if (currentRequest.RequestTwo.Equals(presenterName) )
                    {
                        if (SecondClasses.ContainsKey(presenterName))
                        {
                            int currentCount = SecondClasses[presenterName];
                            ++currentCount;
                            SecondClasses[presenterName] = currentCount;
                        }
                        else
                        {
                            SecondClasses.Add(presenterName, 1);
                        }
                    }

                    if (currentRequest.RequestOne.Equals(presenterName))
                    {
                        if (FirstClasses.ContainsKey(presenterName))
                        {
                            int currentCount = FirstClasses[presenterName];
                            ++currentCount;
                            FirstClasses[presenterName] = currentCount;
                        }
                        else
                        {
                            FirstClasses.Add(presenterName, 1);
                        }
                    }
                }
            #endregion
            }

            AllClasses = AllClasses.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
            ThirdClasses = ThirdClasses.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
            SecondClasses = SecondClasses.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
            FirstClasses = FirstClasses.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
        }
Ejemplo n.º 9
0
        private void WriteDicionaryBase(object input)
        {
            int count = ((DictionaryBase) input).Count;
            WritePrimativeObject(count, typeof(int));
            IDictionaryEnumerator dicEnum = (input as DictionaryBase).GetEnumerator();
            var keyValList = new Dictionary<object, object>();

            while (dicEnum.MoveNext())
            {
                keyValList[dicEnum.Key] = dicEnum.Value;
            }

            var query = keyValList.OrderBy(keyVal => keyVal.Key.ToString());
            foreach (KeyValuePair<object, object> keyValuePair in query)
            {
                WriteObject(keyValuePair.Key);
                WriteObject(keyValuePair.Value);
            }

            //while (dicEnum.MoveNext())
            //{
            //    WriteObject(dicEnum.Key);
            //    WriteObject(dicEnum.Value);
            //}

            // Custom fields
            WriteCustomFields(input);
        }
Ejemplo n.º 10
0
        private void solidLoad(Info n)
        {


            Dictionary<string, int> keycache = new Dictionary<string, int>();
            SpecialBitmap jz;
            getAngleMap(n, jz = new SpecialBitmap(dir2 + "plane solid ang 1.png"), keycache, 1);
            getAngleMap(n, jz = new SpecialBitmap(dir2 + "plane solid ang 2.png"), keycache, 2);

            getHightMap(n, jz = new SpecialBitmap(dir2 + "plane solid n 1.png"), keycache, 1);
            getHightMap(n, jz = new SpecialBitmap(dir2 + "plane solid n 2.png"), keycache, 2);



            n.HeightMaps = keycache.OrderBy(a => a.Value).Select(a => a.Key).ToArray();

        }
Ejemplo n.º 11
0
        /// <summary>
        /// Describes the schema of the underlying data and services to the K2 platform.
        /// </summary>
        public void DescribeSchema()
        {
            TypeMappings map = GetTypeMappings();
            PDFInfo info = new PDFInfo();
            Dictionary<string, PDFField> fields = new Dictionary<string,PDFField>();

            // get PDDocument
            try
            {
                using (PdfReader doc = new PdfReader(pdfUri))
                {
                    // discover pdf doc
                    info = GetPDFDoucmentInformation(doc);
                    fields = DiscoverPDFFormFields(doc);
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            // create objects
            ServiceObject pdfServiceObject = new ServiceObject();
            pdfServiceObject.Name = info.Title.Replace(" ", "_");
            pdfServiceObject.MetaData.DisplayName = info.Title;
            pdfServiceObject.Active = true;

            List<Property> allprops = new List<Property>();
            List<Property> allfields = new List<Property>();
            List<Property> allmetadata = new List<Property>();

            Property inputUriproperty = new Property();
            inputUriproperty.Name = "pdfuri";
            inputUriproperty.MetaData.DisplayName = "PDF Uri";
            inputUriproperty.Type = typeof(System.String).ToString();
            inputUriproperty.SoType = SoType.Text;

            pdfServiceObject.Properties.Add(inputUriproperty);

            // has signatures
            Property hasSigsProperty = new Property();
            hasSigsProperty.Name = "containssignatures";
            hasSigsProperty.MetaData.DisplayName = "Contains Signatures";
            hasSigsProperty.Type = typeof(System.Boolean).ToString();
            hasSigsProperty.SoType = SoType.YesNo;

            pdfServiceObject.Properties.Add(hasSigsProperty);

            // has unsigned signatures
            Property containsUnsignedSigsProperty = new Property();
            containsUnsignedSigsProperty.Name = "containsunsignedsignatures";
            containsUnsignedSigsProperty.MetaData.DisplayName = "Contains Unsigned Signatures";
            containsUnsignedSigsProperty.Type = typeof(System.Boolean).ToString();
            containsUnsignedSigsProperty.SoType = SoType.YesNo;

            pdfServiceObject.Properties.Add(containsUnsignedSigsProperty);

            // for update - return base64?
            Property includebase64Property = new Property();
            includebase64Property.Name = "returnbase64";
            includebase64Property.MetaData.DisplayName = "Return Base64";
            includebase64Property.Type = typeof(System.Boolean).ToString();
            includebase64Property.SoType = SoType.YesNo;

            pdfServiceObject.Properties.Add(includebase64Property);

            // for update - base64
            Property base64Property = new Property();
            base64Property.Name = "base64pdf";
            base64Property.MetaData.DisplayName = "Base64 PDF";
            base64Property.Type = typeof(System.String).ToString();
            base64Property.SoType = SoType.Memo;

            pdfServiceObject.Properties.Add(base64Property);

            // for update - return path
            Property returnpathProperty = new Property();
            returnpathProperty.Name = "returnpath";
            returnpathProperty.MetaData.DisplayName = "Return Path";
            returnpathProperty.Type = typeof(System.String).ToString();
            returnpathProperty.SoType = SoType.Text;

            pdfServiceObject.Properties.Add(returnpathProperty);

            Type type = typeof(PDFInfo);
            PropertyInfo[] props = type.GetProperties();
            foreach (var p in props)
            {
                //text += docinfo.GetType().GetProperty(field.Name).GetValue(docinfo, null);

                Property infoproperty = new Property();
                infoproperty.Name = p.Name;
                infoproperty.MetaData.DisplayName = p.Name;
                infoproperty.Type = p.PropertyType.ToString();

                // needs to be mapped properly
                infoproperty.SoType = SoType.Text;

                pdfServiceObject.Properties.Add(infoproperty);
                allmetadata.Add(infoproperty);
                allprops.Add(infoproperty);
            }

            foreach (KeyValuePair<string, PDFField> field in fields.OrderBy(p => p.Key))
            {
                Property property = new Property();
                property.Name = field.Value.FullName.Replace(" ", "_");
                property.MetaData.DisplayName = field.Value.FullName;
                property.Type = typeof(System.String).ToString();
                property.SoType = SoType.Text;
                property.MetaData.ServiceProperties.Add("pdffullname", field.Value.FullName);
                property.MetaData.ServiceProperties.Add("pdfalternativename", field.Value.AlternativeName);
                property.MetaData.ServiceProperties.Add("pdfisreadonly", field.Value.IsReadOnly);
                property.MetaData.ServiceProperties.Add("pdfisrequired", field.Value.IsRequired);
                property.MetaData.ServiceProperties.Add("pdfpartialname", field.Value.PartialName);
                property.MetaData.ServiceProperties.Add("pdftype", field.Value.Type);

                allfields.Add(property);
                allprops.Add(property);
                pdfServiceObject.Properties.Add(property);
            }

            // add methods
            Method GetAllFieldValues = new Method();
            GetAllFieldValues.Name = "getallfieldvalues";
            GetAllFieldValues.MetaData.DisplayName = "Get All Field Values";
            GetAllFieldValues.Type = SourceCode.SmartObjects.Services.ServiceSDK.Types.MethodType.Read;

            GetAllFieldValues.InputProperties.Add(inputUriproperty);
            GetAllFieldValues.Validation.RequiredProperties.Add(inputUriproperty);

            GetAllFieldValues.ReturnProperties.Add(inputUriproperty);
            foreach (Property prop in allprops)
            {
                GetAllFieldValues.ReturnProperties.Add(prop);
            }

            pdfServiceObject.Methods.Add(GetAllFieldValues);

            // contains signatures method
            Method HasSigs = new Method();
            HasSigs.Name = "containssignatures";
            HasSigs.MetaData.DisplayName = "Contains Signatures";
            HasSigs.Type = SourceCode.SmartObjects.Services.ServiceSDK.Types.MethodType.Read;

            HasSigs.InputProperties.Add(inputUriproperty);
            HasSigs.Validation.RequiredProperties.Add(inputUriproperty);

            HasSigs.ReturnProperties.Add(inputUriproperty);
            HasSigs.ReturnProperties.Add(hasSigsProperty);

            pdfServiceObject.Methods.Add(HasSigs);

            // contains unsigned signatures method
            Method ContainsUnsigned = new Method();
            ContainsUnsigned.Name = "containsunsignedsignatures";
            ContainsUnsigned.MetaData.DisplayName = "Contains Unsigned Signatures";
            ContainsUnsigned.Type = SourceCode.SmartObjects.Services.ServiceSDK.Types.MethodType.Read;

            ContainsUnsigned.InputProperties.Add(inputUriproperty);
            ContainsUnsigned.Validation.RequiredProperties.Add(inputUriproperty);

            ContainsUnsigned.ReturnProperties.Add(inputUriproperty);
            ContainsUnsigned.ReturnProperties.Add(containsUnsignedSigsProperty);

            pdfServiceObject.Methods.Add(ContainsUnsigned);

            // add update
            Method UpdateMethod = new Method();
            UpdateMethod.Name = "updatepdffields";
            UpdateMethod.MetaData.DisplayName = "Update PDF Fields";
            UpdateMethod.Type = SourceCode.SmartObjects.Services.ServiceSDK.Types.MethodType.Update;

            UpdateMethod.InputProperties.Add(inputUriproperty);
            UpdateMethod.Validation.RequiredProperties.Add(inputUriproperty);
            UpdateMethod.InputProperties.Add(includebase64Property);
            UpdateMethod.Validation.RequiredProperties.Add(includebase64Property);

            foreach (Property prop in allfields)
            {
                UpdateMethod.InputProperties.Add(prop);
            }

            UpdateMethod.ReturnProperties.Add(inputUriproperty);
            UpdateMethod.ReturnProperties.Add(includebase64Property);

            foreach (Property prop in allprops)
            {
                UpdateMethod.ReturnProperties.Add(prop);
            }
            UpdateMethod.ReturnProperties.Add(returnpathProperty);
            UpdateMethod.ReturnProperties.Add(base64Property);

            pdfServiceObject.Methods.Add(UpdateMethod);

            if (!serviceBroker.Service.ServiceObjects.Contains(pdfServiceObject))
            {
                serviceBroker.Service.ServiceObjects.Add(pdfServiceObject);
            }

            // admin object
            ServiceObject adminServiceObject = new ServiceObject();
            adminServiceObject.Name = "Functions" + info.Title.Replace(" ", "_");
            adminServiceObject.MetaData.DisplayName = "Functions - " + info.Title;
            adminServiceObject.Active = true;

            adminServiceObject.Properties.Add(inputUriproperty);

            Property sqlProperty = new Property();
            sqlProperty.Name = "generatedsql";
            sqlProperty.MetaData.DisplayName = "Generated SQL";
            sqlProperty.Type = typeof(System.String).ToString();
            sqlProperty.SoType = SoType.Memo;

            adminServiceObject.Properties.Add(sqlProperty);

            // generate create table sql
            Method generateCreateTable = new Method();
            generateCreateTable.Name = "generatecreatetablesql";
            generateCreateTable.MetaData.DisplayName = "Generate Create Table SQL";
            generateCreateTable.Type = SourceCode.SmartObjects.Services.ServiceSDK.Types.MethodType.Read;

            generateCreateTable.ReturnProperties.Add(sqlProperty);

            adminServiceObject.Methods.Add(generateCreateTable);

            Property smoProperty = new Property();
            smoProperty.Name = "formstoresmartobjectname";
            smoProperty.MetaData.DisplayName = "Form Store SmartObject Name";
            smoProperty.Type = typeof(System.String).ToString();
            smoProperty.SoType = SoType.Text;

            adminServiceObject.Properties.Add(smoProperty);

            Property smoMethodProperty = new Property();
            smoMethodProperty.Name = "formstoremethodname";
            smoMethodProperty.MetaData.DisplayName = "Form Store Method Name";
            smoMethodProperty.Type = typeof(System.String).ToString();
            smoMethodProperty.SoType = SoType.Text;

            adminServiceObject.Properties.Add(smoMethodProperty);

            Property smoIdProperty = new Property();
            smoIdProperty.Name = "returnidpropertyname";
            smoIdProperty.MetaData.DisplayName = "Return Id Property Name";
            smoIdProperty.Type = typeof(System.String).ToString();
            smoIdProperty.SoType = SoType.Text;

            adminServiceObject.Properties.Add(smoIdProperty);

            Property returnIdProperty = new Property();
            returnIdProperty.Name = "returnid";
            returnIdProperty.MetaData.DisplayName = "Return Id";
            returnIdProperty.Type = typeof(System.String).ToString();
            returnIdProperty.SoType = SoType.Text;

            adminServiceObject.Properties.Add(returnIdProperty);

            // copy form data to smartobject
            Method copyFormData = new Method();
            copyFormData.Name = "copyformdatatosmartobject";
            copyFormData.MetaData.DisplayName = "Copy Form Data to SmartObject";
            copyFormData.Type = SourceCode.SmartObjects.Services.ServiceSDK.Types.MethodType.Read;

            copyFormData.InputProperties.Add(inputUriproperty);
            copyFormData.Validation.RequiredProperties.Add(inputUriproperty);
            copyFormData.ReturnProperties.Add(inputUriproperty);

            copyFormData.InputProperties.Add(smoProperty);
            copyFormData.Validation.RequiredProperties.Add(smoProperty);
            copyFormData.ReturnProperties.Add(smoProperty);

            copyFormData.InputProperties.Add(smoMethodProperty);
            copyFormData.Validation.RequiredProperties.Add(smoMethodProperty);
            copyFormData.ReturnProperties.Add(smoMethodProperty);

            copyFormData.InputProperties.Add(smoIdProperty);
            copyFormData.Validation.RequiredProperties.Add(smoIdProperty);
            copyFormData.ReturnProperties.Add(smoIdProperty);

            copyFormData.ReturnProperties.Add(returnIdProperty);

            adminServiceObject.Methods.Add(copyFormData);

            if (!serviceBroker.Service.ServiceObjects.Contains(adminServiceObject))
            {
                serviceBroker.Service.ServiceObjects.Add(adminServiceObject);
            }
        }
Ejemplo n.º 12
0
        // print in the order
        private static void reOrderPipeLine(Dictionary<string, int> clusterList, StreamWriter output)
        {
            foreach (var data in clusterList.OrderBy(key => key.Value))
            {
                output.WriteLine(data.Key);

            }
        }
Ejemplo n.º 13
0
        void Sort(List<MmlResolvedEvent> l)
        {
            var msgBlockByTime = new Dictionary<int,List<MmlResolvedEvent>> ();
            int m = 0;
            int prev = 0;
            while (m < l.Count) {
                var e = l [m];
                List<MmlResolvedEvent> pl;
                if (!msgBlockByTime.TryGetValue (l [m].Tick, out pl)) {
                    pl = new List<MmlResolvedEvent> ();
                    msgBlockByTime.Add (e.Tick, pl);
                }
                for (; m < l.Count; m++) {
                    pl.Add (l [m]);
                    if (m + 1 < l.Count && l [m + 1].Tick != prev)
                        break;
                }
                m++;
            }

            l.Clear ();
            foreach (var sl in msgBlockByTime.OrderBy (kvp => kvp.Key).Select (kvp => kvp.Value))
                l.AddRange (sl);
        }
Ejemplo n.º 14
0
 //Return the contained search key
 private string[] GetContainedSearchKeys(string[] searchKeys, string line)
 {
     searchKeys = RemovePartialWords(searchKeys.Where(k => line.IndexOf(k,
         StringComparison.InvariantCultureIgnoreCase) >= 0).ToArray());
     var containedKeys = new Dictionary<String, int>();
     foreach (string key in searchKeys)
     {
         var index = line.IndexOf(key, StringComparison.InvariantCultureIgnoreCase);
         if (index >= 0)
         {
             containedKeys.Add(key, index);
         }
     }
     return containedKeys.OrderBy(p => p.Value).Select(p => p.Key).ToArray();
 }
 public void Problem16()
 {
     Dictionary<string, double> d = new Dictionary<string,double>();
     int f;
     Console.ReadLineQ<int>(out f, "Fjöldi");
     for (int i = 0; i < f; i++)
     {
         string n;
         double h, t;
         Console.ReadLineQ(out n, "Nafn " + (i + 1)).ReadLineQ<double>(out h, "Hæð " + (i + 1)).ReadLineQ<double>(out t, "Þyngd " + (i + 1));
         Console.WriteLine("\n");
         d.Add(n, t / Math.Pow(h, 2));
     }
     foreach (var i in d.OrderBy(x => x.Value))
     {
         Console.WriteLine("{0} {1:0.#}" ,i.Key, i.Value);
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Export this ResxData to an .xlsx file
        /// 
        /// Adds a first page with instructions
        /// </summary>
        /// <param name="outputPath">Path to write .xlsx file to</param>
        public void ToXls(string outputPath, string screenshotsPath, Action<string> addSummaryDelegate)
        {
            Excel.Application app = new Excel.Application();
            Excel.Workbook wb = app.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
            Excel.Sheets sheets = wb.Worksheets;
            var cultures = this.exportCultures.Select(c => c.Name).ToList();

            var firstSheet = app.ActiveSheet as Excel.Worksheet;
            int sheetIndex = firstSheet.Index;

            // Iterate over all filesources that have keys assigned
            var filesources = this.PrimaryTranslation.Select(r => r.ResxRow.FileSource)
                                                     .Distinct();
            var filesourcesdict = new Dictionary<string, string>();
            foreach (var filesource in filesources)
            {
                // Create a dictionary for name:relative_path for all resx files
                var name = Regex.Replace(filesource, @"^.*\\", "");
                name = Regex.Replace(name, @"\.[^\.]*$", "");
                name = name.Substring(0, Math.Min(name.Length, 31));
                Debug.Assert(!filesourcesdict.ContainsKey(name), "Resource files with same name exist.");
                filesourcesdict.Add(name, filesource);
            }

            foreach (var filesource in filesourcesdict.OrderBy(kvp => kvp.Key))
            {
                // add sheet
                var sheet = sheets.Add(After: sheets[sheetIndex]) as Excel.Worksheet;
                sheet.Name = filesource.Key;
                sheetIndex = sheet.Index;
                addSummaryDelegate("Created sheet " + filesource.Key);

                FillXlsSheet(screenshotsPath, cultures, filesource, sheet);
            }

            // Make the first sheet active
            CreateExplanationSheet(firstSheet);
            ((Excel._Worksheet)firstSheet).Activate();

            // Save the Workbook and force overwriting by rename trick
            string tmpFile = Path.GetTempFileName();
            File.Delete(tmpFile);

            Excel.XlFileFormat fileFormat = Path.GetExtension(outputPath) == ".xls" ? Excel.XlFileFormat.xlExcel8 : Excel.XlFileFormat.xlWorkbookDefault;
            wb.SaveAs(Filename: tmpFile, AccessMode: Excel.XlSaveAsAccessMode.xlNoChange, FileFormat: fileFormat);
            File.Delete(outputPath);

            ExcelQuit(app, wb);

            // Move file otherwise handle is still used by excel
            File.Move(tmpFile, outputPath);

            if (!string.IsNullOrEmpty(this.ReadResxReport))
            {
                File.WriteAllText(outputPath + ".log", this.ReadResxReport);
            }
        }
Ejemplo n.º 17
0
        static List<MergeAction> FindDuplicateStories(Dictionary<long, SimpleStory> stories)
        {
            List<MergeAction> mergeActions = new List<MergeAction>();

            foreach (SimpleStory story in stories.OrderBy(n => n.Key).Select(n => n.Value))
            {
                var newerStories = stories
                    .Where(n => n.Key > story.StoryID).OrderBy(n => n.Key).Select(n => n.Value);

                if (!newerStories.Any())
                    break;

                //Get the distribution of similarity scores between this cluster and each of the most active stories
                var similarities = newerStories
                    .Select(n => new { StoryID = n.StoryID, Similarity = n.WordVector * story.WordVector })
                    .OrderByDescending(n => n.Similarity)
                    .ToList();

                //Check if there is a rapid drop somewhere in the similarity distribution
                bool distrHasRapidDrop = false;
                if (similarities.Count > 1)
                {
                    for (int i = 1; i < similarities.Count; i++)
                    {
                        if (similarities[i].Similarity > 0.01 
                            && similarities[i].Similarity < Settings.TweetClusterer_SW_MergeDropScale * similarities[i - 1].Similarity)
                        {
                            distrHasRapidDrop = true;
                            break;
                        }
                    }
                }

                //Merge the stories if similar
                if ((similarities[0].Similarity > Settings.TweetClusterer_SW_MergeThreshold
                    || similarities[0].Similarity > Settings.TweetClusterer_SW_MergeThresholdWithDrop && distrHasRapidDrop))
                {
                    long targetStoryID = story.StoryID;
                    var thisStoryMerges = mergeActions.Where(n => n.MergedStoryID == story.StoryID);
                    if (thisStoryMerges.Any())
                        targetStoryID = thisStoryMerges.Min(n => n.KeptStoryID);
                    mergeActions.Add(new MergeAction() { KeptStoryID = targetStoryID, MergedStoryID = similarities[0].StoryID });
                }
            }

            return mergeActions;
        }
Ejemplo n.º 18
0
 public void InitializeTwoParameterAdd(bool useInterpreter)
 {
     Expression<Func<Dictionary<string, int>>> dictInit = () => new Dictionary<string, int>
     {
         { "a", 1 }, {"b", 2 }, {"c", 3 }
     };
     Func<Dictionary<string, int>> func = dictInit.Compile(useInterpreter);
     var expected = new Dictionary<string, int>
     {
         { "a", 1 }, {"b", 2 }, {"c", 3 }
     };
     Assert.Equal(expected.OrderBy(kvp => kvp.Key), func().OrderBy(kvp => kvp.Key));
 }
Ejemplo n.º 19
0
        public static string CreateOauthSignature(Dictionary<string, string> dic, string url, string method, string consumer_secret, string oauth_token_secret)
        {
            string HashKey = consumer_secret + "&" + oauth_token_secret;
            string OauthSignature = "";
            string Paras = "";
            string BaseString = method + "&" + RFC3986_UrlEncode(url) + "&";
            Paras = RFC3986_UrlEncode(dic.OrderBy(x => x.Key).ToDictionary(x => x.Key, y => y.Value).ToQueryString());
            BaseString += Paras;

            using (HMACSHA1 crypto = new HMACSHA1())
            {
                crypto.Key = Encoding.ASCII.GetBytes(HashKey);
                OauthSignature = Convert.ToBase64String(crypto.ComputeHash(Encoding.ASCII.GetBytes(BaseString)));
            }

            return OauthSignature;
        }
Ejemplo n.º 20
0
		private void GenerateMethod(Type interfaceType, FieldBuilder handlerField, TypeBuilder typeBuilder) {

			MetaDataFactory.Add(interfaceType);

			// Obtém a lista de todos os métodos a serem criados.
			MethodInfo[] interfaceMethods = interfaceType.GetMethods().OrderBy(p => p.Name).ToArray();

			// Verifica se existe algum método a ser implementado na interface.
			if (interfaceMethods != null) {

				// Cria cada um dos métodos definidos na interface.
				for (int i = 0; i < interfaceMethods.Length; i++) {

					MethodInfo methodInfo = interfaceMethods[i];

					// Obtém os parâmetros do método que está sendo criado.
					ParameterInfo[] methodParams = methodInfo.GetParameters();
					int numOfParams = methodParams.Length;
					Type[] methodParameters = new Type[numOfParams];

					// Armazena o tipo de cada parâmetro do método.
					for (int j = 0; j < numOfParams; j++) {
						methodParameters[j] = methodParams[j].ParameterType;
					}

					// Armazena todos os tipos genéricos do método.
					Type[] genericArguments = methodInfo.GetGenericArguments();

					MethodBuilder methodBuilder = null;

					// Verifica se o método não possui tipos genéricos.
					if (genericArguments.Length == 0) {

						// Cria um MethodBuilder para o método da interface que esta sendo criado. Como não há tipos genéricos, a definição é feita em apenas uma etapa.
						methodBuilder = typeBuilder.DefineMethod(
							methodInfo.Name,
							MethodAttributes.Public | MethodAttributes.Virtual,
							CallingConventions.Standard,
							methodInfo.ReturnType, methodParameters);
					}
					else {

						// Cria um MethodBuilder que deverá ser preenchido em etapas, pois os tipos genéricos do método precisam ser identificados.
						methodBuilder = typeBuilder.DefineMethod(
							methodInfo.Name,
							MethodAttributes.Public | MethodAttributes.Virtual,
							CallingConventions.Standard);

						// Define o tipo de retorno do método.
						methodBuilder.SetReturnType(methodInfo.ReturnType);

						Dictionary<int, string> typeParamNames = new Dictionary<int, string>();
						Dictionary<int, Type> parameters = new Dictionary<int, Type>();

						int currentIndex = 0;

						// Analisa todos os parâmetros do método.
						foreach (ParameterInfo parameterInfo in methodParams) {

							// Caso o parâmetro não possua a propriedade FullName preenchida, indica que é um tipo genérico. Caso contrário, é um tipo forte.
							if (parameterInfo.ParameterType.FullName == null) {
								typeParamNames.Add(currentIndex, parameterInfo.ParameterType.Name);
							}
							else {
								parameters.Add(currentIndex, parameterInfo.ParameterType);
							}

							currentIndex++;
						}

						// Verifica se existe algum tipo genérico.
						if (typeParamNames.Count > 0) {

							// Informa ao MethodBuilder os nomes dos tipos genéricos.
							GenericTypeParameterBuilder[] typeParameters = methodBuilder.DefineGenericParameters(typeParamNames.Values.ToArray());

							// Adiciona os tipos genéricos na lista de tipos do método.
							for (int j = 0; j < typeParameters.Length; j++) {
								int parameterIndex = typeParamNames.ElementAt(j).Key;
								parameters.Add(parameterIndex, typeParameters[j]);
							}

							// Define o tipo de retorno do método.
							methodBuilder.SetReturnType(methodInfo.ReturnType);
						}
						// Verifica se o tipo de retorno é um tipo genérico.
						else if (methodInfo.ReturnType.IsGenericParameter == true) {

							// Informa ao MethodBuilder o nome do tipo genérico.
							GenericTypeParameterBuilder[] returnParameter = methodBuilder.DefineGenericParameters(methodInfo.ReturnType.Name);

							// Define o tipo de retorno do método.
							methodBuilder.SetReturnType(returnParameter[0]);
						}
						else {
							// Informa ao MethodBuilder os nomes dos tipos genéricos.
							methodBuilder.DefineGenericParameters(genericArguments.Select(p => p.Name).ToArray());
						}

						IEnumerable<Type> orderedParameters = parameters.OrderBy(p => p.Key).Select(p => p.Value);

						// Informa ao MethodBuilder os nomes de todos os parâmetros do método.
						methodBuilder.SetParameters(orderedParameters.ToArray());
					}

					#region( "Handler Method IL Code" )

					bool hasReturnValue = (methodInfo.ReturnType.Equals(typeof(void)) == false);

					ILGenerator methodIL = methodBuilder.GetILGenerator();

					// Sempre declare um array para conter os parâmetros para o método a ser chamado pelo proxy.
					methodIL.DeclareLocal(typeof(System.Object[]));

					// Emite a declaração de uma variável local, caso exista um tipo de retorno para o método.
					if (hasReturnValue == true) {

						methodIL.DeclareLocal(methodInfo.ReturnType);

						//if (methodInfo.ReturnType.IsValueType && (methodInfo.ReturnType.IsPrimitive == false)) {
						//	methodIL.DeclareLocal(methodInfo.ReturnType);
						//}
					}

					// Cria um label para indicar onde o uso do proxy é iniciado.
					Label handlerLabel = methodIL.DefineLabel();

					// Cria um label para indicar onde está a saída do método (return).
					Label returnLabel = methodIL.DefineLabel();

					// Carrega "this" no stack.
					methodIL.Emit(OpCodes.Ldarg_0);

					// Carrega o handler para o proxy.
					methodIL.Emit(OpCodes.Ldfld, handlerField);

					// Caso exista um proxy, pula para o label que será utilizado para executá-lo.
					methodIL.Emit(OpCodes.Brtrue_S, handlerLabel);

					// Verifica se o método possui retorno.
					if (hasReturnValue == true) {

						// Caso seja um tipo primitivo apenas cria a variável de retorno, com o valor default do tipo.
						if (methodInfo.ReturnType.IsValueType && methodInfo.ReturnType.IsPrimitive == false && methodInfo.ReturnType.IsEnum == false
							&& (methodInfo.ReturnType.IsGenericType && methodInfo.ReturnType.GetGenericTypeDefinition() == typeof(Nullable<>)) == false) {
							//methodIL.Emit(OpCodes.Ldloc_1);
							methodIL.Emit(OpCodes.Ldloc_0);
						}
						// Caso o retorno seja uma classe, carrega nulo na variável de retorno.
						else {
							methodIL.Emit(OpCodes.Ldnull);
						}

						// Armazena o valor de retorno.
						methodIL.Emit(OpCodes.Stloc_0);

						// Passa para o fim do método.
						//methodIL.Emit(OpCodes.Br_S, returnLabel);
						methodIL.Emit(OpCodes.Br, returnLabel);
					}
					else {
						// Passa para o fim do método.
						//methodIL.Emit(OpCodes.Br_S, returnLabel);
						methodIL.Emit(OpCodes.Br, returnLabel);
					}

					// Define o label que indica o início do trecho de execução do proxy.
					methodIL.MarkLabel(handlerLabel);

					// Carrega "this" no stack.
					methodIL.Emit(OpCodes.Ldarg_0);

					// Carrega o handler para o IDinamicProxy.
					methodIL.Emit(OpCodes.Ldfld, handlerField);

					// Carrega "this" no stack. Será utilizado para chamar o método GetMethod mais abaixo.
					methodIL.Emit(OpCodes.Ldarg_0);

					// Carrega o nome da interface no stack.
					methodIL.Emit(OpCodes.Ldstr, interfaceType.FullName);

					// Carrega o índice do método no stack.
					methodIL.Emit(OpCodes.Ldc_I4, i);

					// Executa o método GetMethod da classe MetaDataFactory, passando como parâmetros o nome da interface e o índice do método, carregados no stack.
					methodIL.Emit(OpCodes.Call, typeof(MetaDataFactory).GetMethod("GetMethod", new Type[] { typeof(string), typeof(int) }));

					// Carrega a quantidade de parâmetros do método no topo do stack.
					methodIL.Emit(OpCodes.Ldc_I4, numOfParams);

					// Cria um array de objetos. A quantidade de parâmetros carregados no stack é utilizado para definir o tamanho do array.
					methodIL.Emit(OpCodes.Newarr, typeof(System.Object));

					// Adiciona cada parâmetro existente na lista de parâmetros que serão utilizados ao invocar o método concreto.
					if (numOfParams > 0) {

						//methodIL.Emit(OpCodes.Stloc_1);
						methodIL.Emit(OpCodes.Stloc_0);

						for (int j = 0; j < numOfParams; j++) {

							//methodIL.Emit(OpCodes.Ldloc_1);
							methodIL.Emit(OpCodes.Ldloc_0);
							methodIL.Emit(OpCodes.Ldc_I4, j);
							methodIL.Emit(OpCodes.Ldarg, j + 1);

							if (methodParameters[j].IsValueType) {
								methodIL.Emit(OpCodes.Box, methodParameters[j]);
							}

							methodIL.Emit(OpCodes.Stelem_Ref);
						}

						//methodIL.Emit(OpCodes.Ldloc_1);
						methodIL.Emit(OpCodes.Ldloc_0);
					}

					// Carrega a quantidade de argumentos genéricos para criar o próximo array.
					methodIL.Emit(OpCodes.Ldc_I4, genericArguments.Length);

					// Cria um array que conterá todos os tipos genéricos do método.
					methodIL.Emit(OpCodes.Newarr, typeof(System.Type));

					// Adicionamos o tipo de cada parâmetro genérico no array.
					if (genericArguments.Length > 0) {

						// Salva o array.
						methodIL.Emit(OpCodes.Stloc_0);

						// Obtém cada parâmetro genérico a ser adicionado.
						for (int j = 0; j < genericArguments.Length; j++) {

							// Carrega o array.
							methodIL.Emit(OpCodes.Ldloc_0);

							// Seleciona a posição j do array.
							methodIL.Emit(OpCodes.Ldc_I4, j);

							// Carrega o item a ser adicionado no array.
							methodIL.Emit(OpCodes.Ldtoken, genericArguments[j]);

							// Caso o parâmetro seja value type, é preciso fazer box.
							if (genericArguments[j].IsValueType) {
								methodIL.Emit(OpCodes.Box, genericArguments[j]);
							}

							// Insere o item no array.
							methodIL.Emit(OpCodes.Stelem_Ref);
						}

						// Carrega o array preenchido, para que seja usado no método a seguir.
						methodIL.Emit(OpCodes.Ldloc_0);
					}

					// Chama o método concreto através do Invoke.
					methodIL.Emit(OpCodes.Callvirt, typeof(IDynamicProxy).GetMethod("Invoke"));

					// Verifica se o método possui returno.
					if (hasReturnValue == true) {

						// Faz o unbox do valor de retorno, caso seja um valueType ou generic.
						if (methodInfo.ReturnType.IsValueType == true || methodInfo.ReturnType.IsGenericParameter == true) {

							methodIL.Emit(OpCodes.Unbox, methodInfo.ReturnType);
							if (methodInfo.ReturnType.IsEnum) {
								methodIL.Emit(OpCodes.Ldind_I4);
							}
							else if (methodInfo.ReturnType.IsPrimitive == false) {
								methodIL.Emit(OpCodes.Ldobj, methodInfo.ReturnType);
							}
							else {
								methodIL.Emit((OpCode)opCodeTypeMapper[methodInfo.ReturnType]);
							}
						}
						else {

							methodIL.Emit(OpCodes.Castclass, methodInfo.ReturnType);
						}

						// Armazena o valor retornado pelo método Invoke.
						//methodIL.Emit(OpCodes.Stloc_0);
						methodIL.Emit(OpCodes.Stloc_1);

						// Pula para o label de saída do método.
						//methodIL.Emit(OpCodes.Br_S, returnLabel);
						methodIL.Emit(OpCodes.Br, returnLabel);

						// Define o label para o ponto de saída do método;
						methodIL.MarkLabel(returnLabel);

						// Carrega o valor armazenado antes de retornar. Será nulo, caso não exista retorno, ou será o valor retornado pelo método Invoke.
						//methodIL.Emit(OpCodes.Ldloc_0);
						methodIL.Emit(OpCodes.Ldloc_1);
					}
					else {
						// Como o método não possui retorno, remove qualquer valor armazenado antes de retornar. 
						methodIL.Emit(OpCodes.Pop);

						// Define o label para o ponto de saída do método;
						methodIL.MarkLabel(returnLabel);
					}

					// Define o ponto de saída do método (return);
					methodIL.Emit(OpCodes.Ret);
					#endregion

				}
			}

			// Chama todas as demais interfaces herdadas pela interface atual, recursivamente.
			foreach (Type parentType in interfaceType.GetInterfaces()) { GenerateMethod(parentType, handlerField, typeBuilder); }
		}
        private void button8_Click_1(object sender, EventArgs e)
        {
            List<string> final_lst = new List<string>();
            ListViewItem li;

            string[] arr = new string[3];

            string col1 = "";
            string col2 = "";

            // treeView2.Nodes.Add("Topical Tweets");
            //  treeView3.Nodes.Add("Topical Tweets");
            foreach (string data in c1)
            {
                col2 = "";
                foreach (string str in collfin3)
                {
                    //if (str.Contains("#"))
                    //{
                    //    //if (!str.Contains("#followfriday") && !str.Contains("#ff") && !str.Contains("#FF") && !str.Contains("#follow friday") && !str.Contains("was") && !str.Contains("had"))
                    //    //{
                    //    //    treeView2.Nodes[0].Nodes.Add(str);
                    //    //    //string col1=
                    //    //}
                    //    //else
                    //    //{
                    //    //    if (!str.Contains("#followfriday") && !str.Contains("#ff") && !str.Contains("#FF") && !str.Contains("#follow friday"))
                    //    //        treeView3.Nodes[0].Nodes.Add(str);
                    //    //}

                    //}
                    //else
                    //{
                    List<string> gern = new List<string>() { };

                    if (str.Contains(data))
                    {
                        //if (!str.Contains("was") && !str.Contains("had"))
                        //{
                        //    treeView2.Nodes[0].Nodes.Add(str);
                        col1 = data;
                        //col2 = "";
                        var coll_col2 = str.Split(' ');
                        gern = coll_col2.ToList();
                        foreach (string chk in rem_topic)
                        {
                            gern.Remove(chk);
                        }

                        foreach (string spli_str in gern)
                        {
                            if (spli_str.Length > 5)
                            {

                                if (!col2.Contains(spli_str))
                                {
                                    col2 += spli_str + ", ";

                                }

                            }
                        }
                        if(!final_lst .Contains (col2 ))
                        final_lst.Add(col2);

                        //   }
                        //else
                        //{
                        //    treeView3.Nodes[0].Nodes.Add(str);
                        //}
                    }

                }
                // }
                if (col2 != "")
                {
                    //Random r = new Random();
                    //int num = r.Next(10, 50);
                    //arr[0] = col1;
                    //arr[1] = col2;
                    //arr[2] = num.ToString();
                    //li = new ListViewItem(arr);
                    //listView2.Items.Add(li);
                }
                //col2 = "";

            }

            Random r1 = new Random();
            int num1 = r1.Next(8, 15);
            List<int> re=new List<int> ();
            for (int j = 0; j < num1; )
            {
                Random r = new Random();
                int num = r.Next(j, 25);
                if (!re.Contains(num))
                {
                    re.Add(num);
                    j = j + 1;
                }
            }
            //for(int i=0;i<num1;i++)
            //{

            //    //arr[0] = col1;
            //    arr[0] = final_lst[i].ToString ();
            //    arr[1] = re[i].ToString();
            //    li = new ListViewItem(arr);
            //    listView2.Items.Add(li);

            //}

            temp t = new temp();
            Dictionary<List<int>, List<string>> newdic = new Dictionary<List<int>, List<string>>();

            newdic=t.reasonC(textBox2.Text.ToString ());

            foreach (KeyValuePair<List<int>, List<string>> kvp in newdic.OrderBy(key => key.Key ))
            {
                for (int i = 0, j = 0; i < kvp.Key.Count  && j < kvp.Value.Count ; i++, j++)
                {
                    arr[1] = kvp.Key[i].ToString();
                    arr[0] = kvp.Value[j].ToString();
                    li = new ListViewItem(arr);
                    listView2.Items.Add(li);
                }
            }
            //treeView2.ExpandAll();
            //treeView3.ExpandAll();
            //button16_Click1(null, null);
        }
Ejemplo n.º 22
0
        private static void GetEnumValuesAndNames(IEdmEnumType enumType, ref ulong[] values, ref string[] names, bool getValues, bool getNames)
        {
            Dictionary<string, ulong> dict = new Dictionary<string, ulong>();
            foreach (var member in enumType.Members)
            {
                EdmIntegerConstant intValue = member.Value as EdmIntegerConstant;
                if (intValue != null)
                {
                    dict.Add(member.Name, (ulong)intValue.Value);
                }
            }

            Dictionary<string, ulong> sortedDict = dict.OrderBy(d => d.Value).ToDictionary(d => d.Key, d => d.Value);
            values = sortedDict.Select(d => d.Value).ToArray();
            names = sortedDict.Select(d => d.Key).ToArray();
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="xmlSource"></param>
        /// <param name="logger"> </param>
        /// <param name="format">must include "{LineNo}" for Line Number spot</param>
        /// <param name="ignoreElements"> </param>
        /// <returns></returns>
        public string TagXmlElements(string xmlSource, Action<string> logger, string format, IEnumerable<string> ignoreElements)
        {
            var prefixXOnceList = new List<string>();

            format = format.Replace(LineNumberFormatTag, "{0}");
            var frameworkElements = new AssemblyHelper()
                .GetFrameworkElements().Select(fe => fe.Name).ToList();

            StringBuilder output = new StringBuilder();
            XmlWriterSettings ws = new XmlWriterSettings();
            XmlWriter writer = null;

            var q = this.TraverseTree(xmlSource);

            bool isFirstElement = true;

            // Create an XmlReader
            using (XmlTextReader reader =
                new XmlTextReader(new StringReader(xmlSource)))
            {
                ws.ConformanceLevel = ConformanceLevel.Auto;

                using (writer = XmlWriter.Create(output, ws))
                {
                    // Parse the file and display each of the nodes.
                    while (reader.Read())
                    {
                        switch (reader.NodeType)
                        {
                            case XmlNodeType.Element:
                                //writer.WriteAttributes(reader, false);
                                var eName = reader.Name;

                                if (isFirstElement)
                                {
                                    isFirstElement = false;

                                    if (!_validFirstElement.Contains(eName))
                                    {
                                        logger(string.Format("Not tagging file with first Element: {0}", eName));
                                        return xmlSource;
                                    }
                                }

                                var hasValue = !reader.IsEmptyElement;
                                var currentNode = q.Dequeue();

                                //nodes may have more elements than reader shows, resync if needed
                                int maxTries = 15;
                                while (currentNode.Name != eName && (currentNode = q.Dequeue()) != null && maxTries-- > 0)
                                {
                                }

                                if (currentNode == null || maxTries == 0)
                                {
                                    throw new InvalidOperationException("Can't sync to xaml.  aborting.");
                                }

                                var attributes = new Dictionary<string, string>();

                                for (int i = 0; i < reader.AttributeCount; ++i)
                                {
                                    reader.MoveToNextAttribute();

                                    attributes.Add(reader.Name, reader.Value);
                                }

                                string xmlns = null;
                                if (attributes.ContainsKey("xmlns"))
                                {
                                    xmlns = attributes["xmlns"];
                                    attributes.Remove("xmlns");
                                }
                                //xmlns:cfx

                                if (eName.Contains(":"))
                                {
                                    var split = eName.Split(':');

                                    var extraNamespace = "xmlns:" + split[0];
                                    if (xmlns == null && attributes.ContainsKey(extraNamespace))
                                    {
                                        xmlns = attributes[extraNamespace];
                                        attributes.Remove(extraNamespace);
                                    }

                                    writer.WriteStartElement(split[0], split[1], xmlns);
                                }
                                else
                                {
                                    writer.WriteStartElement(eName, xmlns);
                                }

                                foreach (var attribute in attributes.OrderBy(pair => pair.Key.StartsWith("xmlns") ? 0 : 1))  //put the xmlns first to get the proper output
                                {
                                    //for (int i = 0; i < reader.AttributeCount; ++i)
                                    //{
                                    //    reader.MoveToNextAttribute();
                                    var name = attribute.Key;

                                    if (this._requiresXPrefix.Contains(name) && !prefixXOnceList.Contains(name))
                                    {
                                        prefixXOnceList.Add(name);
                                        name = "x:" + name;
                                    }

                                    if (name.Contains(":"))
                                    {
                                        var split = name.Split(':');
                                        writer.WriteAttributeString(split[0], split[1], null, attribute.Value);
                                    }
                                    else
                                    {
                                        writer.WriteAttributeString(name, attribute.Value);
                                    }

                                }

                                if (frameworkElements.Contains(eName) && !ignoreElements.Contains(eName))
                                {

                                    bool hasTag = reader.GetAttribute("Tag") != null
                                        || (currentNode.ChildNodes.Cast<XmlNode>())
                                        .Any(n => n.Name == eName + ".Tag");

                                    if (!hasTag)
                                        writer.WriteAttributeString("Tag",
                                            string.Format(format, reader.LineNumber.ToString()));
                                }

                                if (!hasValue)
                                {
                                    writer.WriteEndElement();
                                }
                                break;
                            case XmlNodeType.Text:
                                writer.WriteString(reader.Value);
                                break;
                            case XmlNodeType.XmlDeclaration:
                            case XmlNodeType.ProcessingInstruction:
                                writer.WriteProcessingInstruction(reader.Name, reader.Value);
                                break;
                            case XmlNodeType.Comment:
                                writer.WriteComment(reader.Value);
                                break;
                            case XmlNodeType.EndElement:
                                writer.WriteFullEndElement();
                                break;
                        }
                    }

                }
            }

            XDocument doc = XDocument.Parse(output.ToString());
            return doc.ToString();
        }
Ejemplo n.º 24
0
        private Dictionary<object, object> initXValues(ResultPage page, List<ResultCell[]> XDimensions)
        {
            Dictionary<object, object> result = new Dictionary<object, object>();
            bool hasNVD3Pie = Model.Elements.Exists(i => i.SerieDefinition == SerieDefinition.NVD3Serie && i.Nvd3Serie == NVD3SerieDefinition.PieChart && i.PivotPosition == PivotPosition.Data);
            bool orderAsc = true;
            foreach (var dimensions in XDimensions)
            {
                //One value -> set the raw value, several values -> concat the display value
                if (dimensions.Length == 1)
                {

                    if (!dimensions[0].Element.IsEnum && dimensions[0].Element.AxisUseValues && !hasNVD3Pie)
                    {
                        result.Add(dimensions, dimensions[0].Value);
                    }
                    else
                    {
                        result.Add(dimensions, dimensions[0].ValueNoHTML);
                    }
                }
                else result.Add(dimensions, Helper.ConcatCellValues(dimensions, ","));

                if (dimensions.Length > 0 && dimensions[0].Element.SortOrder.Contains(SortOrderConverter.kAutomaticDescSortKeyword)) orderAsc = false;
            }

            return orderAsc ? result.OrderBy(i => i.Value).ToDictionary(i => i.Key, i => i.Value) : result.OrderByDescending(i => i.Value).ToDictionary(i => i.Key, i => i.Value);
        }
Ejemplo n.º 25
0
        private string CalculateAuthSignature(Dictionary<string, string> parameters)
        {

                var sorted = parameters.OrderBy(p => p.Key);

            StringBuilder sb = new StringBuilder(ApiSecret);
            foreach (KeyValuePair<string, string> pair in sorted)
            {
                sb.Append(pair.Key);
                sb.Append(pair.Value);
            }
            string signature = UtilityMethods.MD5Hash(sb.ToString());
            return signature;
        }
        public void GeneratePLTS()
        {
            int i, j, m, k;
            uint eidcount = 10;
            uint sidbegin;
            uint sid;
            uint layernum;
            uint current;
            uint Allsnum = 0;
            HashSet<uint> tmpeset = new HashSet<uint>();

    
            Queue<uint> generatelts = new Queue<uint>();
            Dictionary<uint, uint> tmpdic = new Dictionary<uint,uint>();
            List<KeyValuePair<uint,uint>> tmplist;
            
            Random rd = new Random((int)System.DateTime.Today.Ticks);
            
            generatelts.Enqueue(1);

            string path1 = "./test/Lts1.txt";
            string path2 = "./test/Lts2.txt";
            string path3 = "./test/evt.txt";
            string path4 = "./test/allsnum.txt";

            StreamWriter [] sw = new StreamWriter[2];
            sw[0] = new StreamWriter(path1, true);
            sw[1] = new StreamWriter(path2, true);

            StreamWriter sw2 = new StreamWriter(path3, true);
            StreamWriter sw3 = new StreamWriter(path4, true);

            for (i = 0; i < LTSnum; i++)
            {
                Allsnum++;
                layernum = (uint)(Math.Pow(2, beginsynlayer)*2 - 1);
                for (j = 0; j < layernum; j++)
                {
                    current = generatelts.Dequeue();
                    
                    //layernum = layernum * 2;
                    sidbegin = current * 2;
                    for (m = 0; m < 2; m++)
                    {
                        sid = sidbegin + (uint)m;
                        generatelts.Enqueue(sid);
                        Allsnum++;
                        if (i == 0)
                        {
                            eidcount = (uint)rd.Next(11, 31);

                            if(!tmpeset.Contains(eidcount))
                            {
                                  tmpeset.Add(eidcount);
                                  if (!this.eventlist.Contains(eidcount))
                                    this.eventlist.Add(eidcount);
                                  //sw[i].Write(eidcount);
                            }
                            else
                            {
                                while (tmpeset.Contains(eidcount))
                                {
                                    eidcount = (uint)rd.Next(11, 31);
                                }
                                tmpeset.Add(eidcount);
                                if (!this.eventlist.Contains(eidcount))
                                    this.eventlist.Add(eidcount);
                                //sw[i].Write(eidcount);
                            }

                        }
                        else
                        {
                            eidcount = (uint)rd.Next(31, 51);

                            if (!tmpeset.Contains(eidcount))
                            {
                                tmpeset.Add(eidcount);
                                if (!this.eventlist.Contains(eidcount))
                                    this.eventlist.Add(eidcount);
                                //sw[i].Write(eidcount);
                            }
                            else
                            {
                                while (tmpeset.Contains(eidcount))
                                {
                                    eidcount = (uint)rd.Next(11, 31);
                                }
                                tmpeset.Add(eidcount);
                                if (!this.eventlist.Contains(eidcount))
                                    this.eventlist.Add(eidcount);
                                //sw[i].Write(eidcount);
                            }
                        }
                       
                        //sw[i].Write(" ");
                        tmpdic.Add(eidcount,sid);
                   
                       
                        
                    }
                    tmpdic = tmpdic.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
                    tmplist = tmpdic.ToList();
                    for(k = 0; k < tmplist.Count; k++){
                        sw[i].Write(tmplist[k].Key);
                        sw[i].Write(" ");
                        sw[i].Write(tmplist[k].Value);
                        sw[i].Write(" ");
                    }
                    
                    tmpeset.Clear();
                    tmpdic.Clear();
                    sw[i].Write("\n");
                }

                layernum = (uint)(Math.Pow(2, beginsynlayer + 1));
                layernum = (uint)((layernum + layernum*4*(totallayer-beginsynlayer-1))*(totallayer-beginsynlayer))/2; 
                for (k = 0; k < layernum; k++ )
                {
                    current = generatelts.Dequeue();
                    sidbegin = current * 4;
                    if (rd.Next(0, 2) == 0)
                    {
                        for (m = 0; m < 4; m++)
                        {
                            sid = sidbegin + (uint)m;
                            generatelts.Enqueue(sid);
                            Allsnum++;
                            if (i == 0)
                            {
                                eidcount = (uint)rd.Next(11, 31);

                                if (!tmpeset.Contains(eidcount))
                                {
                                    tmpeset.Add(eidcount);
                                    if(!this.eventlist.Contains(eidcount))
                                        this.eventlist.Add(eidcount);
                                    //sw[i].Write(eidcount);
                                }
                                else
                                {
                                    while (tmpeset.Contains(eidcount))
                                    {
                                        eidcount = (uint)rd.Next(11, 31);
                                    }
                                    tmpeset.Add(eidcount);
                                    if (!this.eventlist.Contains(eidcount))
                                        this.eventlist.Add(eidcount);
                                    //sw[i].Write(eidcount);
                                }

                            }
                            else
                            {
                                eidcount = (uint)rd.Next(31, 51);

                                if (!tmpeset.Contains(eidcount))
                                {
                                    tmpeset.Add(eidcount);
                                    if (!this.eventlist.Contains(eidcount))
                                        this.eventlist.Add(eidcount);
                                   // sw[i].Write(eidcount);
                                }
                                else
                                {
                                    while (tmpeset.Contains(eidcount))
                                    {
                                        eidcount = (uint)rd.Next(31, 51);
                                    }
                                    tmpeset.Add(eidcount);
                                    if (!this.eventlist.Contains(eidcount))
                                        this.eventlist.Add(eidcount);
                                    //sw[i].Write(eidcount);
                                }
                            }
                            
                            tmpdic.Add(eidcount, sid);
                            
                            //sw[i].Write(" ");
                            //sw[i].Write(sid);
                           
                        }
                        tmpdic = tmpdic.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
                        tmplist = tmpdic.ToList();
                        for(m = 0; m < tmplist.Count; m++){
                            sw[i].Write(tmplist[m].Key);
                            sw[i].Write(" ");
                            sw[i].Write(tmplist[m].Value);
                            sw[i].Write(" ");
                        }
                    
                        tmpeset.Clear();
                        tmpdic.Clear();
                        sw[i].Write("\n");
                    }
                    else
                    {
                        sid = sidbegin;
                        generatelts.Enqueue(sid);
                        Allsnum++;
                        if(i == 0)
                            eidcount = (uint)rd.Next(11, 31);
                        else
                            eidcount = (uint)rd.Next(31, 51);
                        sw[i].Write(eidcount);
                        sw[i].Write(" ");
                        sw[i].Write(sid);
                       
                        sw[i].Write(" 0 1 ");

                        for (m = 1; m < 4; m++)
                        {
                            sid = sidbegin + (uint)m;
                            generatelts.Enqueue(sid);
                            Allsnum++;

                            eidcount = (uint)rd.Next(0, 11);
                            if (!tmpeset.Contains(eidcount))
                            {
                                //sw[i].Write(eidcount);
                                tmpeset.Add(eidcount);
                                if (!this.eventlist.Contains(eidcount))
                                    this.eventlist.Add(eidcount);
                            }
                            else
                            {
                                while (tmpeset.Contains(eidcount))
                                {
                                    eidcount = (uint)rd.Next(11, 31);
                                }
                                tmpeset.Add(eidcount);
                                if (!this.eventlist.Contains(eidcount))
                                    this.eventlist.Add(eidcount);
                                //sw[i].Write(eidcount);
                            }
                            tmpdic.Add(eidcount, sid);
                            
                            //sw[i].Write(" ");
                            //sw[i].Write(sid);
                        }
                        tmpdic = tmpdic.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
                        tmplist = tmpdic.ToList();
                        for(m = 0; m < tmplist.Count; m++){
                            sw[i].Write(tmplist[m].Key);
                            sw[i].Write(" ");
                            sw[i].Write(tmplist[m].Value);
                            sw[i].Write(" ");
                        }
                    
                        tmpeset.Clear();
                        tmpdic.Clear();
                        sw[i].Write("\n");
                    }
                }
                while (generatelts.Count > 0)
                {
                    sw[i].Write("\n");
                    generatelts.Dequeue();
                }
                sw[i].Flush();
                sw[i].Close();
                generatelts.Clear();
                generatelts.Enqueue(1);
            }
            

            for (k = 0; k < this.eventlist.Count; k++)
            {
                sw2.Write(this.eventlist[k]);
                sw2.Write(" ");
            }
            sw2.Flush();
            sw2.Close();

            sw3.Write(Allsnum);
            sw3.Write("\n");
            sw3.Flush();
            sw3.Close();
        }
Ejemplo n.º 27
0
        public static Dictionary<int, long> SortVotes(Dictionary<long, int> dic)
        {
            Dictionary<int, long> res = new Dictionary<int, long>();

            foreach (var item in dic.OrderBy(i => i.Value))
            {
                if (!res.ContainsKey(item.Value))
                {
                    res.Add(item.Value, item.Key);
                }
                else
                {
                    if (item.Key > res[item.Value])
                    {
                        res[item.Value] = item.Key;
                    }
                }
            }

            // Print resulting Dictionary
            //Console.WriteLine("SORTED VOTES:");
            //foreach (int i in res.Keys)
            //{
            //    Console.WriteLine(i + " => " + res[i]);
            //}

            return res;
        }
        private void LoadToolStripMenuItemClick(object sender, EventArgs e)
        {
            var dats = new Dictionary<string, string>();

            bool exists = System.IO.Directory.Exists(Application.StartupPath + @"\mob lists");
            if (!exists) System.IO.Directory.CreateDirectory(Application.StartupPath + @"\mob lists");
            var openFile = new OpenFileDialog();
            openFile.Filter = @"mob files (*.xml)|*.xml";
            openFile.InitialDirectory = Application.StartupPath + @"\mob lists";
            openFile.Title = @"select a mob list file";

            switch (openFile.ShowDialog())
            {
                case DialogResult.OK:
                    var doc = XDocument.Load(openFile.FileName);
                    if (doc.Root == null)
                        return;
                    foreach (var xml in doc.Root.Elements())
                    {
                        dats.Add(xml.Attribute("id").Value, xml.Attribute("name").Value);
                    }
                    SelectedTargets.Items.Clear();
                    foreach (var entry in dats.OrderBy(key => key.Value))
                    {
                        SelectedTargets.Items.Add(entry.Key).SubItems.Add(entry.Value);
                    }
                    break;
            }
        }
Ejemplo n.º 29
0
        private string CalculateAuthSignature(Dictionary<string, string> parameters)
        {
            #if !SILVERLIGHT
            var sorted = new SortedList<string, string>();
            foreach (var pair in parameters) { sorted.Add(pair.Key, pair.Value); }
            #else
            var sorted = parameters.OrderBy(p => p.Key);
            #endif

            var sb = new StringBuilder(ApiSecret);
            foreach (var pair in sorted)
            {
                sb.Append(pair.Key);
                sb.Append(pair.Value);
            }
            return UtilityMethods.MD5Hash(sb.ToString());
        }
Ejemplo n.º 30
0
        public string GenerateCreateTableSQL(PDFInfo info, Dictionary<string, PDFField> fields)
        {
            string formname = info.Title.Replace(" ", "_");
               StringBuilder sb = new StringBuilder();

               sb.Append("USE [XXXX]");
               sb.Append("\n");
               sb.Append("GO");
               sb.Append("\n");
               sb.Append("SET ANSI_NULLS ON");
               sb.Append("\n");
               sb.Append("GO");
               sb.Append("\n");
               sb.Append("SET QUOTED_IDENTIFIER ON ");
               sb.Append("\n");
               sb.Append("GO ");
               sb.Append("\n");
               sb.Append("CREATE TABLE [dbo].[" + formname + "]( ");
               sb.Append("\n");
               sb.Append("[Id] [uniqueidentifier] NOT NULL, ");
               foreach (KeyValuePair<string, PDFField> field in fields.OrderBy(p => p.Key))
               {
               sb.Append("[" + field.Key.Replace(" ", "_") + "] [nvarchar](500) NULL, ");
               sb.Append("\n");
               }
               sb.Append("\n");
               sb.Append("CONSTRAINT [PK_" + formname + "] PRIMARY KEY CLUSTERED ");
               sb.Append("\n");
               sb.Append("( ");
               sb.Append("\n");
               sb.Append("[Id] ASC ");
               sb.Append("\n");
               sb.Append(")WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] ");
               sb.Append("\n");
               sb.Append(") ON [PRIMARY] ");
               sb.Append("\n");
               sb.Append("GO ");
               sb.Append("\n");
               sb.Append("ALTER TABLE [dbo].[" + formname + "] ADD  CONSTRAINT [DF_" + formname + "_Id]  DEFAULT (newid()) FOR [Id] ");
               sb.Append("\n");
               sb.Append("GO");
               sb.Append("\n");

               return sb.ToString();
        }