Ejemplo n.º 1
0
        protected override void ProcessRecord()
        {
            switch (ParameterSetName)
            {
                case "Current":
                    WriteObject(Context.User);
                    break;
                case "Filter":
                    var filter = Filter;

                    if (filter.Contains("?") || filter.Contains("*"))
                    {
                        if (filter.Contains("@"))
                        {
                            var pattern = filter.Replace("*", "%").Replace("?", "%");
                            var emailUsers =
                                new Enumerable<User>(() => Membership.FindUsersByEmail(pattern).GetEnumerator(),
                                    o => User.FromName(((MembershipUser) o).UserName, false));
                            WriteObject(emailUsers, true);
                        }
                        else
                        {
                            var users = WildcardFilter(filter, UserManager.GetUsers(), user => user.Name);
                            WriteObject(users, true);
                        }
                    }
                    break;
                default:
                    if (this.CanFindAccount(Identity, AccountType.User))
                    {
                        WriteObject(User.FromName(Identity.Name, Authenticated));
                    }
                    break;
            }
        }
 public void CanDeserializeAnSimpleArrayAsIEnumerable()
 {
     var e = new Enumerable();
     e.A = new ArrayList {  1, 2 };
     string bson = Serialize<Enumerable>(e);
     Assert.AreEqual("GwAAAARBABMAAAAQMAABAAAAEDEAAgAAAAAA", bson);
 }
Ejemplo n.º 3
0
 static void Main(string[] args)
 {
     var objects = new object[] { "aa", 2, true, "bb", DateTime.Now };
     var enumrable = new Enumerable(objects);
     foreach (var obj in enumrable)
     {
         Console.WriteLine(obj);
     }
     Console.ReadLine();
 }
Ejemplo n.º 4
0
        public void Setup()
        {
            serialTasks1 = new SerialTasks();
            parallelTasks1 = new ParallelTasks();
            serialTasks2 = new SerialTasks();
            parallelTasks2 = new ParallelTasks();

            task1 = new Task(15);
            task2 = new Task(5);

            iterable1 = new Enumerable(15);
            iterable2 = new Enumerable(5);

            iterations = 0;

            _taskRunner = TaskRunner.Instance;
        }
 public ObservableCollectionPlus() : this(Enumerable.Empty<T>()) { }
Ejemplo n.º 6
0
    public static void Main()
    {
        Enumerable list = new Enumerable(new int[]{1,3,4});

        foreach(int num in list)
        {
            Console.WriteLine(num);
        }
    }
 private static bool AreEntitiesEqual(MetaTable table, object entity1, object entity2)
 {
     return(Enumerable.SequenceEqual(table.GetPrimaryKeyValues(entity1), table.GetPrimaryKeyValues(entity2)));
 }
Ejemplo n.º 8
0
        public static ParserResult<T> Build<T>(
            Maybe<Func<T>> factory,
            Func<IEnumerable<string>, IEnumerable<OptionSpecification>, Result<IEnumerable<Token>, Error>> tokenizer,
            IEnumerable<string> arguments,
            StringComparer nameComparer,
            bool ignoreValueCase,
            CultureInfo parsingCulture,
            IEnumerable<ErrorType> nonFatalErrors)
        {
            var typeInfo = factory.MapValueOrDefault(f => f().GetType(), typeof(T));

            var specProps = typeInfo.GetSpecifications(pi => SpecificationProperty.Create(
                    Specification.FromProperty(pi), pi, Maybe.Nothing<object>()));

            var specs = from pt in specProps select pt.Specification;

            var optionSpecs = specs
                .ThrowingValidate(SpecificationGuards.Lookup)
                .OfType<OptionSpecification>();

            Func<T> makeDefault = () =>
                typeof(T).IsMutable()
                    ? factory.MapValueOrDefault(f => f(), Activator.CreateInstance<T>())
                    : ReflectionHelper.CreateDefaultImmutableInstance<T>(
                        (from p in specProps select p.Specification.ConversionType).ToArray());

            Func<IEnumerable<Error>, ParserResult<T>> notParsed =
                errs => new NotParsed<T>(makeDefault().GetType().ToTypeInfo(), errs);

            Func<ParserResult<T>> buildUp = () =>
            {
                var tokenizerResult = tokenizer(arguments, optionSpecs);

                var tokens = tokenizerResult.SucceededWith();

                var partitions = TokenPartitioner.Partition(
                    tokens,
                    name => TypeLookup.FindTypeDescriptorAndSibling(name, optionSpecs, nameComparer));
                var optionsPartition = partitions.Item1;
                var valuesPartition = partitions.Item2;
                var errorsPartition = partitions.Item3;

                var optionSpecPropsResult =
                    OptionMapper.MapValues(
                        (from pt in specProps where pt.Specification.IsOption() select pt),
                        optionsPartition,
                        (vals, type, isScalar) => TypeConverter.ChangeType(vals, type, isScalar, parsingCulture, ignoreValueCase),
                        nameComparer);

                var valueSpecPropsResult =
                    ValueMapper.MapValues(
                        (from pt in specProps where pt.Specification.IsValue() orderby ((ValueSpecification)pt.Specification).Index select pt),
                        valuesPartition,
                        (vals, type, isScalar) => TypeConverter.ChangeType(vals, type, isScalar, parsingCulture, ignoreValueCase));

                var missingValueErrors = from token in errorsPartition
                                         select
                        new MissingValueOptionError(
                            optionSpecs.Single(o => token.Text.MatchName(o.ShortName, o.LongName, nameComparer))
                                .FromOptionSpecification());

                var specPropsWithValue =
                    optionSpecPropsResult.SucceededWith().Concat(valueSpecPropsResult.SucceededWith());

                Func<T> buildMutable = () =>
                {
                    var mutable = factory.MapValueOrDefault(f => f(), Activator.CreateInstance<T>());
                    mutable =
                        mutable.SetProperties(specPropsWithValue, sp => sp.Value.IsJust(), sp => sp.Value.FromJustOrFail())
                            .SetProperties(
                                specPropsWithValue,
                                sp => sp.Value.IsNothing() && sp.Specification.DefaultValue.IsJust(),
                                sp => sp.Specification.DefaultValue.FromJustOrFail())
                            .SetProperties(
                                specPropsWithValue,
                                sp =>
                                    sp.Value.IsNothing() && sp.Specification.TargetType == TargetType.Sequence
                                    && sp.Specification.DefaultValue.MatchNothing(),
                                sp => sp.Property.PropertyType.GetTypeInfo().GetGenericArguments().Single().CreateEmptyArray());
                    return mutable;
                };

                Func<T> buildImmutable = () =>
                {
                    var ctor = typeInfo.GetTypeInfo().GetConstructor((from sp in specProps select sp.Property.PropertyType).ToArray());
                    var values = (from prms in ctor.GetParameters()
                        join sp in specPropsWithValue on prms.Name.ToLower() equals sp.Property.Name.ToLower()
                        select
                            sp.Value.GetValueOrDefault(
                                sp.Specification.DefaultValue.GetValueOrDefault(
                                    sp.Specification.ConversionType.CreateDefaultForImmutable()))).ToArray();
                    var immutable = (T)ctor.Invoke(values);
                    return immutable;
                };

                var instance = typeInfo.IsMutable() ? buildMutable() : buildImmutable();
                
                var validationErrors = specPropsWithValue.Validate(SpecificationPropertyRules.Lookup(tokens));

                var allErrors =
                    tokenizerResult.SuccessfulMessages()
                        .Concat(missingValueErrors)
                        .Concat(optionSpecPropsResult.SuccessfulMessages())
                        .Concat(valueSpecPropsResult.SuccessfulMessages())
                        .Concat(validationErrors)
                        .Memorize();

                var warnings = from e in allErrors where nonFatalErrors.Contains(e.Tag) select e;

                return allErrors.Except(warnings).ToParserResult(instance);
            };

            var preprocessorErrors = arguments.Any()
                ? arguments.Preprocess(PreprocessorGuards.Lookup(nameComparer))
                : Enumerable.Empty<Error>();

            var result = arguments.Any()
                ? preprocessorErrors.Any()
                    ? notParsed(preprocessorErrors)
                    : buildUp()
                : buildUp();

            return result;
        }
Ejemplo n.º 9
0
        public async Task TestInitialConfigUpdate_NoWaitForInit()
        {
            // Arrange
            string id = "id";
            string iotHub = "foo.azure-devices.net";
            var routerConfig = new RouterConfig(Enumerable.Empty<Route>());

            var messageStore = new Mock<IMessageStore>();
            messageStore.Setup(m => m.SetTimeToLive(It.IsAny<TimeSpan>()));

            TimeSpan updateFrequency = TimeSpan.FromMinutes(10);

            Endpoint GetEndpoint() => new ModuleEndpoint("id", Guid.NewGuid().ToString(), "in1", Mock.Of<IConnectionManager>(), Mock.Of<Core.IMessageConverter<IMessage>>());
            var endpointFactory = new Mock<IEndpointFactory>();
            endpointFactory.Setup(e => e.CreateSystemEndpoint($"$upstream")).Returns(GetEndpoint);
            var routeFactory = new EdgeRouteFactory(endpointFactory.Object);

            var endpointExecutorFactory = new Mock<IEndpointExecutorFactory>();
            endpointExecutorFactory.Setup(e => e.CreateAsync(It.IsAny<Endpoint>()))
                    .Returns<Endpoint>(endpoint => Task.FromResult(Mock.Of<IEndpointExecutor>(e => e.Endpoint == endpoint)));
            Router router = await Router.CreateAsync(id, iotHub, routerConfig, endpointExecutorFactory.Object);

            var routes1 = Routes.Take(2)
                .ToDictionary(r => r.Key, r => new RouteConfig(r.Key, r.Value, routeFactory.Create(r.Value)));
            var storeAndForwardConfiguration1 = new StoreAndForwardConfiguration(7200);
            var edgeHubConfig1 = new EdgeHubConfig("1.0", routes1, storeAndForwardConfiguration1);

            var routes2 = Routes.Take(3)
                .ToDictionary(r => r.Key, r => new RouteConfig(r.Key, r.Value, routeFactory.Create(r.Value)));
            var storeAndForwardConfiguration2 = new StoreAndForwardConfiguration(7200);
            var edgeHubConfig2 = new EdgeHubConfig("1.0", routes2, storeAndForwardConfiguration2);

            var configProvider = new Mock<IConfigSource>();
            configProvider.SetupSequence(c => c.GetConfig())
                .Returns(async () =>
                {
                    await Task.Delay(5000);
                    return Option.Some(edgeHubConfig2);
                });

            configProvider.Setup(c => c.SetConfigUpdatedCallback(It.IsAny<Func<EdgeHubConfig, Task>>()));

            var initialConfigSource = new Mock<IConfigSource>();
            initialConfigSource.Setup(c => c.GetConfig())
                .Returns(() =>
                {
                    return Task.FromResult(Option.Some(edgeHubConfig1));
                });

            // Act
            var configUpdater = new ConfigUpdater(router, messageStore.Object, updateFrequency, Option.Some(initialConfigSource.Object));
            await configUpdater.Init(configProvider.Object);

            // Assert
            // First only has updated from prefeched config
            Assert.Equal(2, router.Routes.Count);

            // After 6 seconds updates from init received
            await Task.Delay(TimeSpan.FromSeconds(6));
            Assert.Equal(3, router.Routes.Count);
        }
Ejemplo n.º 10
0
 public override IEnumerable<IJSCSGlue> GetChildren()
 {
     return Enumerable.Empty<IJSCSGlue>();
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Convert the example XML element to Markdown safely.
 /// If element is <value>null</value>, return empty string.
 /// </summary>
 /// <param name="element">The example XML element.</param>
 /// <returns>The generated Markdown.</returns>
 internal static IEnumerable <string> ToMarkdown(XElement element) =>
 element != null
         ? new ExampleUnit(element).ToMarkdown()
         : Enumerable.Empty <string>();
        private SslStreamSettings ConfigureSsl(SslStreamSettings settings, ClusterKey clusterKey)
        {
            if (clusterKey.UseSsl)
            {
                var sslSettings = clusterKey.SslSettings ?? new SslSettings();

                var validationCallback = sslSettings.ServerCertificateValidationCallback;
                if (validationCallback == null && !clusterKey.VerifySslCertificate)
                {
                    validationCallback = AcceptAnySslCertificate;
                }

                return(settings.With(
                           clientCertificates: Optional.Create(sslSettings.ClientCertificates ?? Enumerable.Empty <X509Certificate>()),
                           checkCertificateRevocation: sslSettings.CheckCertificateRevocation,
                           clientCertificateSelectionCallback: sslSettings.ClientCertificateSelectionCallback,
                           enabledProtocols: sslSettings.EnabledSslProtocols,
                           serverCertificateValidationCallback: validationCallback));
            }

            return(settings);
        }
Ejemplo n.º 13
0
 public static IEnumerable <IEnumerable <T> > Transpose <T>(this IEnumerable <IEnumerable <T> > matrix) => matrix
 .Any(row => row.Count() > 0)
         ? new[] { matrix.Select(row => row.FirstOrDefault()) }
 .Concat(matrix.Select(row => row.Skip(1)).Transpose())
         : Enumerable.Empty <IEnumerable <T> >();
Ejemplo n.º 14
0
 public static dynamic Function(JavaScript body)
 {
     return(Function(Enumerable.Empty <string>(), body));
 }
Ejemplo n.º 15
0
 public IEnumerable <Component> GetComponents()
 {
     return(componentFactories?.Select(f => f()) ?? Enumerable.Empty <Component>());
 }
Ejemplo n.º 16
0
Archivo: Tool.cs Proyecto: jnm2/cake
 /// <summary>
 /// Gets alternative file paths which the tool may exist in
 /// </summary>
 /// <param name="settings">The settings.</param>
 /// <returns>The default tool path.</returns>
 protected virtual IEnumerable <FilePath> GetAlternativeToolPaths(TSettings settings)
 {
     return(Enumerable.Empty <FilePath>());
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Initializes the connection.
        /// </summary>
        /// <exception cref="SocketException">Throws a SocketException when the connection could not be established with the host</exception>
        /// <exception cref="AuthenticationException" />
        /// <exception cref="UnsupportedProtocolVersionException"></exception>
        public Task<Response> Open()
        {
            _freeOperations = new ConcurrentStack<short>(Enumerable.Range(0, MaxConcurrentRequests).Select(s => (short)s).Reverse());
            _pendingOperations = new ConcurrentDictionary<short, OperationState>();
            _writeQueue = new ConcurrentQueue<OperationState>();

            if (Options.CustomCompressor != null)
            {
                Compressor = Options.CustomCompressor;
            }
            else if (Options.Compression == CompressionType.LZ4)
            {
                Compressor = new LZ4Compressor();
            }
            else if (Options.Compression == CompressionType.Snappy)
            {
                Compressor = new SnappyCompressor();
            }

            //Init TcpSocket
            _tcpSocket.Init();
            _tcpSocket.Error += CancelPending;
            _tcpSocket.Closing += () => CancelPending(null, null);
            //Read and write event handlers are going to be invoked using IO Threads
            _tcpSocket.Read += ReadHandler;
            _tcpSocket.WriteCompleted += WriteCompletedHandler;
            return _tcpSocket
                .Connect()
                .Then(_ => Startup())
                .ContinueWith(t =>
                {
                    if (t.IsFaulted && t.Exception != null)
                    {
                        //Adapt the inner exception and rethrow
                        var ex = t.Exception.InnerException;
                        if (ex is ProtocolErrorException)
                        {
                            //As we are starting up, check for protocol version errors
                            //There is no other way than checking the error message from Cassandra
                            if (ex.Message.Contains("Invalid or unsupported protocol version"))
                            {
                                throw new UnsupportedProtocolVersionException(ProtocolVersion, ex);
                            }
                        }
                        if (ex is ServerErrorException && ProtocolVersion >= 3 && ex.Message.Contains("ProtocolException: Invalid or unsupported protocol version"))
                        {
                            //For some versions of Cassandra, the error is wrapped into a server error
                            //See CASSANDRA-9451
                            throw new UnsupportedProtocolVersionException(ProtocolVersion, ex);
                        }
                        throw ex;
                    }
                    return t.Result;
                }, TaskContinuationOptions.ExecuteSynchronously)
                .Then(response =>
                {
                    if (response is AuthenticateResponse)
                    {
                        return Authenticate();
                    }
                    if (response is ReadyResponse)
                    {
                        return TaskHelper.ToTask(response);
                    }
                    throw new DriverInternalError("Expected READY or AUTHENTICATE, obtained " + response.GetType().Name);
                });
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="InternalPath" /> class.
 /// </summary>
 /// <param name="segment">The segment.</param>
 /// <param name="isClosedPath">if set to <c>true</c> [is closed path].</param>
 internal InternalPath(ILineSegment segment, bool isClosedPath)
     : this(segment?.Flatten() ?? Enumerable.Empty<PointF>(), isClosedPath)
 {
 }
Ejemplo n.º 19
0
        internal static IEnumerable <IType> GetValidTypes(CSharpAstResolver resolver, Expression expr)
        {
            if (expr.Parent is DirectionExpression)
            {
                var parent = expr.Parent.Parent;
                if (parent is InvocationExpression)
                {
                    var invoke = (InvocationExpression)parent;
                    return(GetAllValidTypesFromInvokation(resolver, invoke, expr.Parent));
                }
            }

            if (expr.Parent is ArrayInitializerExpression)
            {
                var aex = expr.Parent as ArrayInitializerExpression;
                if (aex.IsSingleElement)
                {
                    aex = aex.Parent as ArrayInitializerExpression;
                }
                var type = GetElementType(resolver, resolver.Resolve(aex.Parent).Type);
                if (type.Kind != TypeKind.Unknown)
                {
                    return new [] { type }
                }
                ;
            }

            if (expr.Parent is ObjectCreateExpression)
            {
                var invoke = (ObjectCreateExpression)expr.Parent;
                return(GetAllValidTypesFromObjectCreation(resolver, invoke, expr));
            }

            if (expr.Parent is ArrayCreateExpression)
            {
                var ace = (ArrayCreateExpression)expr.Parent;
                if (!ace.Type.IsNull)
                {
                    return(new [] { resolver.Resolve(ace.Type).Type });
                }
            }

            if (expr.Parent is InvocationExpression)
            {
                var parent = expr.Parent;
                if (parent is InvocationExpression)
                {
                    var invoke = (InvocationExpression)parent;
                    return(GetAllValidTypesFromInvokation(resolver, invoke, expr));
                }
            }

            if (expr.Parent is VariableInitializer)
            {
                var initializer = (VariableInitializer)expr.Parent;
                var field       = initializer.GetParent <FieldDeclaration>();
                if (field != null)
                {
                    return new [] { resolver.Resolve(field.ReturnType).Type }
                }
                ;
                return(new [] { resolver.Resolve(initializer).Type });
            }

            if (expr.Parent is CastExpression)
            {
                var cast = (CastExpression)expr.Parent;
                return(new [] { resolver.Resolve(cast.Type).Type });
            }

            if (expr.Parent is AsExpression)
            {
                var cast = (AsExpression)expr.Parent;
                return(new [] { resolver.Resolve(cast.Type).Type });
            }

            if (expr.Parent is AssignmentExpression)
            {
                var assign = (AssignmentExpression)expr.Parent;
                var other  = assign.Left == expr ? assign.Right : assign.Left;
                return(new [] { resolver.Resolve(other).Type });
            }

            if (expr.Parent is BinaryOperatorExpression)
            {
                var assign = (BinaryOperatorExpression)expr.Parent;
                var other  = assign.Left == expr ? assign.Right : assign.Left;
                return(new [] { resolver.Resolve(other).Type });
            }

            if (expr.Parent is ReturnStatement)
            {
                var state = resolver.GetResolverStateBefore(expr.Parent);
                if (state != null && state.CurrentMember != null)
                {
                    return new [] { state.CurrentMember.ReturnType }
                }
                ;
            }

            if (expr.Parent is YieldReturnStatement)
            {
                var state = resolver.GetResolverStateBefore(expr);
                if (state != null && (state.CurrentMember.ReturnType is ParameterizedType))
                {
                    var pt = (ParameterizedType)state.CurrentMember.ReturnType;

                    if (pt.FullName == "System.Collections.Generic.IEnumerable")
                    {
                        return(new [] { pt.TypeArguments.First() });
                    }
                }
            }

            if (expr.Parent is UnaryOperatorExpression)
            {
                var uop = (UnaryOperatorExpression)expr.Parent;
                switch (uop.Operator)
                {
                case UnaryOperatorType.Not:
                    return(new [] { resolver.Compilation.FindType(KnownTypeCode.Boolean) });

                case UnaryOperatorType.Minus:
                case UnaryOperatorType.Plus:
                case UnaryOperatorType.Increment:
                case UnaryOperatorType.Decrement:
                case UnaryOperatorType.PostIncrement:
                case UnaryOperatorType.PostDecrement:
                    return(new [] { resolver.Compilation.FindType(KnownTypeCode.Int32) });
                }
            }
            return(Enumerable.Empty <IType>());
        }
Ejemplo n.º 20
0
        public async Task TestPeriodicAndCallbackConfigUpdate()
        {
            // Arrange
            string id = "id";
            string iotHub = "foo.azure-devices.net";
            var routerConfig = new RouterConfig(Enumerable.Empty<Route>());

            var messageStore = new Mock<IMessageStore>();
            messageStore.Setup(m => m.SetTimeToLive(It.IsAny<TimeSpan>()));

            TimeSpan updateFrequency = TimeSpan.FromSeconds(10);

            Endpoint GetEndpoint() => new ModuleEndpoint("id", Guid.NewGuid().ToString(), "in1", Mock.Of<IConnectionManager>(), Mock.Of<Core.IMessageConverter<IMessage>>());
            var endpointFactory = new Mock<IEndpointFactory>();
            endpointFactory.Setup(e => e.CreateSystemEndpoint($"$upstream")).Returns(GetEndpoint);
            var routeFactory = new EdgeRouteFactory(endpointFactory.Object);

            var endpointExecutorFactory = new Mock<IEndpointExecutorFactory>();
            endpointExecutorFactory.Setup(e => e.CreateAsync(It.IsAny<Endpoint>()))
                .Returns<Endpoint>(endpoint => Task.FromResult(Mock.Of<IEndpointExecutor>(e => e.Endpoint == endpoint)));
            Router router = await Router.CreateAsync(id, iotHub, routerConfig, endpointExecutorFactory.Object);

            var routes1 = Routes.Take(2)
                .ToDictionary(r => r.Key, r => new RouteConfig(r.Key, r.Value, routeFactory.Create(r.Value)));
            var storeAndForwardConfiguration1 = new StoreAndForwardConfiguration(7200);
            var edgeHubConfig1 = new EdgeHubConfig("1.0", routes1, storeAndForwardConfiguration1);

            var routes2 = Routes.Take(3)
                .ToDictionary(r => r.Key, r => new RouteConfig(r.Key, r.Value, routeFactory.Create(r.Value)));
            var storeAndForwardConfiguration2 = new StoreAndForwardConfiguration(7200);
            var edgeHubConfig2 = new EdgeHubConfig("1.0", routes2, storeAndForwardConfiguration2);

            var routes3 = Routes.Take(4)
                .ToDictionary(r => r.Key, r => new RouteConfig(r.Key, r.Value, routeFactory.Create(r.Value)));
            var storeAndForwardConfiguration3 = new StoreAndForwardConfiguration(7200);
            var edgeHubConfig3 = new EdgeHubConfig("1.0", routes3, storeAndForwardConfiguration3);

            Func<EdgeHubConfig, Task> updateCallback = null;
            var configProvider = new Mock<IConfigSource>();
            configProvider.SetupSequence(c => c.GetConfig())
                .ReturnsAsync(Option.Some(edgeHubConfig1))
                .ReturnsAsync(Option.Some(edgeHubConfig2))
                .ReturnsAsync(Option.Some(edgeHubConfig3));
            configProvider.Setup(c => c.SetConfigUpdatedCallback(It.IsAny<Func<EdgeHubConfig, Task>>()))
                .Callback<Func<EdgeHubConfig, Task>>(callback => { updateCallback = callback; });

            // Act
            var configUpdater = new ConfigUpdater(router, messageStore.Object, updateFrequency, Option.None<IConfigSource>());
            await configUpdater.Init(configProvider.Object);

            // Assert
            configProvider.Verify(c => c.GetConfig(), Times.Once);
            endpointExecutorFactory.Verify(e => e.CreateAsync(It.IsAny<Endpoint>()), Times.Once);
            messageStore.Verify(m => m.SetTimeToLive(It.IsAny<TimeSpan>()), Times.Once);

            // call update with no changes
            await updateCallback(edgeHubConfig1);
            configProvider.Verify(c => c.GetConfig(), Times.Exactly(1));
            endpointExecutorFactory.Verify(e => e.CreateAsync(It.IsAny<Endpoint>()), Times.Once);
            messageStore.Verify(m => m.SetTimeToLive(It.IsAny<TimeSpan>()), Times.Once);

            await Task.Delay(TimeSpan.FromSeconds(12));
            configProvider.Verify(c => c.GetConfig(), Times.Exactly(2));
            endpointExecutorFactory.Verify(e => e.CreateAsync(It.IsAny<Endpoint>()), Times.Once);
            messageStore.Verify(m => m.SetTimeToLive(It.IsAny<TimeSpan>()), Times.Exactly(2));

            // call update with changes
            await updateCallback(edgeHubConfig3);
            configProvider.Verify(c => c.GetConfig(), Times.Exactly(2));
            endpointExecutorFactory.Verify(e => e.CreateAsync(It.IsAny<Endpoint>()), Times.Once);
            messageStore.Verify(m => m.SetTimeToLive(It.IsAny<TimeSpan>()), Times.Exactly(3));

            await Task.Delay(TimeSpan.FromSeconds(10));
            configProvider.Verify(c => c.GetConfig(), Times.Exactly(3));
            endpointExecutorFactory.Verify(e => e.CreateAsync(It.IsAny<Endpoint>()), Times.Once);
            messageStore.Verify(m => m.SetTimeToLive(It.IsAny<TimeSpan>()), Times.Exactly(3));
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Gets an enumerator that enumerates the collection
 /// </summary>
 /// <returns>A generic enumerator</returns>
 public override IEnumerator <IModelElement> GetEnumerator()
 {
     return(Enumerable.Empty <IModelElement>().Concat(this._parent.GmlTextSymbols).GetEnumerator());
 }
Ejemplo n.º 22
0
        private void startButton_Click(object sender, EventArgs e)
        {
            if (megaCount.Text.Equals(""))
            {
                megaCount.Text = "0";
            }
            if (OUCount.Text.Equals(""))
            {
                OUCount.Text = "0";
            }
            int megasCount  = int.Parse(megaCount.Text);
            int othersCount = int.Parse(OUCount.Text);

            if (labels.Count <= 2)
            {
                MessageBox.Show("Add more players", "Not enough players", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            //if (megasCount < labels.Count + 1)
            //{
            //    MessageBox.Show("Add more megas", "Not enough megas", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    return;
            //}
            if (othersCount < labels.Count * 5 + 2)
            {
                MessageBox.Show("Add more others", "Not enough others", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            top           = 10;
            currentPlayer = 0;
            pkmnPicked    = 0;
            flag          = false;
            flag2         = true;
            List <int> playerOrder = Enumerable.Range(0, labels.Count()).ToList();

            Shuffle(playerOrder);
            List <Label> tempLabels = new List <Label>();

            for (int i = 0; i < labels.Count(); i++)
            {
                tempLabels.Add(new Label());
                tempLabels[i].Text = labels[playerOrder[i]].Text;
            }
            for (int i = 0; i < labels.Count(); i++)
            {
                labels[i].Text = tempLabels[i].Text;
            }
            tempLabels.Clear();
            AddNewLabel1(10, 40, "Megas:");
            AddNewLabel1(10, 140, "Other:");
            List <int>    randomMegas  = new List <int>(megasCount);
            List <int>    randomOthers = new List <int>(othersCount);
            List <string> chosenMegas  = new List <string>();
            List <string> chosenOthers = new List <string>();

            //for (int i = 0; i < megasCount; ++i)
            //{
            //    int curr = new int();
            //    do
            //    {
            //        curr = rng.Next(0, Lists.megas.Count);
            //    } while (randomMegas.Contains(curr));
            //    randomMegas.Add(curr);
            //    chosenMegas.Add(Lists.megas[randomMegas[i]]);
            //    //AddNewButton1(top += 25, left, Lists.megas[randomMegas[i]]);
            //}
            //chosenMegas.Sort();
            //for (int i = 0; i < megasCount; ++i)
            //{
            //    AddNewButton1(top += 25, left, chosenMegas[i]);
            //    if (i == 21)
            //    {
            //        left += 100;
            //    }
            //}
            left = 10;
            top  = 10;
            for (int i = 0; i < othersCount; ++i)
            {
                int curr = new int();
                do
                {
                    curr = rng.Next(0, Lists.all.Count);
                } while (randomOthers.Contains(curr));
                randomOthers.Add(curr);
                chosenOthers.Add(Lists.all[randomOthers[i]]);
                //AddNewButton2(top += 25, left + 100, Lists.all[randomOthers[i]]);
            }
            chosenOthers.Sort();
            for (int i = 0; i < othersCount; ++i)
            {
                AddNewButton2(top += 25, left + 100, chosenOthers[i]);
                if (i == 21)
                {
                    left += 100;
                    top   = 10;
                }
            }
            startButton.Enabled = false;
            newPlayer.Enabled   = false;
            textBox1.Clear();
            textBox1.Enabled = false;
            label4.Text      = labels[currentPlayer].Text;
            label3.Show();

            foreach (Button button in othersButtons)
            {
                button.Enabled = true;
            }
        }
        public void AsIsWithMultipleDependencies()
        {
            var input = new List <Component>
            {
                new Component("a", null, Enumerable.Empty <string>(), Enumerable.Empty <Controller>(), Enumerable.Empty <Script>(), Enumerable.Empty <Style>(), Enumerable.Empty <Resource>()),
                new Component("b", null, new List <string> {
                    "d", "c"
                }, Enumerable.Empty <Controller>(), Enumerable.Empty <Script>(), Enumerable.Empty <Style>(), Enumerable.Empty <Resource>()),
                new Component("c", null, Enumerable.Empty <string>(), Enumerable.Empty <Controller>(), Enumerable.Empty <Script>(), Enumerable.Empty <Style>(), Enumerable.Empty <Resource>()),
                new Component("d", null, Enumerable.Empty <string>(), Enumerable.Empty <Controller>(), Enumerable.Empty <Script>(), Enumerable.Empty <Style>(), Enumerable.Empty <Resource>()),
            };

            var expected = new List <string>
            {
                "a",
                "c",
                "d",
                "b",
            };

            Assert.Equal(expected, new ComponentDependencySorter().Sort(input).Select(c => c.Id));
        }
Ejemplo n.º 24
0
 public IEnumerator<IAIAction> GetEnumerator()
 {
     if (_loop == null) return Enumerable.Empty<IAIAction>().GetEnumerator();
     return _loop.GetEnumerator();
 }
Ejemplo n.º 25
0
        private static void Member(JsonTextWriter writer, string name, NameValueCollection collection)
        {
            Debug.Assert(writer != null);
            Debug.AssertStringNotEmpty(name);

            //
            // Bail out early if the collection is null or empty.
            //

            if (collection == null || collection.Count == 0) 
                return;

            //
            // Save the depth, which we'll use to lazily emit the collection.
            // That is, if we find that there is nothing useful in it, then
            // we could simply avoid emitting anything.
            //

            var depth = writer.Depth;

            //
            // For each key, we get all associated values and loop through
            // twice. The first time round, we count strings that are 
            // neither null nor empty. If none are found then the key is 
            // skipped. Otherwise, second time round, we encode
            // strings that are neither null nor empty. If only such string
            // exists for a key then it is written directly, otherwise
            // multiple strings are naturally wrapped in an array.
            //

            var items = from i in Enumerable.Range(0, collection.Count)
                        let values = collection.GetValues(i)
                        where values != null && values.Length > 0
                        let some = // Neither null nor empty
                            from v in values
                            where !string.IsNullOrEmpty(v)
                            select v
                        let nom = some.Take(2).Count()
                        where nom > 0
                        select new
                        {
                            Key = collection.GetKey(i), 
                            IsArray = nom > 1, 
                            Values = some,
                        };
            
            foreach (var item in items)
            {
                //
                // There is at least one value so now we emit the key.
                // Before doing that, we check if the collection member
                // was ever started. If not, this would be a good time.
                //

                if (depth == writer.Depth)
                {
                    writer.Member(name);
                    writer.Object();
                }

                writer.Member(item.Key ?? string.Empty);

                if (item.IsArray)
                    writer.Array(); // Wrap multiples in an array

                foreach (var value in item.Values)
                    writer.String(value);

                if (item.IsArray) 
                    writer.Pop();   // Close multiples array
            }

            //
            // If we are deeper than when we began then the collection was
            // started so we terminate it here.
            //

            if (writer.Depth > depth)
                writer.Pop();
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            var dimensions = 8;
            var records    = 10000;
            var sourcedata = GenerateData(dimensions).Take(records).ToArray().AsQueryable();
            var securedata = new PINQueryable <double[]>(sourcedata, null);

            // let's start by computing the centroid of the data
            var means = Mean(securedata, dimensions, 0.1);

            Console.WriteLine("mean vector:");
            foreach (var mean in means)
            {
                Console.Write("\t{0:F4}", mean);
            }
            Console.WriteLine();
            Console.WriteLine();


            // we can also center the data and compute its covariance
            var centered   = securedata.Select(x => x.Select((v, i) => v - means[i]).ToArray());
            var covariance = Covariance(centered, dimensions, 8);

            Console.WriteLine("covariance matrix:");
            foreach (var row in covariance)
            {
                foreach (var entry in row)
                {
                    Console.Write("\t{0:F4}", entry);
                }
                Console.WriteLine();
            }
            Console.WriteLine();


            // iterative algorithms are also possible. we'll do k-means first
            var k          = 3;
            var centers    = GenerateData(dimensions).Take(k).ToArray();
            var iterations = 5;

            foreach (var iteration in Enumerable.Range(0, iterations))
            {
                kMeansStep(securedata, centers, 0.1);
            }

            Console.WriteLine("kMeans: {0} centers, {1} iterations", k, iterations);
            foreach (var center in centers)
            {
                foreach (var value in center)
                {
                    Console.Write("\t{0:F4}", value);
                }
                Console.WriteLine();
            }
            Console.WriteLine();


            // Moving to supervised learning, let's label the points by whether they are nearest the first center or not
            var labeled = securedata.Select(x => new Example(x, NearestCenter(x, centers) == centers[0] ? 1.0 : -1.0));

            // the Perceptron algorithm repeatedly adds misclassified examples to a normal vector
            var perceptronnormal = GenerateData(dimensions).First();

            foreach (var index in Enumerable.Range(0, iterations))
            {
                perceptronnormal = PerceptronStep(labeled, perceptronnormal, 0.1);
            }

            var perceptronerror = labeled.NoisyAverage(0.1, x => x.label * x.vector.Select((v, i) => v * perceptronnormal[i]).Sum() < 0.0 ? 1.0 : 0.0);

            Console.WriteLine("perceptron error rate:\t\t{0:F4}", perceptronerror);

            // the Support Vector Machine attempts to find a maximum margin classifier
            var supportvectornormal = GenerateData(dimensions).First();

            foreach (var index in Enumerable.Range(0, iterations))
            {
                supportvectornormal = SupportVectorStep(labeled, supportvectornormal, 0.1);
            }

            var supportvectorerror = labeled.NoisyAverage(0.1, x => x.label * x.vector.Select((v, i) => v * supportvectornormal[i]).Sum() < 0.0 ? 1.0 : 0.0);

            Console.WriteLine("support vector error rate:\t{0:F4}", supportvectorerror);

            // Logistic regression optimizes the likelihood of the labels under the logistic function
            var logisticnormal = GenerateData(dimensions).First();

            foreach (var index in Enumerable.Range(0, iterations))
            {
                logisticnormal = LogisticStep(labeled, logisticnormal, 0.1);
            }

            var logisticerror = labeled.NoisyAverage(0.1, x => x.label * x.vector.Select((v, i) => v * logisticnormal[i]).Sum() < 0.0 ? 1.0 : 0.0);

            Console.WriteLine("logistic error rate:\t\t{0:F4}", logisticerror);

            Console.ReadKey();
        }
 public FaceToNameMatchResult(FaceCategory category)
     : this(category, Enumerable.Empty<FaceToNameMatch>())
 {
 }
Ejemplo n.º 28
0
        public async Task CanBroadcastBlock()
        {
            // If the bucket stored peers are the same, the block may not propagate,
            // so specify private keys to make the buckets different.
            var keyA = ByteUtil.ParseHex(
                "8568eb6f287afedece2c7b918471183db0451e1a61535bb0381cfdf95b85df20");
            var keyB = ByteUtil.ParseHex(
                "c34f7498befcc39a14f03b37833f6c7bb78310f1243616524eda70e078b8313c");
            var keyC = ByteUtil.ParseHex(
                "941bc2edfab840d79914d80fe3b30840628ac37a5d812d7f922b5d2405a223d3");

            var swarmA = CreateSwarm(new PrivateKey(keyA));
            var swarmB = CreateSwarm(new PrivateKey(keyB));
            var swarmC = CreateSwarm(new PrivateKey(keyC));

            BlockChain <DumbAction> chainA = swarmA.BlockChain;
            BlockChain <DumbAction> chainB = swarmB.BlockChain;
            BlockChain <DumbAction> chainC = swarmC.BlockChain;

            foreach (int i in Enumerable.Range(0, 10))
            {
                await chainA.MineBlock(swarmA.Address);
            }

            foreach (int i in Enumerable.Range(0, 3))
            {
                await chainB.MineBlock(swarmB.Address);
            }

            try
            {
                await StartAsync(swarmA);
                await StartAsync(swarmB);
                await StartAsync(swarmC);

                await BootstrapAsync(swarmB, swarmA.AsPeer);
                await BootstrapAsync(swarmC, swarmA.AsPeer);

                swarmB.BroadcastBlock(chainB[-1]);

                // chainA ignores block header received because its index is shorter.
                await swarmA.BlockHeaderReceived.WaitAsync();

                await swarmC.BlockAppended.WaitAsync();

                Assert.False(swarmA.BlockAppended.IsSet);

                // chainB doesn't applied to chainA since chainB is shorter
                // than chainA
                Assert.NotEqual(chainB, chainA);

                swarmA.BroadcastBlock(chainA[-1]);

                await swarmB.BlockAppended.WaitAsync();

                await swarmC.BlockAppended.WaitAsync();

                Log.Debug("Compare chainA and chainB");
                Assert.Equal(chainA.BlockHashes, chainB.BlockHashes);
                Log.Debug("Compare chainA and chainC");
                Assert.Equal(chainA.BlockHashes, chainC.BlockHashes);
            }
            finally
            {
                await StopAsync(swarmA);
                await StopAsync(swarmB);
                await StopAsync(swarmC);

                swarmA.Dispose();
                swarmB.Dispose();
                swarmC.Dispose();
            }
        }
Ejemplo n.º 29
0
    private static async Task PlayListHandler(OwinEnvironment ctx)
    {
      var ct = ctx.Request.CallCancelled;
      var req = ParsedRequest.Parse(ctx);
      if (!req.IsValid) {
        ctx.Response.StatusCode = req.Status;
        return;
      }
      Channel channel;
      try {
        channel = await GetChannelAsync(ctx, req, ct).ConfigureAwait(false);
      }
      catch (TaskCanceledException) {
        ctx.Response.StatusCode = HttpStatusCode.GatewayTimeout;
        return;
      }
      if (channel==null) {
        ctx.Response.StatusCode = HttpStatusCode.NotFound;
        return;
      }

      var fmt = ctx.Request.Query.Get("pls") ?? req.Extension;
      //m3u8のプレイリストを要求された時はHLS用のパスに転送する
      if (fmt?.ToLowerInvariant()=="m3u8") {
        var location = new UriBuilder(ctx.Request.Uri);
        location.Path = $"/hls/{req.ChannelId:N}";
        if (location.Query.Contains("pls=m3u8")) {
          var queries = location.Query.Substring(1).Split('&').Where(seg => seg!="pls=m3u8").ToArray();
          if (queries.Length>0) {
            location.Query = String.Join("&", queries);
          }
          else {
            location.Query = null;
          }
        }
        ctx.Response.Redirect(HttpStatusCode.MovedPermanently, location.Uri.ToString());
        return;
      }

      var scheme = ctx.Request.Query.Get("scheme");
      var pls = CreatePlaylist(channel, fmt, scheme);
      ctx.Response.StatusCode = HttpStatusCode.OK;
      ctx.Response.Headers.Add("Cache-Control", "private");
      ctx.Response.Headers.Add("Cache-Disposition", "inline");
      ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*");
      ctx.Response.ContentType = pls.MIMEType;
      byte[] body;
      try {
        var baseuri = new Uri(
          new Uri(ctx.Request.Uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.UriEscaped)),
          "stream/");
        var acinfo = ctx.GetAccessControlInfo();
        using (var cts=CancellationTokenSource.CreateLinkedTokenSource(ct)) {
          cts.CancelAfter(10000);
          if (acinfo.AuthorizationRequired) {
            var parameters = new Dictionary<string, string>() {
              { "auth", acinfo.AuthenticationKey.GetToken() },
            };
            body = await pls.CreatePlayListAsync(baseuri, parameters, cts.Token).ConfigureAwait(false);
          }
          else {
            body = await pls.CreatePlayListAsync(baseuri, Enumerable.Empty<KeyValuePair<string,string>>(), cts.Token).ConfigureAwait(false);
          }
        }
      }
      catch (OperationCanceledException) {
        ctx.Response.StatusCode = HttpStatusCode.GatewayTimeout;
        return;
      }
      ctx.Response.StatusCode = HttpStatusCode.OK;
      await ctx.Response.WriteAsync(body, ct).ConfigureAwait(false);
    }
Ejemplo n.º 30
0
 /// <summary>
 /// Gets a collection of key name collections that represent the alternate keys of the given entity.
 /// As alternate keys are not supported on V3, this method will always return an empty enumeration.
 /// </summary>
 /// <param name="collectionName">The collection name of the entity</param>
 /// <returns>An empty enumeration of string enumerations representing the key names</returns>
 public override IEnumerable <IEnumerable <string> > GetAlternateKeyPropertyNames(string collectionName)
 {
     return(Enumerable.Empty <IEnumerable <string> >());
 }
Ejemplo n.º 31
0
		public override IEnumerable<string> IsValid(LinkedListNode<Node> node)
		{
			if (node.Previous == null)
				return new[] { $"Expected expression before {Text} but found nothing" };
			return Enumerable.Empty<string>();
		}
 public static IEnumerable <object[]> TimeZoneOffsets()
 => Enumerable.Range(-11, 26).Select(i => new object[] { i });
        private IEnumerable <JournalVoucherReportOutputItem> CreateJournalVoucherOutputItemsForDist(
            string fundId,
            string primaryFundId,
            List <Domain.Core.DistDbModels.Gl00100> distFunds,
            bool isExceptionRule,
            decimal entryValue,
            int entryRowIndex,
            JournalVoucherType journalVoucher,
            JournalVoucherMatchingResultBuilder matchingResultBuilder)
        {
            if (entryValue == 0)
            {
                return(Enumerable.Empty <JournalVoucherReportOutputItem>());
            }

            string debitFundId  = string.Empty;
            string creditFundId = string.Empty;

            switch (journalVoucher)
            {
            case JournalVoucherType.InvestmentPurchases:
                (debitFundId, creditFundId) = GetDebitAndCreditFundIdsForInvestmentPurchases(primaryFundId, entryValue);
                break;

            case JournalVoucherType.InvestmentSales:
                (debitFundId, creditFundId) = GetDebitAndCreditFundIdsForInvestmentSales(primaryFundId, entryValue);
                break;

            case JournalVoucherType.InvestmentInterest:
                (debitFundId, creditFundId) = GetDebitAndCreditFundIdsForInvestmentInterest(primaryFundId, entryValue);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(journalVoucher));
            }
            var debitFund  = distFunds.FirstOrDefault(t => t.Actnumbr3.Trim() == debitFundId);
            var creditFund = distFunds.FirstOrDefault(t => t.Actnumbr3.Trim() == creditFundId);

            if (debitFund == null)
            {
                matchingResultBuilder.ReportUnmatchedDistFund(entryRowIndex, _sheetName, primaryFundId, journalVoucher, debitFundId);
                return(Enumerable.Empty <JournalVoucherReportOutputItem>());
            }

            if (creditFund == null)
            {
                matchingResultBuilder.ReportUnmatchedDistFund(entryRowIndex, _sheetName, primaryFundId, journalVoucher, creditFundId);
                return(Enumerable.Empty <JournalVoucherReportOutputItem>());
            }

            string debitAccountNumber = $"{primaryFundId}.{debitFund?.Actnumbr2?.Trim()}.{debitFundId}";

            if (isExceptionRule)
            {
                fundId = fundId.Replace('-', '.');
                if (fundId.IndexOf('.') == 3)
                {
                    fundId = fundId.Remove(3, 1);
                }
                debitAccountNumber = $"{fundId}.{debitFundId}";
            }
            string creditAccountNumber = $"{primaryFundId}.{creditFund?.Actnumbr2?.Trim()}.{creditFundId}";

            if (isExceptionRule)
            {
                fundId = fundId.Replace('-', '.');
                if (fundId.IndexOf('.') == 3)
                {
                    fundId = fundId.Remove(3, 1);
                }
                creditAccountNumber = $"{fundId}.{creditFundId}";
            }

            return(new[] {
                CreateDebitJournalVoucherOutputItem(debitAccountNumber, debitFund?.Actdescr?.Trim(), entryValue, journalVoucher, DbSource.DIST),
                CreateCreditJournalVoucherOutputItem(creditAccountNumber, creditFund?.Actdescr?.Trim(), entryValue, journalVoucher, DbSource.DIST)
            });
        }
Ejemplo n.º 34
0
 private string RandomString(int length)
 => new string(Enumerable.Repeat(RefreshTokenChars, length)
               .Select(chars => chars[random.Next(chars.Length)])
               .ToArray());
Ejemplo n.º 35
0
 void InitRoles()
 {
     _roles.AddRange(Enumerable.Repeat("Мафия :levitate:", PlayersCount / 3));
     _roles.AddRange(Enumerable.Repeat("Мирный :person_standing:", PlayersCount - (PlayersCount / 3)));
 }