问:
Laravel Route [admin.home.index] not defined
This doesn't happen in my localhost and it only happens periodically and not a constant hit.

I have tried:

```<code>php artisan optimize:clear
php artisan route:clear
php artisan config:clear
php artisan cache:clear
</code>```

Clean all cache files on bootstrap/cache/*

I'm using Laravel 5.7, weird thing is it only happens sometimes and not all the time...

If i run php artisan config:cache, the whole site will be not usable, i'll need to run php artisan config:clear again to make it working again.

Artisan list:

All routes are there with their names etc.

My route file:

```<code>Route::namespace('Admin')->group(function () {

        Route::name('admin.logout')->get('/logout', 'LoginController@logout');

        Route::name('admin.home.index')->get('/', 'HomeController@index');

        Route::name('admin.user.index')->get('/user', 'UserController@index');
        Route::get('/user/dt', 'UserController@dt')->name('admin.user.dt');
        Route::get('/user/edit/{id}', 'UserController@edit')->name('admin.user.edit');
        Route::post('/user/edit/{id}', 'UserController@update')->name('admin.user.update');
        Route::post('/user/adjust/{id}', 'UserController@adjust')->name('admin.user.adjust');
        Route::get('/user/get/{username}', 'UserController@getUserByUsername')->name('admin.user.get');

        Route::get('/cron/remove', 'CronController@remove');
    });
</code>```

Stack trace:

```<code>[2019-10-09 17:03:05] production.ERROR: Route [admin.home.index] not defined. (View: /var/www/html/admimsystem/resources/views/admin/layouts/default.blade.php) (View: /var/www/html/admimsystem/resources/views/admin/layouts/default.blade.php) {"userId":780616,"exception":"[object] (ErrorException(code: 0): Route [admin.home.index] not defined. (View: /var/www/html/admimsystem/resources/views/admin/layouts/default.blade.php) (View: /var/www/html/admimsystem/resources/views/admin/layouts/default.blade.php) at /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php:374, ErrorException(code: 0): Route [admin.home.index] not defined. (View: /var/www/html/admimsystem/resources/views/admin/layouts/default.blade.php) at /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php:374, InvalidArgumentException(code: 0): Route [admin.home.index] not defined. at /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php:374)
[stacktrace]
#0 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/View/Engines/PhpEngine.php(45): Illuminate\\View\\Engines\\CompilerEngine->handleViewException(Object(ErrorException), 1)
#1 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php(59): Illuminate\\View\\Engines\\PhpEngine->evaluatePath('/var/www/html/y...', Array)
#2 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/View/View.php(142): Illuminate\\View\\Engines\\CompilerEngine->get('/var/www/html/y...', Array)
#3 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/View/View.php(125): Illuminate\\View\\View->getContents()
#4 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/View/View.php(90): Illuminate\\View\\View->renderContents()
#5 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Http/Response.php(42): Illuminate\\View\\View->render()
#6 /var/www/html/admimsystem/vendor/symfony/http-foundation/Response.php(202): Illuminate\\Http\\Response->setContent(Object(Illuminate\\View\\View))
#7 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Router.php(747): Symfony\\Component\\HttpFoundation\\Response->__construct(Object(Illuminate\\View\\View))
#8 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Router.php(719): Illuminate\\Routing\\Router::toResponse(Object(Illuminate\\Http\\Request), Object(Illuminate\\View\\View))
#9 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Router.php(679): Illuminate\\Routing\\Router->prepareResponse(Object(Illuminate\\Http\\Request), Object(Illuminate\\View\\View))
#10 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(30): Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#11 /var/www/html/admimsystem/app/Http/Controllers/Controller.php(24): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#12 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(133): App\\Http\\Controllers\\Controller->App\\Http\\Controllers\\{closure}(Object(Illuminate\\Http\\Request), Object(Closure))
#13 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#14 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(43): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#15 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Auth\\Middleware\\Authenticate->handle(Object(Illuminate\\Http\\Request), Object(Closure), 'admin')
#16 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#17 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#18 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Routing\\Middleware\\SubstituteBindings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#19 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#20 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(75): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#21 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#22 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#23 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Session/Middleware/AuthenticateSession.php(39): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#24 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Session\\Middleware\\AuthenticateSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#25 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#26 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#27 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\View\\Middleware\\ShareErrorsFromSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#28 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#29 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(63): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#30 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Session\\Middleware\\StartSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#31 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#32 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#33 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#34 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#35 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(66): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#36 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Cookie\\Middleware\\EncryptCookies->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#37 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#38 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#39 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Router.php(681): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
</code>```

答:
Go to web.php

php artisan route:list

Check routes with controller
https://laravel.com/docs/9.x/routing

Body:
This doesn't happen in my localhost and it only happens periodically and not a constant hit.

I have tried:

php artisan optimize:clear
php artisan route:clear
php artisan config:clear
php artisan cache:clear

Clean all cache files on bootstrap/cache/*

I'm using Laravel 5.7, weird thing is it only happens sometimes and not all the time...

If i run php artisan config:cache, the whole site will be not usable, i'll need to run php artisan config:clear again to make it working again.

Artisan list:

All routes are there with their names etc.

My route file:

Route::namespace('Admin')->group(function () {

        Route::name('admin.logout')->get('/logout', 'LoginController@logout');

        Route::name('admin.home.index')->get('/', 'HomeController@index');

        Route::name('admin.user.index')->get('/user', 'UserController@index');
        Route::get('/user/dt', 'UserController@dt')->name('admin.user.dt');
        Route::get('/user/edit/{id}', 'UserController@edit')->name('admin.user.edit');
        Route::post('/user/edit/{id}', 'UserController@update')->name('admin.user.update');
        Route::post('/user/adjust/{id}', 'UserController@adjust')->name('admin.user.adjust');
        Route::get('/user/get/{username}', 'UserController@getUserByUsername')->name('admin.user.get');

        Route::get('/cron/remove', 'CronController@remove');
    });

Stack trace:

[2019-10-09 17:03:05] production.ERROR: Route [admin.home.index] not defined. (View: /var/www/html/admimsystem/resources/views/admin/layouts/default.blade.php) (View: /var/www/html/admimsystem/resources/views/admin/layouts/default.blade.php) {"userId":780616,"exception":"[object] (ErrorException(code: 0): Route [admin.home.index] not defined. (View: /var/www/html/admimsystem/resources/views/admin/layouts/default.blade.php) (View: /var/www/html/admimsystem/resources/views/admin/layouts/default.blade.php) at /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php:374, ErrorException(code: 0): Route [admin.home.index] not defined. (View: /var/www/html/admimsystem/resources/views/admin/layouts/default.blade.php) at /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php:374, InvalidArgumentException(code: 0): Route [admin.home.index] not defined. at /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php:374)
[stacktrace]
#0 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/View/Engines/PhpEngine.php(45): Illuminate\\View\\Engines\\CompilerEngine->handleViewException(Object(ErrorException), 1)
#1 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php(59): Illuminate\\View\\Engines\\PhpEngine->evaluatePath('/var/www/html/y...', Array)
#2 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/View/View.php(142): Illuminate\\View\\Engines\\CompilerEngine->get('/var/www/html/y...', Array)
#3 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/View/View.php(125): Illuminate\\View\\View->getContents()
#4 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/View/View.php(90): Illuminate\\View\\View->renderContents()
#5 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Http/Response.php(42): Illuminate\\View\\View->render()
#6 /var/www/html/admimsystem/vendor/symfony/http-foundation/Response.php(202): Illuminate\\Http\\Response->setContent(Object(Illuminate\\View\\View))
#7 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Router.php(747): Symfony\\Component\\HttpFoundation\\Response->__construct(Object(Illuminate\\View\\View))
#8 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Router.php(719): Illuminate\\Routing\\Router::toResponse(Object(Illuminate\\Http\\Request), Object(Illuminate\\View\\View))
#9 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Router.php(679): Illuminate\\Routing\\Router->prepareResponse(Object(Illuminate\\Http\\Request), Object(Illuminate\\View\\View))
#10 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(30): Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#11 /var/www/html/admimsystem/app/Http/Controllers/Controller.php(24): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#12 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(133): App\\Http\\Controllers\\Controller->App\\Http\\Controllers\\{closure}(Object(Illuminate\\Http\\Request), Object(Closure))
#13 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#14 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(43): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#15 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Auth\\Middleware\\Authenticate->handle(Object(Illuminate\\Http\\Request), Object(Closure), 'admin')
#16 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#17 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#18 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Routing\\Middleware\\SubstituteBindings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#19 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#20 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(75): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#21 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#22 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#23 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Session/Middleware/AuthenticateSession.php(39): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#24 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Session\\Middleware\\AuthenticateSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#25 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#26 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#27 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\View\\Middleware\\ShareErrorsFromSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#28 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#29 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(63): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#30 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Session\\Middleware\\StartSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#31 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#32 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#33 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#34 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#35 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(66): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#36 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\\Cookie\\Middleware\\EncryptCookies->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#37 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#38 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#39 /var/www/html/admimsystem/vendor/laravel/framework/src/Illuminate/Routing/Router.php(681): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))


来源: stackexchange

问:
Trying to use dynamic rendering extension, validation layers complain about missing renderpass
I want to use the dynamic rendering extension to finally be free of renderpasses.

However when i try to make a pipeline my validation layers yell:

required parameter pCreateInfos[0].renderPass specified as VK_NULL_HANDLE

For this createinfo.

```<code>
    vk::GraphicsPipelineCreateInfo pipelineInfo{};
    pipelineInfo.stageCount = 2;
    pipelineInfo.pStages = shaderStages;
    pipelineInfo.pVertexInputState = &vertexInputInfo;
    pipelineInfo.pInputAssemblyState = &inputAssembly;
    pipelineInfo.pViewportState = &viewportState;
    pipelineInfo.pRasterizationState = &rasterizer;
    pipelineInfo.pMultisampleState = &multisampling;
    pipelineInfo.pColorBlendState = &colorBlending;
    pipelineInfo.layout = pipelineLayout;
    pipelineInfo.pDynamicState = &dynamicState;
    pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
</code>```

I am trying to follow this example: https://github.com/SaschaWillems/Vulkan/blob/master/examples/dynamicrendering/dynamicrendering.cpp

How do I let vulkan know that I don;t need a renderpass?

Setup code

```<code>
    vk::PhysicalDeviceDynamicRenderingFeaturesKHR dynamic_rendering = {};
    dynamic_rendering.dynamicRendering = true;

    features.pNext = &dynamic_rendering;

    // Setup general information about the current application.
    vk::ApplicationInfo program_info(
        "NeverEngine",
        VK_MAKE_VERSION(1, 0, 0),
        "No Engine",
        VK_MAKE_VERSION(1, 0, 0),
        VK_API_VERSION_1_2);
    // Create Vulkan instance to communicate with the loader.
    vk::InstanceCreateInfo create_info = {};
    create_info.pNext = &features;
    create_info.pApplicationInfo = &program_info,
    create_info.enabledLayerCount = static_cast<uint32_t>(VALIDATION_LAYERS.size()),
    create_info.ppEnabledLayerNames = VALIDATION_LAYERS.data(),
    create_info.enabledExtensionCount = static_cast<uint32_t>(required_extensions.size()),
    create_info.ppEnabledExtensionNames = required_extensions.data();

    auto [result, instance] = vk::createInstanceUnique(create_info);
    Assert(result == vk::Result::eSuccess, "Error: Failed to create instance");
</code>```

It seems from the error messages the validation layers are version 1.2.198

答:
From changelog:

VK_KHR_dynamic_rendering (Note: Validation Layer support is incomplete, incorrect results are possible)

ContentLicense: CC BY-SA 4.0

Body:
I want to use the dynamic rendering extension to finally be free of renderpasses.

However when i try to make a pipeline my validation layers yell:

required parameter pCreateInfos[0].renderPass specified as VK_NULL_HANDLE

For this createinfo.

    vk::GraphicsPipelineCreateInfo pipelineInfo{};
    pipelineInfo.stageCount = 2;
    pipelineInfo.pStages = shaderStages;
    pipelineInfo.pVertexInputState = &vertexInputInfo;
    pipelineInfo.pInputAssemblyState = &inputAssembly;
    pipelineInfo.pViewportState = &viewportState;
    pipelineInfo.pRasterizationState = &rasterizer;
    pipelineInfo.pMultisampleState = &multisampling;
    pipelineInfo.pColorBlendState = &colorBlending;
    pipelineInfo.layout = pipelineLayout;
    pipelineInfo.pDynamicState = &dynamicState;
    pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;

I am trying to follow this example: https://github.com/SaschaWillems/Vulkan/blob/master/examples/dynamicrendering/dynamicrendering.cpp

How do I let vulkan know that I don;t need a renderpass?

Setup code

    vk::PhysicalDeviceDynamicRenderingFeaturesKHR dynamic_rendering = {};
    dynamic_rendering.dynamicRendering = true;

    features.pNext = &dynamic_rendering;

    // Setup general information about the current application.
    vk::ApplicationInfo program_info(
        "NeverEngine",
        VK_MAKE_VERSION(1, 0, 0),
        "No Engine",
        VK_MAKE_VERSION(1, 0, 0),
        VK_API_VERSION_1_2);
    // Create Vulkan instance to communicate with the loader.
    vk::InstanceCreateInfo create_info = {};
    create_info.pNext = &features;
    create_info.pApplicationInfo = &program_info,
    create_info.enabledLayerCount = static_cast<uint32_t>(VALIDATION_LAYERS.size()),
    create_info.ppEnabledLayerNames = VALIDATION_LAYERS.data(),
    create_info.enabledExtensionCount = static_cast<uint32_t>(required_extensions.size()),
    create_info.ppEnabledExtensionNames = required_extensions.data();

    auto [result, instance] = vk::createInstanceUnique(create_info);
    Assert(result == vk::Result::eSuccess, "Error: Failed to create instance");

It seems from the error messages the validation layers are version 1.2.198


问:
Why Sub query in leftjoin in typeorm giving me error?
If i am defining innerjoin or leftjoin in subquery of leftjoinandselect, then it is giving me error sqlMessage: "Duplicate column name 'id'".

For example

```<code>.leftJoinAndSelect(
            (qb) =>
              qb
                .from(Email, 'email')
                .innerJoin(User, 'user')
                .where('user.account = :account', {
                  accountId: 4,
                }),
            'email',
            '`email`.`id` = 1',
          )
</code>```

The above will give me error "Duplicate column name 'id'"

But if i remove innerJoin then it is working fine and giving expected result.

```<code>.leftJoinAndSelect(
                (qb) =>
                  qb
                    .from(Email, 'email'),
                'email',
                '`email`.`id` = 1',
              )
</code>```

Any idea why is it giving me this error.

答:
I think the problem is that both email and user tables have id columns.
Can you try the following code?:

.leftJoinAndSelect(
            (qb) =>
              qb
                .select("user.id", "user_id")
                .addSelect("email.id", "email_id")
                // Add whatever you want by .addSelect method
                .from(Email, 'email')
                .innerJoin(User, 'user')
                .where('user.account = :account', {
                  accountId: 4,
                }),
            'email',
            '`email`.`id` = 1',
          )
```

Body:
If i am defining innerjoin or leftjoin in subquery of leftjoinandselect, then it is giving me error sqlMessage: "Duplicate column name 'id'".

For example

.leftJoinAndSelect(
            (qb) =>
              qb
                .from(Email, 'email')
                .innerJoin(User, 'user')
                .where('user.account = :account', {
                  accountId: 4,
                }),
            'email',
            '`email`.`id` = 1',
          )

The above will give me error "Duplicate column name 'id'"

But if i remove innerJoin then it is working fine and giving expected result.

.leftJoinAndSelect(
                (qb) =>
                  qb
                    .from(Email, 'email'),
                'email',
                '`email`.`id` = 1',
              )

Any idea why is it giving me this error.


问:
What is the equivalent of reuseForks=false in Bazel?
I want to set reuseForks=false in Bazel, so my tests don't reuse the same JVM process. How can I do that in Bazel?

According to https://maven.apache.org/surefire/maven-surefire-plugin/examples/fork-options-and-parallel-execution.html

The parameter reuseForks is used to define whether to terminate the spawned process after one test class and to create a new process for the next test in line (reuseForks=false), or whether to reuse the processes to execute the next tests (reuseForks=true).

The default setting is forkCount=1/reuseForks=true, which means that maven-surefire-plugin creates one new JVM process to execute all tests in one Maven module.

forkCount=1/reuseForks=false executes each test class in its own JVM process, one after another. It creates the highest level of separation for the test execution, but it would probably also give you the longest execution time of all the available options. Consider it as a last resort.

答:
By default Bazel doesn't reuse the same JVM process for tests, that functionality is hidden behind an experimental flag.

From the Bazel docs:

--[no]experimental_persistent_test_runner default: "false"

Allows running java_test targets locally within a persistent worker. To enable the persistent test runner one must run bazel test with the flags:--test_strategy=local --strategy=TestRunner=worker --experimental_persistent_test_runner


问:
struct in union nested - understanding behaviour of type punning
The following code uses a structure inside a union inside a structure inside a union.

```<code>#include <cstdio>

union
{
    char abcd[4];
    struct
    {
        unsigned ab : 16;
        union
        {
            unsigned xyz : 8;
            struct
            {
                unsigned x : 3;
                unsigned y : 5;
            };
        };
//      unsigned x : 3;
//      unsigned y : 5;
        unsigned d : 8;
    };
} SpringOnion;

int main ()
{
    SpringOnion.ab = 0xfe57;
    SpringOnion.x = 0x5;
    SpringOnion.y = 0x1c;
    SpringOnion.d = 0xfa;

    printf("%x %x %x\n", SpringOnion.x, SpringOnion.y, SpringOnion.xyz);
    printf("%x %x %x %x\n", SpringOnion.abcd[0], SpringOnion.abcd[1], SpringOnion.abcd[2], SpringOnion.abcd[3]);

    return 0;
}
</code>```

I compiled using g++ (also checked with gcc) and got the following output on running:

```<code>5 1c e5
57 fffffffe 0 0
</code>```

Is that the expected output?

On defining the union in the following manner:

```<code>union
{
    char abcd[4];
    struct
    {
        unsigned ab : 16;
        union
        {
            unsigned xyz;
            struct
            {
                unsigned x : 3;
                unsigned y : 5;
            };
        }c : 8;
        unsigned d : 8;
    };
} SpringOnion;
</code>```

I get the compilation error:
error: bit-field ‘c’ with non-integral type ‘<unnamed union>::<unnamed struct>::<unnamed union>’
which, on checking up, gives answers which seem to me to be not perfectly relatable.
The answer by Jonathan Leffler https://stackoverflow.com/a/18730706/7920584 points out by saying:

Structures, unions: but then you aren't dealing with simple fields.

But then what kind of field should I be using? Is there something else that can meet my expectations?

Expectation:-
I expect the output to be:

```<code>5 1c e5
57 fffffffe ffffffe5 fffffffa
</code>```

Which is similar to what I get upon removing the nested union and using the x :3; and y :5; directly in the main struct.

May I know why I am expecting wrong?

答:
```<code>printf("%x %x %x\n", SpringOnion.x, SpringOnion.y, SpringOnion.xyz);
                                                               ^^^
printf("%x %x %x %x\n", SpringOnion.abcd[0], SpringOnion.abcd[1], SpringOnion.abcd[2], SpringOnion.abcd[3]);
                                    ^^^^                 ^^^^                 ^^^^                 ^^^^
</code>```

Here, you read from an inactive member of a union. You aren't allowed to do that in C++. The behaviour of the program is undefined.

Is that the expected output?

There is no portable expectation for the output. Even if we were to assume that there is a reasonable behaviour defined by the language implementation for reading an inactive union member, there's still no precise definition for allocation of bitfields in the language. That is implementation defined in most regards (in practice, it's determined by the ABI, which varies across different systems).

Furthermore, you have anonymous structs in your union. Anonymous structs are not allowed in C++. The program is ill-formed.

Body:
The following code uses a structure inside a union inside a structure inside a union.

#include <cstdio>

union
{
    char abcd[4];
    struct
    {
        unsigned ab : 16;
        union
        {
            unsigned xyz : 8;
            struct
            {
                unsigned x : 3;
                unsigned y : 5;
            };
        };
//      unsigned x : 3;
//      unsigned y : 5;
        unsigned d : 8;
    };
} SpringOnion;

int main ()
{
    SpringOnion.ab = 0xfe57;
    SpringOnion.x = 0x5;
    SpringOnion.y = 0x1c;
    SpringOnion.d = 0xfa;

    printf("%x %x %x\n", SpringOnion.x, SpringOnion.y, SpringOnion.xyz);
    printf("%x %x %x %x\n", SpringOnion.abcd[0], SpringOnion.abcd[1], SpringOnion.abcd[2], SpringOnion.abcd[3]);

    return 0;
}

I compiled using g++ (also checked with gcc) and got the following output on running:

5 1c e5
57 fffffffe 0 0

Is that the expected output?

On defining the union in the following manner:

union
{
    char abcd[4];
    struct
    {
        unsigned ab : 16;
        union
        {
            unsigned xyz;
            struct
            {
                unsigned x : 3;
                unsigned y : 5;
            };
        }c : 8;
        unsigned d : 8;
    };
} SpringOnion;

I get the compilation error:
error: bit-field ‘c’ with non-integral type ‘<unnamed union>::<unnamed struct>::<unnamed union>’
which, on checking up, gives answers which seem to me to be not perfectly relatable.
The answer by Jonathan Leffler https://stackoverflow.com/a/18730706/7920584 points out by saying:

Structures, unions: but then you aren't dealing with simple fields.

But then what kind of field should I be using? Is there something else that can meet my expectations?

Expectation:-
I expect the output to be:

5 1c e5
57 fffffffe ffffffe5 fffffffa

Which is similar to what I get upon removing the nested union and using the x :3; and y :5; directly in the main struct.

May I know why I am expecting wrong?

Body:
printf("%x %x %x\n", SpringOnion.x, SpringOnion.y, SpringOnion.xyz);
                                                               ^^^
printf("%x %x %x %x\n", SpringOnion.abcd[0], SpringOnion.abcd[1], SpringOnion.abcd[2], SpringOnion.abcd[3]);
                                    ^^^^                 ^^^^                 ^^^^                 ^^^^

Here, you read from an inactive member of a union. You aren't allowed to do that in C++. The behaviour of the program is undefined.

Is that the expected output?

There is no portable expectation for the output. Even if we were to assume that there is a reasonable behaviour defined by the language implementation for reading an inactive union member, there's still no precise definition for allocation of bitfields in the language. That is implementation defined in most regards (in practice, it's determined by the ABI, which varies across different systems).

Furthermore, you have anonymous structs in your union. Anonymous structs are not allowed in C++. The program is ill-formed.


问:
How to check newly generated logfile on a folder path
I'm working on a simple script wherein I wanted to check if a log contains a specific string and give me an output if it contains the string or not. However the logfile gets updated daily and I wanted to check the most recent file. Is there a command I can add to my script to get the output I needed?. Or is there other way I can do this without using Select-String?.</p>
```<code>$SEL = Select-String -Path Pathfile.LOG -Pattern "String"
if ($SEL -ne $null)
{
    echo Contains String
}
else
{
    echo Not Contains String
}}
</code>```

答:
If the desired log file was most recently written, this might do what you want.</p>
```<code>$SEL = Get-ChildItem -Path 'C:\log\dir' -Filter '*.log' |
    Sort-Object -Property LastWriteTime |
    Select-Object -Last 1 |
    Select-String -Pattern 'String'
</code>```

Body:
I'm working on a simple script wherein I wanted to check if a log contains a specific string and give me an output if it contains the string or not. However the logfile gets updated daily and I wanted to check the most recent file. Is there a command I can add to my script to get the output I needed?. Or is there other way I can do this without using Select-String?.

$SEL = Select-String -Path Pathfile.LOG -Pattern "String"
if ($SEL -ne $null)
{
    echo Contains String
}
else
{
    echo Not Contains String
}}

Body:
If the desired log file was most recently written, this might do what you want.

$SEL = Get-ChildItem -Path 'C:\log\dir' -Filter '*.log' |
    Sort-Object -Property LastWriteTime |
    Select-Object -Last 1 |
    Select-String -Pattern 'String'


问:
Common interface to object and array
I wrote a Typescript function where my argument could be either a string's array or a raw object.

its prototype is:

```<code>export const myFunction = async (line: string[] | myCustomType, config: any): Promise<String> => {
  if (line?.length < 2)
    //line is a string[]
  else
    //line is a mysCustomType
}
</code>```

Where myCustomType is a raw object with a lot of properties / method.

In JavaScript I would have just tried to access to line?.length and if it would have been undefined I would have treated line like an instance of myCustomType (because myCustomType doesn't have length properties.

an array being an object, I already created a method in the Object class allowing me to directly differences the two type:

```<code>declare global {
  interface Object {
    isCustom(): boolean;
  }
}

Object.prototype.isCustom = function () {
  return false;
};
</code>```

Where the method isCustom already exist in type myCustomType and doesn't return false. So I can differencies line's type, but the typescript doesn't allow me to compile.

```<code>Property 'length' does not exist on type 'string[] | myCustomType'.
  Property 'length' does not exist on type 'myCustomType'
</code>```

Shall I declare line's type to be of Object and use my isCustom() method ? or is it uggly ?

Any ideas to get rid of this problem ?

答:
The proper logic is

```<code>var isStringArray = false;
if (Array.isArray(line)) {
    isStringArray = true;
    line.forEach(function(item) {
        if (typeof item !== "string") {
            isStringArray = false;
        }
    });
}
</code>```

Explanation: you need to check whether your variable is an array and then whether all its members are strings. Your way of checking for the value of length and validating based on that is incorrect even in principle, because your custom object may have a length member even if it's not an array. Also, in practice, your string array could have a length of 1 or 0 as well and it would be a string array even then.

Title: Common interface to object and array

Body:
I wrote a Typescript function where my argument could be either a string's array or a raw object.

its prototype is:

export const myFunction = async (line: string[] | myCustomType, config: any): Promise<String> => {
  if (line?.length < 2)
    //line is a string[]
  else
    //line is a mysCustomType
}

Where myCustomType is a raw object with a lot of properties / method.

In JavaScript I would have just tried to access to line?.length and if it would have been undefined I would have treated line like an instance of myCustomType (because myCustomType doesn't have length properties.

an array being an object, I already created a method in the Object class allowing me to directly differences the two type:

declare global {
  interface Object {
    isCustom(): boolean;
  }
}

Object.prototype.isCustom = function () {
  return false;
};

Where the method isCustom already exist in type myCustomType and doesn't return false. So I can differencies line's type, but the typescript doesn't allow me to compile.

Property 'length' does not exist on type 'string[] | myCustomType'.
  Property 'length' does not exist on type 'myCustomType'

Shall I declare line's type to be of Object and use my isCustom() method ? or is it uggly ?

Any ideas to get rid of this problem ?

Body:
The proper logic is

var isStringArray = false;
if (Array.isArray(line)) {
    isStringArray = true;
    line.forEach(function(item) {
        if (typeof item !== "string") {
            isStringArray = false;
        }
    });
}

Explanation: you need to check whether your variable is an array and then whether all its members are strings. Your way of checking for the value of length and validating based on that is incorrect even in principle, because your custom object may have a length member even if it's not an array. Also, in practice, your string array could have a length of 1 or 0 as well and it would be a string array even then.


问:
laravel bulk sms notification sending
hello I'm new for laravel I'm trying to send SMS notification from api.

I'm using 3rd party service for sending sms thy have less documentation for php code integration. and API URL

When I tried in laravel form controller when form submit sms notification will triggers by this
but problem is my API User name and passwords displayed in browser URL and inspect network tab too is was problem I don't want to show my API Credentials to any one

```<code>return redirect()->away("http://api.bulksmsgateway.in/sendmessage.php?user=....&password=.......&mobile=........&message=hello&sender=.......&type=3&template_id=123");
</code>```

** php code integration service provider document**

```<code><?php
error_reporting (E_ALL ^ E_NOTICE);
$username="XXXXXXX";
$password ="XXXXXXX";
$number=$_POST['number'];
$sender="abc";
$message=$_POST['message'];
$template_id='12345';
if($_POST['submitted']=='true')
{
$url="http://api.bulksmsgateway.in/sendmessage.php?user=".urlencode($username)."&password=".urlencode($password)."&mobile=".urlencode($number)."&sender=".urlencode($sender)."&message=".urlencode($message)."&type=".urlencode('3')."&template_id=".urlencode($template_id);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $curl_scraped_page = curl_exec($ch);
curl_close($ch);
}

?>
<html>
<head>
</head>
<body>
<form action="" method="post" name="sms_gate" >
<br />
Number : <br />
<input type="text" name="number" />
<br /><br />
Message:<br/>
<textarea name="message" ></textarea>
<input type="hidden" name="submitted" value="true" />
<br />
<input type="submit" name="submit" value="send" />
</form>
</body>
</html>
</code>```

** API URL code integration service provider document provided this**

```<code>URL : http://api.bulksmsgateway.in/sendmessage.php?user=....&password=.......&mobile=........&message=hello&sender=.......&type=3&template_id=123
</code>```

my controller

```<code>public function Store_Enrollment(Request $request)

    {

      $this->validate($request, [

  'student_name' => 'required|string|max:255',
  'student_phone_no' => 'required|string|max:10',

    ]);

   $input['student_name'] = ucfirst ($request['student_name']);
   $input['student_phone_no'] = $request->student_phone_no;
   $redirect = Student::create($input);

return redirect()->away("http://api.bulksmsgateway.in/sendmessage.php?user=XXX&password=XXX&mobile=$redirect->student_phone_no&message=Dear  $redirect->student_name,  G&sender=ABC&type=3&template_id=112");

}
</code>```

答:
In my case, I use Laravel Trait and guzzlehttp/guzzle Package to send bulk sms.
The steps I did was something like below

i) I installed guzzlehttp/guzzle Package. Associated documentation is https://laravel.com/docs/8.x/http-client.

ii) I created Laravel trait class. Inside the trait class, I write a method to send SMS. I use CURL to call the third party SMS API.

iii) In the controller I import the Trait class and call the SMS sending trait method from there.

I hope this steps help.

Title: laravel bulk sms notification sending

Body:
hello I'm new for laravel I'm trying to send SMS notification from api.

I'm using 3rd party service for sending sms thy have less documentation for php code integration. and API URL

When I tried in laravel form controller when form submit sms notification will triggers by this
but problem is my API User name and passwords displayed in browser URL and inspect network tab too is was problem I don't want to show my API Credentials to any one

return redirect()->away("http://api.bulksmsgateway.in/sendmessage.php?user=....&password=.......&mobile=........&message=hello&sender=.......&type=3&template_id=123");

** php code integration service provider document**

<?php
error_reporting (E_ALL ^ E_NOTICE);
$username="XXXXXXX";
$password ="XXXXXXX";
$number=$_POST['number'];
$sender="abc";
$message=$_POST['message'];
$template_id='12345';
if($_POST['submitted']=='true')
{
$url="http://api.bulksmsgateway.in/sendmessage.php?user=".urlencode($username)."&password=".urlencode($password)."&mobile=".urlencode($number)."&sender=".urlencode($sender)."&message=".urlencode($message)."&type=".urlencode('3')."&template_id=".urlencode($template_id);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $curl_scraped_page = curl_exec($ch);
curl_close($ch);
}

?>

<form action="" method="post" name="sms_gate" >

Number :

<input type="text" name="number" />

Message:

<textarea name="message" ></textarea>
<input type="hidden" name="submitted" value="true" />

<input type="submit" name="submit" value="send" />
</form>

** API URL code integration service provider document provided this**

URL : http://api.bulksmsgateway.in/sendmessage.php?user=....&password=.......&mobile=........&message=hello&sender=.......&type=3&template_id=123

my controller

public function Store_Enrollment(Request $request)

    {

      $this->validate($request, [

  'student_name' => 'required|string|max:255',
  'student_phone_no' => 'required|string|max:10',

    ]);

   $input['student_name'] = ucfirst ($request['student_name']);
   $input['student_phone_no'] = $request->student_phone_no;
   $redirect = Student::create($input);

return redirect()->away("http://api.bulksmsgateway.in/sendmessage.php?user=XXX&password=XXX&mobile=$redirect->student_phone_no&message=Dear  $redirect->student_name,  G&sender=ABC&type=3&template_id=112");

}


问:
Inheritance problem in C#
I'm refactoring some code and want to classes a bit higher in the inheritance chain be a bit more strict with their parameters. As I'm not sure I'm explaining this correctly, here's what I've got:

```<code>public interface ISvdPredictor
{
    List<string> Users { get; set; }
    List<string> Artists { get; set; }
    float PredictRating(ISvdModel model, string user, string artist);
    float PredictRating(ISvdModel model, int userIndex, int artistIndex);
}
</code>```

ISvdPredictor uses ISvdModel:

```<code>public interface ISvdModel
{
    float[,] UserFeatures { get; set; }
    float[,] ArtistFeatures { get; set; }
}
</code>```

Now I want to implement another variation:

```<code>public interface IBiasSvdPredictor : ISvdPredictor
{
    float PredictRating(IBiasSvdModel model, string user, string artist);
    float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}
</code>```

Which uses IBiasSvdModel which derives from ISvdModel:

```<code>public interface IBiasSvdModel : ISvdModel
{
    float GlobalAverage { get; set; }
    float[] UserBias { get; set; }
    float[] ArtistBias { get; set; }
}
</code>```

IBiasSvdPredictor will not work with ISvdModel.

The problem is that when I implement IBiasSvdPredictor I'd have to implement 2 pairs of PredictRating methods. One from ISvdPredictor and the other from IBiasSvdPredictor. What do I need to do to be able to just implement those from IBiasSvdPredictor?

I've tried generics as well, but couldn't restrict the PredictRating for BiasSvdPredictor to IBiasSvdModel using the where directive. I may be doing this all wrong so any suggestion might help. I think you get what I'm trying to do.

EDIT: If anyone needs more context see https://github.com/gligoran/RecommendationSystem. I'm writing this code for my thesis for BSc.

答:
I'd have to implement 2 pairs of PredictRating methods.

Of course you do.  What did you expect?

If your IBiasSvdPredictor must take a IBiasSvdModel in its PredictRating method, than IBiasSvdPredictor is not an ISvdPredictor (because it cannot take a ISvdModel as the first parameter to PredictRating) and inheriting IBiasSvdPredictor from ISvdPredictor is the wrong choice.

In my opinion, you should simply keep the interfaces separate and not inherit one from the other.

ContentLicense: CC BY-SA 3.0

Title: Inheritance problem in C#

Body:
I'm refactoring some code and want to classes a bit higher in the inheritance chain be a bit more strict with their parameters. As I'm not sure I'm explaining this correctly, here's what I've got:

public interface ISvdPredictor
{
    List<string> Users { get; set; }
    List<string> Artists { get; set; }
    float PredictRating(ISvdModel model, string user, string artist);
    float PredictRating(ISvdModel model, int userIndex, int artistIndex);
}

ISvdPredictor uses ISvdModel:

public interface ISvdModel
{
    float[,] UserFeatures { get; set; }
    float[,] ArtistFeatures { get; set; }
}

Now I want to implement another variation:

public interface IBiasSvdPredictor : ISvdPredictor
{
    float PredictRating(IBiasSvdModel model, string user, string artist);
    float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}

Which uses IBiasSvdModel which derives from ISvdModel:

public interface IBiasSvdModel : ISvdModel
{
    float GlobalAverage { get; set; }
    float[] UserBias { get; set; }
    float[] ArtistBias { get; set; }
}

IBiasSvdPredictor will not work with ISvdModel.

The problem is that when I implement IBiasSvdPredictor I'd have to implement 2 pairs of PredictRating methods. One from ISvdPredictor and the other from IBiasSvdPredictor. What do I need to do to be able to just implement those from IBiasSvdPredictor?

I've tried generics as well, but couldn't restrict the PredictRating for BiasSvdPredictor to IBiasSvdModel using the where directive. I may be doing this all wrong so any suggestion might help. I think you get what I'm trying to do.

EDIT: If anyone needs more context see https://github.com/gligoran/RecommendationSystem. I'm writing this code for my thesis for BSc.


问:
Serialization of 'Illuminate\Http\UploadedFile' is not allowed laravel excel import
i am trying to import an excel using laravel excel package and trying to use the queue feature for that like below :

```<code> $import = new OrderFileImport($request->all());
 $import->Sheets('Sheet1');
 Excel::queueImport($import,$request->file('file'));
 return redirect()->back();
</code>```

and then in my FirstSheetImport i am doing like below :

```<code>class FirstSheetImport implements ToModel,WithStartRow,WithChunkReading,ShouldQueue
{
    private $request;
    public function __construct(array $request)
    {
        $this->request = $request;
    }
    /**
    * @param array $row
    */
    public function model(array $row)
    {

        return new Order([
            'id' => (string) Str::orderedUuid(),
            'shop_id' => 6696,

        ]);
    }
    public function startRow(): int
    {
        return 2;
    }
    public function chunkSize(): int
    {
     return 100;
    }
    public function batchSize(): int
    {
     return 100;
    }
}
</code>```

but when i send the request i get the error below :

```<code>Serialization of 'Illuminate\Http\UploadedFile' is not allowed
</code>```

i read over the net that its because i dont upload the file and sending it to job is not possible , but i saw it in storage/framework/laravel-excel its generating the temp files there .
thanks in advance

UPDATE 1

i have changed my controller to upload the file first and then pass it to queueimport like below :

```<code> $import = new OrderFileImport($request->all());
        $fileName = uniqid().'.xlsx';
        $request->file('file')->move(storage_path('/excels'),$fileName);
        $import->Sheets('Sheet1');
       Excel::queueImport($import,storage_path('excels/'.$fileName));
       return redirect()->back();
</code>```

but yet again the i got the same error :

```<code>Serialization of 'Illuminate\Http\UploadedFile' is not allowed

</code>```

答:
Your $request object contains an uploaded file, which cannot be serialized and should not be serialized. You cant pass that whole object to the Job, you have to pick out the components you need.

So instead, you should be passing a filepath to the file, such that the job can retrieve the file on its own instead of trying to pass it as an argument. Every argument you pass to a Job has to be serializable (like Eloquent models) since at one point it has be hydrated from the database.

Body:
i am trying to import an excel using laravel excel package and trying to use the queue feature for that like below :

 $import = new OrderFileImport($request->all());
 $import->Sheets('Sheet1');
 Excel::queueImport($import,$request->file('file'));
 return redirect()->back();

and then in my FirstSheetImport i am doing like below :

class FirstSheetImport implements ToModel,WithStartRow,WithChunkReading,ShouldQueue
{
    private $request;
    public function __construct(array $request)
    {
        $this->request = $request;
    }
    /**
    * @param array $row
    */
    public function model(array $row)
    {

        return new Order([
            'id' => (string) Str::orderedUuid(),
            'shop_id' => 6696,

        ]);
    }
    public function startRow(): int
    {
        return 2;
    }
    public function chunkSize(): int
    {
     return 100;
    }
    public function batchSize(): int
    {
     return 100;
    }
}

but when i send the request i get the error below :

Serialization of 'Illuminate\Http\UploadedFile' is not allowed

i read over the net that its because i dont upload the file and sending it to job is not possible , but i saw it in storage/framework/laravel-excel its generating the temp files there .
thanks in advance

UPDATE 1

i have changed my controller to upload the file first and then pass it to queueimport like below :

 $import = new OrderFileImport($request->all());
        $fileName = uniqid().'.xlsx';
        $request->file('file')->move(storage_path('/excels'),$fileName);
        $import->Sheets('Sheet1');
       Excel::queueImport($import,storage_path('excels/'.$fileName));
       return redirect()->back();

but yet again the i got the same error :

Serialization of 'Illuminate\Http\UploadedFile' is not allowed


问:
How to delete last 6 characters from a column in .xlsx file using R?
I have an .xlsx file with 845 rows and 61 columns, and one of the columns is a list of location names. Each cell in this column, however, ends with six unwanted characters like ' (001)', ' (014)' ' (013)', etc..., having a space, brackets and numbers, which i want to delete. Also, the header does not have this issue and I need all other columns intact, so these should not be affected.

enter image description here

I can do this in MS Excel with the following formula

=LEFT(A1,LEN(A1)-6)

(https://www.mrexcel.com/board/threads/how-can-i-remove-the-last-5-characters-from-a-cell.272639/)

But i want to do it in R. (PS - am an amateur at R)

Please help.

答:
I suggest looking at the answer from another post:

How to remove last n characters from every element in the R vector

I adapted the solution from @nfmcclure to your situation.

```<code>#Example dataframe
df <- structure(list(location = c("Akola (001)", "Jamkhed (014)", "Karjat (013)",
                                  "Kopargaeon (003)")), class = "data.frame", row.names = c(NA,
                                                                                -4L))
#Solution
substr(df$location,1,nchar(df$location)-5)
</code>```

Body:
I suggest looking at the answer from another post:

How to remove last n characters from every element in the R vector

I adapted the solution from @nfmcclure to your situation.

#Example dataframe
df <- structure(list(location = c("Akola (001)", "Jamkhed (014)", "Karjat (013)",
                                  "Kopargaeon (003)")), class = "data.frame", row.names = c(NA,
                                                                                -4L))
#Solution
substr(df$location,1,nchar(df$location)-5)


问:
Modifying String in Java
I have a String  , String a = newNumber + "*" + nn + "+" + difference;
the newNumber = 106 , nn = 3 and difference = 3.
so the output should be as follow ;

Output :
106*3+3

I would like to modify the String so that the output becomes (35*3+1)*3+3 and then with this new String I would like to modify it again so that it becomes ((11*3+2)*3+1)*3+3
Basically I just need to replace the newNumber which was 106 and kept changing to 11, as you can see I'm trying to modify only the newNumber and replacing it with another while keeping the entire String untouched , I'm just replacing and adding to it , how can this be achieved ?
The output should be like this,
Output :

```<code>106*3+3
(35*3+1)*3+3
((11*3+2)*3+1)*3+3
</code>```

I'm solving an equation with steps , the formulas don't matter I'm just trying to figure out how can I modify the String by replacing the newNumber with a another number and adding new brackets to the equation.
I hope I wrote my problem in a way you would understand , I'd really appreciate the help.

答:
Strings in java are immutable. You will have to use StringBuilder or String Buffer

However if you insist then you may try(from what I understood of the pattern)

```<code>    int num = 106;
    String rep = "";
    String S = "106*3+3";
    String target;
    int b = 1;
    int largestfactor = 1;
    System.out.println(S);
    for (int i = num; i > 0; i--) {

        for (int j = 1; j < (num - b); j++) {
            if ((num - b) % j == 0)
                largestfactor = j;
        }

        target = "" + num;
        rep = "(" + largestfactor + "*" + (num - b) / largestfactor + ")" + "+" + b;
        S = S.replace(target,rep);
        System.out.println(S);
        num = largestfactor;
        b++;
        if(b>num)
            break;
    }
</code>```

Title: Modifying String in Java

Body:
I have a String  , String a = newNumber + "*" + nn + "+" + difference;
the newNumber = 106 , nn = 3 and difference = 3.
so the output should be as follow ;

Output :
106*3+3

I would like to modify the String so that the output becomes (35*3+1)*3+3 and then with this new String I would like to modify it again so that it becomes ((11*3+2)*3+1)*3+3
Basically I just need to replace the newNumber which was 106 and kept changing to 11, as you can see I'm trying to modify only the newNumber and replacing it with another while keeping the entire String untouched , I'm just replacing and adding to it , how can this be achieved ?
The output should be like this,
Output :

106*3+3
(35*3+1)*3+3
((11*3+2)*3+1)*3+3

I'm solving an equation with steps , the formulas don't matter I'm just trying to figure out how can I modify the String by replacing the newNumber with a another number and adding new brackets to the equation.
I hope I wrote my problem in a way you would understand , I'd really appreciate the help.

Body:
Strings in java are immutable. You will have to use StringBuilder or String Buffer

However if you insist then you may try(from what I understood of the pattern)

    int num = 106;
    String rep = "";
    String S = "106*3+3";
    String target;
    int b = 1;
    int largestfactor = 1;
    System.out.println(S);
    for (int i = num; i > 0; i--) {

        for (int j = 1; j < (num - b); j++) {
            if ((num - b) % j == 0)
                largestfactor = j;
        }

        target = "" + num;
        rep = "(" + largestfactor + "*" + (num - b) / largestfactor + ")" + "+" + b;
        S = S.replace(target,rep);
        System.out.println(S);
        num = largestfactor;
        b++;
        if(b>num)
            break;
    }


问:
Google Maps Issue Cannot call method 'apply' of undefined?
I have searched all over google for a solution however this seems a new one? I am trying to implement google maps API on a site however I keep getting the following error:

Uncaught TypeError: Cannot call method 'apply' of undefined

My JS is as follows:

```<code>        var map;
        function initialize(location) {
            var mapDiv = document.getElementById('map-canvas');
            var latLng;
            if (location == 0) {
                latLng = new google.maps.LatLng(52.066356, 1.102388);
            }
            else if (location == 1) {
                latLng = new google.maps.LatLng(52.672492, 1.232196);
            }
            else if (location == 2) {
                latLng = new google.maps.LatLng(52.207607, 0.123017);
            }
            map = new google.maps.Map(mapDiv, {
                center: latLng,
                zoom: 14,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            google.maps.event.addDomListener(map, 'tilesloaded', addMarker(location));

        }

        function addMarker(location) {
            var latLng;
            if (location == 0) {
                latLng = new google.maps.LatLng(52.066703, 1.113573);
            }
            else if (location == 1) {
                latLng = new google.maps.LatLng(52.672492, 1.232196);
            }
            else if (location == 2) {
                latLng = new google.maps.LatLng(52.207607, 0.123017);
            }
            var marker = new google.maps.Marker({
                position: latLng,
                map: map
            });
        }

        $(document).ready(function () {
            initialize(0);
        });
</code>```

答:
In this line

```<code>google.maps.event.addDomListener(map, 'tilesloaded', addMarker(location));
</code>```

You're calling the function addMarker instead of passing it as a function reference. Therefore, addMarker is getting executed before map is defined. Try changing that line to:

```<code>google.maps.event.addDomListener(map, 'tilesloaded', function() {addMarker(location)});
</code>```

Body:
I have searched all over google for a solution however this seems a new one? I am trying to implement google maps API on a site however I keep getting the following error:

Uncaught TypeError: Cannot call method 'apply' of undefined

My JS is as follows:

        var map;
        function initialize(location) {
            var mapDiv = document.getElementById('map-canvas');
            var latLng;
            if (location == 0) {
                latLng = new google.maps.LatLng(52.066356, 1.102388);
            }
            else if (location == 1) {
                latLng = new google.maps.LatLng(52.672492, 1.232196);
            }
            else if (location == 2) {
                latLng = new google.maps.LatLng(52.207607, 0.123017);
            }
            map = new google.maps.Map(mapDiv, {
                center: latLng,
                zoom: 14,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            google.maps.event.addDomListener(map, 'tilesloaded', addMarker(location));

        }

        function addMarker(location) {
            var latLng;
            if (location == 0) {
                latLng = new google.maps.LatLng(52.066703, 1.113573);
            }
            else if (location == 1) {
                latLng = new google.maps.LatLng(52.672492, 1.232196);
            }
            else if (location == 2) {
                latLng = new google.maps.LatLng(52.207607, 0.123017);
            }
            var marker = new google.maps.Marker({
                position: latLng,
                map: map
            });
        }

        $(document).ready(function () {
            initialize(0);
        });

Body:
In this line

google.maps.event.addDomListener(map, 'tilesloaded', addMarker(location));

You're calling the function addMarker instead of passing it as a function reference. Therefore, addMarker is getting executed before map is defined. Try changing that line to:

google.maps.event.addDomListener(map, 'tilesloaded', function() {addMarker(location)});


问:
Getting error #152 with React and Axios when rendering a list
I am trying to add react component that gets a notifications list with Ajax using axios, on a web page.

I'm getting an error #152, which tells me I'm rendering nothing. But when I console log the notifications inside renderItems (inside the map loop), I can see the notifications as I expect it to be.

Here is my code:

```<code>'use strict';
const e = React.createElement;

const NofiticationSingle = ({item}) => {
    <li>
        <p>
            {item}
        </p>
    </li>
}

class Notifications extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            notifications : [],
        }
    }

    componentDidMount() {
        const url = ajax_object.url;
        let data = {action: 'get_notifications'};
        let currentComponent = this;
        axios.post(url, Qs.stringify(data))
            .then(function (response) {
                let data = response.data;
                currentComponent.setState({
                    notifications : data.notifications
                })
            })
            .catch(function (error) {
                console.log(error);
            });

    }

    renderItems(){
        return this.state.notifications.map((notification) => (
                <NofiticationSingle key={notification.id} notification={notification} />
        ))
    }

    render(){
        return (
            <ul>
                {this.renderItems()}
            </ul>
        )
    }
}

const notificationsDomContainer = document.querySelector('#goes');
ReactDOM.render(e(Notifications), notificationsDomContainer);
</code>```

答:
Oh you are missing a return statement here, or you have extra {} brackets:

```<code>const NofiticationSingle = ({item}) => {
    <li>
        <p>
            {item}
        </p>
    </li>
}
</code>```

You shall either introduce explicit return statement, or just wrap your result with brackets, like:

```<code>const NofiticationSingle = ({item}) => {
    return <li>
        <p>
            {item}
        </p>
    </li>;
})
---
const NofiticationSingle = ({item}) => (
    <li>
        <p>
            {item}
        </p>
    </li>
)
</code>```

Body:
I am trying to add react component that gets a notifications list with Ajax using axios, on a web page.

I'm getting an error #152, which tells me I'm rendering nothing. But when I console log the notifications inside renderItems (inside the map loop), I can see the notifications as I expect it to be.

Here is my code:

'use strict';
const e = React.createElement;

const NofiticationSingle = ({item}) => {

            {item}

}

class Notifications extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            notifications : [],
        }
    }

    componentDidMount() {
        const url = ajax_object.url;
        let data = {action: 'get_notifications'};
        let currentComponent = this;
        axios.post(url, Qs.stringify(data))
            .then(function (response) {
                let data = response.data;
                currentComponent.setState({
                    notifications : data.notifications
                })
            })
            .catch(function (error) {
                console.log(error);
            });

    }

    renderItems(){
        return this.state.notifications.map((notification) => (
                <NofiticationSingle key={notification.id} notification={notification} />
        ))
    }

    render(){
        return (

                {this.renderItems()}

        )
    }
}

const notificationsDomContainer = document.querySelector('#goes');
ReactDOM.render(e(Notifications), notificationsDomContainer);

Body:
Oh you are missing a return statement here, or you have extra {} brackets:

const NofiticationSingle = ({item}) => {
    <li>
        <p>
            {item}
        </p>
    </li>
}

You shall either introduce explicit return statement, or just wrap your result with brackets, like:

const NofiticationSingle = ({item}) => {
    return <li>
        <p>
            {item}
        </p>
    </li>;
})
---
const NofiticationSingle = ({item}) => (
    <li>
        <p>
            {item}
        </p>
    </li>
)


问:
R: Turning row data from one dataframe into column data by group in another
I have data in the following format:

ID
Age
Sex

1
29
M

2
32
F

3
18
F

4
89
M

5
45
M

and;

ID
subID
Type
Status
Year

1
3
Car
Y

1
11
Toyota
NULL
2011

1
23
Kia
NULL
2009

2
5
Car
N

3
2
Car
Y

3
4
Honda
NULL
2019

3
7
Fiat
NULL
2006

3
8
Mitsubishi
NULL
2020

4
1
Car
N

5
7
Car
Y

Each ID in the second table has a row specifying if they have a car, and additional rows stating the brand of car/s they own. Each person has a maximum of 3 cars. I want to simplify this data into a single table as so.

ID
Age
Sex
Car?
Car.1
Car1.year
Car.2
Car2.year
Car.3
Car3.year

1
29
M
Y
Toyota
2011
Kia
2009
NULL
NULL

2
32
F
N
NULL
NULL
NULL
NULL
NULL
NULL

3
18
F
Y
Honda
2019
Fiat
2006
Mitsubishi
2020

4
89
M
N
NULL
NULL
NULL
NULL
NULL
NULL

5
45
M
Y
NULL
NULL
NULL
NULL
NULL
NULL

I've tried using the mutate function in dplyr with the case_when function, but I can't check conditions in another dataframe. If I try to join the tables together, I would have multiple rows for each ID which I want to avoid. The non-standard set up of the second table makes things complicated. My only remaining idea is to switch to Python/Pandas and create a for loop that slowly loops through each ID, searches the second dataframe if the person has a car and the car brands, then mutates a column in the first dataframe. But given the size of my dataset, this would be inefficient and take a long time.

What is the best way to do this?

答:
You can try the following codes:

```<code>library(tidyverse)

df1

# A tibble: 5 x 3
     ID   Age Sex
  <dbl> <dbl> <chr>
1     1    29 M
2     2    32 F
3     3    18 F
4     4    89 M
5     5    45 M

df2

# A tibble: 10 x 5
      ID subID Type       Status  Year
   <dbl> <dbl> <chr>      <chr>  <dbl>
 1     1     3 Car        Y         NA
 2     1    11 Toyota     Y       2011
 3     1    23 Kia        Y       2009
 4     2     5 Car        N         NA
 5     3     2 Car        Y         NA
 6     3     4 Honda      Y       2019
 7     3     7 Fiat       Y       2006
 8     3     8 Mitsubishi Y       2020
 9     4     1 Clothed    N         NA
10     5     7 Clothed    Y         NA

df2 <- df2 %>% mutate(Status = if_else(Status == "NULL", "Y", Status))
df3 <- df2 %>% filter(!is.na(Year)) %>% group_by(ID) %>% mutate(index = row_number())
df4 <- df3  %>% pivot_wider(id_cols = c(ID), values_from = c(Type, Year), names_from = index )
</code>```

So your desired output will be produced:

```<code>df1 %>% left_join(df2 %>% select(ID, Status) %>% distinct()) %>% left_join(df4)

# A tibble: 5 x 10
     ID   Age Sex   Status Type_1 Type_2 Type_3     Year_1 Year_2 Year_3
  <dbl> <dbl> <chr> <chr>  <chr>  <chr>  <chr>       <dbl>  <dbl>  <dbl>
1     1    29 M     Y      Toyota Kia    NA           2011   2009     NA
2     2    32 F     N      NA     NA     NA             NA     NA     NA
3     3    18 F     Y      Honda  Fiat   Mitsubishi   2019   2006   2020
4     4    89 M     N      NA     NA     NA             NA     NA     NA
5     5    45 M     Y      NA     NA     NA             NA     NA     NA
</code>```

Body:
You can try the following codes:

library(tidyverse)

df1

# A tibble: 5 x 3
     ID   Age Sex
  <dbl> <dbl> <chr>
1     1    29 M
2     2    32 F
3     3    18 F
4     4    89 M
5     5    45 M

df2

# A tibble: 10 x 5
      ID subID Type       Status  Year
   <dbl> <dbl> <chr>      <chr>  <dbl>
 1     1     3 Car        Y         NA
 2     1    11 Toyota     Y       2011
 3     1    23 Kia        Y       2009
 4     2     5 Car        N         NA
 5     3     2 Car        Y         NA
 6     3     4 Honda      Y       2019
 7     3     7 Fiat       Y       2006
 8     3     8 Mitsubishi Y       2020
 9     4     1 Clothed    N         NA
10     5     7 Clothed    Y         NA

df2 <- df2 %>% mutate(Status = if_else(Status == "NULL", "Y", Status))
df3 <- df2 %>% filter(!is.na(Year)) %>% group_by(ID) %>% mutate(index = row_number())
df4 <- df3  %>% pivot_wider(id_cols = c(ID), values_from = c(Type, Year), names_from = index )

So your desired output will be produced:

df1 %>% left_join(df2 %>% select(ID, Status) %>% distinct()) %>% left_join(df4)

# A tibble: 5 x 10
     ID   Age Sex   Status Type_1 Type_2 Type_3     Year_1 Year_2 Year_3
  <dbl> <dbl> <chr> <chr>  <chr>  <chr>  <chr>       <dbl>  <dbl>  <dbl>
1     1    29 M     Y      Toyota Kia    NA           2011   2009     NA
2     2    32 F     N      NA     NA     NA             NA     NA     NA
3     3    18 F     Y      Honda  Fiat   Mitsubishi   2019   2006   2020
4     4    89 M     N      NA     NA     NA             NA     NA     NA
5     5    45 M     Y      NA     NA     NA             NA     NA     NA


问:
Fragment returns null while reading from sharedpreferences file
I am reading string value from sharedpreferences in fragment but it return null sometime? Here is my logcat output:

```<code>java.lang.IllegalStateException: Fragment Home{fc6bf3a} (14420322-2dbf-46e9-9f52-12586f9fa36b) not attached to a context.
    at androidx.fragment.app.Fragment.requireContext(Fragment.java:900)
    at com.example.socialmediacloneapp.Fragments.Home.getUserName(Home.java:114)
    at com.example.socialmediacloneapp.Fragments.Home.access$000(Home.java:34)
    at com.example.socialmediacloneapp.Fragments.Home$1.onDataChange(Home.java:77)
    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
</code>```

Here is my sharedPreference code:

```<code> private void setUserName(String name){
    SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyFile",MODE_PRIVATE);
    SharedPreferences.Editor editor;
    editor = sharedPreferences.edit();
    editor.putString("name",name);

    editor.apply();

    b.textView.setText("Hi," + name);
}
</code>```

How to avoid this exception while reading a value from sharedpreferences?

答: call fun "setUserName" in to onViewCreated!</p>

Body:
I am reading string value from sharedpreferences in fragment but it return null sometime? Here is my logcat output:

java.lang.IllegalStateException: Fragment Home{fc6bf3a} (14420322-2dbf-46e9-9f52-12586f9fa36b) not attached to a context.
    at androidx.fragment.app.Fragment.requireContext(Fragment.java:900)
    at com.example.socialmediacloneapp.Fragments.Home.getUserName(Home.java:114)
    at com.example.socialmediacloneapp.Fragments.Home.access$000(Home.java:34)
    at com.example.socialmediacloneapp.Fragments.Home$1.onDataChange(Home.java:77)
    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)

Here is my sharedPreference code:

 private void setUserName(String name){
    SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyFile",MODE_PRIVATE);
    SharedPreferences.Editor editor;
    editor = sharedPreferences.edit();
    editor.putString("name",name);

    editor.apply();

    b.textView.setText("Hi," + name);
}

How to avoid this exception while reading a value from sharedpreferences?


问:
Relational database design for photography website
I'm creating a database for a photography website and I want it to allow three main things -

Allow the owner/admin to create client accounts and credentials,

Specifying which photos should go into three different portfolio galleries on the site, and,

Displaying a unique client's photos (and only their photos!) to them when they log in.

This is my first database design ever - based on responses below, I've added that emphasis ;) and edited the design as below.

IMAGES
image_id,
filename,
description,
client_id,
date_uploaded,

USERS/CLIENTS

client_id,

client_name

username,

password,

PORTFOLIO

portfolio_id,

portfolio_name,

PORTFOLIO_IMAGES

id,

image_id,

portfolio_id,

Am I correct in thinking that the final id in PORTFOLIO_IMAGES would allow me to display one image in multiple galleries?

Thanks

答:
use client id instead of client_name on the images and users table

Add another table, portfolio with at least name and id columns

Add another table, portfolio_images with two columns, image_id and portfolio_id.  This will allow the feature mentioned by @Alex in the comments

response to edit

You can do the one image in multiple portfolios by querying PORTFOLIO_IMAGES and JOINing with images or portfolios as necessary.  For example, if you want to display the wedding portfolio (psuedo-code)

```<code>SELECT filename,...
FROM images img
INNER JOIN portfolio_images pimg on img.image_id = portfolio_images.image_id
WHERE pimg.portfolio_id = <whatever the id is for wedding portfolio>
</code>```

Body:
use client id instead of client_name on the images and users table

Add another table, portfolio with at least name and id columns

Add another table, portfolio_images with two columns, image_id and portfolio_id.  This will allow the feature mentioned by @Alex in the comments

response to edit

You can do the one image in multiple portfolios by querying PORTFOLIO_IMAGES and JOINing with images or portfolios as necessary.  For example, if you want to display the wedding portfolio (psuedo-code)

SELECT filename,...
FROM images img
INNER JOIN portfolio_images pimg on img.image_id = portfolio_images.image_id
WHERE pimg.portfolio_id = <whatever the id is for wedding portfolio>


问:
Is there a way to disconnect user from Signlar server side?
I'm building an app that use SignalR to transmit realtime message and I was wandering if there was any way for me to disconnect user on the server side.

I want to disconnect them because of the way SignalR handle authentification. Signalr dosen't seem to check if a token is expire inside an open websocket connection (it only check at the start of the request or when the client send a message).

Another solution would be to disconnect the client after a given time.

For the moment all I have for the authentification is a JWT token sent inside the accessTokenProvider.

ClientSide :

 new HubConnectionBuilder()
      .withUrl(`${env.APPURL}/hub`, {
        skipNegotiation: true,
        transport: HttpTransportType.WebSockets,
        accessTokenFactory: async () => {
          const { token } = store;

          return token;
        },
      })

```

答:
I handle this on the client side. My angular application uses a silent refresh token call to refresh the jwt token and keep the user authenticated.

When I added SignalR functionality to my app, I also needed to update the access token for the active SignalR connections.
After some research, the only way to do this is to 'reset' the connection. When you stop and start the connection again, SignalR will use the newest token you pass to it via the access token factory.

If you wanted to do this server side, you could send a message to all the clients, upon which the clients stop their connection and immediately restart it.

Ultimately, the code that stops the connection has to be done on the client side.

-- UPDATE --

ASP.NET Core SignalR has the Abort method in the Hub class. (It is not possible to do this in ASP.NET SignalR however.)

With this Abort method, you could run your logic on a per connection basis and if the connection needs to be stopped then:

```<code>    public void AuthenticateConnection()
    {
        // Run your logic to determine if connection needs to be stopped

        // If connection must be stopped
        Context.Abort();
    }
</code>```

Although this does stop the connection, it provides no way to start it again, and as such you're stuck with the client permanently disconnected. So if you intention is to update the clients bearer token, then I am not sure this would work for you.

For the use case of updating the JWT bearer token, I would recommend setting a 'refresh-token' timer on client side as you get the token.

E.G. If I log in and the token expires 15 minutes from now, I will set a 14 minutes timer, after which I will refresh the token to keep the user logged in. Every time the token is successfully refreshed, I then  stop and start the connection (passing the updated token).

If it is imperative that you do this from server side, one solution could be to send a disconnect message out along with a client id, then the client with that id will receive the message:

server side

```<code>Clients.All.SendAsync($"disconnect-{clientId}");
</code>```

client side

```<code>this.connection.on(
  `disconnect-${this.clientId}`, async () => {
    await this.connection.stop();
    await this.connectionstart();
  }
);
</code>```

Body:
I handle this on the client side. My angular application uses a silent refresh token call to refresh the jwt token and keep the user authenticated.

When I added SignalR functionality to my app, I also needed to update the access token for the active SignalR connections.
After some research, the only way to do this is to 'reset' the connection. When you stop and start the connection again, SignalR will use the newest token you pass to it via the access token factory.

If you wanted to do this server side, you could send a message to all the clients, upon which the clients stop their connection and immediately restart it.

Ultimately, the code that stops the connection has to be done on the client side.

-- UPDATE --

ASP.NET Core SignalR has the Abort method in the Hub class. (It is not possible to do this in ASP.NET SignalR however.)

With this Abort method, you could run your logic on a per connection basis and if the connection needs to be stopped then:

    public void AuthenticateConnection()
    {
        // Run your logic to determine if connection needs to be stopped

        // If connection must be stopped
        Context.Abort();
    }

Although this does stop the connection, it provides no way to start it again, and as such you're stuck with the client permanently disconnected. So if you intention is to update the clients bearer token, then I am not sure this would work for you.

For the use case of updating the JWT bearer token, I would recommend setting a 'refresh-token' timer on client side as you get the token.

E.G. If I log in and the token expires 15 minutes from now, I will set a 14 minutes timer, after which I will refresh the token to keep the user logged in. Every time the token is successfully refreshed, I then  stop and start the connection (passing the updated token).

If it is imperative that you do this from server side, one solution could be to send a disconnect message out along with a client id, then the client with that id will receive the message:

server side

Clients.All.SendAsync($"disconnect-{clientId}");

client side

this.connection.on(
  `disconnect-${this.clientId}`, async () => {
    await this.connection.stop();
    await this.connectionstart();
  }
);


问:
Why Laravel don't show or execute new Routes?
I don't know if I'm so stupid or my laravel is broken, BUT, here it is.

That's my api.php:

```<code>Route::get('/airport', [\App\Http\Controllers\AirportsController::class, 'index']);
Route::post('/airports', [\App\Http\Controllers\AirportsController::class, 'create']);
Route::get('/registrator', [\App\Http\Controllers\RegistrationController::class, 'index']);
</code>```

The airport and airports work great. It's add all data in db or get data from db.
But registartor just don't work. It shows ERROR 404 and that's all.

RegistrationController:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class RegistrationController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return 1;
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
</code>```

It's just show ERROR 404 in anyway, not matter what request I do. I mean, I can rename airport in airportt and restart my server, but It still will show me ERROR 404, until I change airportt to airport

答:
All what I need to do is just clear route cache using artisan. Just enter a command in cmd:
php artisan route:clear

Body:
I don't know if I'm so stupid or my laravel is broken, BUT, here it is.

That's my api.php:

Route::get('/airport', [\App\Http\Controllers\AirportsController::class, 'index']);
Route::post('/airports', [\App\Http\Controllers\AirportsController::class, 'create']);
Route::get('/registrator', [\App\Http\Controllers\RegistrationController::class, 'index']);

The airport and airports work great. It's add all data in db or get data from db.
But registartor just don't work. It shows ERROR 404 and that's all.

RegistrationController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class RegistrationController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return 1;
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

It's just show ERROR 404 in anyway, not matter what request I do. I mean, I can rename airport in airportt and restart my server, but It still will show me ERROR 404, until I change airportt to airport


问:
Unable to get value onchange from reactstrap switch input
I have a reactstrap switch which should return true/ false onchange.
Problem is I'm unable to get the value onchange.
this is how im doing this

```<code>         <div className='form-switch'>
          <Input type='switch' defaultChecked={orginalChoice} id={1}
            nChange={setUserSwitchChoice}
             />
           <Label className='form-check-label' for={''}>
            <span className='switch-icon-left'>
             <Check size={14} />
              </span>
            <span className='switch-icon-right'>
               <X size={14} />
              </span>
              </Label>
          </div>
</code>```

when I check the setUserSwitchChoice on console it returns the data like this :

```<code>SyntheticBaseEvent {_reactName: 'onChange', _targetInst: null, type: 'change', nativeEvent: PointerEvent, target: input#1.form-check-input, …}
bubbles: true
cancelable: true
currentTarget: null
defaultPrevented: false
eventPhase: 3
isDefaultPrevented: ƒ functionThatReturnsFalse()
isPropagationStopped: ƒ functionThatReturnsFalse()
isTrusted: true
nativeEvent: PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
target: input#1.form-check-input
timeStamp: 553191.0999999996
type: "change"
_reactName: "onChange"
_targetInst: null
[[Prototype]]: Object
</code>```

So please let me know how to get the correct value in boolean format like true, false.

```<code>onChange={(e) => setUserSwitchChoice(e) // also tried this but working
</code>```

答:
There are multiple ways to achieve it. But what I most like making a handler for that purpose. So,
Make a handler to get the response onChange implementing the useState.

```<code>const [orginalChoice , setOrginalChoice ] = useState(orginalChoice)
// handle accordingly as ur original state
// originalChoice should be true or false.
</code>```

Then, create a change handler like this:

```<code>const onChangeHandler = () => {
    if (orginalChoice === true) {
      setOrginalChoice(!orginalChoice) # that will reverse the true to false
    } else {
      setOrginalChoice(!orginalChoice) # that will reverse the false to true
    }
     // console.log(orginalChoice) // To check the data on console
  }
</code>```

Finally, update the switch input code with submit handler like that

```<code>   <div className='form-switch'>
     <Input type='switch' defaultChecked={orginalChoice} id={1}
       onChange={onChangeHandler}/>
      <Label className='form-check-label' for={''}>
        <span className='switch-icon-left'>
          <Check size={14} />
        </span>
        <span className='switch-icon-right'>
         <X size={14} />
         </span>
      </Label>
    </div>
</code>```

Now this should return the value in bool. true / false

Body:
I have a reactstrap switch which should return true/ false onchange.
Problem is I'm unable to get the value onchange.
this is how im doing this

          <Input type='switch' defaultChecked={orginalChoice} id={1}
            nChange={setUserSwitchChoice}
             />

             <Check size={14} />

               <X size={14} />

when I check the setUserSwitchChoice on console it returns the data like this :

SyntheticBaseEvent {_reactName: 'onChange', _targetInst: null, type: 'change', nativeEvent: PointerEvent, target: input#1.form-check-input, …}
bubbles: true
cancelable: true
currentTarget: null
defaultPrevented: false
eventPhase: 3
isDefaultPrevented: ƒ functionThatReturnsFalse()
isPropagationStopped: ƒ functionThatReturnsFalse()
isTrusted: true
nativeEvent: PointerEvent {isTrusted: true, pointerId: 1, width: 1, height: 1, pressure: 0, …}
target: input#1.form-check-input
timeStamp: 553191.0999999996
type: "change"
_reactName: "onChange"
_targetInst: null
[[Prototype]]: Object

So please let me know how to get the correct value in boolean format like true, false.

onChange={(e) => setUserSwitchChoice(e) // also tried this but working

Body:
There are multiple ways to achieve it. But what I most like making a handler for that purpose. So,
Make a handler to get the response onChange implementing the useState.

const [orginalChoice , setOrginalChoice ] = useState(orginalChoice)
// handle accordingly as ur original state
// originalChoice should be true or false.

Then, create a change handler like this:

const onChangeHandler = () => {
    if (orginalChoice === true) {
      setOrginalChoice(!orginalChoice) # that will reverse the true to false
    } else {
      setOrginalChoice(!orginalChoice) # that will reverse the false to true
    }
     // console.log(orginalChoice) // To check the data on console
  }

Finally, update the switch input code with submit handler like that

   <div className='form-switch'>
     <Input type='switch' defaultChecked={orginalChoice} id={1}
       onChange={onChangeHandler}/>
      <Label className='form-check-label' for={''}>
        <span className='switch-icon-left'>
          <Check size={14} />
        </span>
        <span className='switch-icon-right'>
         <X size={14} />
         </span>
      </Label>
    </div>

Now this should return the value in bool. true / false