Esempio n. 1
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="variable"></param>
 /// <param name="previousValue"></param>
 /// <param name="newValue"></param>
 public Change(Variables.IVariable variable, Values.IValue previousValue, Values.IValue newValue)
 {
     Variable = variable;
     PreviousValue = previousValue;
     NewValue = newValue;
     Applied = false;
 }
Esempio n. 2
0
 public static string Plural(Values value)
 {
     if (value == Values.Six)
         return "Sixes";
     else
         return value.ToString() + "s";
 }
Esempio n. 3
0
 public bool ContainsValue(Values value)
 {
     foreach (Card card in cards)
         if (card.Value == value)
             return true;
     return false;
 }
Esempio n. 4
0
        public void AskForACard(IEnumerable<Player> players, int myIndex, Deck stock, Values value)
        {
            List<Player> _players = (List<Player>)players;

            textBoxOnForm.Content +=  name + " asks if anyone has a " + value + "." + Environment.NewLine;

            int cardsAdded = 0;
            for (int playerIndex = 0; playerIndex < _players.Count; playerIndex++)
            {
                if (playerIndex != myIndex)
                {
                    Deck cardsGiven = _players[playerIndex].DoYouHaveAny(value);
                    if (cardsGiven.Count > 0)
                    {
                        while (cardsGiven.Count > 0)
                        {
                            cards.Add(cardsGiven.Deal());
                            cardsAdded++;
                        }
                    }
                }
            }
            textBoxOnForm.Content += Environment.NewLine;

            if (cardsAdded == 0 && stock.Count > 0)
            {
                textBoxOnForm.Content += name + " has to draw from the stock." + Environment.NewLine;
                cards.Add(stock.Deal());
            }
        }
Esempio n. 5
0
 public Deck DoYouHaveAny(Values value)
 {
     Deck cardsIHave = cards.PullOutValues(value);
     textBoxOnForm.Text += Name + " has " + cardsIHave.Count + " "
            + Card.Plural(value) + Environment.NewLine;
     return cardsIHave;
 }
Esempio n. 6
0
        public void ToListening(Command.Endpoint.IInstance commandEndpoint, Values.Version version)
        {
            Context.IListen context = _contextFactory.ForListen(commandEndpoint, version);
            Event.Transition message = _eventFactory.ForStateTransition(context);

            _eventMediator.Publish(message);
        }
Esempio n. 7
0
 public Deck PullOutValues(Values value)
 {
     Deck deckToReturn = new Deck(new Card[] { });
     for (int i = cards.Count - 1; i >= 0; i--)
         if (cards[i].Value == value)
             deckToReturn.Add(Deal(i));
     return deckToReturn;
 }
Esempio n. 8
0
 public Move(Columns column, Rows row, Values value, int score = 0)
     : this()
 {
     Row = row;
     Column = column;
     Value = value;
     Score = score;
 }
Esempio n. 9
0
 public void pileColourCards_init(Values value, Colours colour)
 {
     pileColourCards.Clear();
     foreach (Card item in cardsToPlay)
     {
         if (item.colour == colour)
             pileColourCards.Add(item);
     }
 }
Esempio n. 10
0
 public IntPtr hasCard(Values value)
 {
     foreach (Card item in cardsToPlay)
     {
         if (item.value == value)
             return new IntPtr(1);
     }
     return new IntPtr(0);
 }
 /// <summary>
 /// Generate a random IISLog
 /// </summary>
 /// <returns></returns>
 public static Values GetRandomIISLog()
 {
     var values = new Values(
         DateTime.UtcNow,
         RandomClientIps[random.Next(RandomClientIps.Count)],
         RandomUris[random.Next(RandomUris.Count)],
         RandomMethods[random.Next(RandomMethods.Count)],
         RandomResponses[random.Next(RandomResponses.Count)]);
     return values;
 }
Esempio n. 12
0
 public bool HasBook(Values value)
 {
     int NumberOfCards = 0;
     foreach (Card card in cards)
         if (card.Value == value)
             NumberOfCards++;
     if (NumberOfCards == 4)
         return true;
     else
         return false;
 }
Esempio n. 13
0
 public Script(string name, string description, string databaseName, string connectionString, bool wrapInTransaction, Values.Version currentVersion, Values.Version newVersion, string command)
 {
     Name = name;
     Description = description;
     DatabaseName = databaseName;
     ConnectionString = connectionString;
     WrapInTransaction = wrapInTransaction;
     CurrentVersion = currentVersion;
     NewVersion = newVersion;
     Command = command;
 }
Esempio n. 14
0
 public static bool DoesCardMatch(Card cardToCheck, Values value)
 {
     if (cardToCheck.Value == value)
     {
         return true;
     }
     else
     {
         return false;
     }
 }
        public Values.Pick DoesPickRightPick(Values.Pick pick)
        {
            List<IStratergy> strats = new List<IStratergy>();
            var exampleStrat = Substitute.For<IStratergy>();
            exampleStrat.SuggestedPick.Returns(pick);
            exampleStrat.MinimumConfidence.Returns(0);
            exampleStrat.DifficultyRequired.Returns(0);
            exampleStrat.Confidence.Returns(1);
            strats.Add(exampleStrat);
            var ai = new ArtificalIntelligence(strats);

            ai.LoadPlayersMoves(null);

            return ai.Pick;
        }
Esempio n. 16
0
 public Device(Status status, int index, string deviceAddress, string deviceType, string deviceState, Values.SignalStrength signalStrength, Values.LinkQuality linkQuality, Values.BatteryState batteryState, TimeSpan timeSinceLastPacketReceived, int receivedPackets, int sentPackets, params string[] unknown)
 {
     Status = status;
     Index = index;
     DeviceAddress = deviceAddress;
     DeviceType = deviceType;
     DeviceState = deviceState;
     SignalStrength = signalStrength;
     LinkQuality = linkQuality;
     BatteryState = batteryState;
     TimeSinceLastPacketReceived = timeSinceLastPacketReceived;
     ReceivedPackets = receivedPackets;
     SentPackets = sentPackets;
     Unknown = unknown ?? Enumerable.Empty<string>();
 }
Esempio n. 17
0
        public double GetPrice(Values v)
        {
            switch (v)
            {
                case Values.Nine_DollarsNintyNine:
                    return 9.99;
                case Values.Fourteen_Dollars_NintyNine:
                    return 14.99;
                case Values.Ninteen_Dollars_NintyNine:
                    return 19.99;
                default:
                    return 0;

            }
        }
Esempio n. 18
0
        /// <summary>
        /// Creates this instance.
        /// </summary>
        /// <returns></returns>
        public static ICollection<Entities.Script> Create(Values.Configuration configuration, Values.ExecutionPlan executionPlan, Domain.Strategies.ConfigInjector configInjector)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (executionPlan == null)
            {
                throw new ArgumentNullException("executionPlan");
            }

            if (configInjector == null)
            {
                throw new ArgumentNullException("configInjector");
            }

            var scripts = new List<Entities.Script>();

            foreach (var scriptName in executionPlan.NameOfScriptsToRun)
            {
                var scriptManifest = configuration.Manifest.GetManifest(scriptName);
                if (scriptManifest == null)
                {
                    //TODO: add errors to scripts
                    var message = string.Format(CultureInfo.InvariantCulture, "Could not find script \"{0}\" in the manifest file.", scriptName);
                    log.Error(message);
                    throw new DatabaseScripterException(ErrorCode.CouldNotFindScriptInManifest, message);
                }

                var environmentConfiguration = configuration.EnvironmentConfigurations.Find(executionPlan.Environment);
                if (environmentConfiguration == null)
                {
                    //TODO: add errors to scripts
                    var message = string.Format(CultureInfo.InvariantCulture, "Could not find environment configuration \"{0}\"", executionPlan.Environment);
                    log.Error(message);
                    throw new DatabaseScripterException(ErrorCode.CouldNotFindEnvironmentConfiguration, message);
                }

                var flatScriptConfiguration = environmentConfiguration.GetFlatConfigurationForScript(scriptName);
                var connectionString = configuration.ConnectionStrings[flatScriptConfiguration.Properties.Find("connection").Value].ConnectionString;

                scripts.Add(CreateScript(flatScriptConfiguration, scriptManifest, configuration, configInjector, connectionString));
            }

            return scripts;
        }
 public static string Plural(Values value)
 {
     if (value == Values.Seis)
         return Values.Seis.ToString();
     else
         if (value == Values.As)
             return value.ToString() + "es";
     else
         if (value == Values.Dez)
             return Values.Dez.ToString();
     else
         if (value == Values.Dois)
             return Values.Dois.ToString();
     else
         if (value == Values.Tres)
             return Values.Tres.ToString();
     else
         return value.ToString() + "s";
 }
        public void AskForACard(List<Player> players, int myIndex, Deck stock, Values value)
        {
            /*
                Pergunte para os outros jogadores se eles têm uma valor.
                Primeiro, adicione uma linha a TextBox: "João pergunta se alguém tem algum 8".
                Então, percorra a lista de jogadores passada como parâmetro e pergunte a cada um
                deles se ele tem o valor (usando seu método DoYouHaveAny()). Ele deve passar um baralho
                - adicione ao seu. Controle quantas cartas foram adicionadas. Se não houver nenhuma, você
                mesmo terá lidar com uma do stock (que também foi passado como parâmetro) e você terá que
                adicionar uma linha a TextBox: "João tem que pegar uma carta do stock"
            */

            txtBoxOnForm.Text += string.Format("{0} pergunta se alguém tem algum {1}." + Environment.NewLine, Name, value);

            //foreach (Player player in players)
            //{
            //    player.DoYouHaveAny(value);
            //}

            /**/
            int totalCardsGiven = 0;

            for (int i = 0; i < players.Count; i++)
            {
                if (i != myIndex)
                {
                    Player player = players[i];
                    Deck CardsGiven = player.DoYouHaveAny(value);
                    totalCardsGiven += CardsGiven.Count;
                    while (CardsGiven.Count > 0)
                    {
                        deckCards.Add(CardsGiven.Deal());
                    }
                }
            }
            /**/
            if (totalCardsGiven == 0)
            {
                txtBoxOnForm.Text += Name + " deve tirar do stock." + Environment.NewLine;
            }
            deckCards.Add(stock.Deal());
        }
Esempio n. 21
0
        public void AskForACard(List<Player> players, int myIndex, Deck stock, Values value)
        {
            textBoxOnForm.Text += Name + " asks if anyone has a " + value.ToString() + Environment.NewLine;
            int numberOfFoundCards = 0;
            for(int i=0; i<players.Count; ++i)
            {
                if(i != myIndex)
                {
                    Deck foundCards = players[i].DoYouHaveAny(value);
                    numberOfFoundCards += foundCards.Count;
                    TakeCards(foundCards);
                }
            }

            if (numberOfFoundCards == 0 && stock.Count > 0)
            {
                TakeCard(stock.Deal());
                textBoxOnForm.Text += Name + " had to draw from the stock." + Environment.NewLine;
            }
        }
Esempio n. 22
0
        public void AskForACard(List<Player> players, int myIndex, Deck stock, Values value)
        {
            game.AddProgress(Name + " asks if anyone has a " + value.ToString());
            int numberOfFoundCards = 0;
            for(int i=0; i<players.Count; ++i)
            {
                if(i != myIndex)
                {
                    Deck foundCards = players[i].DoYouHaveAny(value);
                    numberOfFoundCards += foundCards.Count;
                    TakeCards(foundCards);
                }
            }

            if (numberOfFoundCards == 0 && stock.Count > 0)
            {
                TakeCard(stock.Deal());
                game.AddProgress(Name + " had to draw from the stock.");
            }
        }
Esempio n. 23
0
 public void AskForACard(List<Player> players, int myIndex, Deck stock, Values value)
 {
     game.AddProgress(Name + " asks if anyone has a " + value);
     int totalCardsGiven = 0;
     for (int i = 0; i < players.Count; i++)
     {
         if (i != myIndex)
         {
             Player player = players[i];
             Deck CardsGiven = player.DoYouHaveAny(value);
             totalCardsGiven += CardsGiven.Count;
             while (CardsGiven.Count > 0)
                 cards.Add(CardsGiven.Deal());
         }
     }
     if (totalCardsGiven == 0)
     {
         game.AddProgress(Name + " must draw from the stock.");
         cards.Add(stock.Deal());
     }
 }
Esempio n. 24
0
		Values _Values;		// The default values for the parameter

		internal DefaultValue(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
		{
			_DataSetReference=null;
			_Values=null;

			// Loop thru all the child nodes
			foreach(XmlNode xNodeLoop in xNode.ChildNodes)
			{
				if (xNodeLoop.NodeType != XmlNodeType.Element)
					continue;
				switch (xNodeLoop.Name)
				{
					case "DataSetReference":
						_DataSetReference = new DataSetReference(r, this, xNodeLoop);
						break;
					case "Values":
						_Values = new Values(r, this, xNodeLoop);
						break;
					default:
						break;
				}
			}
		}
Esempio n. 25
0
		public void ProcessSemantics(string name)
		{
			switch (name)
			{
				case LEFT_OF:
					m_type = Values.LeftOf;
					break;
				case RIGHT_OF:
					m_type = Values.RightOf;
					break;
				case ABOVE:
					m_type = Values.Above;
					break;
				case BELOW:
					m_type = Values.Below;
					break;
				case LEFT_ALIGNED:
					m_type = Values.LeftAligned;
					break;
				case RIGHT_ALIGNED:
					m_type = Values.RightAligned;
					break;
				case TOP_ALIGNED:
					m_type = Values.TopAligned;
					break;
				case BOTTOM_ALIGNED:
					m_type = Values.BottomAligned;
					break;
				case BEHIND:
					m_type = Values.Behind;
					break;
				case IN_FRONT_OF:
					m_type = Values.InFrontOf;
					break;
			}
		}
Esempio n. 26
0
 public void AskForACard(List<Player> players, int myIndex,
       Deck stock, Values value)
 {
     textBoxOnForm.Text += Name + " asks if anyone has a "
                                   + value + Environment.NewLine;
     int totalCardsGiven = 0;
     for (int i = 0; i < players.Count; i++)
     {
         if (i != myIndex)
         {
             Player player = players[i];
             Deck CardsGiven = player.DoYouHaveAny(value);
             totalCardsGiven += CardsGiven.Count;
             while (CardsGiven.Count > 0)
                 cards.Add(CardsGiven.Deal());
         }
     }
     if (totalCardsGiven == 0 && stock.Count > 0)
     {
         textBoxOnForm.Text += Name +
               " must draw from the stock." + Environment.NewLine;
         cards.Add(stock.Deal());
     }
 }
Esempio n. 27
0
    public void GoodSuggestion()
    {
        using Key key = new();

        List <SmartCoin> coins   = GenerateDummySmartCoins(key, 6_025, 6_561, 8_192, 13_122, 50_000, 100_000, 196_939, 524_288);
        Money            target  = Money.Satoshis(150_000);
        FeeRate          feeRate = new(Money.Satoshis(2));
        TxOut            txOut   = new(target, BitcoinFactory.CreateBitcoinAddress(Network.TestNet, key));

        long[] inputCosts = coins.Select(x => feeRate.GetFee(x.ScriptPubKey.EstimateInputVsize()).Satoshi).ToArray();

        Dictionary <SmartCoin, long> inputEffectiveValues = new(coins.ToDictionary(x => x, x => x.EffectiveValue(feeRate).Satoshi));
        StrategyParameters           parameters           = new(target, inputEffectiveValues.Values.ToArray(), inputCosts);
        MoreSelectionStrategy        strategy             = new(parameters);

        bool found = ChangelessTransactionCoinSelector.TryGetCoins(strategy, inputEffectiveValues, out var selectedCoins);

        Assert.True(found);

        long[] solution = selectedCoins !.Select(x => x.Amount.Satoshi).ToArray();
        Assert.Equal(new long[] { 100_000, 50_000, 6_025 }, solution);
 public override void VisitObjectVisitorException(ObjectVisitorException exception)
 {
     Values.Add(exception.InnerException.Message);
 }
Esempio n. 29
0
        public override string ToString()
        {
            string s = "";

            for (int i = 0; i < Values.GetLength(0); i++)
            {
                for (int j = 0; j < Values.GetLength(1); j++)
                {
                    s += $"{(currSelectionX == j && currSelectionY == i ? "[" : " ")}{Values[i, j]}{(currSelectionX == j && currSelectionY == i ? "]" : " ")}{(j < Values.GetLength(1) - 1 ? "|" : "")}";
                }
                s += ("\n");
                if (i < Values.GetLength(0) - 1)
                {
                    for (int j = 0; j < Values.GetLength(1); j++)
                    {
                        s += $"---{(j < Values.GetLength(1) - 1 ? "+" : "")}";
                    }
                    s += ("\n");
                }
            }

            return(s);
        }
Esempio n. 30
0
 public string GetText(int n)
 {
     return(Values != null?Values.GetText(n) : "");
 }
Esempio n. 31
0
 public void RemoveValueByPosition(int pos)
 {
     Values.RemoveAt(pos);
     ResetMask();
 }
Esempio n. 32
0
File: Cards.cs Progetto: sven82/HFCS
 public Card(Values value, Suits suit)
 {
     Value = value;
     Suit  = suit;
 }
 protected override void OnItemChanged()
 {
     base.OnItemChanged();
     _pluginOptionViewModelImplementation.Value = Values.Select(v => v.Value ?? string.Empty).ToList();
 }
Esempio n. 34
0
 /// <summary>
 /// Gets the value of a field from an instance of a class using reflection
 /// <para/> Extension from <see langword="AlexejheroYTB.Utilities.Extensions"/>
 /// </summary>
 /// <typeparam name="classInstance">The class type</typeparam>
 /// <param name="instance">The instance of <typeparamref name="classInstance"/></param>
 /// <param name="field">The name of the field</param>
 /// <param name="bindingFlags">The <see cref="BindingFlags"/> to use with <see cref="Type.GetField(string, BindingFlags)"/></param>
 /// <returns>The value of field from the instance of the class</returns>
 /// <exception cref="ArgumentNullException"/>
 /// <exception cref="TargetException"/>
 /// <exception cref="NotSupportedException"/>
 /// <exception cref="FieldAccessException"/>
 /// <exception cref="ArgumentException"/>
 public static object GetValue <classInstance>(this classInstance instance, string field, BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance) where classInstance : class
 => Values.GetValue(instance, field, bindingFlags);
Esempio n. 35
0
        private int NumberOfSquaresInRegionCouldUseValue(Columns column, Rows row, Values value)
        {
            int r = (int)row / 3;
            int c = (int)column / 3;
            var result = 0;
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j ++ )
                {
                    Rows ro = (Rows)(r*3+i);
                    Columns co = (Columns)(c * 3 + i);
                    if (CouldPutValueInSquare(co, ro, value)) result++;
                }

            return result;
        }
 public override void VisitVisitedObject(string id, object value)
 {
     Visited.Add(String.Format("Visited {0}", id));
     Values.Add("Visited");
     base.VisitVisitedObject(id, value);
 }
 public override void VisitStringValue(string stringValue)
 {
     Values.Add(stringValue);
     base.VisitStringValue(stringValue);
 }
Esempio n. 38
0
 public int CountMessagesNonLu(long noDest)
 => Values.Where(x => x.NoDestinataire.Value == noDest && x.EtatLu == 1 && x.Lieu == 1).Count();
Esempio n. 39
0
            private Vector2 calculateBallPosition(int index)
            {
                float y = GetYPosition(Values.ElementAt(index));

                return(new Vector2(index / (float)(DefaultValueCount - 1), y));
            }
Esempio n. 40
0
 /// <summary>
 /// True when <see cref="Values"/> is not empty.
 /// </summary>
 /// <returns></returns>
 public bool HasValue()
 {
     return(Values.Any());
 }
Esempio n. 41
0
 public Card(Suits Suit, Values Value)
 {
     this.Suit  = Suit;
     this.Value = Value;
 }
Esempio n. 42
0
    void AddZone()
    {
        ZoneManager zm = Instantiate(prefabZone, zoneHolder) as ZoneManager;

        zm.Init(ifName.text, Values.GetCurrentColorAdjusted());
    }
Esempio n. 43
0
 public Xwt.Drawing.Image GetIcon(int n)
 {
     return(Values != null?Values.GetIcon(n) : null);
 }
Esempio n. 44
0
 public bool HasValue() => Values.Any();
        /// <summary>
        /// This method runs when the update starts
        /// </summary>
        public override void OnSeriesUpdateStart()
        {
            ActiveSplitters = 0;

            if (SplittersCollector == short.MaxValue - 1)
            {
                //just in case!
                Splitters.ForEach(s => s.SplitterCollectorIndex = 0);
                SplittersCollector = 0;
            }

            SplittersCollector++;

            if (Figure != null && Values != null)
            {
                var yIni = ChartFunctions.ToDrawMargin(Values.GetTracker(this).YLimit.Min, AxisOrientation.Y, Model.Chart, ScalesYAt);

                if (Model.Chart.View.DisableAnimations)
                {
                    Figure.StartPoint = new Point(0, yIni);
                }
                else
                {
                    Figure.BeginPointAnimation(nameof(PathFigure.StartPoint), new Point(0, yIni),
                                               Model.Chart.View.AnimationsSpeed);
                }
            }

            if (IsPathInitialized)
            {
                Model.Chart.View.EnsureElementBelongsToCurrentDrawMargin(Path);
                Path.Stroke          = Stroke;
                Path.StrokeThickness = StrokeThickness;
                Path.Fill            = Fill;
                Path.Visibility      = Visibility;
                Path.StrokeDashArray = StrokeDashArray;
                return;
            }

            IsPathInitialized = true;

            Path = new Path
            {
                Stroke          = Stroke,
                StrokeThickness = StrokeThickness,
                Fill            = Fill,
                Visibility      = Visibility,
                StrokeDashArray = StrokeDashArray
            };

            Canvas.SetZIndex(Path, Canvas.GetZIndex(this));

            var geometry = new PathGeometry();

            Figure = new PathFigure();
            geometry.Figures.Add(Figure);
            Path.Data = geometry;
            Model.Chart.View.AddToDrawMargin(Path);

            var y = ChartFunctions.ToDrawMargin(ActualValues.GetTracker(this).YLimit.Min, AxisOrientation.Y, Model.Chart, ScalesYAt);

            Figure.StartPoint = new Point(0, y);

            var i = Model.Chart.View.Series.IndexOf(this);

            Canvas.SetZIndex(Path, Model.Chart.View.Series.Count - i);
        }
Esempio n. 46
0
        public void Visit(ElementNode node, INode parentNode)
        {
            if (TryGetPropertyName(node, parentNode, out XmlName propertyName) && propertyName == XmlName._CreateContent)
            {
                var s0 = Values[parentNode];
                if (s0 is ElementTemplate)
                {
                    SetTemplate(s0 as ElementTemplate, node);
                    return;
                }
            }

            var parentElement = parentNode as IElementNode;

            propertyName = XmlName.Empty;

            //Simplify ListNodes with single elements
            if (parentNode is ListNode pList && pList.CollectionItems.Count == 1)
            {
                propertyName  = pList.XmlName;
                parentNode    = parentNode.Parent;
                parentElement = parentNode as IElementNode;
            }

            if (!Values.TryGetValue(node, out var value) && Context.ExceptionHandler != null)
            {
                return;
            }

            if (propertyName != XmlName.Empty || TryGetPropertyName(node, parentNode, out propertyName))
            {
                if (Skips.Contains(propertyName))
                {
                    return;
                }
                if (parentElement.SkipProperties.Contains(propertyName))
                {
                    return;
                }

                if (!Values.TryGetValue(parentNode, out var source) && Context.ExceptionHandler != null)
                {
                    return;
                }
                ProvideValue(ref value, node, source, propertyName);
                SetPropertyValue(source, propertyName, value, Context.RootElement, node, Context, node);
            }
            else if (IsCollectionItem(node, parentNode) && parentNode is IElementNode)
            {
                if (!Values.TryGetValue(parentNode, out var source) && Context.ExceptionHandler != null)
                {
                    return;
                }

                ProvideValue(ref value, node, source, XmlName.Empty);
                string    contentProperty;
                Exception xpe = null;

                string xKey = null;
                if (xpe == null &&
                    node.Properties.ContainsKey(XmlName.xKey))
                {
                    if ((node.Properties[XmlName.xKey] is ValueNode valueNode))
                    {
                        xKey = valueNode.Value as string;
                    }
                    if (xKey == null)
                    {
                        xpe = new XamlParseException("x:Key expects a string literal.", node as IXmlLineInfo);
                    }
                }

                //ResourceDictionary
                if (xpe == null &&
                    TryAddToResourceDictionary(source as ResourceDictionary, value, xKey, node, out xpe))
                {
                    return;
                }

                //ContentProperty
                if (xpe == null &&
                    (contentProperty = GetContentPropertyName(Context.Types[parentElement])) != null)
                {
                    var name = new XmlName(node.NamespaceURI, contentProperty);
                    if (Skips.Contains(name))
                    {
                        return;
                    }
                    if (parentElement.SkipProperties.Contains(propertyName))
                    {
                        return;
                    }

                    SetPropertyValue(source, name, value, Context.RootElement, node, Context, node);
                    return;
                }

                // Collection element, implicit content, or implicit collection element.
                if (xpe == null &&
                    typeof(IEnumerable).IsAssignableFrom(Context.Types[parentElement]) &&
                    Context.Types[parentElement].GetRuntimeMethods().Any(mi => mi.Name == "Add" && mi.GetParameters().Length == 1))
                {
                    var addMethod =
                        Context.Types[parentElement].GetRuntimeMethods().First(mi => mi.Name == "Add" && mi.GetParameters().Length == 1);
                    try
                    {
                        addMethod.Invoke(source, new[] { value.ConvertTo(addMethod.GetParameters()[0].ParameterType, (Func <TypeConverter>)null, new XamlServiceProvider(node, Context), out xpe) });
                    }
                    catch (Exception e)
                    {
                        xpe ??= e;
                    }

                    return;
                }

                xpe = xpe ?? new XamlParseException($"Can not set the content of {((IElementNode)parentNode).XmlType.Name} as it doesn't have a ContentPropertyAttribute", node);
                if (Context.ExceptionHandler != null)
                {
                    Context.ExceptionHandler(xpe);
                }
                else
                {
                    throw xpe;
                }
            }
            else if (IsCollectionItem(node, parentNode) && parentNode is ListNode)
            {
                if (!Values.TryGetValue(parentNode.Parent, out var source) && Context.ExceptionHandler != null)
                {
                    return;
                }
                ProvideValue(ref value, node, source, XmlName.Empty);
                var parentList = (ListNode)parentNode;
                if (Skips.Contains(parentList.XmlName))
                {
                    return;
                }
                Exception xpe  = null;
                string    xKey = null;
                if (xpe == null && node.Properties.ContainsKey(XmlName.xKey))
                {
                    if ((node.Properties[XmlName.xKey] is ValueNode valueNode))
                    {
                        xKey = valueNode.Value as string;
                    }
                    if (xKey == null)
                    {
                        xpe = new XamlParseException("x:Key expects a string literal.", node as IXmlLineInfo);
                    }
                }

                var collection = GetPropertyValue(source, parentList.XmlName, Context.RootElement, parentList, out _, out _) as IEnumerable;
                if (xpe == null && collection == null)
                {
                    xpe = new XamlParseException($"Property {parentList.XmlName.LocalName} is null or is not IEnumerable", node);
                }

                if (xpe == null && TryAddToResourceDictionary(collection as ResourceDictionary, value, xKey, node, out xpe))
                {
                    return;
                }

                MethodInfo addMethod;
                if (xpe == null && (addMethod = collection.GetType().GetRuntimeMethods().First(mi => mi.Name == "Add" && mi.GetParameters().Length == 1)) != null)
                {
                    addMethod.Invoke(collection, new[] { value });
                    return;
                }
                xpe = xpe ?? new XamlParseException($"Value of {parentList.XmlName.LocalName} does not have a Add() method", node);
                if (Context.ExceptionHandler != null)
                {
                    Context.ExceptionHandler(xpe);
                }
                else
                {
                    throw xpe;
                }
            }
        }
Esempio n. 47
0
 public static string LookupString(Values v)
 {
     return(String.Format("IABPMODE:{0}", Enum.GetValues(typeof(Values)).GetValue((int)v).ToString()));
 }
 public IImageUrlProvider GetProvider(string provider)
 {
     return(string.IsNullOrEmpty(provider) ?
            Values.First(v => v.Name.Equals(ImageUrlProvider.DefaultName, StringComparison.InvariantCultureIgnoreCase)) :
            Values.First(v => v.Name.Equals(provider, StringComparison.InvariantCultureIgnoreCase)));
 }
Esempio n. 49
0
 public void AskForACard(List <Player> players, int myIndex,
                         Deck stock)
 {
     //Carta aleatoria do stock
     Values randomValue = GetRandomValue();
 }
Esempio n. 50
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ZipatoValues"/> class.
        /// </summary>
        /// <param name="client">The Initial State client instance.</param>
        /// <param name="logger">The logger instance.</param>
        /// <param name="options">The setting options instance.</param>
        public ZipatoValues(IInitialStateClient client,
                            ILogger <ZipatoValues> logger,
                            IOptions <AppSettings> options) : base(client, logger, options)
        {
            _client = new HttpClient()
            {
                BaseAddress = new Uri(_settings.Servers.Zipato),
                Timeout     = TimeSpan.FromSeconds(_settings.Timeout)
            };

            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Plug 1"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Plug 2"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Plug 3"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Plug 4"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Plug 5"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Plug 6"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Plug 7"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Plug 8"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Heavy Duty Switch"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Thermostat 1"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Thermostat 2"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Thermostat 3"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Thermostat 4"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Smoke Sensor"
            });
            Values.Add(new InitialStateValue()
            {
                Key = "Zipato Flood Sensor"
            });
        }
Esempio n. 51
0
 public void Clear()
 {
     Values.Clear();
 }
Esempio n. 52
0
    /// <inheritdoc/>
    public async Task<(IReadOnlyList<RouteConfig> Routes, IReadOnlyList<ClusterConfig> Clusters)> DiscoverAsync(CancellationToken cancellation)
    {
        // Take a snapshot of current options and use that consistently for this execution.
        var options = _optionsMonitor.CurrentValue;

        _serviceFabricCaller.CleanUpExpired();

        var discoveredBackends = new Dictionary<string, ClusterConfig>(StringComparer.Ordinal);
        var discoveredRoutes = new List<RouteConfig>();
        IEnumerable<ApplicationWrapper> applications;

        try
        {
            applications = await _serviceFabricCaller.GetApplicationListAsync(cancellation);
        }
        catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
        {
            throw;
        }
        catch (Exception ex) // TODO: davidni: not fatal?
        {
            // The serviceFabricCaller does their best effort to use LKG information, nothing we can do at this point
            Log.GettingApplicationFailed(_logger, ex);
            applications = Enumerable.Empty<ApplicationWrapper>();
        }

        foreach (var application in applications)
        {
            IEnumerable<ServiceWrapper> services;

            try
            {
                services = await _serviceFabricCaller.GetServiceListAsync(application.ApplicationName, cancellation);
            }
            catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
            {
                throw;
            }
            catch (Exception ex) // TODO: davidni: not fatal?
            {
                Log.GettingServiceFailed(_logger, application.ApplicationName, ex);
                continue;
            }

            foreach (var service in services)
            {
                try
                {
                    var serviceExtensionLabels = await _serviceFabricExtensionConfigProvider.GetExtensionLabelsAsync(application, service, cancellation);

                    // If this service wants to use us as the proxy
                    if (serviceExtensionLabels.GetValueOrDefault("YARP.Enable", null) != "true")
                    {
                        // Skip this service
                        continue;
                    }

                    var destinations = await DiscoverDestinationsAsync(options, service, serviceExtensionLabels, cancellation);
                    var cluster = LabelsParser.BuildCluster(service.ServiceName, serviceExtensionLabels, destinations);
                    var clusterValidationErrors = await _configValidator.ValidateClusterAsync(cluster);
                    if (clusterValidationErrors.Count > 0)
                    {
                        throw new ConfigException($"Skipping cluster id '{cluster.ClusterId} due to validation errors.", new AggregateException(clusterValidationErrors));
                    }

                    if (!discoveredBackends.TryAdd(cluster.ClusterId, cluster))
                    {
                        throw new ConfigException($"Duplicated cluster id '{cluster.ClusterId}'. Skipping repeated definition, service '{service.ServiceName}'");
                    }

                    var routes = LabelsParser.BuildRoutes(service.ServiceName, serviceExtensionLabels);
                    var routeValidationErrors = new List<Exception>();
                    foreach (var route in routes)
                    {
                        routeValidationErrors.AddRange(await _configValidator.ValidateRouteAsync(route));
                    }

                    if (routeValidationErrors.Count > 0)
                    {
                        // Don't add ANY routes if even a single one is bad. Trying to add partial routes
                        // could lead to unexpected results (e.g. a typo in the configuration of higher-priority route
                        // could lead to a lower-priority route being selected for requests it should not be handling).
                        throw new ConfigException($"Skipping ALL routes for cluster id '{cluster.ClusterId} due to validation errors.", new AggregateException(routeValidationErrors));
                    }

                    discoveredRoutes.AddRange(routes);

                    ReportServiceHealth(options, service.ServiceName, HealthState.Ok, $"Successfully built cluster '{cluster.ClusterId}' with {routes.Count} routes.");
                }
                catch (ConfigException ex)
                {
                    // User error
                    Log.InvalidServiceConfig(_logger, service.ServiceName, ex);

                    // TODO: emit Error health report once we are able to detect config issues *during* (as opposed to *after*) a target service upgrade.
                    // Proactive Error health report would trigger a rollback of the target service as desired. However, an Error report after rhe fact
                    // will NOT cause a rollback and will prevent the target service from performing subsequent monitored upgrades to mitigate, making things worse.
                    ReportServiceHealth(options, service.ServiceName, HealthState.Warning, $"Could not load service configuration: {ex.Message}.");
                }
                catch (Exception ex) // TODO: davidni: not fatal?
                {
                    // Not user's problem
                    Log.ErrorLoadingServiceConfig(_logger, service.ServiceName, ex);
                }
            }
        }

        Log.ServiceDiscovered(_logger, discoveredBackends.Count, discoveredRoutes.Count);
        return (discoveredRoutes, discoveredBackends.Values.ToList());
    }
 public override void VisitEnumeratonLimitExceeded()
 {
     Values.Add("Limit Exceeded");
     base.VisitEnumeratonLimitExceeded();
 }
Esempio n. 54
0
 /// <summary>
 /// Sets the value of a field from an instance of a class using reflection
 /// <para/> Extension from <see langword="AlexejheroYTB.Utilities.Extensions"/>
 /// </summary>
 /// <typeparam name="classInstance">The class type</typeparam>
 /// <param name="instance">The instance of <typeparamref name="classInstance"/></param>
 /// <param name="field">The name of the field</param>
 /// <param name="newValue">The new value to set</param>
 /// <param name="bindingFlags">The <see cref="BindingFlags"/> to use with <see cref="Type.GetField(string, BindingFlags)"/></param>
 /// <exception cref="ArgumentNullException"/>
 /// <exception cref="FieldAccessException"/>
 /// <exception cref="TargetException"/>
 /// <exception cref="ArgumentException"/>
 public static void SetValue <classInstance>(this classInstance instance, string field, object newValue, BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance) where classInstance : class
 => Values.SetValue(instance, field, newValue, bindingFlags);
Esempio n. 55
0
 private int NumberOfSquaresInColumnCouldUseValue(Columns column, Values value)
 {
     var result = 0;
     for (int i = 0; i < 9; i++)
     {
         Rows r = (Rows)i;
         if (CouldPutValueInSquare(column, r, value))
             result++;
     }
     return result;
 }
 public override void VisitMember(string name, Type type, object value, int depth)
 {
     base.VisitMember(name, type, value, depth);
     type = type ?? (value != null ? value.GetType() : null);
     if (type == null)
     {
         Members.Add(String.Format("{0} = null", name));
     }
     else
     {
         Members.Add(String.Format("{0} {1} = {2}", GetTypeName(type), name, Values.Last()));
     }
 }
Esempio n. 57
0
 private int NumberOfSquaresInRowCouldUseValue(Rows row, Values value)
 {
     var result = 0;
     for (int i = 0; i < 9; i++)
     {
         Columns c = (Columns)i;
         if (CouldPutValueInSquare(c, row, value))
             result ++;
     }
     return result;
 }
 public override void VisitNull()
 {
     Values.Add("null");
     base.VisitNull();
 }
        public void Setup()
        {
            _dictionary = new Dictionary<string, object>
            {
                {"IntValue", 27},
                {"StringValue", "Hello"},
                {"LongValue", (long?)123},
                {"TimeSpanValue", TimeSpan.FromSeconds(5)},
                {"TimeSpanValueAsString", "00:00:00.0200000"},
                {"ValueType", ValueType.Integer},
                {"ValueTypeAsInt", 2},
                {"ValueTypeAsString", "String"},
                {
                    "SubValue", new Dictionary<string, object>
                    {
                        {"A", "A"},
                        {"B", "B"}
                    }
                },
                {"StringValues", new object[] {"A", "B", "C"}},
                {
                    "SubValues", new object[]
                    {
                        new Dictionary<string, object>
                        {
                            {"A", "A"},
                            {"B", "B"}
                        },
                        new Dictionary<string, object>
                        {
                            {"A", "1"},
                            {"B", "2"}
                        }
                    }
                },
                {
                    "ListOfSubValues", new object[]
                    {
                        new Dictionary<string, object>
                        {
                            {"A", "A"},
                            {"B", "B"}
                        },
                        new Dictionary<string, object>
                        {
                            {"A", "1"},
                            {"B", "2"}
                        }
                    }
                },
                {
                    "BagOfDicts", new object[]
                    {
                        new object[] {"First", "One"},
                        new object[] {"Second", "Two"},
                    }
                }
            };


            var converterCache = new DynamicObjectConverterCache(new DynamicImplementationBuilder());

            _values = (Values)converterCache.GetConverter(typeof(Values)).GetObject(_dictionary);
        }
Esempio n. 60
0
        private void DrawBars(Graphics gr, Bitmap bmpChart)
        {
            #region Variables
            HBarData   bar;
            RectangleF rectBar      = new Rectangle();
            SizeF      sizeDesc     = Size.Empty;
            SizeF      sizeBar      = Size.Empty;
            float      nLabelHeight = 0;
            float      fValueHeight = 0;
            float      nStartX      = 0;
            #endregion

            if (description == null)
            {
                return;
            }
            if (label == null)
            {
                return;
            }
            if (values == null)
            {
                return;
            }

            // Store some original values
            #region StoreObjects

            int nLastBarGaps = nBarsGap;
            //Font fntTip = fontTooltip;

            Description.SaveObject();
            Label.SaveObject();
            Values.SaveObject();

            #endregion

            #region Calculations
            if (SizingMode == BarSizingMode.AutoScale)
            {
                // Calculate gap size
                if (bars.Count > 0)
                {
                    nBarsGap = 4 + (12 * bmpChart.Size.Width) / (int)(345 * bars.Count * 7);
                }
                if (nBarsGap > 50)
                {
                    nBarsGap = 50;
                }

                // Calculate maximum bar size
                sizeBar = new SizeF(this.nBarWidth, bmpChart.Size.Height - 2 * nBarsGap);
                if (bars.Count > 0)
                {
                    sizeBar.Width = (bmpChart.Size.Width - ((bars.Count + 1) * nBarsGap)) / bars.Count;
                }
                if (sizeBar.Width <= 0)
                {
                    sizeBar.Width = 24;
                }

                // Calcuate font sizes & create fonts
                CreateLabelFont(gr, sizeBar);
                nLabelHeight = Label.Font.GetHeight(gr);

                CreateValueFont(gr, sizeBar);
                fValueHeight = Values.Font.GetHeight(gr);

                CreateDescFont(gr, bmpChart.Size);
                sizeDesc = new SizeF(bmpChart.Size.Width - 2 * nBarsGap, description.Font.GetHeight(gr) + 2 * nBarsGap);

                // Calculate actual bar size (depends to font sizes)
                if (description.Visible)
                {
                    sizeBar.Height -= sizeDesc.Height;
                }
                if (Label.Visible)
                {
                    sizeBar.Height -= nLabelHeight;
                }
                if (Values.Visible)
                {
                    sizeBar.Height -= fValueHeight;
                }
                nStartX = this.ClientRectangle.Left;
            }
            else if (SizingMode == BarSizingMode.Normal)
            {
                //fontTooltip = fntTip;
                Values.RestoreObject();
                nBarsGap = nLastBarGaps;

                Description.RestoreObject();
                Label.RestoreObject();

                float fFntHeight = description.Font.GetHeight(gr) + 2 * nBarsGap;
                sizeDesc = new SizeF(bmpChart.Size.Width - 2 * nBarsGap, fFntHeight);

                nLabelHeight = Label.Font.GetHeight(gr);
                fValueHeight = Values.Font.GetHeight(gr);

                sizeBar = new SizeF(this.nBarWidth, bmpChart.Size.Height - 2 * nBarsGap);
                if (Description.Visible)
                {
                    sizeBar.Height -= sizeDesc.Height;
                }
                if (Label.Visible)
                {
                    sizeBar.Height -= nLabelHeight;
                }
                if (Values.Visible)
                {
                    sizeBar.Height -= fValueHeight;
                }

                // Bars start from here (This align graph to the center of the control)
                nStartX = (bmpChart.Size.Width - bars.Count * sizeBar.Width - (bars.Count + 1) * nBarsGap) / 2;
            }
            #endregion

            // Draw description label
            if (description.Visible)
            {
                StringFormat stringFormat = StringFormat.GenericDefault;
                stringFormat.LineAlignment = StringAlignment.Center;
                stringFormat.Alignment     = StringAlignment.Center;
                stringFormat.Trimming      = StringTrimming.None;
                stringFormat.FormatFlags   = StringFormatFlags.NoWrap |
                                             StringFormatFlags.LineLimit;

                gr.DrawString(
                    description.Text,
                    description.Font,
                    new SolidBrush(description.Colour),
                    new RectangleF(
                        nBarsGap,
                        bmpChart.Height - sizeDesc.Height,
                        sizeDesc.Width,
                        sizeDesc.Height),
                    stringFormat);
            }

            // Draw bars (A bar, label and it's value)
            for (int i = 0; i < bars.Count; i++)
            {
                if (bars.GetAt(i, out bar))
                {
                    rectBar.Width  = sizeBar.Width;
                    rectBar.Height = (float)((bar.Value * sizeBar.Height) / bars.MaxValue);
                    rectBar.X      = nStartX + i * sizeBar.Width + (i + 1) * nBarsGap;
                    rectBar.Y      = nBarsGap + sizeBar.Height - rectBar.Height;
                    if (Values.Visible)
                    {
                        rectBar.Y += fValueHeight;
                    }


                    // Set this bar rectangle area on screen. This will be used later for displaying
                    // tooltips for example. Note that the saved value is not the bar bounding rectangle
                    // it's the rectangle that bar is drawn inside, so height might be longer than
                    // the bar.
                    // If you need to have exact rectangle, replace current value with commented value below
                    bar.BarRect = new RectangleF(rectBar.Left, /*rectBar.Top*/ 0, sizeBar.Width, /*sizeBar.Height*/ this.ClientRectangle.Height);

                    DrawBar(gr, rectBar, bar);
                }
            }

            // restore values that changed during the transition to auto scale mode
            #region RestoreObjects

            nBarsGap = nLastBarGaps;
            //fontTooltip = fntTip;
            Description.RestoreObject();
            Label.RestoreObject();
            Values.RestoreObject();

            #endregion
        }