Beispiel #1
0
        public bool ValidAttributesFor(string table, string featureType, IEnumerable<FeatureActions> actions)
        {
            if (string.IsNullOrEmpty(featureType))
            {
                return false;
            }

            featureType = featureType.ToLower();

            if (featureType == "affected area" && actions == null)
            {
                return true;
            }

            if (string.IsNullOrEmpty(table))
            {
                return false;
            }

            table = table.ToLower();

            if (actions == null)
            {
                return false;
            }

            switch (table)
            {
                case "poly":
                    return
                        actions.All(
                            x =>
                                !string.IsNullOrEmpty(x.Action) &&
                                x.Treatments.All(t => !string.IsNullOrEmpty(t.Treatment)));
                case "point":
                    if (actions.Count() != 1)
                    {
                        return false;
                    }

                    if (new[] {"guzzler", "fish passage structure"}.Contains(featureType))
                    {
                        return actions.All(x => !string.IsNullOrEmpty(x.Action) &&
                                                 !string.IsNullOrEmpty(x.Type));
                    }

                    return actions.All(x => !string.IsNullOrEmpty(x.Description));
                case "line":
                    if (actions.Count() != 1)
                    {
                        return false;
                    }

                    return actions.All(x => !string.IsNullOrEmpty(x.Action) &&
                                                 !string.IsNullOrEmpty(x.Type));

            }

            return false;
        }
        /// <summary>
        /// Exports specified stops to serializable stop information.
        /// </summary>
        /// <param name="stops">The reference to the collection of stops to be exported.</param>
        /// <param name="capacitiesInfo">The reference to capacities info object to be used
        /// for retrieving custom order properties for stops.</param>
        /// <param name="orderCustomPropertiesInfo">The reference custom order properties info
        /// object.</param>
        /// <param name="addressFields">The reference to address fields object to be used
        /// for retrieving custom order properties for stops.</param>
        /// <param name="solver">The reference to VRPSolver to be used for retrieving
        /// curb approach policies for stops.</param>
        /// <param name="orderPropertiesFilter">Function returning true for custom order
        /// property names which should not be exported.</param>
        /// <returns>A reference to the collection of serializable stop information objects.
        /// </returns>
        public static IEnumerable<StopInfo> ExportStops(
            IEnumerable<Stop> stops,
            CapacitiesInfo capacitiesInfo,
            OrderCustomPropertiesInfo orderCustomPropertiesInfo,
            AddressField[] addressFields,
            IVrpSolver solver,
            Func<string, bool> orderPropertiesFilter = null)
        {
            Debug.Assert(stops != null);
            Debug.Assert(stops.All(stop => stop != null));
            Debug.Assert(stops.All(stop => stop.Route != null));
            Debug.Assert(capacitiesInfo != null);
            Debug.Assert(orderCustomPropertiesInfo != null);
            Debug.Assert(addressFields != null);

            if (!stops.Any())
            {
                return Enumerable.Empty<StopInfo>();
            }

            var capacityProperties = Order.GetPropertiesInfo(capacitiesInfo);
            var addressProperties = Order.GetPropertiesInfo(addressFields);
            var customProperties = Order.GetPropertiesInfo(orderCustomPropertiesInfo);

            var exportOrderProperties = _CreateExportOrderProperties(
                capacitiesInfo,
                orderCustomPropertiesInfo,
                addressFields,
                orderPropertiesFilter);

            // Make a dictionary for mapping routes to collection of sorted route stops.
            var routesSortedStops = stops
                .Select(stop => stop.Route)
                .Distinct()
                .ToDictionary(route => route, route => CommonHelpers.GetSortedStops(route));

            // Prepare result by exporting each stop individually.
            var settings = CommonHelpers.GetSolverSettings(solver);
            var result = stops
                .Select(stop => _ExportStop(
                    stop,
                    routesSortedStops[stop.Route],
                    exportOrderProperties,
                    addressProperties,
                    capacityProperties,
                    customProperties,
                    settings))
                .ToList();

            return result;
        }
Beispiel #3
0
        /// <summary>
        /// Create an aggregations object.
        /// </summary>
        /// <param name="aggregators">Sets the aggregations.</param>
        public Aggregations(IEnumerable<IAggregation> aggregators)
        {
            if (aggregators == null || aggregators.All(x => x == null))
                throw new ArgumentNullException("aggregators", "Aggregations requires at least one aggregator.");

            Aggregators = aggregators.Where(x => x != null);
        }
Beispiel #4
0
        /// <summary>
        /// Create a rescore request.
        /// </summary>
        /// <param name="rescoreQueries">The queries to run that will rescore the documents.</param>
        public Rescore(IEnumerable<RescoreQuery> rescoreQueries)
        {
            if (rescoreQueries == null || rescoreQueries.All(x => x == null))
                throw new ArgumentNullException("rescoreQueries", "RescoreRequest requires at least one rescore query.");

            RescoreQueries = rescoreQueries.Where(x => x != null);
        }
        public static bool AreAllKeysUp(this KeyboardState keyboardState, IEnumerable<Keys> keys)
        {
            keyboardState.ThrowIfNull("keyboardState");
            keys.ThrowIfNull("keys");

            return keys.All(keyboardState.IsKeyUp);
        }
Beispiel #6
0
        public override Func<DataASTMutable.WarewolfAtom, bool> CreateFunc(IEnumerable<DataASTMutable.WarewolfAtom> values, IEnumerable<DataASTMutable.WarewolfAtom> warewolfAtoms, IEnumerable<DataASTMutable.WarewolfAtom> to, bool all)
        {
            if (all)
                return a => values.All(x => DataASTMutable.CompareAtoms(a,x)==0);
            return a => values.Any(x =>  DataASTMutable.CompareAtoms(a, x) == 0);

        }
Beispiel #7
0
        /// <summary>
        /// Queries the plugwise database for the yield in the given month.
        /// </summary>
        /// <param name="from">start point, inclusive</param>
        /// <param name="to">start point, inclusive</param>
        /// <returns></returns>
        public IList<YieldAggregate> Get5minPlugwiseYield(DateTime from, IEnumerable<int> applianceIds)
        {
            // Querying on a datetime fails somehow
            // As a workaround we list the complete table and use linq to objects for the filter
            // This presents some scalability issues and should be looked in to.
            IList<Minute_Log_5> latest;
            if (!applianceIds.Any())
                latest = LoadAll5minData();
            else
                latest = Load5minApplianceData(applianceIds);

            Console.WriteLine("Loading 5minute plugwise production data since {0}", from);

            var applianceLog = (from logline in latest
                                where logline.LogDate >= @from.AddHours(-1)
                                from log in Get5minParts(logline)
                                where log.Date >= @from && log.Yield > 0.0
                                group log by log.Date into logbydate
                                orderby logbydate.Key
                                where applianceIds.All(
                                  appliance => logbydate.Any(log => log.ApplianceID == appliance))

                                select new YieldAggregate(
                                    date: logbydate.Key,
                                    yield: logbydate.Sum(l => l.Yield),
                                    duration: logbydate.First().Duration)
                                ).ToList();
            return applianceLog;
        }
        public static bool CanZip(IEnumerable<IProtectAttachment> attachments)
        {
            if (!PolicyBridge.IsEnabled("InteractiveProtectAllowUsersToCompressToZip"))
                return false;

            return !attachments.All(x => x.FileType == FileType.ZIP);
        }
		public IReadOnlyCollection<string> GetBlockWrapper(IEnumerable<string> code)
		{
			// If the code doesn't have any braces, surround it in a ruleset so that properties are valid.
			if (code.All(t => t.IndexOfAny(new[] { '{', '}' }) == -1))
				return new[] { ".GeneratedClass-" + Guid.NewGuid() + " {", "}" };
			return null;
		}
		public void Prepend( IEnumerable<object> sut, object[] items )
		{
			var prepended = sut.Prepend( items );
			Assert.Equal( sut.Count() + items.Length, prepended.Count() );
			Assert.True( sut.All( x => prepended.Contains( x ) ) );
			Assert.True( items.All( x => prepended.Contains( x ) ) );
		}
Beispiel #11
0
        /// <summary>
        /// Creates a source filter to include multiple fields.
        /// </summary>
        /// <param name="includeFields"></param>
        public SourceFilter(IEnumerable<string> includeFields)
        {
            if (includeFields == null || includeFields.All(x => string.IsNullOrWhiteSpace(x)))
                throw new ArgumentNullException("includeFields", "SourceFilter requires at least one field to include in this constructor.");

            IncludeFields = includeFields;
        }
Beispiel #12
0
        /// <summary>
        /// Create a span_near query.
        /// </summary>
        /// <param name="clauses">The span queries used to find documents.</param>
        public SpanNearQuery(IEnumerable<SpanQueryBase> clauses)
        {
            if (clauses == null || clauses.All(x => x == null))
                throw new ArgumentNullException("clauses", "SpanNearQuery requires at least one span query for clauses.");

            Clauses = clauses;
        }
Beispiel #13
0
        private bool AddNewTorgetItems(IEnumerable<HtmlNode> items)
        {
            foreach (var torgetItem in items.Where(IsNewTorgetItem).Select(CreateTorgetItem))
                _items.Add(torgetItem);

            return items.All(IsNewTorgetItem);
        }
Beispiel #14
0
 public void Save(IEnumerable<Sim> simList)
 {
     if (simList.Count() == 0)
         return;
     using (MySqlConnection conn = new MySqlConnection("server = localhost; user id = root; password = ; database = test"))
     {
         conn.Open();
         var cmd = conn.CreateCommand();
         cmd.CommandText = "set character set 'utf8'";
         cmd.ExecuteNonQuery();
         var cmdText = @"select * from quest_sim";
         cmd = conn.CreateCommand();
         cmd.CommandText = cmdText;
         var quest_sim = @"INSERT INTO quest_sim SET quest_id=?quest_id,compare_id=?compare_id,value=?value,start=?start";
         //路径
         simList.All(sim =>
         {
             cmd = conn.CreateCommand();
             cmd.CommandText = quest_sim;
             cmd.Parameters.AddWithValue("?quest_id", sim.QuestID);
             cmd.Parameters.AddWithValue("?compare_id", sim.CompareID);
             cmd.Parameters.AddWithValue("?value", sim.Value);
             cmd.Parameters.AddWithValue("?start", sim.StartCity);
             cmd.ExecuteNonQuery();
             return true;
         });
     }
 }
Beispiel #15
0
        public IndicesBoost(IEnumerable<IndexBoost> boostedIndices)
        {
            if (boostedIndices == null || boostedIndices.All(x => x == null))
                throw new ArgumentNullException("boostedIndices", "IndicesBoost requires at least one IndexBoost.");

            BoostedIndices = boostedIndices.Where(x => x != null);
        }
Beispiel #16
0
        /// <summary>
        /// Create a suggest request body document.
        /// </summary>
        /// <param name="suggestors">Sets the fields to get suggests from.</param>
        public Suggest(IEnumerable<ISuggester> suggestors)
        {
            if (suggestors == null || suggestors.All(x => x == null))
                throw new ArgumentNullException("suggestors", "Suggest requires at least one field suggest.");

            Suggestors = suggestors.Where(x => x != null);
        }
Beispiel #17
0
        private void ValidateUniqueCurrency(IEnumerable<Currency> otherCurrencies, ref ModelStateDictionary modelStateDictionary)
        {
            if (otherCurrencies.All(oc => oc.CurrencyType != CurrencyType))
                return;

            modelStateDictionary.AddModelError(BaseCache.CurrencyTypeField, String.Format(ValidationResource.Global_OwnUnique_ErrorMessage, FieldResource.Global_Currency_Name));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CharacterTemplate"/> class.
        /// </summary>
        /// <param name="templateTable">The template table.</param>
        /// <param name="inventory">The inventory.</param>
        /// <param name="equipment">The equipment.</param>
        /// <param name="quests">The quests.</param>
        /// <param name="knownSkills">The known skills.</param>
        /// <exception cref="ArgumentNullException"><paramref name="templateTable" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="inventory" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="equipment" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="knownSkills" /> is <c>null</c>.</exception>
        public CharacterTemplate(ICharacterTemplateTable templateTable, IEnumerable<CharacterTemplateInventoryItem> inventory,
                                 IEnumerable<CharacterTemplateEquipmentItem> equipment, IEnumerable<IQuest<User>> quests,
                                 IEnumerable<SkillType> knownSkills)
        {
            _templateTable = templateTable;

            if (templateTable == null)
                throw new ArgumentNullException("templateTable");
            if (inventory == null)
                throw new ArgumentNullException("inventory");
            if (equipment == null)
                throw new ArgumentNullException("equipment");
            if (knownSkills == null)
                throw new ArgumentNullException("knownSkills");

            // Compact all the collections given to us to ensure they are immutable and have minimal overhead
            _inventory = inventory.ToCompact();
            _equipment = equipment.ToCompact();
            _quests = quests.ToCompact();
            _knownSkills = knownSkills.ToCompact();

            // Assert values are valid
            Debug.Assert(_inventory.All(x => x != null));
            Debug.Assert(_equipment.All(x => x != null));
            Debug.Assert(_quests.All(x => x != null));
            Debug.Assert(_knownSkills.All(EnumHelper<SkillType>.IsDefined),
                string.Format("One or more SkillTypes for CharacterTemplate `{0}` are invalid!", this));

            if (log.IsInfoEnabled)
                log.InfoFormat("Loaded CharacterTemplate `{0}`.", this);
        }
Beispiel #19
0
        static XDocument MergeXml(IEnumerable<XDocument> inputs)
        {
            // What assembly is this?
            var assemblyName = GetAssemblyName(inputs.First());

            if (!inputs.All(input => GetAssemblyName(input) == assemblyName))
            {
                throw new Exception("All input files must be for the same assembly.");
            }

            // Merge all the member documentation into a single list.
            var mergedMembers = from input in inputs
                                from member in input.Element("doc").Element("members").Elements()
                                where !IsNamespace(member)
                                select member;

            // Remove documentation tags that Intellisense does not use, to minimize the size of the shipping XML files.
            RemoveUnwantedElements(mergedMembers);

            // Generate new Intellisense XML.
            return new XDocument(
                new XElement("doc",
                    new XElement("assembly",
                        new XElement("name", assemblyName)
                    ),
                    new XElement("members",
                        mergedMembers
                    )
                )
            );
        }
Beispiel #20
0
 internal RepositoryVersions( IEnumerable<TagCommit> collected, StringBuilder errors, ReleaseTagVersion startingVersionForCSemVer, bool checkCompactExistingVersions )
 {
     Debug.Assert( collected.All( c => c.ThisTag != null ) );
     _versions = collected.OrderBy( t => t.ThisTag ).ToList();
     if( _versions.Count > 0 )
     {
         var first = _versions[0].ThisTag;
         if( checkCompactExistingVersions && startingVersionForCSemVer == null && !first.IsDirectPredecessor( null ) )
         {
             errors.AppendFormat( "First existing version is '{0}' (on '{1}'). One or more previous versions are missing.", first, _versions[0].CommitSha )
                     .AppendLine();
         }
         for( int i = 0; i < _versions.Count - 1; ++i )
         {
             var prev = _versions[i].ThisTag;
             var next = _versions[i + 1].ThisTag;
             if( next.Equals( prev ) )
             {
                 errors.AppendFormat( "Version '{0}' is defined on '{1}' and '{2}'.", prev, _versions[i].CommitSha, _versions[i + 1].CommitSha )
                         .AppendLine();
             }
             else if( checkCompactExistingVersions && !next.IsDirectPredecessor( prev ) )
             {
                 errors.AppendFormat( "Missing one or more version(s) between '{0}' and '{1}'.", prev, next )
                         .AppendLine();
             }
         }
     }
 }
Beispiel #21
0
        private bool IsRelationshipValid([NotNull] IModelRelationship relationship)
        {
            var sourceNode = GetNode(relationship.Source);
            var targetNode = GetNode(relationship.Target);

            return(_modelRuleProviders?.All(i => i.IsRelationshipTypeValid(relationship.Stereotype, sourceNode, targetNode)) == true);
        }
Beispiel #22
0
        public IdsQuery(IEnumerable<string> documentIds)
        {
            if (documentIds == null || documentIds.All(x => string.IsNullOrWhiteSpace(x)))
                throw new ArgumentNullException("documentIds", "IdsQuery requires at least one document id.");

            DocumentIds = documentIds;
        }
        /// <summary>
        /// Create a script_field value.
        /// </summary>
        /// <param name="fields">The fields to create, and the scripts to create them with.</param>
        public ScriptFieldRequest(IEnumerable<ScriptField> fields)
        {
            if (fields == null || fields.All(x => x == null))
                throw new ArgumentNullException("fields", "ScriptFields requires at least one field.");

            Fields = fields.Where(x => x != null);
        }
Beispiel #24
0
        /// <summary>
        /// Create the highlighter.
        /// </summary>
        /// <param name="fieldHighlighters">Sets the fields to highlight.</param>
        public Highlighter(IEnumerable<FieldHighlighter> fieldHighlighters)
        {
            if (fieldHighlighters == null || fieldHighlighters.All(x => x == null))
                throw new ArgumentNullException("fieldHighlighters", "Highlighter requires at least one field highlighter.");

            FieldHighlighters = fieldHighlighters.Where(x => x != null);
        }
        public async void SavePackageSources(IEnumerable<IPackageSource> packageSources)
        {
            if (_busy)
                return;

            _busy = true;

            await Task.Run(() =>
            {
                foreach (var packageSource in _packageSources.ToArray())
                {
                    if (packageSources.All(n => n != packageSource))
                    {
                        Remove(packageSource);
                    }
                }

                foreach (var packageSource in packageSources.ToArray())
                {
                    if (!_packageSources.Any(n => n.Name == packageSource.Name && n.Location == packageSource.Location && n.Provider == packageSource.Provider))
                    {
                        Add(packageSource);
                    }
                }
            });

            Reload();

            _busy = false;
        }
        /// <summary>
        /// Loads the given target faces
        /// </summary>
        public virtual void SetTargetFaces(IEnumerable<ITargetFace> faces)
        {
            if (!faces.All(x => x is IFaceModelTargetFace))
                throw new ArgumentException("All target faces must implement IFaceModelTargetFace!");

            this.SetTargetFaces(faces.Cast<IFaceModelTargetFace>());
        }
 public void Purge(IEnumerable<int> livingIds)
 {
     foreach (var idToRemove in this.elementMap.Keys.Where(k => livingIds.All(id => id != k)).ToArray())
     {
         this.elementMap.Remove(idToRemove);
     }
 }
 private static IEnumerable<Variant> GenerateVariants(Variant variant, Potter aBook, IEnumerable<Variant> alreadyGenerated)
 {
     return variant.Piles
         .Where(pile => !pile.Contains(aBook))
         .Select(pile => CreateNewVariant(variant, pile, aBook))
         .Where(newVariant => alreadyGenerated.All(v => !v.Equals(newVariant)));
 }
Beispiel #29
0
        public Facets(IEnumerable<IFacet> facetGenerators)
        {
            if (facetGenerators == null || facetGenerators.All(x => x == null))
                throw new ArgumentNullException("facetGenerators", "Facets requires at least one facet generator.");

            FacetGenerators = facetGenerators.Where(x => x != null);
        }
        public static ValidationResult Create(RuleValidator validator, RuleValidatorContext context, IList<Object> parameterValues, object messageKey, IEnumerable<ValidationResult> nestedValidationResults = null)
        {
            string message = string.Empty;
            var messageService = new MessageService();

            if (String.IsNullOrEmpty(validator.Message))
            {
                var messageContext = new MessageContext(context, validator.GetType(), validator.Negate, validator.MessageStoreName, messageKey, validator.MessageFormatter);
                message = messageService.GetDefaultMessageAndFormat(messageContext, parameterValues);
            }
            else
            {
                //Since the message was supplied, don't get the default message from the store, just format it
                message = messageService.FormatMessage(validator.Message, context, parameterValues, validator.MessageFormatter);
            }

            //Override level if all the nested validation errors are Warnings

            if (nestedValidationResults != null && nestedValidationResults.All(vr => vr.Level == ValidationLevelType.Warn))
            {
                return new ValidationResult(context.PropertyInfo, message, ValidationLevelType.Warn, context.PropertyValue, nestedValidationResults);
            }
            else
            {
                return new ValidationResult(context.PropertyInfo, message, context.Level, context.PropertyValue, nestedValidationResults);
            }

            //return new ValidationResult(context.PropertyInfo, message, context.Level, context.PropertyValue, nestedValidationResults);
        }
Beispiel #31
0
        /// <summary>
        /// Creates a range facet, some combination of key/value field/script values are expected.
        /// </summary>
        /// <param name="facetName"></param>
        /// <param name="rangeBuckets"></param>
        public RangeFacet(string facetName, IEnumerable<RangeBucket> rangeBuckets)
            : this(facetName)
        {
            if (rangeBuckets == null || rangeBuckets.All(x => x == null))
                throw new ArgumentNullException("rangeBuckets", "RangeFacet requires at least one range bucket.");

            RangeBuckets = rangeBuckets.Where(x => x != null);
        }
Beispiel #32
0
 protected virtual void ProcessNewResult(OptimizationResult result)
 {
     // check if the incoming result is not the initial seed
     if (result.Id > 0)
     {
         if (Constraints?.All(constraint => constraint.IsMet(result.JsonBacktestResult)) != false)
         {
             if (Target.MoveAhead(result.JsonBacktestResult))
             {
                 Solution = result;
                 Target.CheckCompliance();
             }
         }
     }
 }
Beispiel #33
0
        /// <summary>
        ///     List repositories with ignored repositories removed.
        /// </summary>
        /// <param name="repositoriesToIgnore">A collection of Regex for repository names to ignore.</param>
        /// <returns></returns>
        public IEnumerable <GitRepository> GetRepositories(IEnumerable <Regex> repositoriesToIgnore = null)
        {
            Logger.Trace("Entering");

            var info = $"RepositoriesToIgnore: {(repositoriesToIgnore == null ? "Null" : "Not Null")}";

            var result =
                WaitAndRetryPolicyAsync.ExecuteAndCaptureAsync(
                    _ => _client.Value.GetRepositoriesAsync(_vsTsTool.ProjectName),
                    MakeContext(info)
                    ).Result;

            HandlePolicyResult(result, info);

            var results = result.Result;

            var output = results
                         .Where(x => repositoriesToIgnore?.All(y => !y.IsMatch(x.Name)) != false);

            Logger.Trace("Exiting");

            return(output);
        }
Beispiel #34
0
 public override bool IsSatisfiedBy(ITypeElement typeElement)
 {
     return(moduleBasedOnRegistration.IsSatisfiedBy(typeElement) &&
            basedOnRegistrations.All(registration => registration.IsSatisfiedBy(typeElement)));
 }
Beispiel #35
0
        private bool AllActivitiesBelongToSameCard(IEnumerable <Activity> activities)
        {
            var cardId = activities.First().CardId;

            return(activities.All(a => a.CardId == cardId));
        }
Beispiel #36
0
 public static bool forall <T>(Func <T, bool> predicate, IEnumerable <T> source)
 {
     return(source.All(predicate));
 }
Beispiel #37
0
 private static bool AllCharsInDictionary(IEnumerable <char> c, IReadOnlyDictionary <char, byte> d) => c.All(d.ContainsKey);
 public static IComparisonResult Includes <T>(this IEnumerable <T> collection1, IEnumerable <T>?collection2) =>
 Test.Collection(collection1) ??
 Test.Collection(collection2) ??
 ComparisonResult.FromBoolean(collection2?.All(c => collection1.Contains(c)), "First collection does not contain all elements of second collection");
Beispiel #39
0
        private static bool IsValidSetOfNodes(IEnumerable <IProjectTree> treeNodes)
        {
            Requires.NotNull(treeNodes, nameof(treeNodes));

            return(treeNodes.All(node => node.Flags.Contains(DependencyTreeFlags.Dependency | DependencyTreeFlags.SupportsBrowse)));
        }
Beispiel #40
0
 private static bool HasJustAllFlattenableOperator(IEnumerable <ResultOperatorBase> resultOperators)
 {
     return(resultOperators.All(x => FlattenableResultOperators.Contains(x.GetType())));
 }
 /// <summary>
 /// Проверить ошибки на корректность
 /// </summary>
 protected static bool ValidateCollection <T>(IEnumerable <T> collection) =>
 collection?.All(t => t != null) == true;
Beispiel #42
0
 public override Func<DataASTMutable.WarewolfAtom, bool> CreateFunc(IEnumerable<DataASTMutable.WarewolfAtom> values, IEnumerable<DataASTMutable.WarewolfAtom> warewolfAtoms, IEnumerable<DataASTMutable.WarewolfAtom> to, bool all)
 {
     if (all)
         return a => values.All(x => !a.ToString().ToLower(CultureInfo.InvariantCulture).StartsWith(x.ToString().ToLower(CultureInfo.InvariantCulture)));
     return a => values.Any(x => !a.ToString().ToLower(CultureInfo.InvariantCulture).StartsWith(x.ToString().ToLower(CultureInfo.InvariantCulture)));
 }
 /// <summary>
 /// Contains All
 /// Checks whether a list contains all values
 /// </summary>
 /// <typeparam name="T">List Generic Template</typeparam>
 /// <param name="source">Source IEnumerable</param>
 /// <param name="values">Values to be contained in the source collection</param>
 /// <returns>True if source contains all values, otherwise false</returns>
 public static bool ContainsAll <T>(this IEnumerable <T> source, IEnumerable <T> values)
 {
     return(values.All(value => source.Contains(value)));
 }
Beispiel #44
0
 public static bool ArchiveAllDownloaded(IEnumerable <string> archiveCodes)
 {
     lock (MangaCodeHash)
         return(archiveCodes?.All(e => MangaCodeHash.Contains(e)) ?? false);
 }
 public static bool AllAndSelfNotNull <T>(this IEnumerable <T> source)
 => source?.All(value => value != null) ?? false;
        public virtual bool IsValid(IEnumerable <T> model)
        {
            _validationResults = Validate(model);

            return(_validationResults?.All(r => r.IsValid) == true);
        }
Beispiel #47
0
 private bool IsEmptyChange(IEnumerable <TextEdit> changes)
 => changes.All(x => string.IsNullOrEmpty(x.NewText) && IsRangeEmpty(x.Range));
 private bool ShouldShowDiagnosticContextMenu(IEnumerable <object> items)
 {
     return(_initialized && items.All(item => item is DiagnosticItem));
 }
Beispiel #49
0
 private static int CountNonAccents(string input, IEnumerable <Accent>?accents)
 {
     return(input.Count(c => accents?.All(a => a.Character != c) ?? true));
 }
 private bool ShouldShowAnalyzerContextMenu(IEnumerable <object> items)
 {
     return(items.All(item => item is AnalyzerItem));
 }
Beispiel #51
0
        public static void DoImport(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            // Parse list input parameters
            BackgroundWorkParameters param = (BackgroundWorkParameters)e.Argument;
            string _URL          = param.Url;
            int    categoryId    = param.CategoryId;
            int    portalId      = param.PortalId;
            int    vendorId      = param.VendorId;
            string countryFilter = param.CountryFilter;
            string cityFilter    = param.CityFilter;
            int?   stepImport    = param.StepImport;
            int    feedId        = param.FeedId;

            if (!File.Exists(_URL))
            {
                // unzip file to temp folder if needed
                if (_URL.EndsWith(".zip"))
                {
                    string zipFileName = String.Format("{0}\\{1}", Properties.Settings.Default.TempPath,
                                                       "Hotels_Standard.zip");
                    // inside this function show progressBar for step: LoadFile
                    if (File.Exists(zipFileName))
                    {
                        File.Delete(zipFileName);
                    }
                    Common.SaveFileFromURL(_URL, zipFileName, 60, bw, e, log);

                    // if user cancel during saving file or ERROR
                    if (e.Cancel || (e.Result != null) && e.Result.ToString().Substring(0, 6).Equals("ERROR:"))
                    {
                        return;
                    }
                    // Set step for backgroundWorker
                    Form1.activeStep = "Extract file..";
                    bw.ReportProgress(0); // start new step of background process

                    using (ZipFile zip1 = ZipFile.Read(zipFileName))
                    {
                        foreach (ZipEntry zipEntry in zip1)
                        {
                            zipEntry.Extract(Properties.Settings.Default.TempPath,
                                             ExtractExistingFileAction.OverwriteSilently);
                        }
                    }
                    _URL = String.Format("{0}\\{1}", Properties.Settings.Default.TempPath, "Hotels_Standard.xml");
                }
            }

            XmlSchemaSet schemas = new XmlSchemaSet();

            schemas.Add("", "Hotels_Standard.xsd");
            Form1.activeStep = "Validating input..";
            bw.ReportProgress(0); // start new step of background process
            XDocument xDoc   = XDocument.Load(_URL);
            bool      errors = false;

            xDoc.Validate(schemas, (o, e2) =>
            {
                e.Result = "ERROR:" + e2.Message;
                log.Error(e2.Message);
                errors = true;
            });
            if (errors)
            {
                e.Cancel = true;
                return;
            }

            // show progress & catch Cancel
            if (bw.CancellationPending)
            {
                e.Cancel = true;
                return;
            }
            else if (bw.WorkerReportsProgress)
            {
                bw.ReportProgress(50);
            }

            // read hotels from XML
            // use XmlReader to avoid huge file size dependence
            var xmlProducts =
                from el in Common.StreamRootChildDoc(_URL, "hotel")
                select new ProductView
            {
                Country         = (string)el.Element("hotel_country"),
                County          = (string)el.Element("hotel_county"),
                City            = (string)el.Element("hotel_city"),
                ProductNumber   = (string)el.Element("hotel_ref"),
                Name            = (string)el.Element("hotel_name"),
                Images          = el.Element("images"),
                UnitCost        = (string)el.Element("PricesFrom"),
                Description     = (string)el.Element("hotel_description"),
                DescriptionHTML = (string)el.Element("alternate_description"),
                URL             = (string)el.Element("hotel_link"),
                Star            = (string)el.Element("hotel_star"),
                CustomerRating  = (string)el.Element("customerrating"),
                Rooms           = (string)el.Element("hotel_total_rooms"),
                Address         = (string)el.Element("hotel_address"),
                PostCode        = (string)el.Element("hotel_pcode"),
                CurrencyCode    = (string)el.Element("CurrencyCode"),
                Lat             = (string)el.Element("geo_code").Element("lat"),
                Long            = (string)el.Element("geo_code").Element("long")
            };

            if (!String.IsNullOrEmpty(countryFilter))
            {
                xmlProducts = xmlProducts.Where(p => p.Country == countryFilter);
            }

            if (!String.IsNullOrEmpty(cityFilter))
            {
                xmlProducts = xmlProducts.Where(p => p.City == cityFilter);
            }

            // show progress & catch Cancel
            if (bw.CancellationPending)
            {
                e.Cancel = true;
                return;
            }
            else if (bw.WorkerReportsProgress)
            {
                bw.ReportProgress(100);
            }
            Thread.Sleep(100); // a little bit slow working for visualisation Progress

            // Set step for backgroundWorker
            Form1.activeStep = "Import records..";
            bw.ReportProgress(0); // start new step of background process
            int productCount = xmlProducts.Count();

            try
            {
                int initialStep = 0;
                if (stepImport.HasValue)
                {
                    initialStep = stepImport.Value;
                }

                using (SelectedHotelsEntities db = new SelectedHotelsEntities())
                {
                    int i = 0;
                    foreach (ProductView product in xmlProducts)
                    {
                        if (i < initialStep)
                        {
                            i++;
                            continue;
                        }

#if DEBUG
                        Console.WriteLine(i + " - " + product.Name); // debug print
#endif
                        // create new product record
                        Hotel hotel =
                            db.Products.SingleOrDefault(
                                p => p.ProductTypeId == (int)Enums.ProductTypeEnum.Hotels && p.Categories.Any(c => c.Id == categoryId) && p.Name == product.Name && p.Number == product.ProductNumber) as Hotel;
                        if (hotel == null)
                        {
                            hotel = new Hotel();
                            hotel.ProductTypeId = (int)Enums.ProductTypeEnum.Hotels;
                            hotel.Name          = product.Name;
                            hotel.Number        = product.ProductNumber;
                            if (!String.IsNullOrEmpty(product.UnitCost))
                            {
                                hotel.UnitCost = Convert.ToDecimal(product.UnitCost);
                            }
                            hotel.Description = product.Description;
                            hotel.URL         = product.URL.Replace("[[PARTNERID]]", "2248").Trim(' ');
                            hotel.Image       = (string)product.Images.Element("url");
                            int    star    = 0;
                            string strStar = new string(product.Star.TakeWhile(char.IsDigit).ToArray());
                            if (strStar.Length > 0)
                            {
                                star       = int.Parse(strStar);
                                hotel.Star = star;
                            }
                            if (!String.IsNullOrEmpty(product.CustomerRating))
                            {
                                hotel.CustomerRating = int.Parse(product.CustomerRating);
                            }
                            if (!String.IsNullOrEmpty(product.Rooms))
                            {
                                hotel.Rooms = int.Parse(product.Rooms);
                            }
                            if (!String.IsNullOrEmpty(product.Address))
                            {
                                hotel.Address = product.Address;
                            }
                            if (!String.IsNullOrEmpty(product.PostCode))
                            {
                                hotel.PostCode = product.PostCode;
                            }
                            if (!String.IsNullOrEmpty(product.CurrencyCode))
                            {
                                hotel.CurrencyCode = product.CurrencyCode;
                            }
                            hotel.CreatedByUser = vendorId;
                            hotel.CreatedDate   = DateTime.Now;
                            hotel.IsDeleted     = false;
                            hotel.HotelTypeId   = (int)Enums.HotelTypeEnum.Hotels;
                            hotel.FeedId        = feedId;
                            db.Products.Add(hotel);
                            db.SaveChanges();

                            Common.SetLocation(product, db, hotel, log);
                            Common.SetGeoNameId(product, db, hotel, log);

                            Category category = db.Categories.Find(categoryId);
                            if (category != null)
                            {
                                hotel.Categories.Add(category);
                            }
                            db.SaveChanges();

                            var imageURLs = product.Images.Elements("url").Where(xe => xe.Value.EndsWith(".jpg") || xe.Value.EndsWith(".png")).Select(xe => xe.Value);
                            IEnumerable <string> imageURLList = imageURLs as IList <string> ?? imageURLs.ToList();
                            foreach (var imageURL in imageURLList)
                            {
                                ProductImage productImage = new ProductImage
                                {
                                    URL = imageURL
                                };
                                hotel.ProductImages.Add(productImage);
                            }
                            db.SaveChanges();

                            i++;
                            Common.UpdateSteps(stepImport: i);
                        }
                        else
                        {
                            if (hotel.Location == null)
                            {
                                Common.SetLocation(product, db, hotel, log);
                            }
                            if (!hotel.GeoNameId.HasValue)
                            {
                                Common.SetGeoNameId(product, db, hotel, log);
                            }

                            decimal?unitCost = null;
                            if (!String.IsNullOrEmpty(product.UnitCost))
                            {
                                unitCost = decimal.Parse(product.UnitCost);
                            }
                            if (hotel.UnitCost != unitCost)
                            {
                                hotel.UnitCost = unitCost;
                            }
                            if (hotel.Description != product.Description)
                            {
                                hotel.Description = product.Description;
                            }
                            if (hotel.URL != product.URL.Replace("[[PARTNERID]]", "2248").Trim(' '))
                            {
                                hotel.URL = product.URL.Replace("[[PARTNERID]]", "2248").Trim(' ');
                            }
                            if (hotel.Image != (string)product.Images.Element("url"))
                            {
                                hotel.Image = (string)product.Images.Element("url");
                            }
                            int?   star    = null;
                            string strStar = new string(product.Star.TakeWhile(char.IsDigit).ToArray());
                            if (strStar.Length > 0)
                            {
                                star = int.Parse(strStar);
                            }
                            if (hotel.Star != star)
                            {
                                hotel.Star = star;
                            }
                            int?customerRating = null;
                            if (!String.IsNullOrEmpty(product.CustomerRating))
                            {
                                customerRating = int.Parse(product.CustomerRating);
                            }
                            if (hotel.CustomerRating != customerRating)
                            {
                                hotel.CustomerRating = customerRating;
                            }
                            int?rooms = null;
                            if (!String.IsNullOrEmpty(product.Rooms))
                            {
                                rooms = int.Parse(product.Rooms);
                            }
                            if (hotel.Rooms != rooms)
                            {
                                hotel.Rooms = rooms;
                            }
                            if (hotel.Address != product.Address)
                            {
                                hotel.Address = product.Address;
                            }
                            if (hotel.PostCode != product.PostCode)
                            {
                                hotel.PostCode = product.PostCode;
                            }
                            if (hotel.CurrencyCode != product.CurrencyCode)
                            {
                                hotel.CurrencyCode = product.CurrencyCode;
                            }
                            db.SaveChanges();

                            var imageURLs = product.Images.Elements("url").Where(xe => xe.Value.EndsWith(".jpg") || xe.Value.EndsWith(".png")).Select(xe => xe.Value);
                            IEnumerable <string> imageURLList = imageURLs as IList <string> ?? imageURLs.ToList();
                            foreach (var imageURL in imageURLList)
                            {
                                ProductImage productImage =
                                    hotel.ProductImages.SingleOrDefault(pi => pi.URL == imageURL);
                                if (productImage == null)
                                {
                                    productImage = new ProductImage {
                                        URL = imageURL
                                    };
                                    hotel.ProductImages.Add(productImage);
                                }
                            }
                            db.SaveChanges();

                            var productImagesToRemove = db.ProductImages.Where(pi => pi.ProductId == hotel.Id &&
                                                                               imageURLList.All(xe => xe != pi.URL));
                            if (productImagesToRemove.Any())
                            {
                                db.ProductImages.RemoveRange(productImagesToRemove);
                            }
                            db.SaveChanges();

                            i++;
                            Common.UpdateSteps(stepImport: i);
                        }

                        if (bw.CancellationPending)
                        {
                            e.Cancel = true;
                            goto Cancelled;
                        }
                        else if (bw.WorkerReportsProgress && i % 100 == 0)
                        {
                            bw.ReportProgress((int)(100 * i / productCount));
                        }
                    }
                }

                if (!e.Cancel)
                {
                    Common.UpdateSteps();
                }
Cancelled:
                ;
            }
            catch (DbEntityValidationException exception)
            {
                foreach (var eve in exception.EntityValidationErrors)
                {
                    log.Error(String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                            eve.Entry.Entity.GetType().Name, eve.Entry.State), exception);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        log.Error(String.Format("- Property: \"{0}\", Error: \"{1}\"",
                                                ve.PropertyName, ve.ErrorMessage), exception);
                    }
                }
                throw;
            }
            catch (Exception ex)
            {
                e.Result = "ERROR:" + ex.Message;
                log.Error("Error error logging", ex);
            }
        }
 public static bool NotIn(this string str, IEnumerable <string> options)
 {
     return(options.All(opt => opt.ToLower() != str.ToLower()));
 }
 public static bool IsHex(IEnumerable <char> chars)
 => chars.All(c => ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')));
        /// <summary>
        /// Creates a new DAQmx task and adds channels to it
        /// </summary>
        /// <param name="nodes">Graph nodes of type MetricAnalogOutput</param>
        /// <exception cref="InvalidCastException">At least one element in <paramref name="nodes"/> not of type MetricAnalogOutput</exception>
        /// <exception cref="InvalidOperationException">At least one element in <paramref name="nodes"/> not connected to the instance's specified device</exception>
        /// <exception cref="NidaqException">Task or channel could not be created</exception>
        public void CreateTask(IEnumerable <INidaqMetric> nodes)
        {
            if (!nodes.All(n => n is MetricAnalogOutput))
            {
                throw new InvalidCastException("all passed nodes must be of type MetricAnalogOutput");
            }

            if (!nodes.All(n => n.Channel.Device == Device))
            {
                throw new InvalidOperationException("not all passed nodes are connected to device " + Device.Name);
            }

            ClockRate = ((MetricAnalogOutput)nodes.First()).Samplerate;

            if (!nodes.All(n => ((MetricAnalogOutput)n).Samplerate == ClockRate))
            {
                ClockRate         = 0;
                SamplesPerChannel = 0;
                throw new InvalidOperationException("NIDAQ: not all analog output nodes in graph have the same samplerate");
            }

            foreach (var n in nodes.OfType <MetricAnalogOutput>())
            {
                n.Samplerate = ClockRate;
            }

            var nidaqBufferSizePerChannel = (int)(BufferLengthMs * (long)ClockRate / 1000);
            var localBufferSizePerChannel = (int)(2 * (BufferLengthMs + PrebufferLengthMs) * (long)ClockRate / 1000);

            SamplesPerChannel = nidaqBufferSizePerChannel;

            // ------------------------------
            // Configure DAQMX Task

            _task = new NationalInstruments.DAQmx.Task();
            foreach (var output in nodes.OfType <MetricAnalogOutput>())
            {
                output.ChannelNumber = _nodes.Count;

                _task.AOChannels.CreateVoltageChannel(
                    output.Channel.Path,
                    string.Empty,
                    output.VMin,
                    output.VMax,
                    NationalInstruments.DAQmx.AOVoltageUnits.Volts
                    );

                _nodes.Add(output);
            }

            _task.Timing.ConfigureSampleClock(
                "",
                ClockRate,
                NationalInstruments.DAQmx.SampleClockActiveEdge.Rising,
                NationalInstruments.DAQmx.SampleQuantityMode.ContinuousSamples,
                SamplesPerChannel
                );

            try {
                _task.Stream.ConfigureOutputBuffer(SamplesPerChannel);
            } catch (NationalInstruments.DAQmx.DaqException e) {
                throw new NidaqException(e.Error);
            }

            _task.Stream.Timeout = WriteTimeoutMs;
            _task.Stream.WriteRegenerationMode = NationalInstruments.DAQmx.WriteRegenerationMode.DoNotAllowRegeneration;

            try {
                _task.Control(NationalInstruments.DAQmx.TaskAction.Verify);
            } catch (NationalInstruments.DAQmx.DaqException e) {
                throw new NidaqException(e.Error);
            }

            _task.Stream.Buffer.OutputBufferSize = SamplesPerChannel;

            _writer = new NationalInstruments.DAQmx.AnalogMultiChannelWriter(_task.Stream);

            TaskHandle = _task.GetHashCode();

            _usableData   = new double[_nodes.Count, SamplesPerChannel];
            _bufferData   = new double[_nodes.Count, localBufferSizePerChannel];
            _channelCount = new int[_nodes.Count];

            State  = SessionTaskState.Stopped;
            _first = true;
        }
Beispiel #55
0
        private static bool allValuesEqual(IEnumerable <Card> cards)
        {
            var f = cards.First();

            return(cards.All(c => c.Value.Equals(f.Value, StringComparison.OrdinalIgnoreCase)));
        }
        public void VerifyValidYear()
        {
            var hasvalidYears = Rows.All(x => x.Year > 1950 && x.Year < DateTime.Now.Year + 1);

            hasvalidYears.Should().BeTrue();
        }
Beispiel #57
0
        ///////////////////////////////////////////////////////////////////
        #region Private Methods

        private static bool IsConditionMet(bool condition, IEnumerable <bool> values)
        {
            return(values?.All(m => m == condition) ?? false);
        }
Beispiel #58
0
        private static bool allSuitsEqual(IEnumerable <Card> cards)
        {
            var f = cards.First();

            return(cards.All(c => c.Suit == f.Suit));
        }
Beispiel #59
0
 private bool IsAuthorizedToGet <TExecutionUser>(IEnumerable <object> entities, TExecutionUser executionUser = null, object grandparent = null, object parent = null) where TExecutionUser : class
 {
     return(executionUser == null || (entities?.All(entity => IsAuthorizedToGetSingle(entity, executionUser, grandparent, parent)) ?? true));
 }
Beispiel #60
0
 public static bool None <T>(this IEnumerable <T> enumerable, Func <T, bool> predicate)
 {
     // none means: tell me if a certain assumption is false for all elements
     return(enumerable.All(t => !predicate(t)));
 }