Here are the examples of the csharp api System.Predicate.Invoke(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
63 Examples
19
Source : StringHelper.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public static string AddNumberUntilUnique(string input, string delimiter, Predicate<string> test)
{
Regex regex = new Regex($"(.+?){delimiter}(\\d+)");
while (!test(input))
{
int nextNo = 2;
var m = regex.Match(input);
if (m.Success)
{
input = m.Result("$1");
nextNo = int.Parse(m.Result("$2")) + 1;
}
input = input + delimiter + nextNo;
}
return input;
}
19
Source : Utils.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
public static void VerifyDirectories()
{
Predicate<string> isRelDirectory = name => name.Contains( "AGXUnity" ) &&
name.Contains( "Directory" ) &&
!name.Contains( "Full" );
var directories = ( from propertyInfo
in typeof( Utils ).GetProperties( BindingFlags.Public | BindingFlags.Static )
where isRelDirectory( propertyInfo.Name )
select (string)propertyInfo.GetGetMethod().Invoke( null, new object[] { } ) ).ToArray();
foreach ( var dir in directories ) {
if ( !replacedetDatabase.IsValidFolder( dir ) )
Debug.LogWarning( "Missing AGXUnity directory: " + dir );
}
}
19
Source : DictionaryExtensions.cs
with MIT License
from Arkhist
with MIT License
from Arkhist
public static string GetOrThrow<Key>(this Dictionary<Key, string> dict, Key key, string exMessage, Predicate<string> validator = null)
{
if (dict.TryGetValue(key, out var ret))
{
if (validator != null && !validator(ret))
throw new ArgumentException(exMessage);
return ret;
}
throw new KeyNotFoundException(exMessage);
}
19
Source : DictionaryExtensions.cs
with MIT License
from Arkhist
with MIT License
from Arkhist
public static string GetAnyOrThrow<Key>(this Dictionary<Key, string> dict, Key[] keys, string exMessage, Predicate<string> validator = null)
{
foreach (var key in keys)
{
if (dict.TryGetValue(key, out var ret))
{
if (validator != null && !validator(ret))
continue;
return ret;
}
}
throw new KeyNotFoundException(exMessage);
}
19
Source : DictionaryExtensions.cs
with MIT License
from Arkhist
with MIT License
from Arkhist
public static string GetOrWarn<Key>(this Dictionary<Key, string> dict, Key key, string warnMessage,
Predicate<string> validator = null)
{
if (dict.TryGetValue(key, out var ret))
{
if (validator != null && !validator(ret))
{
Logger.Log(LogLevel.Warning, warnMessage);
return "";
}
return ret;
}
Logger.Log(LogLevel.Warning, $"Key not found: {warnMessage}");
return "";
}
19
Source : Utils.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
public static IEnumerable<string> FindResourceName(Predicate<string> match)
{
replacedembly replacedembly = typeof(Utils).replacedembly;
var allResources = replacedembly.GetManifestResourceNames();
foreach (var resource in allResources)
{
if (match(resource))
{
yield return resource;
}
}
}
19
Source : LogEntry.cs
with MIT License
from CatLib
with MIT License
from CatLib
public string[] GetStackTrace(Predicate<string> replacedemblyMatch = null)
{
var callStack = new List<string>(StackTrace.FrameCount);
for (var i = 0; i < StackTrace.FrameCount; i++)
{
var frame = StackTrace.GetFrame(i);
var method = frame.GetMethod();
if (method.DeclaringType == null || !replacedemblyMatch(method.DeclaringType.replacedembly.GetName().Name))
{
callStack.Add(string.Format("{0}(at {1}:{2})", method, frame.GetFileName(),
frame.GetFileLineNumber()));
}
}
return callStack.ToArray();
}
19
Source : DocumentExtensions.cs
with GNU General Public License v3.0
from CircuitLord
with GNU General Public License v3.0
from CircuitLord
public static void ApplyManifest(this Doreplacedent doreplacedent)
{
if (doreplacedent.IsInBrowsingContext)
{
var root = doreplacedent.DoreplacedentElement as IHtmlHtmlElement;
if (root != null)
{
var manifest = root.Manifest;
//TODO
// Replace by algorithm to resolve the value of that attribute
// to an absolute URL, relative to the newly created element.
var CanResolve = new Predicate<String>(str => false);
if (!String.IsNullOrEmpty(manifest) && CanResolve(manifest))
{
// Run the application cache selection algorithm with the
// result of applying the URL serializer algorithm to the
// resulting parsed URL with the exclude fragment flag set.
}
else
{
// Run the application cache selection algorithm with no
// manifest. The algorithm must be preplaceded the Doreplacedent
// object.
}
}
}
}
19
Source : EnumExtensions.cs
with MIT License
from ClosedXML
with MIT License
from ClosedXML
public static object[] GetEnumValues(Type enumType, Predicate<string> checkPredicate)
{
if (enumType == null) throw new ArgumentNullException("enumType");
if (checkPredicate == null) throw new ArgumentNullException("checkPredicate");
if (!enumType.IsEnum)
throw new ArgumentException("enumType is not an Enum.");
FieldInfo[] fieldInfo = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);
return (from field in fieldInfo
let attr = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
where (attr != null && checkPredicate(attr.Description)) || checkPredicate(field.Name)
select field.GetValue(null)).ToArray();
}
19
Source : HeaderValueCheck.cs
with MIT License
from CodeTherapist
with MIT License
from CodeTherapist
public bool Matches(string value)
{
return _when(value);
}
19
Source : GeneralOptionPanel.cs
with MIT License
from dahall
with MIT License
from dahall
private bool ValidateText(Control ctrl, Predicate<string> pred, string error)
{
bool valid = pred(ctrl.Text);
//errorProvider.SetError(ctrl, valid ? string.Empty : error);
//OnComponentError(valid ? ComponentErrorEventArgs.Empty : new ComponentErrorEventArgs(null, error));
//hasError = valid;
return valid;
}
19
Source : DropDownCheckTree.cs
with MIT License
from dahall
with MIT License
from dahall
public void CheckItems(Predicate<string> match, bool keepExisting = false)
{
ForEachChildNode(checkedTreeView.Nodes, n => { if (match == null || match(n.Name)) n.Checked = true; else if (!keepExisting) n.Checked = false; });
UpdateText();
}
19
Source : TaskOptionsEditor.cs
with MIT License
from dahall
with MIT License
from dahall
private bool ValidateText(Control ctrl, Predicate<string> pred, string error)
{
var valid = pred(ctrl.Text);
//errorProvider.SetError(ctrl, valid ? string.Empty : error);
//OnComponentError(valid ? ComponentErrorEventArgs.Empty : new ComponentErrorEventArgs(null, error));
//hasError = valid;
return valid;
}
19
Source : ExternalConverterBase.cs
with MIT License
from DevExpress
with MIT License
from DevExpress
static string GenerateSafeNameCore(Type type, string originalName = null, object rootComponent = null, Predicate<string> isNameExists = null) {
bool hasOriginalName = !string.IsNullOrEmpty(originalName);
if(hasOriginalName) {
originalName = originalName
.Replace(' ', '_')
.Replace(',', '_')
.Replace('/', '_')
.Replace(';', '_')
.Replace('<', '_')
.Replace('>', '_');
for(int i = 0; i < 0xffff; i++) {
string suffix = i == 0 ? "" : "_" + i.ToString();
string newName = originalName + suffix;
if(IsValidName(newName, rootComponent) && (isNameExists == null || !isNameExists(newName)))
return newName;
}
}
string baseName = XRNameCreationService.GetDefaultBaseName(type);
int number = 1;
while(isNameExists != null && isNameExists(baseName + number.ToString()))
number++;
return baseName + number;
}
19
Source : MicrosoftExtensionsConfigurationBuildRepo.cs
with MIT License
from dotnet-campus
with MIT License
from dotnet-campus
public override void ClearValues(Predicate<string> keyFilter)
{
foreach (var key in _concurrentDictionary.Keys)
{
if (keyFilter(key))
{
_concurrentDictionary.TryRemove(key, out _);
}
}
}
19
Source : MicrosoftExtensionsConfigurationRepo.cs
with MIT License
from dotnet-campus
with MIT License
from dotnet-campus
public override void ClearValues(Predicate<string> keyFilter)
{
var removeList = new List<string>();
foreach (var (key, _) in Configuration.AsEnumerable())
{
if (keyFilter(key))
{
removeList.Add(key);
}
}
foreach (var key in removeList)
{
SetValue(key, null);
}
}
19
Source : NUnitTest.cs
with Apache License 2.0
from duyanming
with Apache License 2.0
from duyanming
public string PredicateNewTest(Predicate<string> item)
{
string[] arrayString = new string[]
{
"One","Two","Three","Four","Fice","Six","Seven","Eight","Nine","Ten"
};
foreach (string str in arrayString)
{
if (item(str))
{
return str;
}
}
return null;
}
19
Source : DescriptionPattern.cs
with Mozilla Public License 2.0
from ehsan2022002
with Mozilla Public License 2.0
from ehsan2022002
private void GoToNextTreeNodeMatch()
{
//Console.WriteLine("goToNextTreeNodeMatch()");
DecommitVariableGroups(); // make sure variable groups are free.
RemoveNamedNodes(); // if we named a node, it should now be unnamed
finished = true;
Match m = null;
string value = null;
if (treeNodeMatchCandidateIterator == null)
{
treeNodeMatchCandidateIterator = myNode.rel.GetSearchNodeIterator(tree, this);
}
while (treeNodeMatchCandidateIterator.MoveNext())
{
//Console.WriteLine("success = true");
nextTreeNodeMatchCandidate = treeNodeMatchCandidateIterator.Current;
if (myNode.descriptionMode == null)
{
//Console.WriteLine("myNode.descriptionMode == null");
// this is a backreference or link
if (myNode.isLink)
{
//Console.WriteLine("myNode.isLink");
Tree otherTree = namesToNodes[myNode.linkedName];
if (otherTree != null)
{
//Console.WriteLine("otherTree != null");
string otherValue = myNode.basicCatFunction == null
? otherTree.Value()
: myNode.basicCatFunction(otherTree.Value());
string myValue = myNode.basicCatFunction == null
? nextTreeNodeMatchCandidate.Value()
: myNode.basicCatFunction(nextTreeNodeMatchCandidate.Value());
if (otherValue.Equals(myValue))
{
//Console.WriteLine("otherValue.Equals(myValue)");
finished = false;
break;
}
}
}
else if (namesToNodes[myNode.name] == nextTreeNodeMatchCandidate)
{
//Console.WriteLine("namesToNodes[myNode.name] == nextTreeNodeMatchCandidate");
finished = false;
break;
}
}
else
{
// try to match the description pattern.
// cdm: Nov 2006: Check for null label, just make found false
// string value = (myNode.basicCatFunction == null ? nextTreeNodeMatchCandidate.value() : myNode.basicCatFunction.apply(nextTreeNodeMatchCandidate.value()));
// m = myNode.descPattern.matcher(value);
// bool found = m.find();
//Console.WriteLine("else");
bool found;
value = nextTreeNodeMatchCandidate.Value();
if (value == null)
{
found = false;
}
else
{
if (myNode.basicCatFunction != null)
{
value = myNode.basicCatFunction(value);
}
switch (myNode.descriptionMode)
{
case DescriptionMode.EXACT:
found = value.Equals(myNode.exactMatch);
break;
case DescriptionMode.PATTERN:
m = myNode.descPattern.Match(value);
found = m.Success;
break;
case DescriptionMode.ANYTHING:
found = true;
break;
case DescriptionMode.STRINGS:
found = myNode.stringFilter(value);
break;
default:
throw new ArgumentException("Unexpected match mode");
}
}
if (found)
{
//Console.WriteLine("found = true");
foreach (Tuple<int, string> varGroup in myNode.variableGroups)
{
// if variables have been captured from a regex, they must match any previous matchings
string thisVariable = varGroup.Item2;
string thisVarString = variableStrings.GetString(thisVariable);
if (m != null)
{
if (thisVarString != null &&
!thisVarString.Equals(m.Groups[varGroup.Item1].Value))
{
// failed to match a variable
found = false;
break;
}
}
else
{
if (thisVarString != null &&
!thisVarString.Equals(value))
{
// here we treat any variable group # as a match
found = false;
break;
}
}
}
}
if (found != myNode.negDesc)
{
//Console.WriteLine("found != myNode.negDesc");
finished = false;
break;
}
}
}
if (!finished)
{
// I successfully matched.
//Console.WriteLine("!finished");
ResetChild();
// reset my unique TregexMatcher child based on the Tree node I successfully matched at.
// cdm bugfix jul 2009: on next line need to check for descPattern not null, or else this is a backreference or a link to an already named node, and the map should _not_ be updated
if ((myNode.descriptionMode != null || myNode.isLink) && myNode.name != null)
{
// note: have to fill in the map as we go for backreferencing
namesToNodes.Add(myNode.name, nextTreeNodeMatchCandidate);
}
if (m != null)
{
// commit variable groups using a matcher, meaning
// it extracts the expressions from that matcher
CommitVariableGroups(m);
}
else if (value != null)
{
// commit using a set string (all groups are treated as the string)
CommitVariableGroups(value);
}
}
// finished is false exiting this if and only if nextChild exists
// and has a label or backreference that matches
// (also it will just have been reset)
}
19
Source : AbstractTreebankLanguagePack.cs
with Mozilla Public License 2.0
from ehsan2022002
with Mozilla Public License 2.0
from ehsan2022002
public bool IsPunctuationTag(string str)
{
return PunctTagStringAcceptFilter()(str);
}
19
Source : AbstractTreebankLanguagePack.cs
with Mozilla Public License 2.0
from ehsan2022002
with Mozilla Public License 2.0
from ehsan2022002
public bool IsPunctuationWord(string str)
{
return PunctWordStringAcceptFilter()(str);
}
19
Source : AbstractTreebankLanguagePack.cs
with Mozilla Public License 2.0
from ehsan2022002
with Mozilla Public License 2.0
from ehsan2022002
public bool IsSentenceFinalPunctuationTag(string str)
{
return SFPunctTagStringAcceptFilter()(str);
}
19
Source : AbstractTreebankLanguagePack.cs
with Mozilla Public License 2.0
from ehsan2022002
with Mozilla Public License 2.0
from ehsan2022002
public bool IsEvalBIgnoredPunctuationTag(string str)
{
return EIPunctTagStringAcceptFilter()(str);
}
19
Source : AbstractTreebankLanguagePack.cs
with Mozilla Public License 2.0
from ehsan2022002
with Mozilla Public License 2.0
from ehsan2022002
public bool IsStartSymbol(string str)
{
return StartSymbolAcceptFilter()(str);
}
19
Source : Indexer.cs
with GNU General Public License v3.0
from FredTungsten
with GNU General Public License v3.0
from FredTungsten
public static DirectoryEntry FromDirectory(string path, Predicate<string> fileMatcher = null, Predicate<string> directoryMatcher = null)
{
DirectoryEntry result =
new DirectoryEntry {Name = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar))};
foreach (string directory in Directory.GetDirectories(path))
{
if (directoryMatcher != null)
{
if (!directoryMatcher(directory))
continue;
}
if (result.Directories == null)
result.Directories = new List<DirectoryEntry>();
result.Directories.Add(FromDirectory(directory, fileMatcher, directoryMatcher));
}
foreach (string file in Directory.GetFiles(path))
{
if (fileMatcher != null)
{
if (!fileMatcher(file))
continue;
}
if (result.Files == null)
result.Files = new List<FileEntry>();
result.Files.Add(FileEntry.FromFile(file));
}
return result;
}
19
Source : MetricsFilter.cs
with Apache License 2.0
from gigya
with Apache License 2.0
from gigya
public bool IsMatch(string context)
{
if (this.context != null && !this.context(context))
{
return false;
}
return true;
}
19
Source : MetricsFilter.cs
with Apache License 2.0
from gigya
with Apache License 2.0
from gigya
private bool IsNameMatch(string name)
{
if (this.name != null && !this.name(name))
{
return false;
}
return true;
}
19
Source : NicoDirectoryIO.cs
with MIT License
from Hayao-H
with MIT License
from Hayao-H
public void DeleteAll(Predicate<string> predicate, bool recurse = true)
{
var dirs = this.GetDirectorys(@"/").Where(p => predicate(p));
foreach (var directory in dirs)
{
this.Delete(directory, recurse);
}
}
19
Source : PlayerActionSetConverter.cs
with MIT License
from hk-modding
with MIT License
from hk-modding
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var set = (PlayerActionSet)Activator.CreateInstance(objectType);
Predicate<string> filter = set is IMappablePlayerActions mpa ? mpa.IsMappable : _ => true;
reader.Read();
while (reader.TokenType == JsonToken.PropertyName)
{
var name = (string)reader.Value;
if (!filter(name))
{
// value
reader.Read();
// JsonToken.PropertyName
reader.Read();
continue;
}
var ac = set.GetPlayerActionByName(name);
reader.Read();
if (ac != null)
{
if (reader.Value is string val)
{
if (val == new InputHandler.KeyOrMouseBinding().ToString() || val == InputControlType.None.ToString())
{
ac.ClearBindings();
}
else if (KeybindUtil.ParseBinding(val) is InputHandler.KeyOrMouseBinding bind)
{
ac.ClearBindings();
ac.AddKeyOrMouseBinding(bind);
}
else if (KeybindUtil.ParseInputControlTypeBinding(val) is InputControlType button)
{
ac.ClearBindings();
ac.AddInputControlType(button);
}
else
{
Logger.APILogger.LogWarn($"Invalid keybinding {val}");
}
}
else
{
Logger.APILogger.LogWarn($"Expected string for keybind, got `{reader.Value}");
}
}
else
{
Logger.APILogger.LogWarn($"Invalid keybind name {name}");
}
// JsonToken.PropertyName
reader.Read();
}
return set;
}
19
Source : PlayerActionSetConverter.cs
with MIT License
from hk-modding
with MIT License
from hk-modding
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var set = (PlayerActionSet)value;
Predicate<string> filter;
if (set is IMappablePlayerActions mpa) filter = mpa.IsMappable;
else filter = _ => true;
writer.WriteStartObject();
foreach (var ac in set.Actions)
{
if (filter(ac.Name))
{
writer.WritePropertyName(ac.Name);
var keyOrMouse = ac.GetKeyOrMouseBinding();
var controllerButton = ac.GetControllerButtonBinding();
if(keyOrMouse.Key != Key.None){
writer.WriteValue(keyOrMouse.ToString());
} else if(controllerButton != InputControlType.None) {
writer.WriteValue(controllerButton.ToString());
} else {
writer.WriteValue("None");
}
}
}
writer.WriteEndObject();
}
19
Source : Common.cs
with MIT License
from huangjia2107
with MIT License
from huangjia2107
public static string GetCopyName(string originalName, string copyFlag, Predicate<string> isExists)
{
if (string.IsNullOrWhiteSpace(originalName))
throw new ArgumentNullException("originalName");
if (isExists == null)
return originalName.Trim();
var copyName = originalName;
int i = 0;
while (isExists(copyName.Trim()))
{
i++;
if (i == 1)
copyName += copyFlag;
else
{
if (Regex.IsMatch(copyName, copyFlag + @"\(\d+\)$"))
copyName = Regex.Replace(copyName, copyFlag + @"\(\d+\)$", copyFlag + "(" + i + ")");
else
copyName += ("(" + i + ")");
}
}
return copyName.Trim();
}
19
Source : FileSearch.cs
with MIT License
from ibrahimpenekli
with MIT License
from ibrahimpenekli
private static void FindFilesRecursively(string path, List<string> files, Predicate<string> predicate)
{
foreach (var d in Directory.GetDirectories(path))
{
foreach (var f in Directory.GetFiles(d))
{
if (predicate.Invoke(f))
{
files.Add(f);
}
}
FindFilesRecursively(d, files, predicate);
}
}
19
Source : SetterConvention.cs
with MIT License
from JasperFx
with MIT License
from JasperFx
public void NameMatches(Predicate<string> rule)
{
Matching(prop => rule(prop.Name));
}
19
Source : CustomersHandler.cs
with MIT License
from jirenius
with MIT License
from jirenius
private void sendQueryEvent(IResourceContext r, Predicate<string> possiblyAffected) {
r.Service.Resource("search.customers").QueryEvent(qreq =>
{
// A null value signals the end of the query event.
// As we have nothing related to dispose, we do a quick exit.
if (qreq == null) return;
// By making a preliminary check if a query is possibly affected or not,
// we can avoid doing unneccesary database searches.
// Eg. a deleted person from Sweden will not affect a country=France query.
if (possiblyAffected(qreq.Query))
{
// Respond with what that query collection looks like now.
// RequireValue will use the Get method above to get the collection.
qreq.Collection(qreq.RequireValue<IEnumerable<Ref>>());
}
});
}
19
Source : FileSystem.cs
with MIT License
from JosefNemec
with MIT License
from JosefNemec
private static bool PathExistsOnAnyDrive(string originalPath, Predicate<string> predicate, out string existringPath)
{
originalPath = FixPathLength(originalPath);
existringPath = null;
try
{
if (predicate(originalPath))
{
existringPath = originalPath;
return true;
}
if (!Paths.IsFullPath(originalPath))
{
return false;
}
var rootPath = Path.GetPathRoot(originalPath);
var availableDrives = DriveInfo.GetDrives().Where(d => d.IsReady);
foreach (var drive in availableDrives)
{
var pathWithoutDrive = originalPath.Substring(drive.Name.Length);
var newPath = Path.Combine(drive.Name, pathWithoutDrive);
if (predicate(newPath))
{
existringPath = newPath;
return true;
}
}
}
catch (Exception ex) when (!Debugger.IsAttached)
{
logger.Error(ex, $"Error checking if path exists on different drive \"{originalPath}\"");
}
return false;
}
19
Source : SpiderHttpClient.cs
with GNU General Public License v3.0
from LeaFrock
with GNU General Public License v3.0
from LeaFrock
public async Task<string> GetStringOrRetryAsync(Uri uri, Predicate<string> rspValidator = null, byte retryTimes = 2, int millisecondsDelay = 0)
{
string rspText = null;
for (byte i = 0; i < retryTimes + 1; i++)
{
try
{
rspText = await GetStringAsync(uri);
rspText = rspText?.Trim();
}
catch
{
rspText = null;
}
if (!string.IsNullOrEmpty(rspText) && rspValidator?.Invoke(rspText) != false)
{
break;
}
if (millisecondsDelay > 0)
{
await Task.Delay(millisecondsDelay);
}
}
return rspText;
}
19
Source : DefaultWebProxyValidator.cs
with GNU General Public License v3.0
from LeaFrock
with GNU General Public License v3.0
from LeaFrock
async Task<bool> IWebProxyValidator.VerifyProxyAsync<T>(T proxy, Uri targetUri)
{
using (HttpClient client = ClientFactory.Invoke(proxy))
{
string rspText = await client.GetStringAsync(targetUri);
if (string.IsNullOrWhiteSpace(rspText))
{
return false;
}
return ResponseTextValidator?.Invoke(rspText.Trim()) != false;
}
}
19
Source : HttpConsole.cs
with GNU General Public License v3.0
from LeaFrock
with GNU General Public License v3.0
from LeaFrock
private static async Task<string> GetResponseTextByProxyAsync(Uri uri, Func<Uri, IWebProxy, Task<HttpResponseMessage>> rspFetcher, IWebProxy proxy, Predicate<string> rspValidator)
{
string rspText;
try
{
var rspMsg = await rspFetcher.Invoke(uri, proxy).ConfigureAwait(false);
if (rspMsg == null || !rspMsg.IsSuccessStatusCode)
{
rspText = null;
}
rspText = await rspMsg.ToTextAsync();
}
catch
{
rspText = null;
}
if (string.IsNullOrEmpty(rspText))
{
return null;
}
if (rspValidator?.Invoke(rspText) == false)
{
return null;
}
return rspText;
}
19
Source : ReflectionUtils.cs
with MIT License
from liangxiegame
with MIT License
from liangxiegame
private static bool Ignorereplacedembly(replacedembly replacedembly, Predicate<string> ignoreFilter)
{
try
{
if (replacedembly.GlobalreplacedemblyCache)
{
// Ignore system replacedemblies by default.
return true;
}
if (replacedembly.ManifestModule.Name == "<In Memory Module>" || // MS
replacedembly.ManifestModule.Name == "Default Dynamic Module") // Mono
{
// Ignore dynamically generated replacedemblies.
return true;
}
if (replacedembly.Location.EndsWith(".vshost.exe"))
{
// Ignore VS generated replacedemblies.
return true;
}
// Ignore specific replacedemblies.
var replacedemblyName = Path.GetFileNameWithoutExtension(replacedembly.Location);
if (replacedembliesToIgnore.Contains(replacedemblyName))
{
return true;
}
// Ignore replacedemblies specified by caller.
if (ignoreFilter != null && ignoreFilter(replacedemblyName))
{
return true;
}
return false;
}
catch (Exception ex)
{
throw new ApplicationException("Failed to replacedess replacedembly for ignoring:\n" + replacedembly.ManifestModule.Name, ex);
}
}
19
Source : OptionsDialog.cs
with MIT License
from marcellarius
with MIT License
from marcellarius
private void UpdateVisiblePropertiesCheckState()
{
Predicate<string> isVisible = (id) => _settings.HiddenProperties == null || !_settings.HiddenProperties.Contains(id);
for (int i = 0; i < _cameraPropertyDescriptors.Count; i++)
{
visiblePropertiesListbox.SereplacedemChecked(i, isVisible(_cameraPropertyDescriptors[i].Id));
}
}
19
Source : PartyReservationFilterModule.cs
with GNU General Public License v3.0
from martinmladenov
with GNU General Public License v3.0
from martinmladenov
public static void Main()
{
string[] people = Console.ReadLine().Split();
Dictionary<string, Predicate<string>> filters = new Dictionary<string, Predicate<string>>();
string input;
while ((input = Console.ReadLine()) != "Print")
{
var split = input.Split(';');
string funcName = split[0];
string filterName = split[1];
string argument = split[2];
string filterKey = $"{filterName};{argument}";
if (funcName == "Remove filter")
{
filters.Remove(filterKey);
}
else if (funcName == "Add filter")
{
Predicate<string> filter = null;
if (filterName == "Starts with")
{
filter = name => name.StartsWith(argument);
}
else if (filterName == "Ends with")
{
filter = name => name.EndsWith(argument);
}
else if (filterName == "Length")
{
filter = name => name.Length == int.Parse(argument);
}
else if (filterName == "Contains")
{
filter = name => name.Contains(argument);
}
filters.Add(filterKey, filter);
}
}
people = people.Where(person => !filters.Values.Any(filter => filter(person))).ToArray();
Console.WriteLine(string.Join(" ", people));
}
19
Source : PredicateParty.cs
with GNU General Public License v3.0
from martinmladenov
with GNU General Public License v3.0
from martinmladenov
public static void Main()
{
string[] people = Console.ReadLine().Split();
string input;
while ((input = Console.ReadLine()) != "Party!")
{
var split = input.Split();
string funcName = split[0];
string criteriaName = split[1];
string argument = split[2];
Func<string[], Predicate<string>, string[]> func = null;
if (funcName == "Remove")
{
func = (names, crit) => names.Where(s => !crit(s)).ToArray();
}
else if (funcName == "Double")
{
func = (names, crit) =>
{
List<string> doubled = new List<string>();
foreach (var name in names)
{
if (crit(name))
{
doubled.Add(name);
}
doubled.Add(name);
}
return doubled.ToArray();
};
}
Predicate<string> criteria = null;
if (criteriaName == "StartsWith")
{
criteria = name => name.StartsWith(argument);
}
else if (criteriaName == "EndsWith")
{
criteria = name => name.EndsWith(argument);
}
else if (criteriaName == "Length")
{
criteria = name => name.Length == int.Parse(argument);
}
people = func(people, criteria);
}
if (people.Length > 0)
{
Console.WriteLine($"{string.Join(", ", people)} are going to the party!");
}
else
{
Console.WriteLine("Nobody is going to the party!");
}
}
19
Source : LinuxInfoProvider.cs
with MIT License
from microsoft
with MIT License
from microsoft
private static int GetPortCount(int processId, Predicate<string> predicate, ServiceContext context = null)
{
string processIdStr = processId == -1 ? string.Empty : " " + processId + "/";
/*
** -t - tcp
** -p - display PID/Program name for sockets
** -n - don't resolve names
** -a - display all sockets (default: connected)
*/
string arg = "-tna";
string bin = "netstat";
if (processId > -1)
{
if (context == null)
{
return -1;
}
// We need the full path to the currently deployed FO CodePackage, which is were our
// proxy binary lives, which is used for elevated netstat call.
string path = context.CodePackageActivationContext.GetCodePackageObject("Code").Path;
arg = string.Empty;
// This is a proxy binary that uses Capabilities to run netstat -tpna with elevated privilege.
// FO runs as sfappsuser (SF default, Linux normal user), which can't run netstat -tpna.
// During deployment, a setup script is run (as root user)
// that adds capabilities to elevated_netstat program, which will *only* run (execv) "netstat -tpna".
bin = $"{path}/elevated_netstat";
}
var startInfo = new ProcessStartInfo
{
Arguments = arg,
FileName = bin,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardInput = false,
RedirectStandardOutput = true,
RedirectStandardError = false
};
int count = 0;
using (Process process = Process.Start(startInfo))
{
string line;
while (process != null && (line = process.StandardOutput.ReadLine()) != null)
{
if (!line.StartsWith("tcp ", StringComparison.OrdinalIgnoreCase))
{
// skip headers
continue;
}
if (processId != -1 && !line.Contains(processIdStr))
{
continue;
}
if (!predicate(line))
{
continue;
}
++count;
}
process?.WaitForExit();
if (process != null && process.ExitCode != 0)
{
return -1;
}
}
return count;
}
19
Source : GitCommandLineParser.cs
with MIT License
from microsoft
with MIT License
from microsoft
private bool HasAnyArgument(Predicate<string> argumentPredicate, out int argumentIndex)
{
argumentIndex = -1;
if (!this.IsValidGitCommand)
{
return false;
}
for (int i = ArgumentsOffset; i < this.parts.Length; i++)
{
if (argumentPredicate(this.parts[i]))
{
argumentIndex = i - ArgumentsOffset;
return true;
}
}
return false;
}
19
Source : AssetManager.cs
with MIT License
from mob-sakai
with MIT License
from mob-sakai
public static void ClearRuntimeCacheAll(Predicate<string> predicate)
{
ClearRuntimeCacheAll(m_RuntimeCache.Where(x => predicate(x.Key)).Select(x => x.Key).ToArray());
}
19
Source : FindWindow.cs
with MIT License
from mode51
with MIT License
from mode51
public static List<IntPtr> Find(Predicate<string> filter, bool findAll = false)
{
return Find((w, p) => { return filter.Invoke(GetWindowText(w)); }, findAll);
}
19
Source : EntryPoint.cs
with GNU General Public License v3.0
from NeuroWhAI
with GNU General Public License v3.0
from NeuroWhAI
private static bool RemoveResource(Predicate<string> predicate)
{
var dictionaries = Application.Current.Resources.MergedDictionaries;
int index = 0;
foreach (var dir in dictionaries)
{
string path = dir.Source.ToString();
if (predicate(path))
{
break;
}
++index;
}
if (index < dictionaries.Count)
{
dictionaries.RemoveAt(index);
return true;
}
return false;
}
19
Source : NuGet.Core.cs
with MIT License
from oleg-shilo
with MIT License
from oleg-shilo
XElement GetCompatibleTargetFramework(IEnumerable<XElement> freameworks, PackageInfo package)
{
// https://docs.microsoft.com/en-us/dotnet/standard/frameworks
// netstandard?.?
// netcoreapp?.?
// net?? | net???
// "" (no framework element, meaning "any framework")
// Though packages use Upper case with '.' preffix: '<group targetFramework=".NETStandard2.0">'
XElement findMatch(Predicate<string> matchTest)
{
var items = freameworks.Select(x => new { Name = x.Attribute("targetFramework")?.Value, Element = x })
.OrderByDescending(x => x.Name)
.ToArray();
var match = items.FirstOrDefault(x => matchTest(x.Name ?? ""))?.Element ?? // exact match
items.FirstOrDefault(x => x.Name == null)?.Element; // universal dependency specified by not supplying targetFramework element
return match;
}
if (package.PreferredRuntime != null)
{
// by requested runtime
return findMatch(x => x.Contains(package.PreferredRuntime));
}
else
{
if (CSharpCompiler.DefaultCompilerRuntime == DefaultCompilerRuntime.Standard)
{
// by configured runtime
return findMatch(x => x.Contains("netstandard", ignoreCase: true));
}
else
{
if (Runtime.IsCore)
// by runtime of the host
return findMatch(x => x.Contains("netcore", ignoreCase: true))
?? findMatch(x => x.Contains("netstandard", ignoreCase: true));
else
// by .NET full as tehre is no other options
return findMatch(x => (x.StartsWith("net", ignoreCase: true)
|| x.StartsWith(".net", ignoreCase: true))
&& !x.Contains("netcore", ignoreCase: true)
&& !x.Contains("netstandard", ignoreCase: true))
?? findMatch(x => x.Contains("netstandard", ignoreCase: true));
}
}
}
19
Source : Helper.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
public IEnumerable<ProductViewModel> FilterOutInvalidProductNames(
IEnumerable<ProductViewModel> productViewModels) => productViewModels.ToList()
.Where(p => _isProductNamereplacedleCase(p.ProductName));
19
Source : PasteDlg.cs
with Apache License 2.0
from ProteoWizard
with Apache License 2.0
from ProteoWizard
public bool PeptideRowsContainProtein(Predicate<string> found)
{
var peptideRows = new DataGridViewRow[gridViewPeptides.RowCount];
gridViewPeptides.Rows.CopyTo(peptideRows, 0);
return peptideRows.Take(gridViewPeptides.RowCount-1).Contains(row =>
{
var protein = row.Cells[colPeptideProtein.Index].Value;
return found(protein != null ? protein.ToString() : null);
});
}
19
Source : PasteDlg.cs
with Apache License 2.0
from ProteoWizard
with Apache License 2.0
from ProteoWizard
public bool PeptideRowsContainPeptide(Predicate<string> found)
{
var peptideRows = new DataGridViewRow[gridViewPeptides.RowCount];
gridViewPeptides.Rows.CopyTo(peptideRows, 0);
return peptideRows.Take(gridViewPeptides.RowCount-1).Contains(row =>
{
var peptide = row.Cells[colPeptideSequence.Index].Value;
return found(peptide != null ? peptide.ToString() : null);
});
}
See More Examples