private string BeautyMyCode(string Source)
        {
            Source = RemoveStr(Source, new string[] { "\n", "\x09", "  " });
            Source = new Regex("#include <(.*?)>").Replace(Source, "$0\n");
            Source = new Regex(";").Replace(Source, "$0\n");
            Source = new Regex("{").Replace(Source, "\n$0\n");
            Source = new Regex("}").Replace(Source, "$0\n");
            int DeepCount = 0;
            for (int i = 0; i < Source.Length; i++)
            {
                if (Source[i] == '}') DeepCount--;
                else if (Source[i] == '{') DeepCount++;
                else if (Source[i]  == '\n')
                {
                    int NextNewLinePos = Source.IndexOf("\n", i + 1);
                    if (NextNewLinePos != -1)
                    {
                        Console.WriteLine(Source.Substring(i, NextNewLinePos - i));
                        if (Source.Substring(i, NextNewLinePos - i).Contains("}"))
                        {
                            Source = Source.Insert(i + 1, GetManyBlankStr(DeepCount -1));
                        }
                        else
                        {
                            Source = Source.Insert(i + 1, GetManyBlankStr(DeepCount));
                        }

                    }
                }
            }
            return (Source);
        }
Beispiel #2
0
 protected override void ParseAdditionalInformation()
 {
     string bankName = new Regex(@"/BBK/.*\|?").Match(statementLine).Value;
     if (!string.IsNullOrEmpty(bankName))
     {
         bankName = bankName.Substring(5);
         if (bankName.EndsWith("|"))
         {
             bankName = bankName.Substring(0, bankName.Length - 1);
         }
         int vertical = bankName.IndexOf("|");
         if (-1 < vertical)
         {
             bankName = bankName.Substring(0, vertical);
         }
         bankStatement.CptyBankName = bankName.Trim();
     }
     AddInformation();
     //put tag 86 information to remark
     string[] remarks = statementLine.Split(new string[] { TAG_ADDITIONAL_INFO }, StringSplitOptions.None);
     if (remarks.Length > 1)
     {
         bankStatement.Remark = remarks[1];
     }
 }
Beispiel #3
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var e = value as Event;

            if (e != null)
            {
                if ((String)parameter == "title")
                {
                    return new EventManager().GetTitle(e);
                }
                if ((String)parameter == "description")
                {
                    var description = new EventManager().GetDescription(e);

                    if (description != null) {
                        description = new Regex("\\s+").Replace(description, " ");
                        if (description.Length > 128) {
                            description = description.Substring(0, 128).Trim() + "...";
                        }
                    }

                    return description;
                }
                else if ((String)parameter == "image")
                {
                    return new EventManager().GetImage(e);
                }
            }
            return null;
        }
        private string GetName()
        {
            string name = new Regex("[^A-Za-z0-9]").Replace(indicatorName,"");

            if (name.Length > CharacterLimit)
            {
                name = name.Substring(0, CharacterLimit);
            }
            return name;
        }
Beispiel #5
0
        private Dictionary<string, string> _tokenCache; // {facade, token}

        /// <summary>
        /// Constructor for use if the keys and SIN are managed by this library.
        /// </summary>
        /// <param name="clientName">The label for this client.</param>
        /// <param name="envUrl">The target server URL.</param>
        public BitPay(String clientName = BITPAY_PLUGIN_INFO, String envUrl = BITPAY_URL)
        {
            // IgnoreBadCertificates();

            if (clientName.Equals(BITPAY_PLUGIN_INFO))
            {
                clientName += " on " + System.Environment.MachineName;
            }
            // Eliminate special characters from the client name (used as a token label).  Trim to 60 chars.
            string _clientName = new Regex("[^a-zA-Z0-9_ ]").Replace(clientName, "_");
            if (_clientName.Length > 60)
            {
                _clientName = _clientName.Substring(0, 60);
            }

            _baseUrl = envUrl;
    	    _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri(_baseUrl);

            this.initKeys();
            this.deriveIdentity();
            this.tryGetAccessTokens();
        }
 private bool SaveParameters(ListView parameterListView, IDictionary<string, string> parameterList)
 {
     parameterList.Clear();
     List<string> names = new List<string>();
     foreach (ListViewItem lvi in parameterListView.Items)
     {
         // some sanity checking on the parameter names
         string param = lvi.SubItems[0].Text;
         string name = new Regex("[^a-z0-9_]").Replace(param, "");
         if (name == "" || new Regex("[0-9]").IsMatch(name.Substring(0, 1)))
         {
             MessageBox.Show(string.Format("{0} is not a valid parameter name", param), TemplateName);
             parameterListView.Focus();
             parameterListView.SelectedItems.Clear();
             lvi.Selected = true;
             DialogResult = DialogResult.None;
             return false;
         }
         if (names.Contains(name))
         {
             MessageBox.Show(string.Format("{0}: duplicated parameter", name), TemplateName);
             parameterListView.Focus();
             parameterListView.SelectedItems.Clear();
             lvi.Selected = true;
             DialogResult = DialogResult.None;
             return false;
         }
         names.Add(name);
         parameterList.Add(lvi.SubItems[0].Text, lvi.SubItems[1].Text);
     }
     return true;
 }
        public void Render(Graphics g, Nullable<Color> overlayColor, string replacementText)
        {
            string text = null;
            bool horizontal = true;
            string fontName;
            double fontSize = 0;
            bool fauxBold = false;
            bool fauxItalic = false;
            bool underline = false;
            bool strikethrough = false;

            Color fillColor;
            bool fillFlag = false;
            Color strokeColor;
            bool strokeFlag = false;
            double outlineWidth = 0;

            bool fillFirst = true;

            Color glowColor = Color.Yellow;
            bool glowFlag = false;
            double glowWidth = 0;
            double glowOpacity = 1;

            Rectangle rect = l.Rect;
            StringAlignment hAlign = StringAlignment.Center;
            StringAlignment vAlign = StringAlignment.Center;

            //Parse information from file.
            Glow outerGlow = null;
            TypeToolObject tto = null;
            TypeTool tt = null;
            bool foundTxt2 = false;
            //Loop through adjustment info
            List<PhotoshopFile.Layer.AdjustmentLayerInfo> adjustments = l.AdjustmentInfo;
            for (int j = 0; j < adjustments.Count; j++)
            {
                if (adjustments[j].Key.Equals("TySh"))
                    tto = new TypeToolObject(adjustments[j]);
                if (adjustments[j].Key.Equals("oglw"))
                    outerGlow = new Glow(adjustments[j]);
                //if (adjustments[j].Key.Equals("iglw"))
                //    innerGlow = new Glow(adjustments[j]);
                if (adjustments[j].Key.Equals("lrFX"))
                    //throw new Exception("We don't parse these effects do we?");
                if (adjustments[j].Key.Equals("tySh"))
                    tt = new TypeTool(adjustments[j]);
                if (adjustments[j].Key.Equals("Txt2"))
                    foundTxt2 = true;
            }
            //We know the TySh format best.
            if (tto != null){
                Dictionary<string,object> d = tto.StylesheetReader.GetStylesheetDataFromLongestRun();
                Matrix2D mat = tto.Transform;
                text = tto.StylesheetReader.Text;
                horizontal = tto.isTextHorizontal;
                fontName = TdTaParser.getString(tto.StylesheetReader.getFontSet()[(int)TdTaParser.query(d,"Font")],"Name$");
                fontSize = (double)TdTaParser.query(d,"FontSize");
                fauxBold = TdTaParser.getBool(d,"FauxBold");
                fauxItalic = TdTaParser.getBool(d,"FauxItalic");
                underline = TdTaParser.getBool(d,"Underline");
                strikethrough = TdTaParser.getBool(d,"Strikethrough");
                int styleRunAlignment = (int)TdTaParser.query(d,"StyleRunAlignment");//No idea what this maps to.
                //string info = tto.TxtDescriptor.getString();
                outlineWidth =  (double)TdTaParser.query(d,"OutlineWidth");

                fillColor = TdTaParser.getColor(d,"FillColor");
                strokeColor = TdTaParser.getColor(d,"StrokeColor");
                fillFlag = TdTaParser.getBool(d,"FillFlag");
                strokeFlag = TdTaParser.getBool(d,"StrokeFlag");
                fillFirst = TdTaParser.getBool(d,"FillFirst");

                //TODO: get alignment data
            }else if (tt != null){
                throw new Exception("Old style tySh font syntax not implemented, found on layer " + l.Name + ". Use a newer version of Photoshop");
            }else if (foundTxt2){
                throw new Exception("Txt2 text layer info not supported, found on layer " + l.Name + ". Where did you find this file? What version of photoshop?");
            }else{
                throw new Exception("No text layer information found on " + l.Name + "!");
            }

            if (outerGlow != null){
                glowColor = outerGlow.Color;
                glowFlag = outerGlow.Enabled;
                glowWidth = (int)outerGlow.Blur;
                glowOpacity = (double)outerGlow.Opacity / 255.0;
            }

            //Replace text if requested.
            if (replacementText != null) text = replacementText;

            //Fix newlines
            text = text.Replace("\r\n", "\n").Replace("\r", "\n");

            //Do graphics stuff
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            using(GraphicsPath path = new GraphicsPath()){
                FontFamily fontFamily = null;
                StringFormat strformat = null;
                try{
                    FontStyle style = FontStyle.Regular;
                    //Remove MT
                    if (fontName.EndsWith("MT")) fontName = fontName.Substring(0, fontName.Length - 2);
                    //Remove -Bold, -Italic, -BoldItalic
                    if (fontName.EndsWith("-Bold", StringComparison.OrdinalIgnoreCase)) style |= FontStyle.Bold;
                    if (fontName.EndsWith("-Italic", StringComparison.OrdinalIgnoreCase)) style |= FontStyle.Italic;
                    if (fontName.EndsWith("-BoldItalic", StringComparison.OrdinalIgnoreCase)) style |= FontStyle.Bold | FontStyle.Italic;
                    //Remove from fontName
                    fontName = new Regex("\\-(Bold|Italic|BoldItalic)$", RegexOptions.IgnoreCase | RegexOptions.IgnoreCase).Replace(fontName, "");
                    //Remove PS
                    if (fontName.EndsWith("PS")) fontName = fontName.Substring(0, fontName.Length - 2);
                    //Find font family
                    try {
                        fontFamily = new FontFamily(fontName);
                    } catch (ArgumentException ae) {
                        if (IgnoreMissingFonts) {
                            fontFamily = FontFamily.GenericSansSerif;
                        } else throw ae;

                    }
                    if (fauxBold) style |= FontStyle.Bold;
                    if (fauxItalic) style |= FontStyle.Italic;
                    if (underline) style |= FontStyle.Underline;
                    if (strikethrough) style |= FontStyle.Strikeout;

                    strformat = new StringFormat();
                    strformat.LineAlignment = hAlign;
                    strformat.Alignment = vAlign;
                    strformat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.NoClip;
                    if (!horizontal) strformat.FormatFlags |= StringFormatFlags.DirectionVertical;
                    strformat.Trimming = StringTrimming.None;

                    path.AddString(text, fontFamily,
                        (int)style, (float)(fontSize),rect, strformat);
                }finally{
                    fontFamily.Dispose();
                    strformat.Dispose();
                }

                if (glowFlag)
                {
                    if (glowWidth == 3) glowWidth = 2; //To replicate photoshop rounding bug

                    double finalOpacity = (glowOpacity + 1.5)/2.5; //Because Photoshop doesn't actually use the opacity as the final opacity...
                    //Add a 30% fade inside the glow width
                    int fadeWidth = (int)Math.Floor(glowWidth * 0.33);

                    double totalOpacity = 0; //Start at transparent

                    //start with outermost ring, work inwards
                    for (int i = fadeWidth; i >=0; i--)
                    {
                        //How much opacity do we lack to complete the desired opacity?
                        //totalOpacity = prevOpacity * (1-curOpacity) + curOpacity
                        //a=b *(1-c) + c
                        //>>> where b!=1, c=(b-a/b-1)
                        double missingOpacity = (totalOpacity - finalOpacity) / (totalOpacity - 1);

                        int remainingRings = fadeWidth;

                        double currentOpacity = missingOpacity / (fadeWidth + 1);
                        //Update total opacity
                        totalOpacity = totalOpacity * (1 - currentOpacity) + currentOpacity;
                        //Draw it
                        using (Pen pen = new Pen(Color.FromArgb((int)Math.Round(currentOpacity * 255.0), glowColor), (float)((glowWidth - fadeWidth + (double)i) * 2)))
                        {
                            pen.LineJoin = LineJoin.Round;
                            g.DrawPath(pen, path);
                        }
                    }
                }

                if (fillFirst){
                    //Draw fill
                    if (fillFlag){
                        using(SolidBrush brush = new SolidBrush(fillColor)){
                            g.FillPath(brush, path);
                        }
                    }
                    //Draw stroke
                    if (strokeFlag){
                        using (Pen p = new Pen(strokeColor,(float)outlineWidth)){
                            p.LineJoin = LineJoin.Round;
                            g.DrawPath(p,path);
                        }
                    }
                }else{
                    //Draw stroke
                    if (strokeFlag){
                        using (Pen p = new Pen(strokeColor, (float)outlineWidth))
                        {
                            p.LineJoin = LineJoin.Round;
                            g.DrawPath(p,path);
                        }
                    }
                                        //Draw fill
                    if (fillFlag){
                        using(SolidBrush brush = new SolidBrush(fillColor)){
                            g.FillPath(brush, path);
                        }
                    }
                }
            }
        }
Beispiel #8
0
 private void WeatherYandexRu()
 {
     try
     {
         var city = string.Empty;
         var sr = new StreamReader(LoadSetting);
         Line = sr.ReadLine();
         sr.Close();
         var users = new Users();
         var list = users.Read(UsersPath);
         if (Line != "Гостем")
         {
             foreach (var t in list.Where(t => t.Login == Line))
             {
                 textBoxInput.Text = @"Вы зашли под," + t.Login;
                 city = t.City;
                 User = t.Login;
                 break;
             }
         }
         else
         {
             textBoxInput.Text = @"Вы зашли под," + Line;
             User = Line;
             ExitFromAccount.Visible = false;
             textBoxCityVariable.Text = @"Grodno";
         }
         var request = WebRequest.Create(@"https://pogoda.yandex.ru/" + city);
         using (var response = request.GetResponse())
         {
             using (var stream = response.GetResponseStream())
                 if (stream != null)
                     using (var reader = new StreamReader(stream))
                     {
                         var data = reader.ReadToEnd();
                         var temp =
                             new Regex(
                                 @"<div class=""current-weather__thermometer current-weather__thermometer_type_now"">(?<temp>([+][0-9]{1,2})|(-[0-9]{1,2})|[0]+)")
                                 .Match(data).Groups["temp"].Value;
                         textBoxWeather.Text = temp + @" °C";
                         var temp1 =
                             new Regex(
                                 @"<span class=""current-weather__comment"">(?<temp1>([а-я]+\s[а-я]+)|([а-я]+,\s[а-я]+)|([а-я]+))")
                                 .Match(data).Groups["temp1"].Value;
                         textBoxWeaher1.Text = temp1.Substring(0, 1).ToUpper() + temp1.Remove(0, 1);
                         if (city != string.Empty)
                         {
                             textBoxCityVariable.Text = city.Substring(0, 1).ToUpper() + city.Remove(0, 1);
                         }
                         else
                         {
                             city = @"Grodno";
                             textBoxCityVariable.Text = city.Substring(0, 1).ToUpper() + city.Remove(0, 1);
                         }
                     }
         }
         Log.Info("WeatherConnect");
     }
     catch (Exception exception)
     {
         Log.Fatal(exception.Message);
         MessageBox.Show(exception.Message);
     }
 }
        private string CollapseRegionEvaluator2(Match m)
        {
            string retCode = m.Value;

            //add rectangle
            retCode = retCode.Replace("style='width: 9px; height: 9px'", "style='position: relative; left: -6px; top: 0px; border-color: #808080; border-style: solid; border-width: 1px; background: white; width: 9px; height: 9px'");

            string spaces = new Regex("(&nbsp;)+").Match(m.Value).Value;
            string regionDescWidthTag = new Regex("#region</span> ([^<]*)</code>").Match(m.Value).Value;
            string regionDesc = regionDescWidthTag.Substring(15, regionDescWidthTag.Length - ("#region</span> ").Length - ("</code>").Length);

            //add "+" tag
            retCode = retCode.Replace("<td style='width: 0px'></td>", "<td style='width: 0px'><span style='position: relative; left: -16px; top: -1px; font: 12px; cursor: hand' onclick='if (this.childNodes[0].innerHTML == \"_\") { this.childNodes[0].innerHTML = \"+\"; this.style.top = \"-1px\"; this.parentNode.nextSibling.childNodes[0].innerHTML = \"<span>" + spaces + "</span><span><font color=gray>" + regionDesc + "</font></span>\"; this.parentNode.nextSibling.childNodes[0].childNodes[1].style.border = \"1px solid gray\"; for (var i = 1 + this.parentNode.parentNode.rowIndex; i < this.parentNode.parentNode.parentNode.childNodes.length; i++) { this.parentNode.parentNode.parentNode.childNodes[i].style.display=\"none\"; if ( this.parentNode.parentNode.parentNode.childNodes[i].childNodes[1].innerText.length > 0 ) { break; } } } else { this.childNodes[0].innerHTML = \"_\"; this.style.top = \"-6px\"; var oldDesc = this.parentNode.nextSibling.childNodes[0].childNodes[1].childNodes[0].innerHTML; this.parentNode.nextSibling.childNodes[0].innerHTML = \"<span>" + spaces + "</span><span><font color=blue>#region </font></span><span></span>\"; this.parentNode.nextSibling.childNodes[0].childNodes[2].innerHTML = oldDesc; for (var i = 1 + this.parentNode.parentNode.rowIndex; i < this.parentNode.parentNode.parentNode.childNodes.length; i++) { this.parentNode.parentNode.parentNode.childNodes[i].style.display=\"block\"; if ( this.parentNode.parentNode.parentNode.childNodes[i].childNodes[1].innerText.length > 0 ) { break; } } }'><font color=#808080 face='Tahoma'>+</font></span></td>");

            return retCode;
        }
Beispiel #10
0
        private string CollapseRegionEvaluator(Match m)
        {
            //get region code block

            string retCode = m.Value;

            string lineHeader = "<tr><td style='width: 0px'><table style='width: 9px; height: 9px'><tr><td></td></tr></table></td><td style='width: 0px'></td><td style='width: 100%'><code style='font: 9pt Tahoma'>";
            string lineTailer = "</code></td></tr>";

            Regex r = new Regex("^" + lineHeader + @"(&nbsp;)*<span style=\""color: blue\"">#region</span>[^<]*" + lineTailer, RegexOptions.Multiline);
            retCode = r.Replace(retCode, new MatchEvaluator(this.CollapseRegionEvaluator2));

            //find out #region - #endregion block & add collapse code
            string endRegionLinePattern = "<tr><td style='width: 0px'><table style='width: 9px; height: 9px'><tr><td></td></tr></table></td><td style='width: 0px'></td><td style='width: 100%'><code style='font: 9pt Tahoma'>(&nbsp;)*<span style=\"color: blue\">#endregion</span></code></td></tr>";
            Regex r2 = new Regex(endRegionLinePattern);
            string endRegionLine = r2.Match(retCode).Value;
            string formatedEndRegionLine = endRegionLine.Replace("<td style='width: 0px'></td><td style='width: 100%'>", "<td style='width: 0px'><span style='position: relative; left: -12px; font: 12px'><font color=#808080 face='Tahoma'>-</font></span></td><td style='width: 100%'>");
            string regionBlock = retCode.Substring(0, retCode.IndexOf(endRegionLine)) + formatedEndRegionLine;

            string spaces = new Regex("(&nbsp;)+").Match(regionBlock).Value;
            string regionDescWidthTag = new Regex("#region</span> ([^<]*)</code>").Match(regionBlock).Value;
            string regionDesc = regionDescWidthTag.Substring(15, regionDescWidthTag.Length - ("#region</span> ").Length - ("</code>").Length);

            regionBlock = regionBlock.Replace("</tr><tr><td style='width: 0px'>", "</tr><tr style='display: none'><td style='width: 0px'>");
            regionBlock = regionBlock.Substring(0, regionBlock.IndexOf("<code style='font: 9pt Tahoma'>") + "<code style='font: 9pt Tahoma'>".Length) +
                "<span>" + spaces + "</span>" + "<span style='border: 1px solid gray'><font color=gray>" + regionDesc + "</font></span>" +
                regionBlock.Substring(regionBlock.IndexOf("</code>"));

            retCode = regionBlock + retCode.Substring(retCode.IndexOf(endRegionLine) + endRegionLine.Length);

            return retCode;
        }
Beispiel #11
0
        //executeDownload(mh.GetCurrentTrack().GetArtistName(), mh.GetCurrentTrack().GetTrackName(), true);
        private async Task executeDownload(string artist, string name, bool tellIfAlreadyExists = false)
        {
            tryNumber = 0;
            time = 0;

            startdownload:
            try
            {
                if (downloading)
                {
                    addToLog("Already downloading a song, ignoring requested download", logBox);
                    return;
                }

                downloading = true;
                
                string term = artist + " - " + name; //Building search term
                term = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars())))).Replace(term, "");  //Removing any invalid characters?
                
                if (string.IsNullOrWhiteSpace(artist) || string.IsNullOrWhiteSpace(name) || mh.IsAdRunning())   //If there is no artist or no name or an ad is running return since theres nothing to download
                {
                    downloading = false;
                    return;
                }

                if (term.Length > 16)
                    if (term.Substring(term.Length - 15).ToLower() == " - original mix")
                        term = term.Substring(0, term.Length - 15); //Remove "Original Mix"
                if (term.Contains(" - feat"))
                    term = term.Split(new string[] { " - feat" }, StringSplitOptions.None)[0]; //Remove feat

                lastDownloaded = term;

                if (!File.Exists(browseForFolderBox.Text + lastDownloaded + ".mp3")) //If the song wasent downloaded to the folder already
                {
                    addToLog("Searching MP3Clan for term \"" + term + "\"", logBox);
                    string pageSource = client.DownloadString(new Uri(string.Format("http://mp3clan.com/mp3_source.php?q={0}", term.Replace(" ", "+"))));   //Perform search and get page source
                    //Perfom a search query in your browser and you can view the source to understand the next line
                    Match trackId = new Regex("<div class=\"mp3list-table\" id=\"(.+?)\">").Match(pageSource); //Checks if div exists in the page source //What is (.+?) 

                    if (!trackId.Success || string.IsNullOrWhiteSpace(trackId.Groups[1].Value)) //If there was no match or ...I don't know what is trackId.Groups[1].Value? Is it the ID of the div?
                    {
                        if (tryNumber < 3) //If try number is less than 3, retry download
                        {
                            downloading = false;
                            tryNumber++;
                            addToLog("Could not find TrackID, retrying " + tryNumber + "/3", logBox);
                            goto startdownload;
                        }
                        else  //If try number is greater than 3, then skip the download/give up
                        {
                            addToLog("Could not find TrackID, skipping download", logBox);
                            downloading = false;
                            return;
                        }
                    }

                    addToLog("TrackId: " + trackId.Groups[1].Value, logBox);

                    string dlLink = string.Format("http://mp3clan.com/app/get.php?mp3={0}", trackId.Groups[1].Value);
                    addToLog("Downloading from link: " + dlLink, logBox);

                    sw.Start(); //Start the download stopwatch
                    await Task.WhenAll(downloadFileAsync(dlLink, lastDownloaded)); //Download the track
                }
                else { if (tellIfAlreadyExists) { addToLog("Song already downloaded", logBox); } downloading = false; } //FIle already downloaded

                FileInfo fileInfo = new FileInfo(browseForFolderBox.Text + lastDownloaded + ".mp3");
                if (fileInfo.Length < 1000000 && retryIfUnder1Mb.Checked) //If length of file is less than 1mb and retry under 1mb is checked then retry download
                {
                    if (tryNumber < 3)
                    {
                        downloading = false;
                        tryNumber++;
                        if (File.Exists(browseForFolderBox.Text +  lastDownloaded + ".mp3"))
                            File.Delete(browseForFolderBox.Text +  lastDownloaded + ".mp3");
                        addToLog("File downloaded was under 1MB, redownloading try " + tryNumber + "/3", logBox);
                        goto startdownload;
                    }
                    else
                    {
                        downloading = false;
                        addToLog(term + " failed to download every try, skipping", logBox);
                        if (Settings.Default.DownloadNotifications)
                            notifyIcon.ShowBalloonTip(3000, "Download error", "The download for \"" + lastDownloaded + "\" failed to download.", ToolTipIcon.Error);
                    }
                }
                downloading = false;
            }
            catch (Exception e)
            {
                downloading = false;
                tryNumber++;
                addToLog("Error downloading file, retrying " + tryNumber + "\n" + e.ToString(), logBox);
                goto startdownload;
            }
        }
Beispiel #12
0
        private void AddInformation()
        {
            string cptyBankName = new Regex(@"/\|?BI/.*?/", RegexOptions.IgnoreCase).Match(statementLine).Value;
            if (!string.IsNullOrEmpty(cptyBankName))
            {
                cptyBankName = cptyBankName.Substring(4);
                cptyBankName = cptyBankName.Replace("|", string.Empty).Replace("/", string.Empty).Trim();
                bankStatement.CptyBankName = cptyBankName;
            }

            string cptyAcctNo = new Regex(@"/\|?BA/.*?/", RegexOptions.IgnoreCase).Match(statementLine).Value;
            if (!string.IsNullOrEmpty(cptyAcctNo))
            {
                cptyAcctNo = cptyAcctNo.Substring(4);
                cptyAcctNo = cptyAcctNo.Replace("|", string.Empty).Replace("/", string.Empty).Trim();
                bankStatement.CptyAcctNo = cptyAcctNo;
            }

            string cptyAcctName = new Regex(@"/\|?BN/.*?/", RegexOptions.IgnoreCase).Match(statementLine).Value;
            if (!string.IsNullOrEmpty(cptyAcctName))
            {
                cptyAcctName = cptyAcctName.Substring(4);
                cptyAcctName = cptyAcctName.Replace("|", string.Empty).Replace("/", string.Empty).Trim();
                bankStatement.CptyAcctName = cptyAcctName;
            }
        }
Beispiel #13
0
		public static IEnumerable<string> EquationsFromParentheses(string recipe)
		{
			var equations = new List<string>();
			if (string.IsNullOrWhiteSpace(recipe))
			{
				return equations;
			}

			recipe = "(" + recipe + ")"; // If this is a duplication of effort, we'll silently ignore it later.
			recipe = new Regex(@"\s+").Replace(recipe, string.Empty); // Remove all whitespace.
			recipe = LeveledPreparser(recipe);

			var multiLetterMatch = invalidLetterFinder.Match(recipe);
			if (multiLetterMatch.Success)
			{
				throw new ArgumentException("The gem \"" + multiLetterMatch.Value + "\" must be a single letter. Gem combinations must be expressed as individual components separated with plus signs and brackets, as needed. For example:\nob → o+b\nob+o → (o+b)+o");
			}

			var id = 0;
			foreach (var c in Gem.GemInitializer)
			{
				if (recipe.IndexOf(c) > -1)
				{
					recipe = recipe.Replace(c, id.ToString(CultureInfo.InvariantCulture)[0]);
					equations.Add(string.Format(CultureInfo.InvariantCulture, "{0}={1}", id, c));
					id++;
				}
			}

			if (equations.Count == 0)
			{
				throw new ArgumentException("Recipe did not contain any recognizable gems.");
			}

			// Scan for plus signs within the formula and add gems together appropriately.
			int plus = recipe.IndexOf('+');
			string newNum = (id - 1).ToString(CultureInfo.InvariantCulture);
			while (plus > -1)
			{
				string thisCombine;
				var close = recipe.IndexOf(')', plus);
				if (close >= 0)
				{
					var open = recipe.LastIndexOf('(', close);
					if (open < 0)
					{
						throw new ArgumentException("Bracket mismatch in formula.");
					}

					thisCombine = recipe.Substring(open + 1, close - open - 1);

					string[] combineGems = thisCombine.Split('+');
					if (combineGems.Length != 2)
					{
						throw new ArgumentException("The formula provided contains more than a single plus sign within a pair of brackets or a term that is over-bracketed (e.g., \"((o+o))\"). These are not currently supported.");
					}

					if (combineGems[0].Length == 0 || combineGems[1].Length == 0)
					{
						throw new ArgumentException("Invalid formula part: (" + thisCombine + ")");
					}

					newNum = id.ToString(CultureInfo.InvariantCulture);
					recipe = recipe.Replace("(" + thisCombine + ")", newNum);
					equations.Add(string.Format(CultureInfo.InvariantCulture, "{0}={1}+{2}", id, combineGems[0], combineGems[1]));
				}
				else
				{
					throw new ArgumentException("Bracket mismatch in formula.");
				}

				plus = recipe.IndexOf('+');
				id++;
			}

			while (recipe.StartsWith("(", StringComparison.Ordinal) && recipe.EndsWith(")", StringComparison.Ordinal))
			{
				recipe = recipe.Substring(1, recipe.Length - 2);
			}

			if (recipe != newNum)
			{
				if (recipe.Contains("("))
				{
					throw new ArgumentException("Bracket mismatch in formula.");
				}

				throw new ArgumentException("Invalid recipe.");
			}

			return equations;
		}
        static void WordWrap(string paragraph)
        {
            paragraph = new Regex(@" {2,}").Replace(paragraph.Trim(), @" ");
            var left = Console.CursorLeft;
            var top = Console.CursorTop;
            var lines = new List<string>();

            for (var i = 0; paragraph.Length > 0; i++)
            {
                lines.Add(paragraph.Substring(0, Math.Min(Console.WindowWidth, paragraph.Length)));
                var length = lines[i].LastIndexOf(" ", StringComparison.Ordinal);
                if (length > 0)
                {
                    lines[i] = lines[i].Remove(length);
                }
                paragraph = paragraph.Substring(Math.Min(lines[i].Length + 1, paragraph.Length));
                Console.SetCursorPosition(left, top + i);
                write(lines[i]);
            }
        }
Beispiel #15
0
 private String xml_parse(String input, String block_name)
 {
     String temp = new Regex("<" + block_name + ">.*</" + block_name + ">").Match(input).ToString();
     return temp.Substring(block_name.Length + 2, temp.Length - 2 * block_name.Length - 5);
 }
Beispiel #16
0
 protected override void ParseSupplementaryDetails()
 {
     string detail = new Regex(@"\|.*\|:").Match(statementLine).Value;
     if (!string.IsNullOrEmpty(detail))
     {
         detail = detail.Substring(1);
         detail = detail.Substring(0, detail.Length - 2);
         if (transactionTypeCode == "TRF")
         {
             bankStatement.CptyAcctName = detail;
         }
         else
         {
             bankStatement.Remark = detail;
         }
     }
 }
        private static string GetCleanID(string path, int limit,
            bool replaceDot = false,
            bool removeDot = false,
            bool replaceDirectorySeparatorChar = false,
            bool removeDirectorySeparatorChar = false,
            bool replaceSpaces = false,
            bool removeSpaces = false,
            bool removeUnderscores = false)
        {
            if (replaceDot)
                path = path.Replace('.', '_');

            if (removeDot)
                path = path.Replace(".", "");

            if (replaceDirectorySeparatorChar)
                path = path.Replace(Path.DirectorySeparatorChar, '_');

            if (removeDirectorySeparatorChar)
                path = path.Replace(Path.DirectorySeparatorChar.ToString(), "");

            if (replaceSpaces)
                path = path.ReplaceWhiteSpace('_');

            if (removeSpaces || !replaceSpaces)
                path = path.RemoveWhiteSpace();

            path = new Regex("[^a-zA-Z0-9_.]").Replace(path, "_");

            path = path.RemoveDuplicates("_").TrimEnd('_').TrimStart('_');

            if (removeUnderscores)
                path = path.Replace("_", "");

            if (path.Length > limit)
            {
                byte[] nameBytes = Encoding.Default.GetBytes(path);
                uint crc = nameBytes.Crc32Checksum(0, nameBytes.Length);
                string suffix = crc.ToString();
                path = path.Substring(0, limit - suffix.Length) + suffix;
            }

            return path;
        }
Beispiel #18
0
        /// <summary>
        /// 入力ファイルの設定
        /// </summary>
        private static void Make_InputPath(Setting_File setting)
        {
            //Input
              TsShortName = new Regex("[ $|()^ ]").Replace(TsName, "_");      //batの特殊文字
              TsShortName = (5 < TsShortName.Length) ? TsShortName.Substring(0, 5) : TsShortName;

              D2vPath = D2vPath ?? TsPath + ".pp.d2v";
              LwiPath = LwiPath ?? TsPath + ".pp.lwi";
              LwiFooterPath = LwiPath + "footer";
              SrtPath = SrtPath ?? Path.Combine(TsDir, TsNameWithoutExt + ".srt");

              if (IsAll)
              {
            if (File.Exists(D2vPath) == false && File.Exists(TsPath + ".d2v"))
              D2vPath = TsPath + ".d2v";
            if (File.Exists(LwiPath) == false && File.Exists(TsPath + ".lwi"))
              LwiPath = TsPath + ".lwi";
              }

              //Plugin  Detector  AvsVpy
              {
            string plugin = setting.InputPlugin.Trim().ToLower();
            string detector = setting.Detector.Trim().ToLower();
            bool isD2v = plugin == "d2v".ToLower();
            bool isLwi = plugin == "lwi".ToLower();
            bool isLG = detector == "LG".ToLower();
            bool isJLS = detector == "JLS".ToLower();

            InputPlugin = isD2v ? Plugin.D2v
              : isLwi ? Plugin.Lwi
              : Plugin.None;
            Detector = isJLS ? Detector.Join_Logo_Scp
              : isLG ? Detector.LogoGuillo
              : Detector.None;

            //Avs固定
            const AvsVpy avs = AvsVpy.Avs;
            AvsVpy = avs;
            if (AvsVpy == AvsVpy.Vpy)
              throw new NotImplementedException();
              }
        }