Пример #1
0
 private Selection(
     Field field,
     IFragment fragment )
 {
     Field = field;
     Fragment = fragment;
 }
Пример #2
0
 private Definition(
     Operation operation,
     IFragment fragment )
 {
     Operation = operation;
     Fragment = fragment;
 }
Пример #3
0
 public Definition(
     IFragment fragment )
     : this (
         null,
         fragment )
 {
     
 }
Пример #4
0
 public Selection(
     IFragment fragment )
     : this(
         null,
         fragment )
 {
     
 }
Пример #5
0
		public IFragment TryMergeWithNext(IFragment nextFragment) {
			LiteralFragment lf = nextFragment as LiteralFragment;
			if (lf == null || lf.IsCData || IsCData)
				return null;
			if (lf.Text == "")
				return this;
			if (Text == "")
				return lf;
			if (Text.EndsWith(" ") && lf.Text.StartsWith(" ")) // Collapse spaces
				return new LiteralFragment(Text.Substring(0, Text.Length - 1) + lf.Text);
			return new LiteralFragment(Text + lf.Text);
		}
Пример #6
0
        public string AttachFragment(IFragment fragment)
        {
            this.fragments.Push(fragment);

            if (fragment.Type == FragmentType.Cooling.ToString())
            {
                this.pressureOnCore -= fragment.PressureAffection;
            }
            else if (fragment.Type == FragmentType.Nuclear.ToString())
            {
                this.pressureOnCore += fragment.PressureAffection;
            }

            this.CheckPressureAndAlterDurability();

            return($"Successfully attached Fragment {fragment.Name} to Core {this.Name}!");
        }
Пример #7
0
        public override string Execute()
        {
            string result = string.Empty;

            try
            {
                IFragment detachedFragment = this.PlantController.DetachFragment();

                result = string.Format(DetachFragmentCommandSuccessMessage, detachedFragment.Name, this.PlantController.SelectedCore.Id);
            }
            catch
            {
                result = DetachFragmentCommandFailMessage;
            }

            return(result);
        }
Пример #8
0
        public void Hit(int x, int y)
        {
            IFragment target = TileSet[y][x];

            Console.WriteLine("SHOT FIRED ON (x:{0} y:{1})", x.ToString(), y.ToString());

            target.Hit = true;

            if (target is BoatFragment)
            {
                Console.WriteLine("xxxxxxx HIT xxxxxxxxx");
            }
            else
            {
                Console.WriteLine("~~~~~~~~ MISS ~~~~~~~~");
            }
        }
Пример #9
0
        public override string Execute()
        {
            if (!this.powerPlant.IsCurrentCoreSet())
            {
                throw new InvalidOperationException($"Failed to attach Fragment {this.Data[2]}!");
            }

            var fragmentType     = this.Data[1];
            var fragmentName     = this.Data[2];
            var fragmentPressure = int.Parse(this.Data[3]);

            IFragment fragment = this.fragmentFactory.CreateFragment(fragmentType, fragmentName, fragmentPressure);

            this.powerPlant.AddFragment(fragment);

            return($"Successfully attached Fragment {this.Data[2]} to Core {this.powerPlant.CurrentCoreName()}!");
        }
Пример #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Ceen.Mvc.RouteParser"/> class.
        /// </summary>
        /// <param name="route">The route specification to parse.</param>
        public RouteParser(string route, bool caseinsensitive, RouteEntry target)
        {
            var fragments = new List <IFragment>();

            var ix    = 0;
            var slurp = false;

            foreach (Match m in CURLY_MATCH.Matches(route))
            {
                if (slurp)
                {
                    throw new Exception($"Cannot have trailing data after slurp: {m.Value}");
                }

                if (ix != m.Index)
                {
                    fragments.Add(new Literal(route.Substring(ix, m.Index - ix), caseinsensitive, null));
                }

                var mv = VARIABLE_MATCH.Match(m.Groups["name"].Value);
                if (!mv.Success)
                {
                    throw new ArgumentException($"Failed to parse {m.Groups["name"].Value} as a valid variable expression");
                }

                var v = new Variable(mv.Groups["name"].Value, mv.Groups["default"].Value, mv.Groups["optional"].Success, mv.Groups["constraint"].Value, mv.Groups["slurp"].Success, null);

                if (fragments.Count > 0 && !(fragments.Last() is Literal))
                {
                    throw new Exception(string.Format("Must have literal spacer between {0} and {1}", fragments[fragments.Count - 2], v));
                }

                fragments.Add(v);

                ix = m.Index + m.Length;
            }

            if (ix != route.Length)
            {
                fragments.Add(new Literal(route.Substring(ix, route.Length - ix), caseinsensitive, null));
            }

            fragments.Add(new Result(target));

            m_root = LinkList(fragments);
        }
Пример #11
0
        public static bool CanTarget(this IFragment fragment, Type targetType)
        {
            if (fragment == null)
            {
                return(false);
            }

            List <TargetsAttribute> attributes = fragment.GetType().GetCustomAttributes(typeof(TargetsAttribute), false).OfType <TargetsAttribute>().ToList();

            if (attributes.Count == 0)
            {
                return(typeof(IBHoMObject).IsAssignableFrom(targetType));
            }
            else
            {
                return(attributes.SelectMany(x => x.ValidTypes).Distinct().Any(x => x.IsAssignableFrom(targetType)));
            }
        }
        private static IDetector GetDetector(IFragment detectable)
        {
            var codecStream = detectable as ICodecStream;

            if (codecStream != null)
            {
                // Return the detector of the codec stream, i.e. not (one of) the detector(s)
                // of the container of the codec stream.
                return(detectable.Detectors.Where(d => !codecStream.DataBlock.Detectors.Contains(d)).First());
            }
            if (detectable is IDataBlock)
            {
                // Note: Data blocks have only one detector!
                return(detectable.Detectors.First());
            }

            throw new InvalidOperationException("Detectable is not a codec stream or data block: " + detectable);
        }
Пример #13
0
        public static IBHoMObject AddFragment(this IBHoMObject iBHoMObject, IFragment fragment, bool replace = false)
        {
            if (iBHoMObject == null)
            {
                return(null);
            }
            IBHoMObject o = iBHoMObject.DeepClone();

            if (!replace)
            {
                o.Fragments.Add(fragment);
            }
            else
            {
                o.Fragments.AddOrReplace(fragment);
            }

            return(o);
        }
        public bool TryCreateFragment(string[] args, out IFragment newFragment)
        {
            newFragment = null;

            try
            {
                newFragment = this.fragmentsFactory.CreateFragment(args);
            }
            catch (TargetInvocationException tie)
            {
                return(false);
            }
            catch (InvalidOperationException Ioe)
            {
                return(false);
            }

            return(true);
        }
Пример #15
0
        public string GetFragmentInLine(IFragment fragment)
        {
            IOrigin        origin = fragment.Origin;
            OriginPosition begPos = fragment.GetBeginOriginPosition();
            OriginPosition endPos = fragment.GetEndOriginPosition();
            int            start  = begPos.CharNumber;
            int            end    = endPos.CharNumber;
            StringBuilder  sb     = new StringBuilder();

            for (int i = 0; i < start; i++)
            {
                sb.Append(' ');
            }
            for (int i = start; i < end; i++)
            {
                sb.Append((i + 1 == end) ? '^' : '~');
            }
            return(sb.ToString());
        }
Пример #16
0
        /// <summary>
        /// Converts the <see cref="IFragment" /> to <see cref="JObject" />.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="useJavaScriptCase">when <c>true</c> use “camel” casing.</param>
        /// <returns></returns>
        public static JObject ToJObject(this IFragment data, bool useJavaScriptCase)
        {
            if (data == null)
            {
                return(null);
            }

            var settings = JsonSerializationUtility
                           .GetConventionalResolver <IFragment>(useJavaScriptCase)
                           .ToJsonSerializerSettings();

            //TODO: consider making these optional:
            settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            settings.NullValueHandling     = NullValueHandling.Ignore;

            var jO = JObject.FromObject(data, JsonSerializer.Create(settings));

            return(jO);
        }
Пример #17
0
        public void WholeSourceFragmentTextTest()
        {
            string source = "I like reading sources!\nEspecially in tests.";

            iOrigin = CreateOriginTest(source);
            iReader = iOrigin.GetReader();

            ILocation locBeg = iReader.CurrentLocation;

            while (iReader.MoveNext())
            {
                ;                        // move to the end of source
            }
            ILocation locEnd = iReader.CurrentLocation;

            IFragment frAll = iOrigin.MakeFragment(locBeg, locEnd);

            Assert.AreEqual(frAll.GetOriginText(), source);
        }
        private IAbstractMarkupData CreateTags(IFragment startTagFragment, Queue <IFragment> fragments)
        {
            var startTagProperties = _propertiesFactory.CreateStartTagProperties(startTagFragment.Content);

            startTagProperties.DisplayText      = CreateDisplayText(startTagFragment.Content);
            startTagProperties.SegmentationHint = startTagFragment.SegmentationHint;

            var enclosedContent = new List <IAbstractMarkupData>();

            while (fragments.Count > 0)
            {
                var fragment = fragments.Dequeue();

                switch (fragment.InlineType)
                {
                case InlineType.Text:
                    enclosedContent.Add(CreateText(fragment.Content));
                    break;

                case InlineType.Placeholder:
                    enclosedContent.Add(CreatePlaceholder(fragment.Content, fragment.SegmentationHint));
                    break;

                case InlineType.StartTag:
                    enclosedContent.Add(CreateTags(fragment, fragments));
                    break;

                case InlineType.EndTag:
                    var endTagProperties = _propertiesFactory.CreateEndTagProperties(fragment.Content);
                    endTagProperties.DisplayText = CreateDisplayText(fragment.Content);

                    return(fragment.IsContentTranslatable
                            ? CreateTagPair(startTagProperties, endTagProperties, enclosedContent)
                            : CreateLockedContent(enclosedContent));

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            throw new ArgumentOutOfRangeException();
        }
Пример #19
0
        public static StatementSyntax GenerateStatement(this IFragment fragment, Context context)
        {
            var syntaxNode = fragment.Generate(context);

            var statementSyntax = syntaxNode as StatementSyntax;

            if (statementSyntax != null)
            {
                return(statementSyntax);
            }

            var expressionSyntax = syntaxNode as ExpressionSyntax;

            if (expressionSyntax != null)
            {
                return(SyntaxFactory.ExpressionStatement(expressionSyntax));
            }

            return(null);
        }
Пример #20
0
        public void OneLineFragmentTextTest()
        {
            string source = "1234";

            iOrigin = CreateOriginTest(source);
            iReader = iOrigin.GetReader();

            iReader.MoveNext();
            ILocation loc1 = iReader.CurrentLocation;

            iReader.MoveNext();
            iReader.MoveNext();
            ILocation loc2 = iReader.CurrentLocation;

            iReader.MoveNext();

            IFragment fr = iOrigin.MakeFragment(loc1, loc2);

            Assert.AreEqual(fr.GetOriginText(), "23");
        }
Пример #21
0
        /// <summary>
        /// Returns a formatted string of the name of a row, e.g. displayed in the FileTree or ProjectKeyframeOverview.
        /// </summary>
        /// <param name="detectable"></param>
        /// <returns></returns>
        public static string GetDescriptiveName(this IFragment detectable)
        {
            string       name        = detectable.DataFormat.GetDescriptiveName();
            ICodecStream codecStream = detectable as ICodecStream;

            if (codecStream != null && !string.IsNullOrEmpty(codecStream.Name))
            {
                name += string.Format(" ({0})", codecStream.Name);
            }

            if ((detectable.DataFormat == CodecID.Unknown) && (detectable.Detectors != null && detectable.Detectors.Count() > 0) && !(detectable.Detectors.First() is ICodecDetector))
            {
                name = detectable.Detectors.First().Name;
            }

            if (detectable.IsFragmented || detectable.FragmentContainer != null)
            {
                name += string.Format(" (fragment {0})", detectable.FragmentIndex + 1);
            }
            return(name);
        }
        public override string Execute()
        {
            string result            = string.Empty;
            string fragmentType      = this.Args[0];
            string fragmentName      = this.Args[1];
            int    pressureAffection = int.Parse(this.Args[2]);

            try
            {
                IFragment fragment = this.PlantController.CreateFragment(fragmentType, fragmentName, pressureAffection);
                this.PlantController.AttachFragment(fragment);

                result = string.Format(AttachFragmentCommandSuccessMessage, fragmentName, this.PlantController.SelectedCore.Id);
            }
            catch
            {
                result = string.Format(AttachFragmentCommandFailMessage, fragmentName);
            }

            return(result);
        }
Пример #23
0
        public IFragment TryMergeWithNext(IFragment nextFragment)
        {
            LiteralFragment lf = nextFragment as LiteralFragment;

            if (lf == null || lf.IsCData || IsCData)
            {
                return(null);
            }
            if (lf.Text == "")
            {
                return(this);
            }
            if (Text == "")
            {
                return(lf);
            }
            if (Text.EndsWith(" ") && lf.Text.StartsWith(" "))             // Collapse spaces
            {
                return(new LiteralFragment(Text.Substring(0, Text.Length - 1) + lf.Text));
            }
            return(new LiteralFragment(Text + lf.Text));
        }
Пример #24
0
        public static IBHoMObject AddFragment(this IBHoMObject iBHoMObject, IFragment fragment, bool replace = false)
        {
            if (iBHoMObject == null || fragment == null)
            {
                return(null);
            }
            IBHoMObject o = iBHoMObject.DeepClone();

            // Give a warning if the fragment is supposed to be unique but is found on the object
            List <Type> currentFragmentTypes = iBHoMObject.Fragments.Select(x => x.GetType()).ToList();

            foreach (Type restriction in fragment.GetType().UniquenessRestrictions())
            {
                if (currentFragmentTypes.Any(x => restriction.IsAssignableFrom(x) && x != fragment.GetType()))
                {
                    Engine.Reflection.Compute.RecordWarning("There is already a fragment of type " + restriction + " on this object. \nThe Fragment will still be added but consider reviewing this task as fragments of that type are supposed to be unique.");
                }
            }

            // Make sure this fragment can be added to that object
            if (fragment.CanTarget(iBHoMObject))
            {
                if (!replace)
                {
                    o.Fragments.Add(fragment);
                }
                else
                {
                    o.Fragments.AddOrReplace(fragment);
                }
            }
            else
            {
                Engine.Reflection.Compute.RecordError("An object of type " + iBHoMObject.GetType() + " is not a valid target for a fragment of type " + fragment.GetType() + ". The fragment was not added.");
            }


            return(o);
        }
        public void PrintFragmentInLineTest()
        {
            string        source = "OK. Error in line 1\nLine 2.";
            IOriginReader reader = new StringOrigin(source).GetReader();

            for (int i = 0; i < 4; i++)
            {
                reader.MoveNext(); // 'OK. '
            }
            ILocation locBeg = reader.CurrentLocation;

            for (int i = 0; i < 5; i++)
            {
                reader.MoveNext(); // 'Error'
            }
            ILocation locEnd = reader.CurrentLocation;
            IFragment fr     = locBeg.Origin.MakeFragment(locBeg, locEnd);

            SourceDiagnostic sd = new SourceDiagnostic();

            sd.PrintFragmentInLine(fr);
        }
Пример #26
0
        /***************************************************/
        /**** Private Methods                           ****/
        /***************************************************/

        private static object GetValue(this IBHoMObject obj, string propName)
        {
            IBHoMObject bhom = obj as IBHoMObject;

            if (obj == null || propName == null)
            {
                return(null);
            }

            if (bhom.CustomData.ContainsKey(propName))
            {
                if (!(bhom is CustomObject))
                {
                    Compute.RecordNote($"{propName} is stored in CustomData");
                }
                return(bhom.CustomData[propName]);
            }
            else
            {
                IFragment fragment     = null;
                Type      fragmentType = Create.Type(propName, true);
                if (fragmentType != null)
                {
                    List <IFragment> matches = bhom.Fragments.Where(fr => fragmentType.IsAssignableFrom(fr.GetType())).ToList();
                    if (matches.Count > 1)
                    {
                        Compute.RecordWarning($"{bhom} contains more than one fragment of type {fragmentType.IToText()}. The first one will be returned.");
                    }
                    fragment = matches.FirstOrDefault();
                }
                if (fragment == null)
                {
                    Compute.RecordWarning($"{bhom} does not contain a property: {propName}, or: CustomData[{propName}], or fragment of type {propName}.");
                }

                return(fragment);
            }
        }
Пример #27
0
        private void backgroundDataBlockScanner_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                ResetAllScanAttributes();
                return;
            }

            bool resultInvalidated = false;

            if (e.Error == null)
            {
                // Get used sourcedata
                IFragment sourceFragment = (_currentCodecStreamIndex == -1) ? ((IFragment)_currentDataBlocks[_currentDataBlockIndex]) : ((IFragment)_currentValidCodecStreams[_currentCodecStreamIndex]);

                // Report result to users of this scanner
                FileScanResult result = new FileScanResult(sourceFragment, e.Result as IResultNode,
                                                           _currentDataBlocks[_currentDataBlockIndex],
                                                           (_currentCodecStreamIndex >= 0) ? _currentValidCodecStreams[_currentCodecStreamIndex] : null,
                                                           _currentValidCodecStreams.Count);
                ResultDetected(this, result);

                // Check if the result is invalidated by one of the event listeners.
                resultInvalidated = ScanNextCodecStreamOnInvalidation && !result.IsValid;
            }

            // Continue scan operation
            if (_currentCodecStreamIndex == -1)
            {
                // We where scanning a Datablock
                ScanNextDataBlock();
            }
            else
            {
                // We where scanning a CodecStream
                ScanNextCodecStream(resultInvalidated);
            }
        }
Пример #28
0
        public override string Execute()
        {
            string result;

            try
            {
                string path = Constants.FragmentTypeFullName + this.LateInstantiationFragmentType
                              + Constants.FragmentModelNameSuffix;

                IFragment newFragment =
                    (IFragment)Activator.CreateInstance(
                        Type.GetType(path),
                        this.LateInstantiationFragmentName,
                        this.LateInstantiationFragmentPressureAffection);

                this.PowerPlant.AttachFragment(newFragment);

                result = string.Format(
                    Messages.SuccessFragmentAttachMessage,
                    newFragment.Name,
                    this.PowerPlant.CurrentlySelectedCore.Name);
            }
            catch (NoSelectedCoreException)
            {
                result = string.Format(
                    Messages.FailureFragmentAttachMessage,
                    this.LateInstantiationFragmentName);
            }
            catch (Exception)
            {
                result = string.Format(
                    Messages.FailureFragmentAttachMessage,
                    this.LateInstantiationFragmentName);
            }

            return(result);
        }
Пример #29
0
        public static List <IFragment> MergeFragments(IEnumerable <IFragment> fragments)
        {
            List <IFragment> result = new List <IFragment>();

            IFragment current = null;
            IEnumerator <IFragment> enumerator = null;

            try {
                enumerator = fragments.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    current = enumerator.Current;
                    while (enumerator.MoveNext())
                    {
                        var item   = enumerator.Current;
                        var merged = current.TryMergeWithNext(item);
                        if (merged == null)
                        {
                            result.Add(current);
                            current = item;
                        }
                        else
                        {
                            current = merged;
                        }
                    }
                    result.Add(current);
                }
            }
            finally {
                if (enumerator is IDisposable)
                {
                    ((IDisposable)enumerator).Dispose();
                }
            }
            return(result);
        }
Пример #30
0
        public string DetachFragment()
        {
            if (this.fragments.IsEmpty())
            {
                throw new ArgumentOutOfRangeException();
            }

            IFragment fragment = this.fragments.Peek();

            this.fragments.Pop();

            if (fragment.Type == FragmentType.Cooling.ToString())
            {
                this.pressureOnCore += fragment.PressureAffection;
            }
            else if (fragment.Type == FragmentType.Nuclear.ToString())
            {
                this.pressureOnCore -= fragment.PressureAffection;
            }

            this.CheckPressureAndAlterDurability();

            return($"Successfully detached Fragment {fragment.Name} from Core {this.Name}!");
        }
Пример #31
0
        /// <summary>
        /// Converts the <see cref="IFragment"/> into a menu display item model.
        /// </summary>
        /// <param name="data">The document.</param>
        /// <param name="group">The group.</param>
        /// <param name="copyFragmentContent">if set to <c>true</c> include <see cref="IFragment"/> content.</param>
        public static MenuDisplayItemModel ToMenuDisplayItemModel(this IFragment data, IGroupable group, bool copyFragmentContent)
        {
            if (data == null)
            {
                return(null);
            }

            var @namespace = typeof(PublicationContext).Namespace;

            var dataOut = new MenuDisplayItemModel()
            {
                DisplayText      = data.FragmentDisplayName,
                GroupDisplayText = (group == null) ? $"{@namespace}.{nameof(Fragment)}" : group.GroupDisplayText,
                GroupId          = (group == null) ? $"{@namespace}.{nameof(Fragment)}".ToLowerInvariant() : group.GroupId,
                Id       = data.FragmentId.GetValueOrDefault(),
                ItemName = data.FragmentName
            };

            if (copyFragmentContent)
            {
                dataOut.Description = data.Content;
            }
            return(dataOut);
        }
Пример #32
0
        private LambdaExpression VisitFragment(IFragment fragment)
        {
            LambdaExpression lambda;

            if (!syntax.Root.FragmentDefinitions.ContainsKey(fragment.Name))
            {
                currentFragment = syntax.AddFragment(fragment);
                using (syntax.Bookmark())
                {
                    var fragmentExpressionLambda = Visit(fragment.Expression).GetLambda();
                    var castedFragmentExpression = fragmentExpressionLambda.Body.AddCast(fragment.ReturnType);
                    lambda = Expression.Lambda(castedFragmentExpression, fragmentExpressionLambda.Parameters);
                }

                currentFragment = null;
                fragmentExpressions.Add(fragment.Name, lambda);
            }
            else
            {
                lambda = fragmentExpressions[fragment.Name];
            }

            return(lambda);
        }
 public void AddFragment(IFragment fragment)
 {
     this.Fragments.Push(fragment);
 }
Пример #34
0
 public bool AddFragmentType( IFragment fragment )
 {
     throw new NotImplementedException();
 }
Пример #35
0
        public IFragment PeekFragment()
        {
            IFragment result = this.attachedFragments.Peek();

            return(result);
        }
		public UntypedMarkupData(IFragment fragment, UntypedMarkupDataValueRetriever valueRetriever) {
			if (initializerString == null) throw Utils.ArgumentNullException("initializerString");
			if (valueRetriever == null) throw Utils.ArgumentNullException("valueRetriever");
			this.Fragment       = fragment;
			this.ValueRetriever = valueRetriever;
		}
Пример #37
0
 public void AddChild(IFragment child)
 {
     this.Children.Add( child );
 }
Пример #38
0
 public bool HasFragmentType( IFragment type )
 {
     throw new NotImplementedException();
 }
Пример #39
0
		public IFragment TryMergeWithNext(IFragment nextFragment) {
			return null;
		}
Пример #40
0
 /// <summary>
 /// Instantiates.
 /// </summary>
 public From(IFragment from)
 {
     this.Source = from;
 }
Пример #41
0
        public IFragment DetachFragment()
        {
            IFragment result = this.attachedFragments.Pop();

            return(result);
        }
Пример #42
0
 public void AddChildTo( IFragment parent , IFragment child ,int indentOffset =0)
 {
     child.ParentIndent= parent.ParentIndent+indentOffset;
     parent.Children.Add( child );
 }
Пример #43
0
 /// <summary>
 /// Instantiates.
 /// </summary>
 public From(IFragment from)
 {
     this.Source = from;
 }
		public void AddFragment(IFragment fragment) {
			fragments.Add(fragment);
		}