System.Tuple.Create(T1, T2, T3, T4, T5, T6, T7, T8)

Here are the examples of the csharp api System.Tuple.Create(T1, T2, T3, T4, T5, T6, T7, T8) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1192 Examples 7

19 Source : ClientReceiveBuffer.cs
with MIT License
from 1ZouLTReX1

public Tuple<List<PlayerState>, List<RayState>> Interpolate()
    {
        WorldState prevState;
        WorldState nextState;

        lock (snapshotBuffer)
        {
            // If we don't have enough snapshots to interpolate in between we simply set the state to the oldest received frame.
            if (snapshotBuffer.Count - 2 - snapshotDesiredGap < 0)
            {
                time = 0;
                lastTimeCallTime = NowInTicks;

                if (snapshotBuffer.Count > 0)
                {
                    lastTickUsed = snapshotBuffer[snapshotBuffer.HeadIndex].serverTickSeq;
                }
                
                return GetFirst();
            }

            // When we first capture a packet we save the received time and from then on we playout the snapshots from the server
            // in constant intervals these intervals are equal the server tick rate, i.e, the lerpTimeFactor.
            if (time >= lerpTimeFactor)
            {
                time %= lerpTimeFactor;

                if (snapshotGap <= 0)
                {
                    Reset();
                }
                else
                {
                    snapshotGap--;
                }
            }

            // Track time (using the base clreplaced stopwatch [inheritance]) 

            // calculate delta time
            now = this.NowInTicks;
            float deltaTime = (now - lastTimeCallTime) / ((float)this.m_FrequencyMS);
            lastTimeCallTime = this.NowInTicks;
            // Advance time by the delta time between function calls.
            time += deltaTime;
            // Interpolation 

            //Debug.Log(snapshotGap);

            //Debug.Log("index of prev state: " + (snapshotBuffer.Count - 2 - snapshotGap));
            //Debug.Log("index of next state: " + (snapshotBuffer.Count - 1 - snapshotGap));

            prevState = snapshotBuffer[snapshotBuffer.Count - 2 - snapshotGap];
            nextState = snapshotBuffer[snapshotBuffer.Count - 1 - snapshotGap];

            if (prevState.serverTickSeq < lastTickUsed)
            {
                // When we return null we basically don't render anything new
                // so the last rendered snapshot or tick will still be displayed.
                return null;
            }

            lastTickUsed = prevState.serverTickSeq;

            //Debug.Log("latest State: " + snapshotBuffer[snapshotBuffer.Count - 1].serverTickSeq + " prevState: " + prevState.serverTickSeq + " nextState: " + nextState.serverTickSeq);
        }

        // This function returns the value and put it in the playerStates variable
        PlayerState.Interp(prevState.playersState, nextState.playersState, time/lerpTimeFactor, ref playerStates);

        // Since we might render the same tick twice (depends on the ratio between server tick rate and client tick rate)
        // after using the raystates which are a one-off action so they happen only once therefore we take the rayStates and then clear the field
        // so when we get to the same frame again we don't reder the same rayStates.
        var rayStates = prevState.raysState.ToList();
        prevState.raysState.Clear();

        return Tuple.Create(playerStates, rayStates);
    }

19 Source : ClientReceiveBuffer.cs
with MIT License
from 1ZouLTReX1

private static Tuple<List<PlayerState>, List<RayState>> GetTupleFromSnapshot(WorldState snapshot)
    {
        // Since we might render the same tick twice (depends on the ratio between server tick rate and client tick rate)
        // after using a snapshot we clear it and remove its content.
        var rayStates = snapshot.raysState.ToList();
        snapshot.raysState.Clear();

        //var playerStates = snapshot.playersState.ToList();
        //snapshot.playersState.Clear();
        // Returns a tuple that contains List of playerState and a List of rayState
        // that tuple is then used in the reder snapshot function
        //return Tuple.Create(playerStates, rayStates);
        return Tuple.Create(snapshot.playersState, rayStates);
    }

19 Source : RedisTuple.cs
with MIT License
from 2881099

protected Tuple<T1, T2, T3> Create(RedisReader reader)
            {
                return Tuple.Create(_command1.Parse(reader), _command2.Parse(reader), _command3.Parse(reader));
            }

19 Source : RedisTransaction.cs
with MIT License
from 2881099

void OnTransactionQueued<T>(RedisCommand<T> command, string response)
        {
            if (_connector.IsPipelined)
                _pipeCommands.Add(Tuple.Create(command.Command, command.Arguments));
            else
                OnTransactionQueued(command.Command, command.Arguments, response);
        }

19 Source : RedisTuple.cs
with MIT License
from 2881099

public override Tuple<string, string> Parse(RedisReader reader)
        {
            reader.ExpectType(RedisMessage.MultiBulk);
            long count = reader.ReadInt(false);
            if (count != 2) return null; //使用 BLPop 命令在 RedisArray.cs 中报错的解决办法。 #22
                                         //reader.ExpectSize(2);
            return Tuple.Create(reader.ReadBulkString(), reader.ReadBulkString());
        }

19 Source : RedisTuple.cs
with MIT License
from 2881099

protected Tuple<T1, T2> Create(RedisReader reader)
            {
                return Tuple.Create(_command1.Parse(reader), _command2.Parse(reader));
            }

19 Source : RedisTuple.cs
with MIT License
from 2881099

protected Tuple<T1, T2, T3, T4> Create(RedisReader reader)
            {
                return Tuple.Create(
                    _command1.Parse(reader),
                    _command2 == null ? default(T2) : _command2.Parse(reader),
                    _command3 == null ? default(T3) : _command3.Parse(reader),
                    _command4 == null ? default(T4) : _command4.Parse(reader));
            }

19 Source : ServerInformation.cs
with Apache License 2.0
from AantCoder

public ModelInfo GetInfo(ModelInt packet, ServiceContext context)
        {
            lock (context.Player)
            {
                switch (packet.Value)
                {
                    case (long)ServerInfoType.Full:
                        {
                            var result = GetModelInfo(context.Player);
                            return result;
                        }

                    case (long)ServerInfoType.SendSave:
                        {
                            if (context.PossiblyIntruder)
                            {
                                context.Disconnect("Possibly intruder");
                                return null;
                            }
                            var result = new ModelInfo();
                            //передача файла игры, для загрузки WorldLoad();
                            // файл передать можно только в том случае если файлы прошли проверку

                            //!Для Pvp проверка нужна всегда, в PvE нет
                            if (ServerManager.ServerSettings.IsModsWhitelisted)
                            {
                                if ((int)context.Player.ApproveLoadWorldReason > 0)
                                {
                                    context.Player.ExitReason = DisconnectReason.FilesMods;
                                    Loger.Log($"Login : {context.Player.Public.Login} not all files checked,{context.Player.ApproveLoadWorldReason.ToString() } Disconnect");
                                    result.SaveFileData = null;
                                    return result;
                                }
                            }

                            result.SaveFileData = Repository.GetSaveData.LoadPlayerData(context.Player.Public.Login, 1);

                            if (result.SaveFileData != null)
                            {
                                if (context.Player.MailsConfirmationSave.Count > 0)
                                {
                                    for (int i = 0; i < context.Player.MailsConfirmationSave.Count; i++) 
                                        context.Player.MailsConfirmationSave[i].NeedSaveGame = false;

                                    Loger.Log($"MailsConfirmationSave add {context.Player.MailsConfirmationSave.Count} (mails={context.Player.Mails.Count})");
                                    //Ого! Игрок не сохранился после приема письма, с обязательным сохранением после получения
                                    //Отправляем письма ещё раз
                                    if (context.Player.Mails.Count == 0)
                                    {
                                        context.Player.Mails = context.Player.MailsConfirmationSave.ToList();
                                    }
                                    else
                                    {
                                        var ms = context.Player.MailsConfirmationSave
                                            .Where(mcs => context.Player.Mails.Any(m => m.GetHashBase() != mcs.GetHashBase()))
                                            .ToList();
                                        context.Player.Mails.AddRange(ms);
                                    }
                                    Loger.Log($"MailsConfirmationSave (mails={context.Player.Mails.Count})");
                                }
                            }
                            Loger.Log($"Load World for {context.Player.Public.Login}. (mails={context.Player.Mails.Count}, fMails={context.Player.FunctionMails.Count})");

                            return result;
                        }

                    case (long)ServerInfoType.FullWithDescription:
                        {
                            var result = GetModelInfo(context.Player);
                            //result.Description = "";
                            var displayAttributes = new List<Tuple<int, string>>();

                            foreach (var prop in typeof(ServerSettings).GetFields())
                            {
                                var attribute = prop.GetCustomAttributes(typeof(DisplayAttribute)).FirstOrDefault();
                                if (attribute is null || !prop.IsPublic)
                                {
                                    continue;
                                }

                                var dispAtr = (DisplayAttribute)attribute;
                                var strvalue = string.IsNullOrEmpty(dispAtr.GetDescription()) ? prop.Name : dispAtr.GetDescription();
                                strvalue = strvalue + "=" + prop.GetValue(ServerManager.ServerSettings).ToString();
                                var order = dispAtr.GetOrder().HasValue ? dispAtr.GetOrder().Value : 0;
                                displayAttributes.Add(Tuple.Create(order, strvalue));
                            }

                            var sb = new StringBuilder();
                            var sorte = new List<string>(displayAttributes.OrderBy(x => x.Item1).Select(y => y.Item2)).AsReadOnly();
                            foreach (var prop in sorte)
                            {
                                sb.AppendLine(prop);
                            }

                            //result.Description = sb.ToString();
                            return result;
                        }
                    case (long)ServerInfoType.Short:
                    default:
                        {
                            // краткая (зарезервированно, пока не используется) fullInfo = false
                            var result = new ModelInfo();
                            return result;
                        }
                }
            }
        }

19 Source : BaseEventSystem.cs
with Apache License 2.0
from abist-co-ltd

public virtual void Register(GameObject listener)
        {
            // Because components on an object can change during its lifetime, we can't enumerate all handlers on an object 
            // at this point in time and register them via the new API.
            // This forces us to store an object and use ExecuteEvents traversal at time of handling events.
            if (eventExecutionDepth == 0)
            {
                if (!EventListeners.Contains(listener))
                {
                    // Due to how events are sent to game objects, if any of registered handlers sits on a 
                    // registered object it will receive any event preplaceded to this object.
                    // We need to mark such handlers, so they don't receive their events twice.
                    // It can be checked in HandleEvent with less code, but this becomes a 
                    // performance bottleneck with many handlers in the system

                    bool report = false;
                    foreach (var typeEntry in EventHandlersByType)
                    {
                        for (int index = 0; index < typeEntry.Value.Count; index++)
                        {
                            var handlerEntry = typeEntry.Value[index];

                            var comp = handlerEntry.handler as Component;

                            if (comp != null && comp.gameObject == listener)
                            {
                                handlerEntry.parentObjectIsInObjectCollection = true;
                                typeEntry.Value[index] = handlerEntry;
                                report = true;
                            }
                        }
                    }

                    if (report)
                    {
                        WarnAboutConflictingApis(listener.name);
                    }

                    EventListeners.Add(listener);
                }
            }
            else
            {
                postponedObjectActions.Add(Tuple.Create(Action.Add, listener));
            }
        }

19 Source : BaseEventSystem.cs
with Apache License 2.0
from abist-co-ltd

public virtual void Unregister(GameObject listener)
        {
            if (eventExecutionDepth == 0)
            {
                if (EventListeners.Contains(listener))
                {
                    // Reset cached flags in handler collection as object will not intercept the events anymore.
                    // This is a slow loop, which is here to maintain backward compatibility and enable co-existing of
                    // new and old API.
                    foreach (var typeEntry in EventHandlersByType)
                    {
                        for (int index = 0; index < typeEntry.Value.Count; index++)
                        {
                            var handlerEntry = typeEntry.Value[index];

                            // if cache flag is true, handler is guaranteed to be a unity component.
                            if (handlerEntry.parentObjectIsInObjectCollection && (handlerEntry.handler as Component).gameObject == listener)
                            {
                                // Don't need to report, because it was reported during registration
                                handlerEntry.parentObjectIsInObjectCollection = false;
                                typeEntry.Value[index] = handlerEntry;
                            }
                        }
                    }

                    EventListeners.Remove(listener);
                }
            }
            else
            {
                postponedObjectActions.Add(Tuple.Create(Action.Remove, listener));
            }
        }

19 Source : BaseEventSystem.cs
with Apache License 2.0
from abist-co-ltd

private void UnregisterHandler(Type handlerType, IEventSystemHandler handler)
        {
            if (eventExecutionDepth == 0)
            {
                RemoveHandlerFromMap(handlerType, handler);
            }
            else
            {
                postponedActions.Add(Tuple.Create(Action.Remove, handlerType, handler));
            }
        }

19 Source : BaseEventSystem.cs
with Apache License 2.0
from abist-co-ltd

private void RegisterHandler(Type handlerType, IEventSystemHandler handler)
        {
            if (eventExecutionDepth == 0)
            {
                AddHandlerToMap(handlerType, handler);
            }
            else
            {
                postponedActions.Add(Tuple.Create(Action.Add, handlerType, handler));
            }
        }

19 Source : KeyBindingInspector.cs
with Apache License 2.0
from abist-co-ltd

public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            SerializedProperty bindingType = property.FindPropertyRelative("bindingType");
            SerializedProperty code = property.FindPropertyRelative("code");

            // Using BeginProperty / EndProperty on the parent property means that
            // prefab override logic works on the entire property.
            EditorGUI.BeginProperty(position, label, property);

            // Draw label
            position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Preplacedive), label);
            Rect autoBindPosition = new Rect(position.x + position.width - 20.0f, position.y, 20.0f, position.height);
            Rect codePosition = new Rect(position.x, position.y, position.width - 22.0f, position.height);

            // Don't make child fields be indented
            var indent = EditorGUI.indentLevel;
            EditorGUI.indentLevel = 0;

            // Show the traditional long dropdown list for selecting a key binding.
            if (KeyBinding.KeyBindingToEnumMap.TryGetValue(Tuple.Create((KeyBinding.KeyType)bindingType.intValue, code.intValue), out int index))
            {
                int newIndex = EditorGUI.Popup(codePosition, index, KeyBinding.AllCodeNames);

                if (newIndex != index)
                {
                    if (KeyBinding.EnumToKeyBindingMap.TryGetValue(newIndex, out var kb))
                    {
                        bindingType.intValue = (int)kb.Item1;
                        code.intValue = kb.Item2;
                    }
                }
            }

            // Show a popup for binding by pressing a key or mouse button.
            // Note that this method does not work for shift keys (Unity event limitation)
            if (GUI.Button(autoBindPosition, ""))
            {
                KeyBindingPopupWindow.Show(property);
            }

            // Set indent back to what it was
            EditorGUI.indentLevel = indent;

            EditorGUI.EndProperty();

            property.serializedObject.ApplyModifiedProperties();
        }

19 Source : ParentParser.cs
with MIT License
from Actipro

public override IParseData Parse(IParseRequest request) {
			if (request == null)
				throw new ArgumentNullException("request");

			// Create parse data
			ParentParseData parseData = new ParentParseData();
			parseData.Snapshot = request.Snapshot;
			
			// Initialize generated text
			StringBuilder generatedText = new StringBuilder();
			generatedText.Append("using System;\n");
			generatedText.Append("using System.Collections.Generic;\n\n");
			generatedText.Append("using System.Linq;\n\n");
			generatedText.Append("[EditorBrowsable(EditorBrowsableState.Never)]\n");
			generatedText.Append("clreplaced __Generated {\n");
			generatedText.Append("\t[EditorBrowsable(EditorBrowsableState.Never)]\n");
			generatedText.Append("\tvoid __WriteOutput() {\n");

			ITextSnapshotReader sourceReader = request.Snapshot.GetReader(0);
			int lastDelimiterOffset = 0;
			bool lastDelimiterWreplacedtart = false;
			while (!sourceReader.IsAtSnapshotEnd) {
				IToken token = sourceReader.ReadToken();
				if (token != null) {
					switch (token.Id) {
						case ParentTokenId.ChildCodeBlockStart:
						case ParentTokenId.ChildOutputBlockStart:
							if (token.StartOffset - lastDelimiterOffset > 0) {
								// Append generated text
								string text = sourceReader.Snapshot.GetSubstring(new TextRange(lastDelimiterOffset, token.StartOffset), LineTerminator.Newline);
								generatedText.Append("\t\tResponse.Write(@\"");
								generatedText.Append(text.Replace("\"", "\"\""));
								generatedText.Append("\");\n");
							}

							// Store the last delimiter offset
							lastDelimiterOffset = token.EndOffset;
							lastDelimiterWreplacedtart = true;
							break;
						case ParentTokenId.ChildCodeBlockEnd:
							if ((lastDelimiterWreplacedtart) && (token.StartOffset - lastDelimiterOffset > 0)) {
								// Get the text between the delimiters
								string text = sourceReader.Snapshot.GetSubstring(new TextRange(lastDelimiterOffset, token.StartOffset), LineTerminator.Newline);
								generatedText.Append("\t\t");

								// Add a mapping
								parseData.TextRangeMappings.Add(Tuple.Create(new TextRange(lastDelimiterOffset, token.StartOffset), TextRange.FromSpan(generatedText.Length, text.Length)));

								// Append the text directly
								generatedText.Append(text);
								generatedText.Append("\n");
							}

							// Store the last delimiter offset
							lastDelimiterOffset = token.EndOffset;
							lastDelimiterWreplacedtart = false;
							break;
						case ParentTokenId.ChildOutputBlockEnd:
							if ((lastDelimiterWreplacedtart) && (token.StartOffset - lastDelimiterOffset > 0)) {
								// Get the text between the delimiters and append a Response.Write
								string text = sourceReader.Snapshot.GetSubstring(new TextRange(lastDelimiterOffset, token.StartOffset), LineTerminator.Newline);
								generatedText.Append("\t\tResponse.Write(");

								// Add a mapping
								parseData.TextRangeMappings.Add(Tuple.Create(new TextRange(lastDelimiterOffset, token.StartOffset), TextRange.FromSpan(generatedText.Length, text.Length)));

								// Append the text directly
								generatedText.Append(text);
								generatedText.Append(");\n");
							}

							// Store the last delimiter offset
							lastDelimiterOffset = token.EndOffset;
							lastDelimiterWreplacedtart = false;
							break;
					}
				}
			}

			if (lastDelimiterOffset < sourceReader.Snapshot.Length) {
				// Append generated text
				string text = sourceReader.Snapshot.GetSubstring(new TextRange(lastDelimiterOffset, sourceReader.Snapshot.Length), LineTerminator.Newline);
				generatedText.Append("\t\tResponse.Write(@\"");
				generatedText.Append(text.Replace("\"", "\"\""));
				generatedText.Append("\");\n");
			}

			// Store the generated text
			generatedText.Append("\t}\n");
			generatedText.Append("}\n");

			// Get parse data for the translated code
			CodeDoreplacedent generatedDoreplacedent = new CodeDoreplacedent();
			generatedDoreplacedent.Language = childLanguage;
			generatedDoreplacedent.SetText(generatedText.ToString());

			// Get a reader
			ITextBufferReader generatedReader = generatedDoreplacedent.CurrentSnapshot.GetReader(0).BufferReader;

			// Create a request
			ParseRequest generatedRequest = new ParseRequest(Guid.NewGuid().ToString(), generatedReader, childParser, generatedDoreplacedent);
			generatedRequest.Snapshot = generatedDoreplacedent.CurrentSnapshot;

			// Parse
			generatedDoreplacedent.ParseData = childParser.Parse(generatedRequest);
			parseData.GeneratedParseData = generatedDoreplacedent.ParseData as ILLParseData;

			return parseData;
		}

19 Source : IntraLineViewportAdornmentManager.cs
with MIT License
from Actipro

private void OnAdornmentRemoved(IAdornment adornment) {
			if (adornment != null) {
				var element = adornment.VisualElement as AdornmentElement;
				if (element != null) {
					cachedElements.Add(Tuple.Create(new WeakReference(adornment.Tag), element));
					element.Tag = null;
				}
			}
		}

19 Source : DarksVMRuntime.cs
with GNU General Public License v3.0
from Aekras1a

public void AddMethod(MethodDef method, ScopeBlock rootScope)
        {
            ILBlock entry = null;
            foreach(ILBlock block in rootScope.GetBasicBlocks())
            {
                if(block.Id == 0)
                    entry = block;
                basicBlocks.Add(Tuple.Create(method, block));
            }
            Debug.replacedert(entry != null);
            methodMap[method] = Tuple.Create(rootScope, entry);
        }

19 Source : DarksVMRuntime.cs
with GNU General Public License v3.0
from Aekras1a

internal void AddHelper(MethodDef method, ScopeBlock rootScope, ILBlock entry)
        {
            methodMap[method] = Tuple.Create(rootScope, entry);
        }

19 Source : DarksVMRuntime.cs
with GNU General Public License v3.0
from Aekras1a

public void AddBlock(MethodDef method, ILBlock block)
        {
            basicBlocks.Add(Tuple.Create(method, block));
        }

19 Source : BlockParser.cs
with GNU General Public License v3.0
from Aekras1a

private static ScopeBlock replacedignScopes(CilBody body, List<BasicBlock<CILInstrList>> blocks)
        {
            var ehScopes = new Dictionary<ExceptionHandler, Tuple<ScopeBlock, ScopeBlock, ScopeBlock>>();
            foreach(var eh in body.ExceptionHandlers)
            {
                var tryBlock = new ScopeBlock(ScopeType.Try, eh);
                var handlerBlock = new ScopeBlock(ScopeType.Handler, eh);

                if(eh.FilterStart != null)
                {
                    var filterBlock = new ScopeBlock(ScopeType.Filter, eh);
                    ehScopes[eh] = Tuple.Create(tryBlock, handlerBlock, filterBlock);
                }
                else
                {
                    ehScopes[eh] = Tuple.Create(tryBlock, handlerBlock, (ScopeBlock) null);
                }
            }

            var root = new ScopeBlock();
            var scopeStack = new Stack<ScopeBlock>();
            scopeStack.Push(root);

            foreach(var block in blocks)
            {
                var header = block.Content[0];

                foreach(var eh in body.ExceptionHandlers)
                {
                    var ehScope = ehScopes[eh];

                    if(header == eh.TryEnd)
                    {
                        var pop = scopeStack.Pop();
                        Debug.replacedert(pop == ehScope.Item1);
                    }

                    if(header == eh.HandlerEnd)
                    {
                        var pop = scopeStack.Pop();
                        Debug.replacedert(pop == ehScope.Item2);
                    }

                    if(eh.FilterStart != null && header == eh.HandlerStart)
                    {
                        // Filter must precede handler immediately
                        Debug.replacedert(scopeStack.Peek().Type == ScopeType.Filter);
                        var pop = scopeStack.Pop();
                        Debug.replacedert(pop == ehScope.Item3);
                    }
                }
                foreach(var eh in body.ExceptionHandlers.Reverse())
                {
                    var ehScope = ehScopes[eh];
                    var parent = scopeStack.Count > 0 ? scopeStack.Peek() : null;

                    if(header == eh.TryStart)
                    {
                        if(parent != null)
                            AddScopeBlock(parent, ehScope.Item1);
                        scopeStack.Push(ehScope.Item1);
                    }

                    if(header == eh.HandlerStart)
                    {
                        if(parent != null)
                            AddScopeBlock(parent, ehScope.Item2);
                        scopeStack.Push(ehScope.Item2);
                    }

                    if(header == eh.FilterStart)
                    {
                        if(parent != null)
                            AddScopeBlock(parent, ehScope.Item3);
                        scopeStack.Push(ehScope.Item3);
                    }
                }

                var scope = scopeStack.Peek();
                AddBasicBlock(scope, block);
            }
            foreach(var eh in body.ExceptionHandlers)
            {
                if(eh.TryEnd == null)
                {
                    var pop = scopeStack.Pop();
                    Debug.replacedert(pop == ehScopes[eh].Item1);
                }
                if(eh.HandlerEnd == null)
                {
                    var pop = scopeStack.Pop();
                    Debug.replacedert(pop == ehScopes[eh].Item2);
                }
            }
            Debug.replacedert(scopeStack.Count == 1);
            Validate(root);

            return root;
        }

19 Source : RedisTuple.cs
with Mozilla Public License 2.0
from agebullhu

public override Tuple<string, string> Parse(RedisReader reader)
        {
            reader.ExpectType(RedisMessage.MultiBulk);
			long count = reader.ReadInt(false);
			if (count != 2) return null; //使用 BLPop 命令在 RedisArray.cs 中报错的解决办法。 #22
			//reader.ExpectSize(2);
            return Tuple.Create(reader.ReadBulkString(), reader.ReadBulkString());
        }

19 Source : LoadBalancingCallInvoker.cs
with Apache License 2.0
from agoda-com

public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(Method<TRequest, TResponse> method, string host, CallOptions options, TRequest request)
        {
            var result = _resourceManager.ExecuteAsync(async (grpcResource, retryCount) =>
            {
                var overriddenOptions = OverrideCallOptions(options);
                var call = new CallInvocationDetails<TRequest, TResponse>(grpcResource.Channel, method, host, overriddenOptions);
                var asyncCall = Calls.AsyncUnaryCall(call, request);
                
                // Await for any exception, but return the original object because we don't want to lose any information
                var response = await asyncCall.ResponseAsync.ConfigureAwait(false);
                var headers = await asyncCall.ResponseHeadersAsync.ConfigureAwait(false);
                var status = asyncCall.GetStatus();
                var trailers = asyncCall.GetTrailers();

                return Tuple.Create(response, headers, status, trailers);
            }, _shouldRetry, _onError);

            return new AsyncUnaryCallWrapper<TResponse>(result).GetAsyncUnaryCall();
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void CreateCacheableKeyRing_NoGenerationRequired_DefaultKeyExpiresBeforeRefreshPeriod()
        {
            // Arrange
            var callSequence = new List<string>();
            var expirationCts = new CancellationTokenSource();

            var now = StringToDateTime("2016-02-29 20:00:00Z");
            var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z");
            var key2 = CreateKey("2016-03-01 00:00:00Z", "2017-03-01 00:00:00Z");
            var allKeys = new[] { key1, key2 };

            var keyRingProvider = SetupCreateCacheableKeyRingTestAndCreateKeyManager(
                callSequence: callSequence,
                getCacheExpirationTokenReturnValues: new[] { expirationCts.Token },
                getAllKeysReturnValues: new[] { allKeys },
                createNewKeyCallbacks: null,
                resolveDefaultKeyPolicyReturnValues: new[]
                {
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys, new DefaultKeyResolution()
                        {
                            DefaultKey = key1,
                            ShouldGenerateNewKey = false
                        })
                });

            // Act
            var cacheableKeyRing = keyRingProvider.GetCacheableKeyRing(now);

            // replacedert
            replacedert.Equal(key1.KeyId, cacheableKeyRing.KeyRing.DefaultKeyId);
            replacedert.Equal(StringToDateTime("2016-03-01 00:00:00Z"), cacheableKeyRing.ExpirationTimeUtc);
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts.Cancel();
            replacedert.False(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            replacedert.Equal(new[] { "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy" }, callSequence);
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void CreateCacheableKeyRing_GenerationRequired_NoDefaultKey_CreatesNewKeyWithImmediateActivation()
        {
            // Arrange
            var callSequence = new List<string>();
            var expirationCts1 = new CancellationTokenSource();
            var expirationCts2 = new CancellationTokenSource();

            var now = StringToDateTime("2015-03-01 00:00:00Z");
            var allKeys1 = new IKey[0];

            var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z");
            var key2 = CreateKey("2016-03-01 00:00:00Z", "2017-03-01 00:00:00Z");
            var allKeys2 = new[] { key1, key2 };

            var keyRingProvider = SetupCreateCacheableKeyRingTestAndCreateKeyManager(
                callSequence: callSequence,
                getCacheExpirationTokenReturnValues: new[] { expirationCts1.Token, expirationCts2.Token },
                getAllKeysReturnValues: new[] { allKeys1, allKeys2 },
                createNewKeyCallbacks: new[] {
                    Tuple.Create((DateTimeOffset)now, (DateTimeOffset)now + TimeSpan.FromDays(90), CreateKey())
                },
                resolveDefaultKeyPolicyReturnValues: new[]
                {
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys1, new DefaultKeyResolution()
                        {
                            DefaultKey = null,
                            ShouldGenerateNewKey = true
                        }),
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys2, new DefaultKeyResolution()
                        {
                            DefaultKey = key1,
                            ShouldGenerateNewKey = false
                        })
                });

            // Act
            var cacheableKeyRing = keyRingProvider.GetCacheableKeyRing(now);

            // replacedert
            replacedert.Equal(key1.KeyId, cacheableKeyRing.KeyRing.DefaultKeyId);
            replacedertWithinJitterRange(cacheableKeyRing.ExpirationTimeUtc, now);
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts1.Cancel();
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts2.Cancel();
            replacedert.False(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            replacedert.Equal(new[] { "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy", "CreateNewKey", "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy" }, callSequence);
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void CreateCacheableKeyRing_GenerationRequired_NoDefaultKey_KeyGenerationDisabled_Fails()
        {
            // Arrange
            var callSequence = new List<string>();

            var now = StringToDateTime("2015-03-01 00:00:00Z");
            var allKeys = new IKey[0];

            var keyRingProvider = SetupCreateCacheableKeyRingTestAndCreateKeyManager(
                callSequence: callSequence,
                getCacheExpirationTokenReturnValues: new[] { CancellationToken.None },
                getAllKeysReturnValues: new[] { allKeys },
                createNewKeyCallbacks: new[] {
                    Tuple.Create((DateTimeOffset)now, (DateTimeOffset)now + TimeSpan.FromDays(90), CreateKey())
                },
                resolveDefaultKeyPolicyReturnValues: new[]
                {
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys, new DefaultKeyResolution()
                        {
                            DefaultKey = null,
                            ShouldGenerateNewKey = true
                        })
                },
                keyManagementOptions: new KeyRotationOptions() { AutoGenerateKeys = false });

            // Act
            replacedert.Throws<InvalidOperationException>(() => keyRingProvider.GetCacheableKeyRing(now));

            // replacedert
            replacedert.Equal(new[] { "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy" }, callSequence);
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void CreateCacheableKeyRing_NoGenerationRequired_DefaultKeyExpiresAfterRefreshPeriod()
        {
            // Arrange
            var callSequence = new List<string>();
            var expirationCts = new CancellationTokenSource();

            var now = StringToDateTime("2015-03-01 00:00:00Z");
            var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z");
            var key2 = CreateKey("2016-03-01 00:00:00Z", "2017-03-01 00:00:00Z");
            var allKeys = new[] { key1, key2 };

            var keyRingProvider = SetupCreateCacheableKeyRingTestAndCreateKeyManager(
                callSequence: callSequence,
                getCacheExpirationTokenReturnValues: new[] { expirationCts.Token },
                getAllKeysReturnValues: new[] { allKeys },
                createNewKeyCallbacks: null,
                resolveDefaultKeyPolicyReturnValues: new[]
                {
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys, new DefaultKeyResolution()
                        {
                            DefaultKey = key1,
                            ShouldGenerateNewKey = false
                        })
                });

            // Act
            var cacheableKeyRing = keyRingProvider.GetCacheableKeyRing(now);

            // replacedert
            replacedert.Equal(key1.KeyId, cacheableKeyRing.KeyRing.DefaultKeyId);
            replacedertWithinJitterRange(cacheableKeyRing.ExpirationTimeUtc, now);
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts.Cancel();
            replacedert.False(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            replacedert.Equal(new[] { "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy" }, callSequence);
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void CreateCacheableKeyRing_GenerationRequired_NoDefaultKey_CreatesNewKeyWithImmediateActivation_StillNoDefaultKey_ReturnsNewlyCreatedKey()
        {
            // Arrange
            var callSequence = new List<string>();
            var expirationCts1 = new CancellationTokenSource();
            var expirationCts2 = new CancellationTokenSource();

            var now = StringToDateTime("2015-03-01 00:00:00Z");
            var allKeys = new IKey[0];

            var newlyCreatedKey = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z");

            var keyRingProvider = SetupCreateCacheableKeyRingTestAndCreateKeyManager(
                callSequence: callSequence,
                getCacheExpirationTokenReturnValues: new[] { expirationCts1.Token, expirationCts2.Token },
                getAllKeysReturnValues: new[] { allKeys, allKeys },
                createNewKeyCallbacks: new[] {
                    Tuple.Create((DateTimeOffset)now, (DateTimeOffset)now + TimeSpan.FromDays(90), newlyCreatedKey)
                },
                resolveDefaultKeyPolicyReturnValues: new[]
                {
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys, new DefaultKeyResolution()
                        {
                            DefaultKey = null,
                            ShouldGenerateNewKey = true
                        }),
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys, new DefaultKeyResolution()
                        {
                            DefaultKey = null,
                            ShouldGenerateNewKey = true
                        })
                });

            // Act
            var cacheableKeyRing = keyRingProvider.GetCacheableKeyRing(now);

            // replacedert
            replacedert.Equal(newlyCreatedKey.KeyId, cacheableKeyRing.KeyRing.DefaultKeyId);
            replacedertWithinJitterRange(cacheableKeyRing.ExpirationTimeUtc, now);
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts1.Cancel();
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts2.Cancel();
            replacedert.False(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            replacedert.Equal(new[] { "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy", "CreateNewKey", "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy" }, callSequence);
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void CreateCacheableKeyRing_GenerationRequired_WithDefaultKey_CreatesNewKeyWithDeferredActivationAndExpirationBasedOnActivationDate()
        {
            // Arrange
            var callSequence = new List<string>();
            var expirationCts1 = new CancellationTokenSource();
            var expirationCts2 = new CancellationTokenSource();

            var now = StringToDateTime("2016-02-01 00:00:00Z");
            var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z");
            var allKeys1 = new[] { key1 };

            var key2 = CreateKey("2016-03-01 00:00:00Z", "2017-03-01 00:00:00Z");
            var allKeys2 = new[] { key1, key2 };

            var keyRingProvider = SetupCreateCacheableKeyRingTestAndCreateKeyManager(
                callSequence: callSequence,
                getCacheExpirationTokenReturnValues: new[] { expirationCts1.Token, expirationCts2.Token },
                getAllKeysReturnValues: new[] { allKeys1, allKeys2 },
                createNewKeyCallbacks: new[] {
                    Tuple.Create(key1.ExpirationDate, key1.ExpirationDate + TimeSpan.FromDays(90), CreateKey())
                },
                resolveDefaultKeyPolicyReturnValues: new[]
                {
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys1, new DefaultKeyResolution()
                        {
                            DefaultKey = key1,
                            ShouldGenerateNewKey = true
                        }),
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys2, new DefaultKeyResolution()
                        {
                            DefaultKey = key2,
                            ShouldGenerateNewKey = false
                        })
                });

            // Act
            var cacheableKeyRing = keyRingProvider.GetCacheableKeyRing(now);

            // replacedert
            replacedert.Equal(key2.KeyId, cacheableKeyRing.KeyRing.DefaultKeyId);
            replacedertWithinJitterRange(cacheableKeyRing.ExpirationTimeUtc, now);
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts1.Cancel();
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts2.Cancel();
            replacedert.False(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            replacedert.Equal(new[] { "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy", "CreateNewKey", "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy" }, callSequence);
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void CreateCacheableKeyRing_GenerationRequired_WithDefaultKey_KeyGenerationDisabled_DoesNotCreateDefaultKey()
        {
            // Arrange
            var callSequence = new List<string>();
            var expirationCts = new CancellationTokenSource();

            var now = StringToDateTime("2016-02-01 00:00:00Z");
            var key1 = CreateKey("2015-03-01 00:00:00Z", "2016-03-01 00:00:00Z");
            var allKeys = new[] { key1 };

            var keyRingProvider = SetupCreateCacheableKeyRingTestAndCreateKeyManager(
                callSequence: callSequence,
                getCacheExpirationTokenReturnValues: new[] { expirationCts.Token },
                getAllKeysReturnValues: new[] { allKeys },
                createNewKeyCallbacks: null, // empty
                resolveDefaultKeyPolicyReturnValues: new[]
                {
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys, new DefaultKeyResolution()
                        {
                            DefaultKey = key1,
                            ShouldGenerateNewKey = true
                        })
                },
                keyManagementOptions: new KeyRotationOptions() { AutoGenerateKeys = false });

            // Act
            var cacheableKeyRing = keyRingProvider.GetCacheableKeyRing(now);

            // replacedert
            replacedert.Equal(key1.KeyId, cacheableKeyRing.KeyRing.DefaultKeyId);
            replacedertWithinJitterRange(cacheableKeyRing.ExpirationTimeUtc, now);
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts.Cancel();
            replacedert.False(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            replacedert.Equal(new[] { "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy" }, callSequence);
        }

19 Source : KeyRingProviderTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void CreateCacheableKeyRing_GenerationRequired_WithFallbackKey_KeyGenerationDisabled_DoesNotCreateDefaultKey()
        {
            // Arrange
            var callSequence = new List<string>();
            var expirationCts = new CancellationTokenSource();

            var now = StringToDateTime("2016-02-01 00:00:00Z");
            var key1 = CreateKey("2015-03-01 00:00:00Z", "2015-03-01 00:00:00Z");
            var allKeys = new[] { key1 };

            var keyRingProvider = SetupCreateCacheableKeyRingTestAndCreateKeyManager(
                callSequence: callSequence,
                getCacheExpirationTokenReturnValues: new[] { expirationCts.Token },
                getAllKeysReturnValues: new[] { allKeys },
                createNewKeyCallbacks: null, // empty
                resolveDefaultKeyPolicyReturnValues: new[]
                {
                        Tuple.Create((DateTimeOffset)now, (IEnumerable<IKey>)allKeys, new DefaultKeyResolution()
                        {
                            FallbackKey = key1,
                            ShouldGenerateNewKey = true
                        })
                },
                keyManagementOptions: new KeyRotationOptions() { AutoGenerateKeys = false });

            // Act
            var cacheableKeyRing = keyRingProvider.GetCacheableKeyRing(now);

            // replacedert
            replacedert.Equal(key1.KeyId, cacheableKeyRing.KeyRing.DefaultKeyId);
            replacedertWithinJitterRange(cacheableKeyRing.ExpirationTimeUtc, now);
            replacedert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            expirationCts.Cancel();
            replacedert.False(CacheableKeyRing.IsValid(cacheableKeyRing, now));
            replacedert.Equal(new[] { "GetCacheExpirationToken", "GetAllKeys", "ResolveDefaultKeyPolicy" }, callSequence);
        }

19 Source : BasicDifferentiationTests.cs
with MIT License
from alexshtf

[Fact]
        public void DiffBinarySimple()
        {
            var v = Vec(new Variable(), new Variable());
            var func = BinaryFunc.Factory(
                (x, y) => x * x - x * y,
                (x, y) => Tuple.Create(2 * x - y, -x));

            // f(x, y) = x² - xy
            // df/dx = 2x - y
            // df/dy = -x
            var term = func(v[0], v[1]);

            var y1 = term.Differentiate(v, Vec(1.0, 0.0)); // (2, -1)
            var y2 = term.Differentiate(v, Vec(0.0, 1.0)); // (-1, 0)
            var y3 = term.Differentiate(v, Vec(1.0, 2.0)); // (0, -1)

            replacedert.Equal(Vec(2.0, -1.0), y1);
            replacedert.Equal(Vec(-1.0, 0.0), y2);
            replacedert.Equal(Vec(0.0, -1.0), y3);
        }

19 Source : BasicDifferentiationTests.cs
with MIT License
from alexshtf

[Fact]
        public void DiffBinaryComplex()
        {
            var v = Vec(new Variable(), new Variable());
            var func = BinaryFunc.Factory(
                (x, y) => x * x - x * y,
                (x, y) => Tuple.Create(2 * x - y, -x));

            // f(x, y) = x² - xy - y² + xy = x² - y²
            // df/dx = 2x
            // df/dy = -2y
            var term = func(v[0], v[1]) - func(v[1], v[0]);

            var y1 = term.Differentiate(v, Vec(1.0, 0.0)); // (2, 0)
            var y2 = term.Differentiate(v, Vec(0.0, 1.0)); // (0, -2)
            var y3 = term.Differentiate(v, Vec(2.0, 1.0)); // (4, -2)

            replacedert.Equal(Vec(2.0, 0.0), y1);
            replacedert.Equal(Vec(0.0, -2.0), y2);
            replacedert.Equal(Vec(4.0, -2.0), y3);
        }

19 Source : BasicEvaluationTests.cs
with MIT License
from alexshtf

[Fact]
        public void TestBinaryFuncSimple()
        {
            var v = Vec(new Variable(), new Variable());
            var func = BinaryFunc.Factory(
                (x, y) => x * x - x * y, 
                (x, y) => Tuple.Create(2 * x - y, -x));

            var term = func(v[0], v[1]);

            var y1 = term.Evaluate(v, NumVec(1, 0)); // 1 - 0 = 1
            var y2 = term.Evaluate(v, NumVec(0, 1)); // 0 - 0 = 0
            var y3 = term.Evaluate(v, NumVec(1, 2)); // 1 - 2 = -1

            replacedert.Equal(1.0, y1);
            replacedert.Equal(0.0, y2);
            replacedert.Equal(-1.0, y3);
        }

19 Source : BasicEvaluationTests.cs
with MIT License
from alexshtf

[Fact]
        public void TestBinaryFuncComplex()
        {
            var v = Vec(new Variable(), new Variable());
            var func = BinaryFunc.Factory(
                (x, y) => x * x - x * y,
                (x, y) => Tuple.Create(2 * x - y, -x));

            // f(x, y) = x² - xy - y² + xy = x² - y²
            var term = func(v[0], v[1]) - func(v[1], v[0]);

            var y1 = term.Evaluate(v, NumVec(1, 0)); // 1 - 0 = 1
            var y2 = term.Evaluate(v, NumVec(0, 1)); // 0 - 1 = -1
            var y3 = term.Evaluate(v, NumVec(2, 1)); // 4 - 1 = 3

            replacedert.Equal(1.0, y1);
            replacedert.Equal(-1.0, y2);
            replacedert.Equal(3.0, y3);
        }

19 Source : Program.cs
with MIT License
from alexshtf

static void Main(string[] args)
        {
            // create function factory for arctangent
            var arctan = UnaryFunc.Factory(
                x => Math.Atan(x),      // evaluate
                x => 1 / (1 + x * x));  // derivative of atan

            // create function factory for atan2
            var atan2 = BinaryFunc.Factory(
                (x, y) => Math.Atan2(y, x),
                (x, y) => Tuple.Create(
                    -y / (x*x + y*y),  // d/dx (from wikipedia)
                    x / (x*x + y*y))); // d/dy (from wikipedia)

            
            // define variables
            var u = new Variable();
            var v = new Variable();
            var w = new Variable();

            // create and compile a term
            var term = atan2(u, v) - arctan(w) * atan2(v, w);
            var compiled = term.Compile(u, v, w);

            // compute value + gradient
            var diff = compiled.Differentiate(1, 2, -2);

            Console.WriteLine("The value at (1, 2, -2) is {0}", diff.Item2);
            Console.WriteLine("The gradient at (1, 2, -2) is ({0}, {1}, {2})", 
                diff.Item1[0], 
                diff.Item1[1], 
                diff.Item1[2]);
        }

19 Source : WikiTextTableParser.cs
with MIT License
from AnnoDesigner

private static Tuple<WorldRegion, string> GetRegionAndTierInfo(string wikiTextTable)
        {
            var result = Tuple.Create(WorldRegion.Unknown, string.Empty);

            foreach (var regionPair in RegionTables)
            {
                foreach (var tierPair in regionPair.Value)
                {
                    if (tierPair.Value.Equals(wikiTextTable, StringComparison.OrdinalIgnoreCase))
                    {
                        return Tuple.Create(regionPair.Key, tierPair.Key);
                    }
                }
            }

            return result;
        }

19 Source : UniFiOrchestrator.cs
with MIT License
from anthturner

public IList<Tuple<INetworkedDevice, int>> GeneratePathTo(INetworkedDevice device)
        {
            var list = new List<Tuple<INetworkedDevice, int>>();
            var thisDevice = device;
            while (thisDevice != null)
            {
                var parent = GetParentPortOf(thisDevice);
                if (parent == null)
                    break;
                list.Add(Tuple.Create((INetworkedDevice)parent.Item1, parent.Item2));
                thisDevice = parent.Item1;
            }
            return list;
        }

19 Source : UniFiOrchestrator.cs
with MIT License
from anthturner

public Tuple<IInfrastructureNetworkedDevice, int> GetParentPortOf(INetworkedDevice device)
        {
            string parentMac = "";
            int viaPort = 0;
            if (device is IClientNetworkedDevice)
            {
                if (device is WirelessClientNetworkedDevice)
                    parentMac = ((WirelessClientNetworkedDevice)device).AccessPointMac;
                else if (device is WiredClientNetworkedDevice)
                {
                    parentMac = ((WiredClientNetworkedDevice)device).SwitchMac;
                    viaPort = ((WiredClientNetworkedDevice)device).SwitchPort;
                }
            }
            else if (device is IInfrastructureNetworkedDevice)
            {
                if (((IInfrastructureNetworkedDevice)device).Uplink != null)
                {
                    parentMac = ((IInfrastructureNetworkedDevice)device).Uplink.UplinkMac;
                    viaPort = ((IInfrastructureNetworkedDevice)device).Uplink.UplinkRemotePort.GetValueOrDefault(0);
                }
            }

            if (string.IsNullOrEmpty(parentMac))
                return null;

            return Tuple.Create(InfrastructureDevices.GetByMac(parentMac), viaPort);
        }

19 Source : HtmlFormatter.cs
with MIT License
from arbelatech

private string GetStyleDefaults(string[] prefixes, bool usesPrefixes)
        {
            Func<string, string> prefix = cls =>
            {
                if (!string.IsNullOrEmpty(cls))
                    cls = "." + cls;

                return string.Join(", ", prefixes.Select(arg => (!string.IsNullOrEmpty(arg) ? arg + " " : "") + cls));
            };

            var lines = _cssToStyleMap
                .Where(kvp => kvp.Key != null && kvp.Value != null)
                .Select(kvp => Tuple.Create(kvp.Value.Depth, kvp.Value.TokenType, kvp.Key, kvp.Value.StyleRules))
                .OrderBy(t => t.Item1)
                .Select(s => $"{prefix(s.Item3)} {{ {s.Item4} }} /* {s.Item2} */")
                .ToList();

            if (usesPrefixes && !Options.NoBackground && _style.BackgroundColor != null)
            {
                var textStyle = "";
                if (_tokenToClreplacedMap.Contains(TokenTypes.Text))
                {
                    textStyle = " " + _cssToStyleMap[_tokenToClreplacedMap[TokenTypes.Text]].StyleRules;
                }

                lines.Insert(0, $"{prefix("")} {{ background: {_style.BackgroundColor}; {textStyle} }}");
            }

            if (_style.HighlightColor != null)
            {
                lines.Insert(0, $"{prefix("")}.hll {{ background-color: {_style.HighlightColor} }}");
            }

            return string.Join("\n", lines);
        }

19 Source : Cooking.cs
with MIT License
from ArchaicQuest

public void Cook(Player player, Room room)
        {
            if(room.Items.FirstOrDefault(x => x.ItemType == Item.Item.ItemTypes.Cooking) == null)
            {
                _writeToClient.WriteLine($"<p>You require a fire and a cooking pot before you can cook.</p>",
                    player.ConnectionId);

                return;
            }

            var pot = room.Items.FirstOrDefault(x => x.ItemType == Item.Item.ItemTypes.Cooking);

            // What happens if player throws in random replaced which is not a food item
            var items = pot.Container.Items.Where(x => x.ItemType == Item.Item.ItemTypes.Food).ToList();

            if(items.Count < 3)
            {
                _writeToClient.WriteLine("<p>You need 3 raw ingredients before you can cook.</p>",
                    player.ConnectionId);
              

                if (pot.Container.Items.FirstOrDefault(x => x.ItemType != Item.Item.ItemTypes.Food) != null)
                {
                    _writeToClient.WriteLine($"<p>The following ingredients cannot be cooked with.</p>",
                        player.ConnectionId);

                    var sb = new StringBuilder();
                    sb.Append("<p>");
                    foreach (var invalidItem in pot.Container.Items.Where(x => x.ItemType != Item.Item.ItemTypes.Food))
                    {
                        sb.Append($"{invalidItem.Name}, ");
                    }
                    sb.Append("</p>");

                    _writeToClient.WriteLine(sb.ToString(),
                        player.ConnectionId);

                    return;
                }

                return;
            }


            if (items.Count > 3)
            {
                _writeToClient.WriteLine("<p>You can only cook with 3 raw food ingredients. The following ingredients are not raw food and can't be cooked.</p>",
                    player.ConnectionId);

                var sb = new StringBuilder();
                    sb.Append("<p>");
                foreach (var invalidItem in pot.Container.Items.Where(x => x.ItemType != Item.Item.ItemTypes.Food))
                {
                    sb.Append($"{invalidItem.Name}, ");
                }
                sb.Append("</p>");

                _writeToClient.WriteLine(sb.ToString(),
                    player.ConnectionId);

                return;
            }

            if (items.Count == 3 && pot.Container.Items.FirstOrDefault(x => x.ItemType != Item.Item.ItemTypes.Food) != null)
            {
                _writeToClient.WriteLine($"<p>You can only cook with 3 raw ingredients. The following ingredients cannot be cooked with.</p>",
                    player.ConnectionId);

                var sb = new StringBuilder();
                sb.Append("<p>");
                foreach (var invalidItem in pot.Container.Items.Where(x => x.ItemType != Item.Item.ItemTypes.Food))
                {
                    sb.Append($"{invalidItem.Name}, ");
                }
                sb.Append("</p>");

                _writeToClient.WriteLine(sb.ToString(),
                    player.ConnectionId);

                return;
            }


            var ingredients = new List<Tuple<Item.Item, int>>();

            foreach (var item in items)
            {
                var ingredient = ingredients.FirstOrDefault(x => x.Item1.Name.Equals(item.Name));
                if (ingredient != null)
                {
                    var index = ingredients.FindIndex(x => x.Item1.Name.Equals(ingredient.Item1.Name));

                    var count = ingredient.Item2 + 1;
                    ingredients[index] = Tuple.Create(item, count);
                }
                else
                {
                    ingredients.Add(new Tuple<Item.Item, int>(item, 1));
                }

            }

            pot.Container.Items = new ItemList();
            var cookedItem = GenerateCookedItem(player, room, ingredients);
            _writeToClient.WriteLine("<p>You begin cooking.</p>",
                player.ConnectionId);
           _writeToClient.WriteLine("<p>You stir the ingredients.</p>",
                player.ConnectionId, 1000);

            _writeToClient.WriteLine("<p>You taste and season the dish.</p>",
                player.ConnectionId, 2500);

            _writeToClient.WriteLine("<p>You stir the ingredients.</p>",
                player.ConnectionId, 5000);

            var success = _skills.SuccessCheck(player, "cooking");

            if (success)
            {

                _writeToClient.WriteLine(
                    $"<p clreplaced='improve'>You have successfully created {Helpers.AddArticle(cookedItem.Name).ToLower()}.</p>",
                    player.ConnectionId, 6000);

                foreach (var pc in room.Players)
                {
                    if (pc.Name == player.Name)
                    {
                        continue;
                    }

                    _writeToClient.WriteLine($"<p>{player.Name} has cooked {cookedItem.Name}</p>",
                        pc.ConnectionId, 6000);

                }

                player.Inventory.Add(cookedItem);
                player.Weight += cookedItem.Weight;
               

            }
            else
            {
                _writeToClient.WriteLine(
                    $"<p clreplaced='improve'>You have fail to create {Helpers.AddArticle(cookedItem.Name).ToLower()}.</p>",
                    player.ConnectionId, 6000);

                foreach (var pc in room.Players)
                {
                    if (pc.Name == player.Name)
                    {
                        continue;
                    }

                    _writeToClient.WriteLine($"<p>{player.Name} fails to cook {cookedItem.Name}</p>",
                        pc.ConnectionId, 6000);

                }

                _skills.LearnMistakes(player, "Cooking", 6000);
            }
            _clientUi.UpdateInventory(player);
            _clientUi.UpdateScore(player);
        }

19 Source : DaumCafeSession.cs
with GNU Affero General Public License v3.0
from asmejkal

public async Task<DaumCafePage> GetPage(Uri mobileUrl, CancellationToken ct)
        {
            string content;
            var response = await _client.GetAsync(mobileUrl, ct);
            if (response.StatusCode == (HttpStatusCode)308)
            {
                // Deal with the wonky 308 status code (permanent redirect) - HttpClient should redirect, but it doesn't (probably because 308 is not even in .NET docs)
                var location = response.Headers.Location;
                var absoluteLocation = location.IsAbsoluteUri ? location : new Uri(new Uri(mobileUrl.GetComponents(UriComponents.Scheme | UriComponents.StrongAuthority, UriFormat.Unescaped)), location);
                content = await _client.GetStringAsync(absoluteLocation);
            }
            else
            {
                content = await response.Content.ReadreplacedtringAsync();
            }

            var properties = new List<Tuple<string, string>>();

            var matches = _metaPropertyRegex.Matches(content);
            foreach (Match match in matches)
                properties.Add(Tuple.Create(match.Groups[1].Value, match.Groups[2].Value));
            
            var url = properties.FirstOrDefault(x => x.Item1 == "og:url")?.Item2;
            if (!string.IsNullOrEmpty(url) && url.Contains("comments"))
            {
                // Comment type board
                return new DaumCafePage()
                {
                    RelativeUrl = url,
                    Type = "comment",
                    Body = DaumCafePageBody.CreateFromComment(content)
                };
            }
            else
            {
                // replacedume regular board
                return new DaumCafePage()
                {
                    RelativeUrl = url,
                    Type = properties.FirstOrDefault(x => x.Item1 == "og:type")?.Item2,
                    replacedle = WebUtility.HtmlDecode(properties.FirstOrDefault(x => x.Item1 == "og:replacedle")?.Item2 ?? ""),
                    ImageUrl = properties.FirstOrDefault(x => x.Item1 == "og:image")?.Item2,
                    Description = WebUtility.HtmlDecode(properties.FirstOrDefault(x => x.Item1 == "og:description")?.Item2 ?? ""),
                    Body = DaumCafePageBody.Create(content)
                };
            }
        }

19 Source : ViewsModule.cs
with GNU Affero General Public License v3.0
from asmejkal

[Command("views", "Checks how releases are doing on YouTube. The releases need to be added by moderators.", CommandFlags.TypingIndicator)]
        [Parameter("SongOrCategoryName", ParameterType.String, ParameterFlags.Optional | ParameterFlags.Remainder, "select songs from a specific category or search for a song from any category")]
        [Comment("Use without parameters to view songs from the default category. \nUse `all` to view all songs regardless of category.")]
        public async Task Views(ICommand command)
        {
            var settings = await _settings.Read<MediaSettings>(command.GuildId);
            string param = string.IsNullOrWhiteSpace(command["SongOrCategoryName"]) ? null : (string)command["SongOrCategoryName"];

            List<ComebackInfo> comebacks;
            if (string.Compare("all", param, true) == 0)
            {
                comebacks = settings.YouTubeComebacks;
            }
            else
            {
                comebacks = settings.YouTubeComebacks.Where(x => string.Compare(x.Category, param, true) == 0).ToList();
                if (comebacks.Count <= 0 && !string.IsNullOrWhiteSpace(param))
                    comebacks = settings.YouTubeComebacks.Where(x => x.Name.Search(param, true)).ToList();
            }

            if (comebacks.Count <= 0)
            {
                string rec;
                if (settings.YouTubeComebacks.Count <= 0)
                    rec = "Use the `views add` command.";
                else
                    rec = "Try " + GetOtherCategoriesRecommendation(settings, param, true, command.Prefix) + ".";

                await command.ReplyError($"No comeback info has been set for this category or song. {rec}");
                return;
            }

            // Get YT data
            var pages = new PageCollection();
            var infos = new List<Tuple<ComebackInfo, YoutubeInfo>>();
            foreach (var comeback in comebacks)
                infos.Add(Tuple.Create(comeback, await GetYoutubeInfo(comeback.VideoIds, _integrationOptions.Value.YouTubeKey)));

            // Compose embeds with info
            string recommendation = "Try also: " + GetOtherCategoriesRecommendation(settings, param, false, command.Prefix) + ".";
            foreach (var info in infos.OrderByDescending(x => x.Item2.PublishedAt))
            {
                if (pages.IsEmpty || pages.Last.Embed.Fields.Count % 5 == 0)
                {
                    pages.Add(new EmbedBuilder().Withreplacedle("YouTube"));

                    if (!string.IsNullOrEmpty(recommendation))
                        pages.Last.Embed.WithFooter(recommendation);
                }                
                
                TimeSpan timePublished = DateTime.Now.ToUniversalTime() - info.Item2.PublishedAt;

                pages.Last.Embed.AddField(eab => eab.WithName($":tv: {info.Item1.Name}").WithIsInline(false).WithValue(
                    $"**Views: **{info.Item2.Views.ToString("N0", GlobalDefinitions.Culture)}\n" +
                    $"**Likes: **{info.Item2.Likes.ToString("N0", GlobalDefinitions.Culture)}\n" +
                    $"**Published: **{string.Format("{0}d {1}h {2}min ago", timePublished.Days, timePublished.Hours, timePublished.Minutes)}\n\n"));
            }

            await command.Reply(pages);
        }

19 Source : DaumCafeService.cs
with GNU Affero General Public License v3.0
from asmejkal

private async Task UpdateFeed(DaumCafeFeed feed, ulong serverId, CancellationToken ct)
        {
            var guild = _client.GetGuild(serverId);
            if (guild == null)
                return;

            var channel = guild.GetTextChannel(feed.TargetChannel);
            if (channel == null)
                return;

            var logger = _logger.WithScope(channel);

            // Choose a session
            DaumCafeSession session;
            if (feed.CredentialId != Guid.Empty)
            {
                if (!_sessionCache.TryGetValue(feed.CredentialId, out var dateSession) || DateTime.Now - dateSession.Item1 > SessionLifetime)
                {
                    var credential = await Modules.CafeModule.GetCredential(_credentialsService, feed.CredentialUser, feed.CredentialId, ct);
                    try
                    {
                        session = await DaumCafeSession.Create(credential.Login, credential.Preplacedword, ct);
                        _sessionCache[feed.CredentialId] = Tuple.Create(DateTime.Now, session);
                    }
                    catch (Exception ex) when (ex is CountryBlockException || ex is LoginFailedException)
                    {
                        session = DaumCafeSession.Anonymous;
                        _sessionCache[feed.CredentialId] = Tuple.Create(DateTime.Now, session);
                    }
                }
                else
                {
                    session = dateSession.Item2;
                }
            }
            else
            {
                session = DaumCafeSession.Anonymous;
            }

            // Get last post ID
            int lastPostId;
            try
            {
                lastPostId = await session.GetLastPostId(feed.CafeId, feed.BoardId, ct);
            }
            catch (WebException ex) when (ex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.Forbidden)
            {
                logger.LogInformation("Cafe feed {CafeId}/{BoardId} update forbidden", feed.CafeId, feed.BoardId);
                return;
            }

            // If new feed -> just store the last post ID and return
            if (feed.LastPostId < 0)
            {
                await _settings.Modify<MediaSettings>(serverId, s =>
                {
                    var current = s.DaumCafeFeeds.FirstOrDefault(x => x.Id == feed.Id);
                    if (current != null && current.LastPostId < 0)
                        current.LastPostId = lastPostId;
                });

                return;
            }
            
            var currentPostId = feed.LastPostId;
            if (lastPostId <= feed.LastPostId)
                return;

            logger.LogInformation("Updating feed {CafeId}/{BoardId} found {PostCount} new posts ({FirstPostId} to {LastPostId})", feed.CafeId, feed.BoardId, lastPostId - currentPostId, currentPostId + 1, lastPostId, guild.Name, guild.Id);

            while (lastPostId > currentPostId)
            {
                var preview = await CreatePreview(session, feed.CafeId, feed.BoardId, currentPostId + 1, ct);

                if (!guild.CurrentUser.GetPermissions(channel).SendMessages)
                {
                    logger.LogInformation("Can't update Cafe feed because of permissions");
                    currentPostId = lastPostId;
                    break;
                }

                await channel.SendMessageAsync(preview.Item1.Sanitise(), false, preview.Item2);
                currentPostId++;
            }

            await _settings.Modify<MediaSettings>(serverId, settings =>
            {
                var current = settings.DaumCafeFeeds.FirstOrDefault(x => x.Id == feed.Id);
                if (current != null && current.LastPostId < currentPostId)
                    current.LastPostId = currentPostId;
            });
        }

19 Source : DaumCafeService.cs
with GNU Affero General Public License v3.0
from asmejkal

private async Task<Tuple<string, Embed>> CreatePreview(DaumCafeSession session, string cafeId, string boardId, int postId, CancellationToken ct)
        {
            var mobileUrl = $"http://m.cafe.daum.net/{cafeId}/{boardId}/{postId}";
            var desktopUrl = $"http://cafe.daum.net/{cafeId}/{boardId}/{postId}";

            var text = $"<{desktopUrl}>";
            Embed embed = null;
            try
            {
                var metadata = await session.GetPage(new Uri(mobileUrl), ct);
                if (metadata.Type == "comment" && (!string.IsNullOrWhiteSpace(metadata.Body.Text) || !string.IsNullOrWhiteSpace(metadata.ImageUrl)))
                {
                    embed = BuildPreview("New memo", mobileUrl, metadata.Body.Text, metadata.Body.ImageUrl, cafeId);
                }
                else if (!string.IsNullOrEmpty(metadata.Body.Subject) && (!string.IsNullOrWhiteSpace(metadata.Body.Text) || !string.IsNullOrWhiteSpace(metadata.ImageUrl)))
                {
                    embed = BuildPreview(metadata.Body.Subject, mobileUrl, metadata.Body.Text, metadata.Body.ImageUrl, cafeId);
                }
                else if (metadata.Type == "article" && !string.IsNullOrWhiteSpace(metadata.replacedle) && (!string.IsNullOrWhiteSpace(metadata.Description) || !string.IsNullOrWhiteSpace(metadata.ImageUrl)))
                {
                    embed = BuildPreview(metadata.replacedle, mobileUrl, metadata.Description, metadata.ImageUrl, cafeId);
                }
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "Failed to create Daum Cafe post preview for {PostUri}", mobileUrl);
            }

            return Tuple.Create(text, embed);
        }

19 Source : ServerFactoryLoader.cs
with Apache License 2.0
from aspnet

private static IEnumerable<Tuple<string, replacedembly>> HuntForreplacedemblies(string configurationString)
        {
            if (configurationString == null)
            {
                yield break;
            }

            int commaIndex = configurationString.IndexOf(',');
            if (commaIndex >= 0)
            {
                // replacedembly is given, break the type and replacedembly apart
                string methodOrTypeName = DotByDot(configurationString.Substring(0, commaIndex)).FirstOrDefault();
                string replacedemblyName = configurationString.Substring(commaIndex + 1).Trim();
                replacedembly replacedembly = TryreplacedemblyLoad(replacedemblyName);
                if (replacedembly != null)
                {
                    yield return Tuple.Create(methodOrTypeName, replacedembly);
                }
            }
            else
            {
                // replacedembly is inferred from type name
                string typeName = DotByDot(configurationString).FirstOrDefault();

                // go through each segment
                foreach (var replacedemblyName in DotByDot(typeName))
                {
                    replacedembly replacedembly = TryreplacedemblyLoad(replacedemblyName);
                    if (replacedembly != null)
                    {
                        if (replacedemblyName.Length == typeName.Length)
                        {
                            // No type specified, use the default.
                            yield return Tuple.Create(replacedemblyName + "." + Constants.OwinServerFactory, replacedembly);
                        }
                        else
                        {
                            yield return Tuple.Create(typeName, replacedembly);
                        }
                    }
                }
            }
        }

19 Source : FutureTests.cs
with Apache License 2.0
from asynkron

[Fact]
        public void TestInATaskIndirect() => Task.Run(async () => {
                var replier = Context.Spawn(Props.FromFunc(ctx => {
                            if (ctx.Message is Tuple<PID, string> msg)
                            {
                                output.WriteLine("replier Got Message " + msg.Item2);
                                msg.Item1.SendUserMessage(System, null!);
                                output.WriteLine("replier Sent Response to " + msg.Item2);
                            }

                            return Task.CompletedTask;
                        }
                    )
                );
                var pid = Context.Spawn(Props.FromFunc(ctx => {
                            if (ctx.Message is string msg)
                            {
                                output.WriteLine("pid Got Message " + msg);
                                replier.SendUserMessage(System, Tuple.Create(ctx.Sender, msg));
                                output.WriteLine("pid Sent Response to " + msg);
                            }

                            return Task.CompletedTask;
                        }
                    )
                );

                output.WriteLine("Starting");
                var reply1 = await Context.RequestAsync<object>(pid, "hello1", TimeSpan.FromSeconds(2));
                replacedert.Null(reply1);
                output.WriteLine("got response 1");
                var reply2 = Context.RequestAsync<object>(pid, "hello2", TimeSpan.FromSeconds(2)).Result;
                replacedert.Null(reply2);
                output.WriteLine("got response 2");
            }
        ).Wait();

19 Source : CloudProviderCredentialsResolver.cs
with Apache License 2.0
from AutomateThePlanet

public static Tuple<string, string> GetCredentials()
        {
            var user = SecretsResolver.GetSecret(USER_ENVIRONMENTAL_VARIABLE);
            var accessKey = SecretsResolver.GetSecret(ACCESS_KEY_ENVIRONMENTAL_VARIABLE);

            if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(accessKey))
            {
                return Tuple.Create(user, accessKey);
            }

            return GetCredentialsFromConfig();
        }

19 Source : Perf.cs
with MIT License
from azist

public override string Execute()
    {
      var duration = m_Args.AttrByName(CONFIG_DURATION_ATTR).ValueAsInt(8000);
      var sample = m_Args.AttrByName(CONFIG_SAMPLE_ATTR).ValueAsInt(500);

      if (duration<1000 || sample <100) return "Sampling rate must be > 100ms and duration >1000ms";


      var watch = Stopwatch.StartNew();

      var lst = new List<Tuple<int, int, int>>();

      while(watch.ElapsedMilliseconds<duration)
      {
          var cpu = Computer.CurrentProcessorUsagePct;
          var ram = Computer.GetMemoryStatus().LoadPct;

          lst.Add(Tuple.Create((int)watch.ElapsedMilliseconds, cpu, (int)ram));
          System.Threading.Thread.Sleep(sample);
      }

      var result = new StringBuilder(1024);
      const int maxw = 70;

      for(int i=0; i<lst.Count; i++)
      {
          var cpu = (int)(maxw * (lst[i].Item2 / 100d));
          var ram = (int)(maxw * (lst[i].Item3 / 100d));
          var l = "";
          if (ram<=cpu)
          {
              l = l.PadLeft(ram, '#').PadRight(cpu-ram, '=');
          }
          else
              l = l.PadLeft(cpu, '#').PadRight(ram-cpu, '|');

          l = l.PadRight(maxw, '·');

          l = (lst[i].Item1 / 1000d).ToString("F1").PadLeft(5) + l;

          result.AppendLine( l );
      }

      result.AppendLine(@"____________________________________________________________________________");
      result.AppendLine(@" Cpu: '==='    Ram: '|||'    Cpu+Ram: '###'    Available: {0} Mb.".Args(Computer.CurrentAvailableMemoryMb));

      return result.ToString();
    }

19 Source : PdfTestForm.cs
with MIT License
from azist

private void button4_Click(object sender, EventArgs e)
    {
      var doreplacedent = new PdfDoreplacedent();
      doreplacedent.Fonts.Add(PdfFont.Courier);

      var sizes = new[]
      {
        Tuple.Create("Letter", PdfPageSize.Letter()),
        Tuple.Create("A0", PdfPageSize.A0()),
        Tuple.Create("A1", PdfPageSize.A1()),
        Tuple.Create("A2", PdfPageSize.A2()),
        Tuple.Create("A3", PdfPageSize.A3()),
        Tuple.Create("A4", PdfPageSize.A4()),
        Tuple.Create("A5", PdfPageSize.A5()),
        Tuple.Create("B4", PdfPageSize.B4()),
        Tuple.Create("B5", PdfPageSize.B5()),
        Tuple.Create("Custom", new PdfSize(PdfUnit.Default, 100, 50))
      };

      foreach (var size in sizes)
      {
        var page = doreplacedent.AddPage(size.Item2);
        page.AddRectangle(0, 0, size.Item2.Width, size.Item2.Height, PdfColor.White, 2.0F, PdfColor.Red);
        var text = page.AddText(string.Format("{0}: w={1} h={2}", size.Item1, size.Item2.Width, size.Item2.Height), 10, PdfFont.Courier);
        text.X = 0;
        text.Y = size.Item2.Height - 20;
      }

      doreplacedent.Save(@"test.pdf");

      Process.Start(@"test.pdf");
    }

19 Source : PdfTestForm.cs
with MIT License
from azist

private void button5_Click(object sender, EventArgs e)
    {
      var doreplacedent = new PdfDoreplacedent();
      doreplacedent.Fonts.Add(PdfFont.Courier);

      var units = new[]
      {
        Tuple.Create("Point: 1 pt", PdfUnit.Point),
        Tuple.Create("Millimeter 2.83 pt", PdfUnit.Millimeter),
        Tuple.Create("Centimeter 28.3 pt", PdfUnit.Centimeter),
        Tuple.Create("Inch: 72 pt", PdfUnit.Inch),
        Tuple.Create("Custom: 100 pt", PdfUnit.ByName("My Custom 100", 100))
      };

      foreach (var unit in units)
      {
        var page = doreplacedent.AddPage(new PdfSize(unit.Item2, 200, 300)); // create 200x300 units page
        page.AddRectangle(0, 280, 10, 290, PdfColor.Blue, 0.0F, PdfColor.White);
        var text = page.AddText(unit.Item1 + "(upper rectangle's size is 10x10 units)", 5, PdfFont.Courier);
        text.X = 0;
        text.Y = 270;
      }

      doreplacedent.Save(@"test.pdf");

      Process.Start(@"test.pdf");
    }

19 Source : RestMedicationStatementService.cs
with Apache License 2.0
from bcgov

private static Tuple<bool, string?> ValidateProtectiveWord(string? protectiveWord)
        {
            bool valid = true;
            string? errMsg = null;
            if (!string.IsNullOrEmpty(protectiveWord))
            {
                if (protectiveWord.Length >= MinLengthProtectiveWord && protectiveWord.Length <= MaxLengthProtectiveWord)
                {
                    Regex regex = new Regex(@"^[0-9A-Za-z_]+$");
                    if (!regex.IsMatch(protectiveWord))
                    {
                        valid = false;
                        errMsg = ErrorMessages.ProtectiveWordInvalidChars;
                    }
                }
                else
                {
                    valid = false;
                    if (protectiveWord.Length > MaxLengthProtectiveWord)
                    {
                        errMsg = ErrorMessages.ProtectiveWordTooLong;
                    }
                    else
                    {
                        // Protective word is too short
                        errMsg = ErrorMessages.ProtectiveWordTooShort;
                    }
                }
            }

            return Tuple.Create(valid, errMsg);
        }

See More Examples