Example #1
1
        // This behavior is case sensitive
        public override IEnumerable<object> FindMatchingItems(string searchText, IList items, IEnumerable<object> escapedItems, string textSearchPath, TextSearchMode textSearchMode)
        {
            var strings = searchText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (strings.Length == 0)
            {
                return base.FindMatchingItems(searchText, items, escapedItems, textSearchPath, textSearchMode);
            }

            string name = string.Empty;
            string capital = string.Empty;
            if (strings.Length > 0)
            {
                name = strings[0];
            }

            if (strings.Length > 1)
            {
                capital = strings[1].TrimStart(' ');
            }

            IEnumerable<object> results = null;
            if (textSearchMode == TextSearchMode.Contains)
            {
                results = items.OfType<Country>().Where(x => x.Name.Contains(name) && x.Capital.Contains(capital));
            }
            else
            {
                results = items.OfType<Country>().Where(x => x.Name.StartsWith(name) && x.Capital.StartsWith(capital));
            }

            return results.Where(x => !escapedItems.Contains(x));
        }
        private static bool ShouldHumanize(ModelMetadata modelMetadata, IList<Attribute> propertyAttributes)
        {
            if (string.IsNullOrEmpty(modelMetadata.PropertyName))
                return false;

            if (propertyAttributes.OfType<DisplayNameAttribute>().Any())
                return false;

            if (propertyAttributes.OfType<DisplayAttribute>().Any())
                return false;

            return true;
        }
        private static bool IsTransformRequired(ModelMetadata modelMetadata, IList<Attribute> propertyAttributes)
        {
            if (string.IsNullOrEmpty(modelMetadata.PropertyName))
                return false;

            if (propertyAttributes.OfType<DisplayNameAttribute>().Any())
                return false;

            if (propertyAttributes.OfType<DisplayAttribute>().Any())
                return false;

            return true;
        }
        /// <summary>
        /// Copies HTTP Request Headers from parent request to all requests from multi-part child requests.
        /// This fixes a problem where content negotiation does not work correctly and JSON is always returned
        /// even when the client expects xml+atom.
        /// </summary>
        public virtual void CopyRequestHeaders(HttpRequestMessage request, IList<ODataBatchRequestItem> items)
        {
            var requests =
                items.OfType<OperationRequestItem>().Select(o => o.Request)
                    .Union(items.OfType<ChangeSetRequestItem>().SelectMany(cs => cs.Requests));

            foreach (var childRequest in requests)
            {
                foreach (var header in request.Headers)
                {
                    childRequest.Headers.Add(header.Key, request.Headers.GetValues(header.Key));
                }
            }
        }
		protected ListPickerBox(IList items, IList selectedItems, bool singleSelection, string _title, bool minOneSelected = true, bool showSelectAllButton = false)
		{
			InitializeComponent();
			this.minOneSelected = minOneSelected; 

			if (string.IsNullOrEmpty(_title))
				title.Visibility = Visibility.Collapsed;
			else
				title.Text = _title; 

			if (selectedItems == null)
				selectedItems = new List<object>();

			SelectAllButton.Visibility = showSelectAllButton ? Visibility.Visible : Visibility.Collapsed;

			list.ItemTemplate = (DataTemplate)(singleSelection ? Resources["singleTemplate"] : Resources["multipleTemplate"]);
			OriginalSelectedItems = selectedItems; 
			
			Dispatcher.BeginInvoke(delegate
			{
				Items = items.OfType<object>().
					Select(i => new ListPickerBoxItem { Item = i, IsChecked = selectedItems.Contains(i) }).
					ToList();

				UpdateSelectedItems();
				UpdateSelectAllButton();

				list.ItemsSource = Items; 
			});
		}
        /// <summary>
        /// Creates a dictionary describing argument based dependencies for the given list of functions.
        /// </summary>
        /// <param name="functions"></param>
        /// <returns></returns>
        public static IDictionary<IVariable, IEnumerable<IVariable>> GetDependentVariables(IList<IFunction> functions)
        {
            var result = new Dictionary<IVariable, IEnumerable<IVariable>>();

            var variables = functions.OfType<IVariable>();

            foreach (var variable in variables)
            {
                var variable1 = variable;
                result[variable] = functions.OfType<IVariable>()
                    .Where(variable2 => variable2.Arguments.Contains(variable1))
                    .ToList();
            }

            return result;
        }
Example #7
1
		public ClassDefinition(Token classToken, Token nameToken, Token baseClassToken, IList<Executable> members)
			: base(classToken)
		{
			this.NameToken = nameToken;
			this.BaseClassToken = baseClassToken;
			this.Members = members.OfType<FunctionDefinition>().ToArray();
		}
        public async Task<IEnumerable<IMediaFile>> StartSearchAsync(IList filesOrDirsCollection)
        {
            this.IsWorking = true;
            // create the cancellation token source
            this.CancelToken = new CancellationTokenSource();
            // create the cancellation token
            var token = this.CancelToken.Token;

            this.MainTask = Task<IEnumerable<IMediaFile>>.Factory
              .StartNew(() => {
                  var results = new ConcurrentQueue<IMediaFile>();

                  // get audio files from input collection
                  var rawFiles = filesOrDirsCollection.OfType<string>().Where(this.IsAudioFile).OrderBy(s => s).ToList();
                  foreach (var rawFile in rawFiles.TakeWhile(rawDir => !token.IsCancellationRequested))
                  {
                      var mf = this.GetMediaFile(rawFile);
                      if (mf != null)
                      {
                          results.Enqueue(mf);
                      }
                  }

                  // handle all directories from input collection
                  var directories = new List<string>();
                  foreach (var source in filesOrDirsCollection.OfType<string>().Except(rawFiles).Where(IsDirectory).TakeWhile(source => !token.IsCancellationRequested))
                  {
                      directories.AddRange(GetSubFolders(token, source));
                  }

                  var orderedDirs = directories.Distinct().OrderBy(s => s);
                  this.Log().Debug("search for files in {0} directories (sub directories included)", orderedDirs.Count());

                  foreach (var rawDir in orderedDirs.TakeWhile(rawDir => !token.IsCancellationRequested))
                  {
                      this.DoFindFiles(token, rawDir, results);
                  }

                  return results;
              }, token, TaskCreationOptions.LongRunning, TaskScheduler.Current);

            var mediaFiles = await this.MainTask;

            this.IsWorking = false;

            return mediaFiles;
        }
        protected override void Render(IList<IBaseTexture> inputs)
        {
            var texture = inputs.OfType<ITexture2D>().SingleOrDefault();
            if (texture == null)
                return;

            Render(texture);
        }
Example #10
0
 public CompiledFilter(MIA_Management miaManagement, IFilter filter, Namespace ns, BindVarNamespace bvNamespace, string outerMIIDJoinVariable, ICollection<TableJoin> tableJoins)
 {
   _statementParts = new List<object>();
   _statementBindVars = new List<BindVar>();
   _requiredMIATypes = new List<MediaItemAspectMetadata>();
   CompileStatementParts(miaManagement, filter, ns, bvNamespace, _requiredMIATypes, outerMIIDJoinVariable, tableJoins,
       _statementParts, _statementBindVars);
   _requiredAttributes = _statementParts.OfType<QueryAttribute>().ToList();
 }
        /// <summary>
        /// OData does not copy headers from the main request to the batch sub-request. Let's do it here...
        /// </summary>
        public virtual void CopyRequestHeadersToBatchItems(HttpRequestMessage request, IList<ODataBatchRequestItem> items)
        {
            var batchRequests = items
                .OfType<OperationRequestItem>().Select(o => o.Request)
                .Union(items.OfType<ChangeSetRequestItem>().SelectMany(cs => cs.Requests));

            foreach (var batchRequest in batchRequests)
            {
                foreach (var header in request.Headers)
                {
                    if (String.Equals(header.Key, DataServiceVersionHeader, StringComparison.OrdinalIgnoreCase) ||
                        String.Equals(header.Key, MaxDataServiceVersionHeader, StringComparison.OrdinalIgnoreCase))
                    {
                        batchRequest.Headers.Add(header.Key, request.Headers.GetValues(header.Key));
                    }
                }
            }
        }
 protected static Device GetDevice(IList<ICallCopyEntity> callCopyEntities)
 {
     Device device = callCopyEntities.OfType<Device>().FirstOrDefault();
     if (device == null)
     {
         device = new Device {Name = "Placeholder", DeviceType = "Placeholder"};
         callCopyEntities.Add(device);
     }
     return device;
 }
    public async Task<IEnumerable<IMediaFile>> StartSearchAsync(IList filesOrDirsCollection) {
      this.IsWorking = true;
      // create the cancellation token source
      this.cancelToken = new CancellationTokenSource();
      // create the cancellation token
      var token = this.cancelToken.Token;

      this.mainTask = Task<IEnumerable<IMediaFile>>.Factory
        .StartNew(() => {
          var results = new ConcurrentQueue<IMediaFile>();

          // get audio files from input collection
          var rawFiles = filesOrDirsCollection.OfType<string>().Where(this.IsAudioFile).OrderBy(s => s).ToList();
          foreach (var rawFile in rawFiles.TakeWhile(rawDir => !token.IsCancellationRequested)) {
            var mf = this.GetMediaFile(rawFile);
            if (mf != null) {
              results.Enqueue(mf);
            }
          }

          // handle all directories from input collection
          var directories = new List<string>();
          foreach (var source in filesOrDirsCollection.OfType<string>().Except(rawFiles).Where(IsDirectory).TakeWhile(source => !token.IsCancellationRequested)) {
            directories.Add(source);
            try {
              directories.AddRange(Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories).TakeWhile(dir => !token.IsCancellationRequested));
            } catch (Exception e) {
              // System.UnauthorizedAccessException
              Console.WriteLine(e);
            }
          }
          foreach (var rawDir in directories.Distinct().OrderBy(s => s).TakeWhile(rawDir => !token.IsCancellationRequested)) {
            this.doFindFiles(token, rawDir, results);
          }

          return results;
        }, token, TaskCreationOptions.LongRunning, TaskScheduler.Current);

      var mediaFiles = await this.mainTask;
      this.IsWorking = false;
      return mediaFiles;
    }
Example #14
0
        public IndexerNode(IList<object> arguments)
        {
            Arguments = arguments;

            var intArgs = Arguments.OfType<int>().ToArray();

            if (intArgs.Length == arguments.Count)
            {
                _intArgs = intArgs;
            }
        }
 public SelectClauseHandler(SelectClause clause)
 {
     _references = clause.Columns.ToList();
     _resolvers = _references.Select(ValueResolver.Create).ToList();
     if (_resolvers.OfType<AggregateValueResolver>().Any())
     {
         _groupingHandler =
             new GroupingHandler(
                 _references.Where(ReferenceIsNotAggregateFunction).Select(r => r.GetAliasOrName()).ToArray());
     }
 }
 protected WorkMode GetWorkMode(IList<ICallCopyEntity> callCopyEntities, string status)
 {
     status = status ?? string.Empty;
     WorkMode workMode = callCopyEntities.OfType<WorkMode>()
         .FirstOrDefault(x => status.Trim().Equals(x.Name));
     if (workMode == null)
     {
         workMode = new WorkMode { Name = status.Trim(), Value = status.GetHashCode() };
         callCopyEntities.Add(workMode);
     }
     return workMode;
 }
Example #17
0
        public MeasureTool()
        {
            geometries = new List<IGeometry>();
            pointGeometries = geometries.OfType<GeoPoint>();

            pointLayer = new VectorLayer();
            pointLayer.Name = "measure";
            pointLayer.DataSource = new DataTableFeatureProvider(geometries);
            pointLayer.Style.Symbol = TrackerSymbolHelper.GenerateSimple(Pens.DarkMagenta, Brushes.Indigo, 6, 6);
            pointLayer.Visible = false;
            pointLayer.ShowInLegend = false;
        }
Example #18
0
		public ByteBuffer GenerateByteCode(Parser parser, IList<Executable> lines, IList<string> spriteSheetOpsStringArgs, IList<int[]> spriteSheetOpsIntArgs)
		{
			FunctionDefinition mainFunction = lines
				.OfType<FunctionDefinition>()
				.Where<FunctionDefinition>(fd => fd.NameToken.Value == "main")
				.FirstOrDefault<FunctionDefinition>();

			if (mainFunction == null) {
				throw new Exception(); // should have thrown before if there was no main function.
			}

			ByteBuffer userCode = new ByteBuffer();

			this.Compile(parser, userCode, lines);

			ByteBuffer literalsTable = parser.LiteralLookup.BuildByteCode();

			ByteBuffer tokenData = this.BuildTokenData(userCode);

			ByteBuffer fileContent = this.BuildFileContent(parser.GetFilesById());

			ByteBuffer switchStatements = this.BuildSwitchStatementTables(parser);

			ByteBuffer spriteSheetStuff = this.BuildSpriteSheetStuff(spriteSheetOpsStringArgs, spriteSheetOpsIntArgs);

			ByteBuffer header = new Crayon.ByteBuffer();
			header.Concat(literalsTable);
			header.Concat(tokenData);
			header.Concat(fileContent);
			header.Concat(switchStatements);
			header.Concat(spriteSheetStuff);
			header.Add(null, OpCode.FINALIZE_INITIALIZATION);

			ByteBuffer output = new Crayon.ByteBuffer();
			output.Add(null, OpCode.USER_CODE_START, header.Size + 1, parser.VariableIds.Size);
			output.Concat(header);
			output.Concat(userCode);

			// artificially inject a function call to main() at the very end after all declarations are done.
			if (parser.MainFunctionHasArg)
			{
				output.Add(null, OpCode.DEF_LIST, 0); // TODO: op code to build a list of the command line args. For now just pass in an empty list.
				output.Add(null, OpCode.CALL_FUNCTION, (int)FunctionInvocationType.NORMAL_FUNCTION, 1, mainFunction.FunctionID, 0, 0);
			}
			else
			{
				output.Add(null, OpCode.CALL_FUNCTION, (int)FunctionInvocationType.NORMAL_FUNCTION, 0, mainFunction.FunctionID, 0, 0);
			}
			output.Add(null, OpCode.RETURN, 0);

			return output;
		}
 protected DeviceAgent GetDeviceAgent(IList<ICallCopyEntity> callCopyEntities, string userId)
 {
     userId = userId ?? string.Empty;
     DeviceAgent deviceAgent = callCopyEntities.OfType<DeviceAgent>()
         .FirstOrDefault(x => userId.Trim().Equals(x.DeviceAgentNumber));
     if (deviceAgent == null)
     {
         Device device = GetDevice(callCopyEntities);
         deviceAgent = new DeviceAgent {Device = device, DeviceAgentNumber = userId.Trim()};
         callCopyEntities.Add(deviceAgent);
     }
     return deviceAgent;
 }
 protected CallSplit GetCallSplit(IList<ICallCopyEntity> callCopyEntities, string huntgroupId)
 {
     huntgroupId = huntgroupId ?? string.Empty;
     CallSplit callSplit = callCopyEntities.OfType<CallSplit>()
         .FirstOrDefault(x => huntgroupId.Trim().Equals(x.Number));
     if (callSplit == null)
     {
         Device device = GetDevice(callCopyEntities);
         callSplit = new CallSplit { Device = device, Number = huntgroupId.Trim()};
         callCopyEntities.Add(callSplit);
     }
     return callSplit;
 }
Example #21
0
 public void VisitChunk(IChunkVisitor visitor, OutputLocation location, IList<Chunk> body, StringBuilder output)
 {
     if (location == OutputLocation.ClassMembers)
     {
         foreach (var snippet in body.OfType<CodeStatementChunk>().SelectMany(chunk => chunk.Code))
         {
             snippet.Value = snippet.Value.Replace("@class", "class");
         }
         var source = new SourceWriter(new StringWriter(output));
         var generator = new GeneratedCodeVisitor(source, new Dictionary<string, object>(), NullBehaviour.Strict);
         generator.Accept(body);
     }
 }
		private static bool IsLeader(IList<InstructionBase> instructions, int index)
		{
			if (index == 0)
				return true;

			var instruction = instructions[index];
			if (instructions.OfType<BranchingInstruction>().Any(x => x.BranchTarget == instruction))
				return true;

			if (index > 0 && instructions[index - 1] is BranchingInstruction)
				return true;

			return false;
		}
Example #23
0
        public static void AutoLayout(IList shapes, Diagram diagram)
        {
            var store = diagram.Store;
            List<ShapeElement> shapeElementCollection = new List<ShapeElement>();
            List<ShapeElement> elements = new List<ShapeElement>();
            List<ShapeElement> list3 = new List<ShapeElement>();
            foreach (ShapeElement element in shapes)
            {
                var condition1 = (element is ClassShape) && ((element as ClassShape).ModelElement != null);

                bool condition2 = false;
                if (element is ClassShape)
                {
                    var modelClass = (element as ClassShape).ModelElement as ModelClass;
                    condition2 = modelClass.Baseclass != null || shapes.OfType<ClassShape>()
                        .Any(cs => (cs.ModelElement as ModelClass).Baseclass == modelClass);
                }
                if (condition1 && condition2)
                {
                    elements.Add(element);
                }
                else
                {
                    if (element is InheritanceConnector)
                    {
                        shapeElementCollection.Add(element);
                        continue;
                    }
                    list3.Add(element);
                }
            }
            using (Transaction transaction = store.TransactionManager.BeginTransaction("AutoLayout"))
            {
                using (new SaveLayoutFlags(elements, VGNodeFixedStates.PermeablePlace | VGNodeFixedStates.FixedPlace))
                {
                    diagram.AutoLayoutShapeElements(shapes, VGRoutingStyle.VGRouteNetwork, PlacementValueStyle.VGPlaceWE, false);
                }
                using (new SaveLayoutFlags(list3, VGNodeFixedStates.FixedPlace))
                {
                    diagram.AutoLayoutShapeElements(shapes, VGRoutingStyle.VGRouteOrgChartNS, PlacementValueStyle.VGPlaceSN, false);
                }
                using (new SaveLayoutFlags(shapes, VGNodeFixedStates.FixedPlace))
                {
                    diagram.AutoLayoutShapeElements(shapeElementCollection, VGRoutingStyle.VGRouteRightAngle, PlacementValueStyle.VGPlaceUndirected, false);
                }
                RunHandleLineRouting(diagram);
                transaction.Commit();
            }
        }
		protected ListPickerBox(IList items, IList selectedItems)
		{
			InitializeComponent();

			OriginalSelectedItems = selectedItems; 
			Dispatcher.BeginInvoke(delegate
			{
				Items = items.OfType<object>().
					Select(i => new ListPickerBoxItem { Item = i, IsChecked = selectedItems.Contains(i) }).
					ToList();

				UpdateSelectedItems();
				list.ItemsSource = Items; 
			});
		}
Example #25
0
        public IList Write(IList content)
        {
            var newData = content.OfType<string>().ToArray();
            if (newData.Length != content.Count)
            {
                throw new ArgumentException("Utf8 encoding accept only strings");
            }

            var stringData = string.Join(Environment.NewLine, newData);
            var binaryData = Encoding.UTF8.GetBytes(stringData);

            this.saveData(binaryData);

            return new ArrayList()
            {
                binaryData
            };
        }
Example #26
0
 public void SaveObjects(IEntitySession session, IList<object> items)
 {
     //Group by WebCallId, SessionId, UserName
       var entries = items.OfType<LogEntry>().ToList();
       var groupedByWebCall = entries.GroupBy(e => e.WebCallId);
       foreach (var wg in groupedByWebCall) {
     if (wg.Key == null) {
       var groupedBySessionId = wg.GroupBy(e => e.UserSessionId);
       foreach (var sg in groupedBySessionId) {
     if (sg.Key == null) {
       var groupedByUserName = sg.GroupBy(e => e.UserName);
       foreach (var ug in groupedByUserName)
         SaveEntries(session, ug);
     } else
       SaveEntries(session, sg);
     }// foreach sg
       } //if wg.Key
       else
     SaveEntries(session, wg);
       }//foreach wg
 }
        /// <summary>
        ///     Allows ledger bucket specific behaviour during reconciliation.
        /// </summary>
        public override void ApplyReconciliationBehaviour(IList<LedgerTransaction> transactions, DateTime reconciliationDate, decimal openingBalance)
        {
            var netAmount = transactions.Sum(t => t.Amount);
            var closingBalance = openingBalance + netAmount;
            var budgetTransaction = transactions.OfType<BudgetCreditLedgerTransaction>().FirstOrDefault();

            if (budgetTransaction == null)
            {
                transactions.AddIfSomething(SupplementToZero(closingBalance, reconciliationDate));

                return;
            }

            // Supplement
            if (closingBalance < budgetTransaction.Amount)
            {
                transactions.AddIfSomething(SupplementToBudgetAmount(closingBalance, reconciliationDate, budgetTransaction.Amount));
                return;
            }

            if (closingBalance < openingBalance)
            {
                transactions.AddIfSomething(SupplementToOpeningBalance(closingBalance, reconciliationDate, openingBalance));
                return;
            }

            // Remove-excess
            if (closingBalance > openingBalance || closingBalance > budgetTransaction.Amount)
            {
                if (openingBalance > budgetTransaction.Amount)
                {
                    transactions.AddIfSomething(RemoveExcessToOpeningBalance(closingBalance, reconciliationDate, openingBalance));
                }
                else
                {
                    transactions.AddIfSomething(RemoveExcessToBudgetAmount(closingBalance, reconciliationDate, budgetTransaction.Amount));
                }
            }
        }
        public void AddSelf(IList<INugetStep> steps)
        {
            var other = steps.OfType<InstallSolutionDependency>().Where(x => x.Dependency.Name.EqualsIgnoreCase(Dependency.Name)).SingleOrDefault();

            if (other == null)
            {
                steps.Add(this);
                return;
            }

            if (Equals(other.Dependency, Dependency))
            {
                return;
            }

            if (Dependency.Mode != UpdateMode.Fixed) return;
            if (other.Dependency.Mode == UpdateMode.Float)
            {
                steps.Remove(other);
                steps.Add(this);
            }
        }
Example #29
0
        internal async System.Threading.Tasks.Task UpdateModules(IList<HierarchyNode> nodes) {
            DoPreCommandActions();
            try {
                using (var commander = NpmController.CreateNpmCommander()) {
                    if (nodes.Count == 1 && nodes[0] == this) {
                        await commander.UpdatePackagesAsync();
                    } else {
                        var valid = nodes.OfType<DependencyNode>().Where(CheckValidCommandTarget).ToList();

                        var list = valid.Where(node => node.GetPropertiesObject().IsGlobalInstall).Select(node => node.Package).ToList();
                        if (list.Count > 0) {
                            await commander.UpdateGlobalPackagesAsync(list);
                        }

                        list = valid.Where(node => !node.GetPropertiesObject().IsGlobalInstall).Select(node => node.Package).ToList();
                        if (list.Count > 0) {
                            await commander.UpdatePackagesAsync(list);
                        }
                    }
                }
            } catch (NpmNotFoundException nnfe) {
                ErrorHelper.ReportNpmNotInstalled(null, nnfe);
            } finally {
                AllowCommands();
            }
        }
        private IList<IOptionArgument> GetOptionArgumentDefinitionsInOrder(IList<ICommandLineArgument> argumentDefinitions)
        {
            IList<IOptionArgument> retValue = argumentDefinitions
                .OfType<IOptionArgument>()
                .OrderBy(x => x.Flag)
                .ToList<IOptionArgument>();

            return retValue;
        }