상속: MonoBehaviour
 /// <summary>Constructs a new Google authorization code flow.</summary>
 public GoogleAuthorizationCodeFlow(Initializer initializer)
     : base(initializer)
 {
     revokeTokenUrl = initializer.RevokeTokenUrl;
     includeGrantedScopes = initializer.IncludeGrantedScopes;
     userDefinedQueryParams = initializer.UserDefinedQueryParams;
 }
예제 #2
0
파일: MySqlTest.cs 프로젝트: ElDT43/iLium
        public void MySqlExecuteQueryTest()
        {
            var sqlhelper = new Initializer();

            Connector mySqlConnector = new MySqlConnector("Server=127.0.0.1;Database=dboptimove;Uid=astro;Pwd=1qazxc;Allow Zero Datetime=False;Convert Zero Datetime=True");
            var dt = (System.Data.DataTable)sqlhelper.ExecuteQuery("SELECT * FROM promotions;", mySqlConnector);

            Assert.IsNotNull(dt);
            //Assert.AreEqual(2, dt.Rows.Count);
        }
예제 #3
0
파일: MsSqlTest.cs 프로젝트: ElDT43/iLium
        public void MsExecuteQueryTest()
        {
            var sqlhelper = new Initializer();
            Connector databaseConnector = new MsSqlConnector(GetConnectionString("cnniLiumDatabaseTest"));

            var dt = (System.Data.DataTable)sqlhelper.ExecuteQuery("SELECT TOP 2 * FROM Users ", databaseConnector);

            Assert.IsNotNull(dt);
            Assert.AreEqual(2, dt.Rows.Count);
        }
예제 #4
0
 public void ShouldReturnABlogWithAuthorDetails()
 {
     //Arrange
       var init = new Initializer();
       var context = new BlogContext(Settings.Default.blog);
       init.InitializeDatabase(context);
       //Act
       var blog = context.Blogs.Include(x => x.AuthorDetail).FirstOrDefault();
       //Assert
       Assert.IsNotNull(blog);
       Assert.IsNotNull(blog.AuthorDetail);
 }
예제 #5
0
파일: Algorithm.cs 프로젝트: Shuvayu/DevBox
        public EnumCategory Categorize(Initializer item, Node first, Node second)
        {
            float forecast = GetForecast(item, first, second);

            if (forecast <= .5f - this.AllowedRanange)
                return EnumCategory.Second;

            if (forecast >= .5 + this.AllowedRanange)
                return EnumCategory.First;

            return EnumCategory.Undetermined;
        }
        public static ParametersObject Create(
            int requiredParameter, Action<Initializer> assign)
        {
            if (assign == null) throw new ArgumentNullException("assign");

            var i = new Initializer(requiredParameter);
            assign(i);

            if (i.RequiredParameter < REQUIRED_PARAMETER_MINIMUM)
                throw new ArgumentOutOfRangeException("RequiredParameter");

            return new ParametersObject(i);
        }
            public static DoSomethingParameters Create(
                Action<Initializer> assign)
            {
                if (assign == null) throw new ArgumentNullException("assign");

                var i = new Initializer();
                assign(i);

                // validation
                if (i.P2 < P2_MINIMUM)
                    throw new ArgumentOutOfRangeException("P2");

                return new DoSomethingParameters(i);
            }
예제 #8
0
파일: MemNodes.cs 프로젝트: Shuvayu/DevBox
 // Add Tokenized Collections with count + 1 for existing count and add new token
 public override void AddContent(Initializer collection)
 {
     foreach (string Tkn in collection)
     {
         if (tbl.ContainsKey(Tkn))
         {
             tbl[Tkn] = tbl[Tkn] + 1;
         }
         else
         {
             tbl.Add(Tkn, 1);
         }
     }
 }
예제 #9
0
파일: MsSqlTest.cs 프로젝트: ElDT43/iLium
        public void MsExecuteProcedureTest()
        {
            var sqlhelper = new Initializer();
            Connector databaseConnector = new MsSqlConnector(GetConnectionString("cnniLiumDatabaseTest"));

            var parameters = new List<System.Data.SqlClient.SqlParameter>
            {
                new System.Data.SqlClient.SqlParameter("@UserId", System.Data.SqlDbType.Int) { Value = 2 },
            };

            var dt = (System.Data.DataTable)sqlhelper.ExecuteProcedure("sp_GetUserById", parameters.ToArray(), databaseConnector);

            Assert.IsNotNull(dt);
            Assert.AreEqual(1, dt.Rows.Count);
        }
예제 #10
0
 /// <summary>
 /// Gets credentials you can use to authenticate with Google services.
 /// </summary>
 public static IConfigurableHttpClientInitializer GetCredentials(
     Initializer init)
 {
     if (AmIRunningOnGoogleComputeEngine())
     {
         return new ComputeCredential(new ComputeCredential.Initializer());
     }
     if (init.LogWriter != null && init.LogWriter.IsLoggingEnabled())
         init.LogWriter.Write("Using credentials from " + init.ServiceAccountP12KeyPath + ".");
     var certificate = new X509Certificate2(init.ServiceAccountP12KeyPath, "notasecret",
         X509KeyStorageFlags.Exportable);
     var credential = new ServiceAccountCredential(
         new ServiceAccountCredential.Initializer(init.ServiceAccountEmail)
         {
             Scopes = init.scopes,
         }.FromCertificate(certificate));
     return credential;
 }
예제 #11
0
파일: Algorithm.cs 프로젝트: Shuvayu/DevBox
        public float GetForecast(Initializer item, Node first, Node second)
        {
            foreach (string token in item)
            {
                int firstCount = first.GetTotalTokenCount(token);
                int secondCount = second.GetTotalTokenCount(token);

                float probability = CalcProbability(firstCount, first.CountIntializers, secondCount, second.CountIntializers);

                Console.WriteLine("{0}: [{1}] ({2}-{3}), ({4}-{5})",
                    token,
                    probability,
                    firstCount,
                    first.CountIntializers,
                    secondCount,
                    second.CountIntializers);
            }

            float prediction = CombineProbability();
            return prediction;
        }
 public Shouter(LogWriter logWriter = null)
 {
     init = new Initializer();
     init.LogWriter = logWriter;
     init.Random = new Random();
     var authInit = new Auth.Initializer();
     authInit.LogWriter = logWriter;
     var credentials = Auth.GetCredentials(authInit);
     init.PubsubService = new PubsubService(new BaseClientService.Initializer()
     {
         ApplicationName = Constants.UserAgent,
         HttpClientInitializer = credentials,
     });
     var args = new Google.Apis.Http.CreateHttpClientArgs
     {
         ApplicationName = Constants.UserAgent,
         GZipEnabled = true,
     };
     args.Initializers.Add(credentials);
     var factory = new Google.Apis.Http.HttpClientFactory();
     init.HttpClient = factory.CreateHttpClient(args);
 }
예제 #13
0
파일: Program.cs 프로젝트: reshadi2/mcjs
    public int Run(Initializer initializer, ProgramConfiguration config)
    {
      var errorCount = 0;
      //var color = ConsoleColor.Blue;
      const int Repeats = 5;
      for (var i = 1; i < Repeats; ++i)
      {
        if (config.MeasureTime)
        {
          //var t = Util.Timers.Start("Write header");
          //if (++color == ConsoleColor.White)
          //    color = ConsoleColor.Blue;
          //Console.ForegroundColor = color;
          Debug.WriteLine("------- Running #{0} -------\n", i);
          //Console.ResetColor();
          //Timers.Stop(t);
        }
        else
          i = Repeats; //One iteration is enough!

        LoadRuntime(config);

        if (initializer != null)
        {
          //This means we are being called from the source code debugger. That will rely on the fact that all scripts are already parsed
          foreach (var pair in _scripts)
            _runtime.Scripts.GetOrAdd(pair.Value, pair.Key, _runtime);

          initializer(_runtime);
        }

        foreach (var pair in _scripts)
          errorCount += _runtime.RunScriptString(pair.Value, pair.Key);

        _runtime.ShutDown();
      }
      return errorCount;
    }
 public Shouter(Initializer init = null)
 {
     _init = init ?? Initializer.CreateDefault();
 }
예제 #15
0
 public void Init()
 {
     _initializer = new Initializer(10);
     _initializer.InitializeDb();
 }
예제 #16
0
        public void SGDRandomTest()
        {
            Python.Initialize();
            Chainer.Initialize();

            int inputCount  = Mother.Dice.Next(2, 50);
            int outputCount = Mother.Dice.Next(2, 50);
            int batchCount  = Mother.Dice.Next(1, 5);

            Real[,] input = (Real[, ])Initializer.GetRealNdArray(new[] { batchCount, inputCount });

            Real[,] dummyGy = (Real[, ])Initializer.GetRealNdArray(new[] { batchCount, outputCount });
            Real[,] w       = (Real[, ])Initializer.GetRealNdArray(new[] { outputCount, inputCount });

            Real[] b = Initializer.GetRealArray(outputCount);

            //Chainer
            NChainer.Linear <Real> cLinear = new NChainer.Linear <Real>(inputCount, outputCount, false, Real.ToBaseNdArray(w), Real.ToBaseArray(b));
            NChainer.SGD <Real>    cSgd    = new NChainer.SGD <Real>();
            cSgd.Setup(cLinear);

            Variable <Real> cX = new Variable <Real>(Real.ToBaseNdArray(input));

            Variable <Real> cY = cLinear.Forward(cX);

            cY.Grad = Real.ToBaseNdArray(dummyGy);

            cY.Backward();

            cSgd.Update();

            //KelpNet
            KelpNet.Linear linear = new KelpNet.Linear(inputCount, outputCount, false, w, b);
            KelpNet.SGD    sgd    = new SGD();
            sgd.SetUp(linear);

            NdArray x = new NdArray(Real.ToRealArray(input), new[] { inputCount }, batchCount);

            NdArray y = linear.Forward(x)[0];

            y.Grad = Real.ToRealArray(dummyGy);

            y.Backward();

            sgd.Update();


            Real[] cW = Real.ToRealArray((Real[, ])cLinear.W.Data);
            Real[] cb = (Real[])cLinear.b.Data;

            //許容範囲を算出
            double delta = 0.00001;

            //W.grad
            Assert.AreEqual(cW.Length, linear.Weight.Data.Length);
            for (int i = 0; i < linear.Weight.Data.Length; i++)
            {
                Assert.AreEqual(cW[i], linear.Weight.Data[i], delta);
            }

            //b.grad
            Assert.AreEqual(cb.Length, linear.Bias.Data.Length);
            for (int i = 0; i < linear.Bias.Data.Length; i++)
            {
                Assert.AreEqual(cb[i], linear.Bias.Data[i], delta);
            }
        }
 public GoogleDriveService(Initializer serviceInitializer)
     : base(serviceInitializer)
 {
 }
예제 #18
0
        public static void Test_Initialize(TestContext context)
        {
            string connectionString = "test";

            Initializer.Init(connectionString);
        }
예제 #19
0
 public void MyTestInitializer()
 {
     qboContextoAuth = Initializer.InitializeQBOServiceContextUsingoAuth();
     //qboContextoAuth.IppConfiguration.Logger.RequestLog.EnableRequestResponseLogging = true;
     //qboContextoAuth.IppConfiguration.Logger.RequestLog.ServiceRequestLoggingLocation = @"C:\IdsLogs";
 }
예제 #20
0
 public UserV10Controller()
 {
     Initializer.Init();
     messages = new ServiceMessages();
     userDao  = new UserDao();
 }
예제 #21
0
 /// <summary>
 /// </summary>
 private static void RefreshNetworkWorker()
 {
     Initializer.RefreshNetworkWorker();
 }
예제 #22
0
 // Awake is called before Start
 private void Awake()
 {
     Initializer.Initialize();
 }
예제 #23
0
        public override void InitParams(Initializer initializer = null, NDArrayDict arg_params = null,
                                        NDArrayDict aux_params  = null, bool allow_missing     = false, bool force_init = false,
                                        bool allow_extra        = false)
        {
            if (ParamsInitialized && !force_init)
            {
                Logger.Warning("Parameters already initialized and force_init=False. init_params call ignored.");
                return;
            }

            if (!Binded)
            {
                throw new Exception("call bind before initializing the parameters");
            }

            void impl(InitDesc name, ref NDArray arr, NDArrayDict cache)
            {
                if (cache != null)
                {
                    NDArray cache_arr = null;
                    if (cache.Contains(name.Name))
                    {
                        cache_arr = cache[name.Name];

                        if (cache_arr != arr)
                        {
                            cache_arr.CopyTo(arr);
                        }
                    }
                    else
                    {
                        if (!allow_missing)
                        {
                            throw new Exception($"{name.Name} is not presented");
                        }

                        if (initializer != null)
                        {
                            initializer.InitWeight(name.Name, ref arr);
                        }
                    }
                }
            }

            var attr = Symbol.AttrDict();

            foreach (var name in _arg_params.Keys)
            {
                if (name == "data")
                {
                    continue;
                }
                var arr  = _arg_params[name];
                var desc = new InitDesc(name, attr.ContainsKey(name) ? attr[name] : null);
                impl(desc, ref arr, arg_params);
            }

            foreach (var name in _aux_params.Keys)
            {
                var arr  = _aux_params[name];
                var desc = new InitDesc(name, attr.ContainsKey(name) ? attr[name] : null);
                impl(desc, ref arr, aux_params);
            }

            ParamsInitialized = true;
            _params_dirty     = false;
            _exec_group.SetParams(_arg_params, _aux_params, allow_extra);
        }
예제 #24
0
        public static void Main(string[] args)
        {
            Directory.CreateDirectory(".\\logs");
            var logName = $".\\logs\\Implem.CodeDefiner_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.log";

            Trace.Listeners.Add(new TextWriterTraceListener(logName));
            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
            AppDomain.CurrentDomain.UnhandledException += (_, e) =>
            {
                if (e.ExceptionObject is SqlException sqlException)
                {
                    Consoles.Write($"UnhandledException: [{sqlException.Number}] {sqlException.Message}", Consoles.Types.Error, true);
                }
                else
                {
                    Consoles.Write("UnhandledException: " + e.ExceptionObject, Consoles.Types.Error, true);
                }
            };
            var argList = args.Select(o => o.Trim());

            ValidateArgs(argList);
            var argHash = new TextData(argList.Skip(1).Join(string.Empty), '/', 1);
            var action  = args[0];
            var path    = argHash.Get("p")?.Replace('\\', System.IO.Path.DirectorySeparatorChar);
            var target  = argHash.Get("t");

            Initializer.Initialize(
                path,
                assemblyVersion: Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                codeDefiner: true,
                setSaPassword: argHash.ContainsKey("s"),
                setRandomPassword: argHash.ContainsKey("r"));
            Performances.Record(MethodBase.GetCurrentMethod().Name);
            DeleteTemporaryFiles();
            switch (action)
            {
            case "_rds":
                ConfigureDatabase();
                break;

            case "rds":
                ConfigureDatabase();
                CreateDefinitionAccessorCode();
                CreateMvcCode(target);
                break;

            case "_def":
                CreateDefinitionAccessorCode();
                break;

            case "def":
                CreateDefinitionAccessorCode();
                CreateMvcCode(target);
                break;

            case "mvc":
                CreateMvcCode(target);
                break;

            case "css":
                CreateCssCode();
                break;

            case "backup":
                CreateSolutionBackup();
                break;

            default:
                WriteErrorToConsole(args);
                break;
            }
            Performances.Record(MethodBase.GetCurrentMethod().Name);
            Performances.PerformanceCollection.Save(Directories.Logs());
            if (Consoles.ErrorCount > 0)
            {
                Consoles.Write(
                    string.Format(DisplayAccessor.Displays.Get("CodeDefinerErrorCount"),
                                  Consoles.ErrorCount,
                                  Path.GetFullPath(logName)),
                    Consoles.Types.Error);
            }
            else
            {
                Consoles.Write(
                    DisplayAccessor.Displays.Get("CodeDefinerCompleted"),
                    Consoles.Types.Success);
            }
            WaitConsole(args);
        }
예제 #25
0
 public void MyTestInitializer()
 {
     qboContextoAuth = Initializer.InitializeQBOServiceContextUsingoAuth();
 }
예제 #26
0
 /// <summary>
 /// </summary>
 private static void SetProcess()
 {
     Initializer.SetProcessID();
 }
 // a private constructor
 ParametersObject(Initializer data)
 {
     _optionalParameter = data.OptionalParameter;
     _requiredParameter = data.RequiredParameter;
 }
 protected override void Initialize()
 {
     Initializer.Initialize();
 }
예제 #29
0
 internal TransformedInstance(
     NormalizedAttribute prototype, Initializer initializeState
     ) : base(prototype, initializeState)
 {
 }
예제 #30
0
        public override void WriteInitializationScript(TextWriter writer)
        {
            var options = new Dictionary <string, object>(Events);

            var animation = Animation.ToJson();

            if (animation.Any())
            {
                if (animation["animation"] is bool)
                {
                    options["animation"] = false;
                }
                else
                {
                    options["animation"] = animation["animation"];
                }
            }

            // properties
            options.Add("modal", Modal);
            options.Add("iframe", Iframe);
            options.Add("draggable", Draggable);
            options.Add("title", Title);
            options.Add("resizable", ResizingSettings.Enabled);
            options.Add("content", ContentUrl);
            if (Width != 0)
            {
                options.Add("width", Width);
            }
            if (Height != 0)
            {
                options.Add("height", Height);
            }
            options.Add("actions", Actions.Container.Select(item => item.Name));


            if (ResizingSettings.Enabled)
            {
                if (ResizingSettings.MinHeight != int.MinValue)
                {
                    options.Add("minHeight", ResizingSettings.MinHeight);
                }

                if (ResizingSettings.MinWidth != int.MinValue)
                {
                    options.Add("minWidth", ResizingSettings.MinWidth);
                }

                if (ResizingSettings.MaxHeight != int.MinValue)
                {
                    options.Add("maxHeight", ResizingSettings.MaxHeight);
                }

                if (ResizingSettings.MaxWidth != int.MinValue)
                {
                    options.Add("maxWidth", ResizingSettings.MaxWidth);
                }
            }

            writer.Write(Initializer.Initialize(Selector, "Window", options));


            base.WriteInitializationScript(writer);
        }
예제 #31
0
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
     app.UseCurrentRequestContext();
     ContextImplement.Init();
     Initializer.Initialize(
         path: env.ContentRootPath,
         assemblyVersion: Assembly.GetExecutingAssembly().GetName().Version.ToString());
     app.UsePathBase(configuration["pathBase"]);
     app.UseStaticFiles();
     app.UseSession();
     app.UseRouting();
     app.UseCors();
     app.UseAuthentication();
     app.UseAuthorization();
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     else
     {
         app.UseExceptionHandler("/errors/internalservererror");
     }
     app.UseStatusCodePages(context =>
     {
         var statusCode = context.HttpContext.Response.StatusCode;
         if (statusCode == 400)
         {
             context.HttpContext.Response.Redirect("/errors/badrequest");
         }
         else if (statusCode == 404)
         {
             context.HttpContext.Response.Redirect("/errors/notfound");
         }
         else if (statusCode == 500)
         {
             context.HttpContext.Response.Redirect("/errors/internalservererror");
         }
         else
         {
             context.HttpContext.Response.Redirect("/errors/internalservererror");
         }
         return(Task.CompletedTask);
     });
     app.Use(async(context, next) => await Invoke(context, next));
     app.UseSessionMiddleware();
     app.UseEndpoints(endpoints =>
     {
         endpoints.MapRazorPages();
         endpoints.MapControllerRoute(
             name: "Default",
             pattern: "{controller}/{action}",
             defaults: new
         {
             Controller = "Items",
             Action     = "Index"
         },
             constraints: new
         {
             Controller = "[A-Za-z][A-Za-z0-9_]*",
             Action     = "[A-Za-z][A-Za-z0-9_]*"
         }
             );
         endpoints.MapControllerRoute(
             name: "Others",
             pattern: "{reference}/{id}/{controller}/{action}",
             defaults: new
         {
             Action = "Index"
         },
             constraints: new
         {
             Reference  = "[A-Za-z][A-Za-z0-9_]*",
             Id         = "[0-9]+",
             Controller = "Binaries|OutgoingMails",
             Action     = "[A-Za-z][A-Za-z0-9_]*"
         }
             );
         endpoints.MapControllerRoute(
             name: "Item",
             pattern: "{controller}/{id}/{action}",
             defaults: new
         {
             Controller = "Items",
             Action     = "Edit"
         },
             constraints: new
         {
             Id     = "[0-9]+",
             Action = "[A-Za-z][A-Za-z0-9_]*"
         }
             );
         endpoints.MapControllerRoute(
             name: "Binaries",
             pattern: "binaries/{guid}/{action}",
             defaults: new
         {
             Controller = "Binaries"
         },
             constraints: new
         {
             Guid   = "[A-Z0-9]+",
             Action = "[A-Za-z][A-Za-z0-9_]*"
         }
             );
     });
 }
예제 #32
0
 // Awake() is called before any Start() method
 private void Awake()
 {
     Initializer.Run();
 }
예제 #33
0
 public FCMClientService(Initializer initializer)
     : base(initializer)
 {
 }
예제 #34
0
    // Each of these provides the behavior when its button is clicked (On_Click())

    // Launches a NewGame by going straight into town with the default setup
    public void Click_NewGame()
    {
        Initializer.ResetData();
        AudioManager.Chirp();
        MenuManager.GoToMenu(MenuName.MainToTown);
    }
예제 #35
0
 private void Initialize()
 {
     Initializer.Initialize(
         path: Server.MapPath("./"),
         assemblyVersion: Assembly.GetExecutingAssembly().GetName().Version.ToString());
 }
예제 #36
0
 public dsAuthorizationCodeFlow(Initializer initializer)
     : base(initializer)
 {
 }
예제 #37
0
 public InitDeclarator InitDeclarator(Declarator decl, Initializer init)
 {
     return new InitDeclarator { Declarator = decl, Init = init };
 }
예제 #38
0
 public InitDeclarator InitDeclarator(Declarator decl, Initializer init)
 {
     return(new InitDeclarator {
         Declarator = decl, Init = init
     });
 }
 public static Initializer CreateDefault()
 {
     var init = new Initializer();
     init.Random = new Random();
     var credentials = Google.Apis.Auth.OAuth2.GoogleCredential.GetApplicationDefaultAsync().Result;
     credentials = credentials.CreateScoped(new[] { PubsubService.Scope.Pubsub });
     init.PubsubService = new PubsubService(new BaseClientService.Initializer()
     {
         ApplicationName = Constants.UserAgent,
         HttpClientInitializer = credentials,
     });
     init.HttpClient = new HttpClient();
     return init;
 }
 /// <summary>Constructs a new Google authorization code flow.</summary>
 public GCSMAuthorizationCodeFlow(Initializer initializer, string userId)
     : base(initializer)
 {
     this.userId = userId;
 }
 public Shouter(LogWriter logWriter)
 {
     _init = Initializer.CreateDefault();
     _init.LogWriter = logWriter;
 }
 /// <summary>Constructs a new Google authorization code flow.</summary>
 public GoogleAuthorizationCodeFlow(Initializer initializer)
     : base(initializer)
 {
     revokeTokenUrl = initializer.RevokeTokenUrl;
 }
예제 #43
0
        public void RandomTest(bool gpuEnable)
        {
            Python.Initialize();
            Chainer.Initialize();

            int batchCount = Mother.Dice.Next(1, 5);
            int chCount    = Mother.Dice.Next(1, 5);
            int wideSize   = Mother.Dice.Next(8, 32);
            int heightSize = Mother.Dice.Next(8, 32);

            int kWidth  = Mother.Dice.Next(1, 5);
            int kHeight = Mother.Dice.Next(1, 5);

            int strideX = Mother.Dice.Next(1, 5);
            int strideY = Mother.Dice.Next(1, 5);

            int padX = Mother.Dice.Next(0, 5);
            int padY = Mother.Dice.Next(0, 5);

            bool coverAll = Mother.Dice.Next(1) == 0;

            int outputHeight = coverAll ?
                               (int)Math.Floor((heightSize - kHeight + padY * 2.0 + strideY - 1) / strideY) + 1 :
                               (int)Math.Floor((heightSize - kHeight + padY * 2.0) / strideY) + 1;

            int outputWidth = coverAll ?
                              (int)Math.Floor((wideSize - kWidth + padX * 2.0 + strideX - 1) / strideX) + 1 :
                              (int)Math.Floor((wideSize - kWidth + padX * 2.0) / strideX) + 1;

            Real[,,,] input = (Real[, , , ])Initializer.GetRealNdArray(new[] { batchCount, chCount, heightSize, wideSize });

            Real[,,,] dummyGy = (Real[, , , ])Initializer.GetRealNdArray(new[] { batchCount, chCount, outputHeight, outputWidth });

            //Chainer
            NChainer.MaxPooling2D <Real> cMaxPooling2D = new NChainer.MaxPooling2D <Real>(
                new[] { kHeight, kWidth },
                new[] { strideY, strideX },
                new[] { padY, padX }
                );

            Variable <Real> cX = new Variable <Real>(Real.ToBaseNdArray(input));

            Variable <Real> cY = cMaxPooling2D.Forward(cX);

            cY.Grad = Real.ToBaseNdArray(dummyGy);

            cY.Backward();


            //KelpNet
            KelpNet.MaxPooling2D maxPooling2D = new KelpNet.MaxPooling2D(
                new[] { kWidth, kHeight },
                new[] { strideX, strideY },
                new[] { padX, padY },
                gpuEnable: gpuEnable);

            NdArray x = new NdArray(Real.ToRealArray(input), new[] { chCount, heightSize, wideSize }, batchCount);

            NdArray y = maxPooling2D.Forward(x)[0];

            y.Grad = Real.ToRealArray(dummyGy);

            y.Backward();

            Real[] cYdata = Real.ToRealArray((Real[, , , ])cY.Data.Copy());
            Real[] cXgrad = Real.ToRealArray((Real[, , , ])cX.Grad.Copy());

            //許容範囲を算出
            double delta = 0.00001;

            Assert.AreEqual(cYdata.Length, y.Data.Length);
            Assert.AreEqual(cXgrad.Length, x.Grad.Length);

            //y
            for (int i = 0; i < y.Data.Length; i++)
            {
                Assert.AreEqual(cYdata[i], y.Data[i], delta);
            }

            //x.grad
            for (int i = 0; i < x.Grad.Length; i++)
            {
                Assert.AreEqual(cXgrad[i], x.Grad[i], delta);
            }
        }
        /// <summary>Constructs a new flow using the initializer's properties.</summary>
        public AuthorizationCodeFlow(Initializer initializer)
        {
            clientSecrets = initializer.ClientSecrets;
            if (clientSecrets == null)
            {
                if (initializer.ClientSecretsStream == null)
                {
                    throw new ArgumentException("You MUST set ClientSecret or ClientSecretStream on the initializer");
                }

                using (initializer.ClientSecretsStream)
                {
                    clientSecrets = GoogleClientSecrets.Load(initializer.ClientSecretsStream).Secrets;
                }
            }
            else if (initializer.ClientSecretsStream != null)
            {
                throw new ArgumentException(
                    "You CAN'T set both ClientSecrets AND ClientSecretStream on the initializer");
            }

            accessMethod = initializer.AccessMethod.ThrowIfNull("Initializer.AccessMethod");
            clock = initializer.Clock.ThrowIfNull("Initializer.Clock");
            tokenServerUrl = initializer.TokenServerUrl.ThrowIfNullOrEmpty("Initializer.TokenServerUrl");
            authorizationServerUrl = initializer.AuthorizationServerUrl.ThrowIfNullOrEmpty
                ("Initializer.AuthorizationServerUrl");

            dataStore = initializer.DataStore;
            if (dataStore == null)
            {
                Logger.Warning("Datastore is null, as a result the user's credential will not be stored");
            }
            scopes = initializer.Scopes;

            // Set the HTTP client.
            var httpArgs = new CreateHttpClientArgs();

            // Add exponential back-off initializer if necessary.
            if (initializer.DefaultExponentialBackOffPolicy != ExponentialBackOffPolicy.None)
            {
                httpArgs.Initializers.Add(
                    new ExponentialBackOffInitializer(initializer.DefaultExponentialBackOffPolicy,
                        () => new BackOffHandler(new ExponentialBackOff())));
            }
            httpClient = (initializer.HttpClientFactory ?? new HttpClientFactory()).CreateHttpClient(httpArgs);
        }
예제 #45
0
 static public bool init(Initializer initializer)
 {
     return(true);
 }
예제 #46
0
 public override IAttributeInstance NewInstance(
     Initializer initializeState
     )
 {
     return(new NormalizedAttribute.TransformedInstance(this, initializeState));
 }
        /// <summary>Constructs a new service account credential using the given initializer.</summary>
        public ServiceCredential(Initializer initializer)
        {
            tokenServerUrl = initializer.TokenServerUrl;
            accessMethod = initializer.AccessMethod.ThrowIfNull("initializer.AccessMethod");
            clock = initializer.Clock.ThrowIfNull("initializer.Clock");

            // Set the HTTP client.
            var httpArgs = new CreateHttpClientArgs();

            // Add exponential back-off initializer if necessary.
            if (initializer.DefaultExponentialBackOffPolicy != ExponentialBackOffPolicy.None)
            {
                httpArgs.Initializers.Add(
                    new ExponentialBackOffInitializer(initializer.DefaultExponentialBackOffPolicy,
                        () => new BackOffHandler(new ExponentialBackOff())));
            }
            httpClient = (initializer.HttpClientFactory ?? new HttpClientFactory()).CreateHttpClient(httpArgs);
        }
예제 #48
0
 private static void RefreshMemoryWorkers()
 {
     Initializer.RefreshMemoryWorkers();
 }
 public MockClientService(Initializer initializer, string baseUri = @"https://testexample.google.com")
     : base(initializer)
 {
     _baseUri = baseUri;
 }
 /// <summary>Constructs a new Compute credential instance.</summary>
 public ComputeCredential(Initializer initializer) : base(initializer) { }
예제 #51
0
 public YoutubeResult(Initializer initializer) : base(initializer)
 {
 }
예제 #52
0
 private static void OnLoad(EventArgs args)
 {
     // ReSharper disable once UnusedVariable
     var init=new Initializer();
 }
예제 #53
0
 /// <summary>
 /// 获取服务实例事件
 /// </summary>
 private static void InstanceProvider_OnGetInstance(InstanceContext instanceContext)
 {
     //初始化SessionId
     Initializer.InitSessionId();
 }
 /// <summary>Constructs a new Google authorization code flow.</summary>
 public GoogleAuthorizationCodeFlow(Initializer initializer)
     : base(initializer)
 {
     revokeTokenUrl = initializer.RevokeTokenUrl;
     includeGrantedScopes = initializer.IncludeGrantedScopes;
 }
 /// <summary>Constructs a new service account credential using the given initializer.</summary>
 /// <param name="initializer"></param>
 public ServiceAccountCredential(Initializer initializer) : base(initializer)
 {
     id = initializer.Id.ThrowIfNullOrEmpty("initializer.Id");
     user = initializer.User;
     scopes = initializer.Scopes;
     key = initializer.Key.ThrowIfNull("initializer.Key");
 }
예제 #56
0
 public bool init(Initializer init)
 {
     return(true);
 }
예제 #57
0
파일: AppDomain.cs 프로젝트: rabink/mono
		public static AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup info)
		{
			if (friendlyName == null)
				throw new System.ArgumentNullException ("friendlyName");

			AppDomain def = AppDomain.DefaultDomain;
			if (info == null) {
				// if null, get default domain's SetupInformation	
				if (def == null)
					info = new AppDomainSetup ();	// we're default!
				else
					info = def.SetupInformation;
			}
			else
				info = new AppDomainSetup (info);	// copy

			// todo: allow setup in the other domain
			if (def != null) {
				if (!info.Equals (def.SetupInformation)) {
					// If not specified use default domain's app base.
					if (info.ApplicationBase == null)
						info.ApplicationBase = def.SetupInformation.ApplicationBase;
					if (info.ConfigurationFile == null)
						info.ConfigurationFile = Path.GetFileName (def.SetupInformation.ConfigurationFile);
				}
			} else if (info.ConfigurationFile == null)
				info.ConfigurationFile = "[I don't have a config file]";

#if !NET_2_1
			if (info.AppDomainInitializer != null) {
				if (!info.AppDomainInitializer.Method.IsStatic)
					throw new ArgumentException ("Non-static methods cannot be invoked as an appdomain initializer");
			}
#endif

			info.SerializeNonPrimitives ();

			AppDomain ad = (AppDomain) RemotingServices.GetDomainProxy (createDomain (friendlyName, info));
			if (securityInfo == null) {
				// get default domain's Evidence (unless we're are the default!)
				if (def == null)
					ad._evidence = null;		// we'll get them later (GetEntryAssembly)
				else
					ad._evidence = def.Evidence;	// new (shallow) copy
			}
			else
				ad._evidence = new Evidence (securityInfo);	// copy

#if !NET_2_1
			if (info.AppDomainInitializer != null) {
				Loader loader = new Loader (
					info.AppDomainInitializer.Method.DeclaringType.Assembly.Location);
				ad.DoCallBack (loader.Load);

				Initializer initializer = new Initializer (
					info.AppDomainInitializer,
					info.AppDomainInitializerArguments);
				ad.DoCallBack (initializer.Initialize);
			}
#endif

			return ad;
		}
예제 #58
0
 /// <summary>
 /// Standardkonstruktor
 /// </summary>
 /// <param name="initializer"></param>
 public ForceOfflineGoogleAuthorizationCodeFlow(Initializer initializer) : base(initializer)
 {
 }
예제 #59
0
 /// <summary>Constructs a new back-off handler with the given initializer.</summary>
 public BackOffHandler(Initializer initializer)
 {
     BackOff = initializer.BackOff;
     MaxTimeSpan = initializer.MaxTimeSpan;
     HandleExceptionFunc = initializer.HandleExceptionFunc;
     HandleUnsuccessfulResponseFunc = initializer.HandleUnsuccessfulResponseFunc;
 }
예제 #60
0
 public static Animate Create(Initializer initializer)
 => new Gnu(initializer.ID, initializer.StartRoom);