I'm trying to make an application that reads two text files, takes the two, and merges them into one single list. Then take said list, and compare it to another list (from another text file). The problem is that no matter what I do my program always goes to else (see the line where it says
if (BoysAndGirlsList.Contains(NameEntered) && MostPopularNamesList.Contains(NameEntered))
). I don't know why it does this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Linq; //Needed for concat.
namespace Name_Search
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string BoyNames = System.IO.File.ReadAllText(#"D:\Google Drive\Course Work\C# Intro\Student Sample Programs\Chap07\BoyNames.txt"); //Reads BoyNames txt file.
List<string> BoyNamesList = BoyNames.Split('\n').ToList(); //Converts it to a list.
//BoyNamesList.ForEach(Console.WriteLine); <-Testing to make sure that the list is working properly.
string GirlNames = System.IO.File.ReadAllText(#"D:\Google Drive\Course Work\C# Intro\Student Sample Programs\Chap07\GirlNames.txt"); //Reads GirlNames txt file.
List<string> GirlNamesList = GirlNames.Split('\n').ToList(); //Converts it to a list.
List<string> BoysAndGirlsList;
BoysAndGirlsList = BoyNamesList.Concat(GirlNamesList).ToList(); //Adds the lists together.
//BoysAndGirlsList.ForEach(Console.WriteLine); <-Again just testing that the list is working.
string MostPopularNames = System.IO.File.ReadAllText(#"D:\Google Drive\Course Work\C# Intro\Student Sample Programs\Chap07\MostPopularBoyAndGirlNames.txt"); //Reads MostPopularBoyAndGirlNames txt file. Compiled from http://goo.gl/1crLcY.)
List<string> MostPopularNamesList = MostPopularNames.Split('\n').ToList(); //Converts it to a list.
string NameEntered = nameInput.Text;
if (BoysAndGirlsList.Contains(NameEntered) && MostPopularNamesList.Contains(NameEntered))
{
MessageBox.Show("This name is one the most popular names!");
}
else
{
MessageBox.Show("This is not one of the most popular names.");
}
}
}
}
What is not working properly here? I've tried putting in a break, and when I did the values looked fine to me.
The issue is probably solved as mentioned by the comments, where redundant spaces in the 'names' causes them to compare unequally. You also have an issue when you want to compare names in a case-insensitive manner.
The first issue can be solved by trimming whitespace from each name:
BoysAndGirlsList = BoysAndGirlsList.Select(name => name.Trim()).ToList();
MostPopularNamesList = MostPopularNamesList.Select(name => name.Trim()).ToList();
The second issue can be solved by using an invariant case comparer:
if (BoysAndGirlsList.Contains(NameEntered, StringComparer.InvariantCultureIgnoreCase) &&
MostPopularNamesList.Contains(NameEntered, StringComparer.InvariantCultureIgnoreCase))
Related
I want to compress every video within every drive and its sub-directories so the code I have used so far finds each drive and looks for .mp4 locations. Then it uses that list of strings to compress each file but it comes up with this error at:
var mediaInfo = FFProbe.Analyse(filePath: d)
and
.FromFileInput(d, verifyExists: true)
System.ComponentModel.Win32Exception: 'The system cannot find the file specified'
I checked what the .Analyse needs and it is a string and d is a string which has the right path location C:\\Users\\Helix\\Desktop\\apartment\\5 Little Monkeys Swinging In The Tree.mp4" which I thought would work but it does not seem to like it. What am I doing wrong?
I am also curious as to if GetDrives() works on network drives? And if it does would two servers running this code conflict when grabbing the same file at the same time?
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MediaToolkit;
using MediaToolkit.Model;
using FFMpegCore;
using FFMpegCore.Enums;
namespace Video_Compressor_for_Servers
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void CompAll_Click(object sender, EventArgs e)
{
//An empty list for later to collect strings
List<string> file = new List<string>();
//extract primary drives strings into a list since there could be more than just C:\
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
//The d.Name output has "Drive C:\" as the output. remove the "Drive " part first
var replacement = d.Name.Replace("Drive ", "");
/*Grab each files location with the Directory tool from the earlier IO libary.
GetFiles is a subcommand of directory with options in the brackets. These
options can be found in more detail by seaching for GetFiles C#*/
string[] files = Directory.GetFiles(#"C:\Users\Helix\Desktop\apartment\","*.mp4", SearchOption.AllDirectories);// replacement//AllDirectories
//Convert the array to a list
List<string> templist = files.ToList();
//Add them to the earlier empty list we made
file.AddRange(templist);
}
//Now that we have paths to all the files we need we can now compress them
foreach (string d in file)
{
var mediaInfo = FFProbe.Analyse(filePath: d);
//Open the video file with MediaToolkit
FFMpegArguments
.FromFileInput(d, verifyExists: true)
.OutputToFile(d, false, options => options
.WithVideoCodec(VideoCodec.LibX264)
.WithConstantRateFactor(21)
.WithAudioCodec(AudioCodec.Aac)
.WithVariableBitrate(4)
.WithVideoFilters(filterOptions => filterOptions
.Scale(VideoSize.Ed))
.WithFastStart())
.ProcessSynchronously();
}
}
}
}
You need to download both ffprobe.exe and ffmpeg.exe.
The executable is missing not the media one.
With a csv file looking like this:
usernames,passwords
us1,ps1
us2,ps2
I would like all usernames in one array an all passwords in another.
Current code:
(Trying to make a login system that interacts with a database.)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;
namespace Login
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string[] usernames = new string[] { };
string[] passwords = new string[] { };
private void btnLogin_Click(object sender, EventArgs e)
{
lblLoginSucsess.Text = "";
for (int i = 0; i < Math.Min(usernames.Length, passwords.Length); i++)
{
if ((usernames[i].ToLower() == txtUsnme.Text.ToLower()) && (passwords[i].ToLower() == txtPass.Text.ToLower()))
{
lblLoginSucsess.Text = $"Welcome, {txtUsnme.Text}.";
// run calc
Process.Start("C:/Users/finch/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/HP Inc/Calculator.appref-ms");
}
}
}
}
}
If you can help, Thanks.
Instead of having two separate list, it would be better if you had a Dictionary of UserName/Password. You could read CSV and convert to dictionary by
var dataLines = File.ReadAllLines(filePath);
var userPassDictionary = dataLines.Skip(1)
.Select(x=> x.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(x=> x.First().ToLower(),v=>v.Last());
Now you could access validate the user as
if (userPassDictionary[txtUsnme.Text.ToLower()] == txtPass.Text)
{
}
Note
It was also curious to note that your were comparing password case-insensitevely. While it might depend on the business requirement, most often than not, passwords are case-sensitive. Wanted to highlight it, just in case, it was by accident.
i'm rather new and am trying to create a C# program that retrieves post from Facebook using FB API.
I have a word count feature which checks against a negative word dictionary.
This means that it would display the negative word along with its frequency occurrence.
The problem i'm facing now is that, i want to display the posts that contains this negative words. However, if the negative word exists 3 times in the post, the post would appear thrice. How do i solve this problem?
Below is my code:
(For designer)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace empTRUST
{
public partial class PostAnalysis : Form
{
DBStatusDL ad;
string target_fbid;
public PostAnalysis(string target_fbid)
{
InitializeComponent();
this.target_fbid = target_fbid;
ad = new DBStatusDL();
}
private void button_Displayposts_Click(object sender, EventArgs e)
{
int i = 1;
var dir = new DirectoryInfo(Application.StartupPath + "\\Dictionary"); //Load the dictionary from debug folder
var ed = new matchingWordsWithPosts();
var rows = ad.LoadStatus(target_fbid); //Call the load status function based on fb_id
foreach (FileInfo file in dir.GetFiles()) //For loop, to loop through files
{
var dict = File.ReadAllLines(dir.FullName + "\\" + file);
foreach (var row in rows)
{
List<DataRow> words = ed.countWordsInStatus(row, dict); // Retrieves word dictionary returned from function
foreach (var word in words)
{
var item = new ListViewItem(new[] { i.ToString() ,word["Status_message"].ToString(), word["Status_time"].ToString() });
listViewPosts.Items.Add(item);
i++;
}
}
}
}
private void button_Back_Click(object sender, EventArgs e)
{
this.Close();
var abc = new AnalysisPage(target_fbid);
abc.Show();
}
}
}
(For class)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
namespace empTRUST
{
class matchingWordsWithPosts
{
public List<DataRow> countWordsInStatus(DataRow status, string[] dictArray)
{
List<DataRow> statusList = new List<DataRow>();
var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase); // local word dictionary is created here
foreach (var dictEntry in dictArray)
{
var wordPattern = new Regex(#"\w+");
string smallDictEntry = dictEntry.ToLower();
foreach (Match match in wordPattern.Matches(status["Status_message"].ToString()))
{
if (match.ToString() == smallDictEntry)
{
statusList.Add(status);
}
}
}
return statusList; // returns local word dictionary to receiving end
}
}
}
Because you didn't provide the countWordsInStatus() function, I can't know if that's the problem. However, it looks like the problem is that that function continues going through a post even if it has already matched one such word. To fix this, you could put continue; (or perhaps a break;, depending on the code you're using) after adding a post to the list you're returning. This would have the loop skip to the next post, and make sure it doesn't continue counting words in the post that has already had a match.
If you post that function, it should be much easier to understand the issue.
After a word is matched and you process the post exit the loop.
I have an n3 file formate and i want to delete a node or triple from it how can i do it? should i use sparql query?please help me
i want to have an n3 file and want to delete a node from it.
i pass a graph that use in my parent form to this delete form and want to work with this graph that i create from an n3 file i mean i read this n3 file and convert it to a graph and send it to this form.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VDS.RDF;
using VDS.RDF.Parsing;
using VDS.RDF.Query;
using System.IO;
using System.Windows;
using System.Runtime.InteropServices;
using VDS.RDF.Writing;
namespace WindowsFormsApplication2
{
public partial class delete : Form
{
Graph gra = new Graph();
public delete(Graph initialValue)
{
InitializeComponent();
ValueFromParent = initialValue;
}
private void delete_Load(object sender, EventArgs e)
{
}
public Graph ValueFromParent
{
set
{
this.gra = value;
}
}
}
}
From the documentation on Working with Graphs please see the section titled Asserting and Retracting triples which makes mention of the Assert() and Retract() methods which can be used to do what you've asked.
For example to delete a specific Triple:
//Assuming you already have the triple to delete in a variable t
g.Retract(t);
Or perhaps more usefully deleting all Triples that match a specific Node:
g.Retract(g.GetTriplesWithSubject(g.CreateUriNode(new Uri("http://example.org"))));
If you aren't sure whether a specific Node exists you can do something like the following:
INode n = g.GetUriNode(new Uri("http://example.org"));
//If n is null then the specified Node does not exist in the Graph
if (n != null)
{
g.Retract(g.GetTriplesWithSubject(n));
}
Note that you can't directly delete a Node from the Graph other than by removing all Triples that have it in the Subject/Object position. Also note that this does not remove it from the collection provided by the Nodes property of the Graph currently.
Yes you can also do this via SPARQL but for just removing a few triples that is very much overkill unless you need to remove triples based on some complex criteria which is not easily expressed directly using API selection and retraction methods.
I am currently working on batch processing application using MSMQ in C#. In the application design, I have an error queue containing XML messages using the ActiveXFormatter. I know that I can write an application to write these error messages to text files or database tables.
Are there other pre-built tools available allowing you to export messages to variety of formats (i.e. text files, database tables, etc.)? I am just looking for best practices.
Ok. I found the solution of writing code to be really easy. Here's my reference solution.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Messaging;
namespace ExportMSMQMessagesToFiles
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnExportTextFiles_Click(object sender, EventArgs e)
{
//Setup MSMQ using path from user...
MessageQueue q = new MessageQueue(txtMSMQ.Text);
//Setup formatter... Whatever you want!?
q.Formatter = new ActiveXMessageFormatter();
// Loop over all messages and write them to a file... (in this case XML)
MessageEnumerator msgEnum = q.GetMessageEnumerator2();
int k = 0;
while (msgEnum.MoveNext())
{
System.Messaging.Message msg = msgEnum.Current;
string fileName = this.txtFileLocation.Text + "\\" + k + ".xml";
System.IO.File.WriteAllText(fileName, msg.Body.ToString());
k++;
}
MessageBox.Show("All done!");
}
}
}