问:
My Own Personal MFC
I can't seem to find this on msdn been searching for a bit (described below).

Please forgive the amount of code posted, I will paste in order. You can really skip most of it. But I just want to put it all out there so my request is clear.

Lets say I wanted to make a really simple MFC. So I have the following abstract and concrete classes (pasted below) that I want in my really crappy framework.

I am also assuming (though not implemented yet) that WinMain will call a users defined main function (like Qt). What do I need to do so I can reuse my code in every other small crappy Win32 program I try to write. To be more clear, I am wondering if I compile it into a DLL, or a Library. If so how do I go about doing this? How do you include a WinMain function in a DLL?

```<code>    #ifndef IAPPLICATION_H_
    #define IAPPLICATION_H_

    #include <Windows.h>

    namespace nApplication
    {
        class IController;
        class IWindow;

        class IApplication
        {
        public:
            virtual int Run( ) = 0;
            virtual HINSTANCE gethInstance( ) = 0;
            virtual int getnCmdShow( ) = 0;
            virtual IController* getMainControl( ) = 0;
        protected:
            IWindow *main_window;
            IController *main_control;
        private:
            virtual int MessageLoop() = 0;
        };
    }

    #endif /* IAPPLICATION */

-

    #ifndef APPLICATION_H_
    #define APPLICATION_H_

    #include <Windows.h>
    #include "IApplication.h"
    #include "IWindow.h"
    #include "IController.h"
    #include "Controller.h"

    namespace nApplication
    {
        class Application : public IApplication
        {
        public:
            Application( HINSTANCE hInstance, int nCmdShow );
            virtual ~Application( );
            virtual int Run( );
            virtual int getnCmdShow( ) { return mnCmdShow; }
            virtual HINSTANCE gethInstance( ) { return mhInstance; }
            virtual IController* getMainControl( ) { return main_control; }
        private:
            int mnCmdShow;
            HINSTANCE mhInstance;
            int MessageLoop();
            Application( Application &app );
            Application& operator= ( const Application &app );
        };

    }

    #endif /* IAPPLICATION */

-

    #include "Application.h"
    #include "MainWindow.h"

    namespace nApplication
    {
        Application::Application( HINSTANCE hInstance, int nCmdShow )
            : mhInstance( hInstance ), mnCmdShow( nCmdShow )
        {
        }

    Application::~Application( )
    {
    }

    int Application::Run( )
    {
        main_window = new MainWindow( this );
        main_control = new Controller( this );
        main_window->Init( );
        main_window->Display( );
        MessageLoop( );
        delete main_window;
        return 0;
    }

    int Application::MessageLoop()
    {
        MSG msg;

        while(GetMessage(&msg, NULL, 0, 0) != 0)
        {
            TranslateMessage(&msg);

        DispatchMessage(&msg);
        }
        return (int)msg.wParam;
    }
}

-

    #ifndef IWINDOW_H_
    #define IWINDOW_H_

    #include <Windows.h>
    #include "IController.h"

    namespace nApplication
    {
        class IWindow
        {
        public:
            virtual void Init() = 0;
            virtual void Display( ) = 0;

    private:
    };
    }
    #endif /* IWINDOW_H_ */

-

    #ifndef MAINWINDOW_H_
    #define MAINWINDOW_H_

    #include <windows.h>
    #include "IWindow.h"
    #include "IController.h"
    #include "IApplication.h"

    namespace nApplication
    {
        class MainWindow : public IWindow
        {
        public:
            MainWindow( IApplication *iApp);
            ~MainWindow();
            void Init();
            void Display( );
        private:
            WNDCLASSEX wc;
            HWND hWnd;
            IApplication *iApp;
        };
    }

    #endif //MAINWINDOW_H_

-

    #include "MainWindow.h"

    namespace nApplication
    {
        namespace
        {
            LRESULT CALLBACK MainWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
            {
                HDC hDC;
                PAINTSTRUCT ps;

                static IController *cntrl;
                cntrl = (IController*)::GetWindowLongPtr(hWnd, GWL_USERDATA);

                if(uMsg == WM_NCCREATE)
                {
                    cntrl = (IController*)(((CREATESTRUCT*)lParam)->lpCreateParams);
                    ::SetWindowLongPtr(hWnd, GWL_USERDATA, (LONG_PTR)cntrl);
                    cntrl->CheckStatus();
                    return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
                }

                switch(uMsg)
                {
                    case WM_CREATE:
                    {
                    }
                    case WM_PAINT:
                    {
                        hDC = BeginPaint( hWnd, &ps );
                        TextOut( hDC, 10, 10, TEXT("Hello, Windows!"), 15 );
                        EndPaint( hWnd, &ps );
                        return 0;
                    }
                    case WM_DESTROY:
                    {
                        PostQuitMessage( 0 );
                        return 0;
                    }
                    default:
                    {
                        return DefWindowProc( hWnd, uMsg, wParam, lParam );
                    }
                }
            }
        }

        MainWindow::MainWindow( IApplication* iApp ) : iApp( iApp )
        {
            wc.cbSize        = sizeof(WNDCLASSEX);
            wc.style         = 0;
            wc.lpfnWndProc   = MainWndProc;
            wc.cbClsExtra    = 0;
            wc.cbWndExtra    = 0;
            wc.hInstance     = iApp->gethInstance( );
            wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
            wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
            wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
            wc.lpszMenuName  = TEXT( "GenericAppMenu");
            wc.lpszClassName = TEXT( "myWindowClass" );
            wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);
        }

        MainWindow::~MainWindow()
        {
        }

        void MainWindow::Init()
        {
            if( !RegisterClassEx(&wc) )
            {
                MessageBox(NULL, TEXT( "Window Registration Failed!" ), TEXT( "Error!" ), MB_ICONEXCLAMATION | MB_OK);
                exit(0);
            }
        }

        void MainWindow::Display( )
        {
            hWnd = ::CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("myWindowClass"),
            TEXT("The title of my window"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
            240, 120, NULL, NULL, iApp->gethInstance( ), iApp->getMainControl( ) );

            if(hWnd == NULL)
            {
                ::MessageBox( NULL, TEXT( "Window Creation Failed!" ),
                    TEXT( "Error!" ), MB_ICONEXCLAMATION | MB_OK );
                exit(0);
            }

        ::ShowWindow( hWnd, iApp->getnCmdShow( ) );
        ::UpdateWindow(hWnd);
    }
}

-

        #ifndef ICONTROLLER_H_
        #define ICONTROLLER_H_

        #include <windows.h>

        namespace nApplication
        {
            class IController
            {
            public:
                virtual int CheckStatus() = 0;
            };
    }

    #endif ICONTROLLER_H_

-

    #ifndef CONTROLLER_H_
    #define CONTROLLER_H_

    #include <windows.h>
    #include "IController.h"
    #include "IApplication.h"

    namespace nApplication
    {
        class Controller : public IController
        {
        public:
            Controller( IApplication *iApp );
            virtual ~Controller();
            virtual int CheckStatus();
        private:
            Controller( Controller &c );
            Controller& operator= ( Controller &c );
            IApplication *iApp;
        };
    }

    #endif //CONTROLLER_H_

-

    #include "Controller.h"

    namespace nApplication
    {
        Controller::Controller( IApplication *iApp ) : iApp( iApp )
        {

        }

        Controller::~Controller()
        {
        }

        int Controller::CheckStatus()
        {
            return 0;
        }
    }

-

#include <windows.h>
#include "Application.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    nApplication::Application app( hInstance, nCmdShow );
    return app.Run( );
}

-

main.exe : main.cpp
    cl /EHsc main.cpp Application.cpp Controller.cpp MainWindow.cpp user32.lib gdi32.lib
    del *.obj
#/link /SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup
</code>```

答:
If you are making a library, you don't have a WinMain, you have a DllMain for dynamic libraries, or nothing for static libraries.

In your case, you'd need to export all the classes functionality from your dll, then in any apps that use your library, you'd include the headers of your project and link to the .lib of the library, then have this in your app where you need the GUI functionality:

```<code>nApplication::Application app( hInstance, nCmdShow );
return app.Run( );
</code>```

Of course this ignores all the side details like registering event callbacks and setup along those lines, however Qt is free and open source, you you might want to look into that before reinventing the wheel, or to help make your own wheel a little rounder.

Title: My Own Personal MFC

Body:
I can't seem to find this on msdn been searching for a bit (described below).

Please forgive the amount of code posted, I will paste in order. You can really skip most of it. But I just want to put it all out there so my request is clear.

Lets say I wanted to make a really simple MFC. So I have the following abstract and concrete classes (pasted below) that I want in my really crappy framework.

I am also assuming (though not implemented yet) that WinMain will call a users defined main function (like Qt). What do I need to do so I can reuse my code in every other small crappy Win32 program I try to write. To be more clear, I am wondering if I compile it into a DLL, or a Library. If so how do I go about doing this? How do you include a WinMain function in a DLL?

    #ifndef IAPPLICATION_H_
    #define IAPPLICATION_H_

    #include <Windows.h>

    namespace nApplication
    {
        class IController;
        class IWindow;

        class IApplication
        {
        public:
            virtual int Run( ) = 0;
            virtual HINSTANCE gethInstance( ) = 0;
            virtual int getnCmdShow( ) = 0;
            virtual IController* getMainControl( ) = 0;
        protected:
            IWindow *main_window;
            IController *main_control;
        private:
            virtual int MessageLoop() = 0;
        };
    }

    #endif /* IAPPLICATION */

-

    #ifndef APPLICATION_H_
    #define APPLICATION_H_

    #include <Windows.h>
    #include "IApplication.h"
    #include "IWindow.h"
    #include "IController.h"
    #include "Controller.h"

    namespace nApplication
    {
        class Application : public IApplication
        {
        public:
            Application( HINSTANCE hInstance, int nCmdShow );
            virtual ~Application( );
            virtual int Run( );
            virtual int getnCmdShow( ) { return mnCmdShow; }
            virtual HINSTANCE gethInstance( ) { return mhInstance; }
            virtual IController* getMainControl( ) { return main_control; }
        private:
            int mnCmdShow;
            HINSTANCE mhInstance;
            int MessageLoop();
            Application( Application &app );
            Application& operator= ( const Application &app );
        };

    }

    #endif /* IAPPLICATION */

-

    #include "Application.h"
    #include "MainWindow.h"

    namespace nApplication
    {
        Application::Application( HINSTANCE hInstance, int nCmdShow )
            : mhInstance( hInstance ), mnCmdShow( nCmdShow )
        {
        }

    Application::~Application( )
    {
    }

    int Application::Run( )
    {
        main_window = new MainWindow( this );
        main_control = new Controller( this );
        main_window->Init( );
        main_window->Display( );
        MessageLoop( );
        delete main_window;
        return 0;
    }

    int Application::MessageLoop()
    {
        MSG msg;

        while(GetMessage(&msg, NULL, 0, 0) != 0)
        {
            TranslateMessage(&msg);

        DispatchMessage(&msg);
        }
        return (int)msg.wParam;
    }
}

-

    #ifndef IWINDOW_H_
    #define IWINDOW_H_

    #include <Windows.h>
    #include "IController.h"

    namespace nApplication
    {
        class IWindow
        {
        public:
            virtual void Init() = 0;
            virtual void Display( ) = 0;

    private:
    };
    }
    #endif /* IWINDOW_H_ */

-

    #ifndef MAINWINDOW_H_
    #define MAINWINDOW_H_

    #include <windows.h>
    #include "IWindow.h"
    #include "IController.h"
    #include "IApplication.h"

    namespace nApplication
    {
        class MainWindow : public IWindow
        {
        public:
            MainWindow( IApplication *iApp);
            ~MainWindow();
            void Init();
            void Display( );
        private:
            WNDCLASSEX wc;
            HWND hWnd;
            IApplication *iApp;
        };
    }

    #endif //MAINWINDOW_H_

-

    #include "MainWindow.h"

    namespace nApplication
    {
        namespace
        {
            LRESULT CALLBACK MainWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
            {
                HDC hDC;
                PAINTSTRUCT ps;

                static IController *cntrl;
                cntrl = (IController*)::GetWindowLongPtr(hWnd, GWL_USERDATA);

                if(uMsg == WM_NCCREATE)
                {
                    cntrl = (IController*)(((CREATESTRUCT*)lParam)->lpCreateParams);
                    ::SetWindowLongPtr(hWnd, GWL_USERDATA, (LONG_PTR)cntrl);
                    cntrl->CheckStatus();
                    return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
                }

                switch(uMsg)
                {
                    case WM_CREATE:
                    {
                    }
                    case WM_PAINT:
                    {
                        hDC = BeginPaint( hWnd, &ps );
                        TextOut( hDC, 10, 10, TEXT("Hello, Windows!"), 15 );
                        EndPaint( hWnd, &ps );
                        return 0;
                    }
                    case WM_DESTROY:
                    {
                        PostQuitMessage( 0 );
                        return 0;
                    }
                    default:
                    {
                        return DefWindowProc( hWnd, uMsg, wParam, lParam );
                    }
                }
            }
        }

        MainWindow::MainWindow( IApplication* iApp ) : iApp( iApp )
        {
            wc.cbSize        = sizeof(WNDCLASSEX);
            wc.style         = 0;
            wc.lpfnWndProc   = MainWndProc;
            wc.cbClsExtra    = 0;
            wc.cbWndExtra    = 0;
            wc.hInstance     = iApp->gethInstance( );
            wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
            wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
            wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
            wc.lpszMenuName  = TEXT( "GenericAppMenu");
            wc.lpszClassName = TEXT( "myWindowClass" );
            wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);
        }

        MainWindow::~MainWindow()
        {
        }

        void MainWindow::Init()
        {
            if( !RegisterClassEx(&wc) )
            {
                MessageBox(NULL, TEXT( "Window Registration Failed!" ), TEXT( "Error!" ), MB_ICONEXCLAMATION | MB_OK);
                exit(0);
            }
        }

        void MainWindow::Display( )
        {
            hWnd = ::CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("myWindowClass"),
            TEXT("The title of my window"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
            240, 120, NULL, NULL, iApp->gethInstance( ), iApp->getMainControl( ) );

            if(hWnd == NULL)
            {
                ::MessageBox( NULL, TEXT( "Window Creation Failed!" ),
                    TEXT( "Error!" ), MB_ICONEXCLAMATION | MB_OK );
                exit(0);
            }

        ::ShowWindow( hWnd, iApp->getnCmdShow( ) );
        ::UpdateWindow(hWnd);
    }
}

-

        #ifndef ICONTROLLER_H_
        #define ICONTROLLER_H_

        #include <windows.h>

        namespace nApplication
        {
            class IController
            {
            public:
                virtual int CheckStatus() = 0;
            };
    }

    #endif ICONTROLLER_H_

-

    #ifndef CONTROLLER_H_
    #define CONTROLLER_H_

    #include <windows.h>
    #include "IController.h"
    #include "IApplication.h"

    namespace nApplication
    {
        class Controller : public IController
        {
        public:
            Controller( IApplication *iApp );
            virtual ~Controller();
            virtual int CheckStatus();
        private:
            Controller( Controller &c );
            Controller& operator= ( Controller &c );
            IApplication *iApp;
        };
    }

    #endif //CONTROLLER_H_

-

    #include "Controller.h"

    namespace nApplication
    {
        Controller::Controller( IApplication *iApp ) : iApp( iApp )
        {

        }

        Controller::~Controller()
        {
        }

        int Controller::CheckStatus()
        {
            return 0;
        }
    }

-

#include <windows.h>
#include "Application.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    nApplication::Application app( hInstance, nCmdShow );
    return app.Run( );
}

-

main.exe : main.cpp
    cl /EHsc main.cpp Application.cpp Controller.cpp MainWindow.cpp user32.lib gdi32.lib
    del *.obj
#/link /SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup

Body:
If you are making a library, you don't have a WinMain, you have a DllMain for dynamic libraries, or nothing for static libraries.

In your case, you'd need to export all the classes functionality from your dll, then in any apps that use your library, you'd include the headers of your project and link to the .lib of the library, then have this in your app where you need the GUI functionality:

nApplication::Application app( hInstance, nCmdShow );
return app.Run( );

Of course this ignores all the side details like registering event callbacks and setup along those lines, however Qt is free and open source, you you might want to look into that before reinventing the wheel, or to help make your own wheel a little rounder.


来源: stackexchange

问:
How can I use a package (such as transformers) in python script through Java ProcessBuilder
To connect Java and Python parts of a pipeline I am experimenting with different methods. Currently I am trying the ProcessBuilder approach using the following code in Java:

```<code>import java.io.*;
import java.util.*;

public class Tryout {
    public static void main(String []args) {
        try {
            var processBuilder = new ProcessBuilder("/usr/bin/python3", "tryout.py", "example string for testing purposes");
            processBuilder.redirectErrorStream(true);
            var process = processBuilder.start();
            process.waitFor();
            System.out.println(process);
            try (var reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {

                String line;

                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            }
        }
        catch(IOException e){
            System.out.println(e.getMessage());
        }
        catch(InterruptedException e){
            System.out.println(e.getMessage());
        }
    }
}
</code>```

And the code for python:

```<code>from transformers import BertTokenizer
import sys

print("hello from python!")
input_string = sys.argv[1]
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
tokens = tokenizer(input_string, padding='max_length', max_length=512, truncation=True, return_tensors="np")
print(list(tokens['input_ids'][0]))
print(list(tokens['attention_mask'][0]))
</code>```

However, this gives me the error: ModuleNotFoundError: No module named 'transformers'.
Before you ask, the transformers package is installed and the python script runs fine when called from the command line.
My question is: How do I include these Modules within the JVM?

I don't fully understand the technical details of ProcessBuilder and assumed it would run in command line using my local python environment, but apparently that is not the case.

答:
Make sure that PYTHONPATH for JVM launch is same as for python from the shell it is launched from. This will ensure that the environment being used when python runs as a sub-process of Java will match the environment when run directly from your shell / terminal.

Edit

For others with same issue, here are a few ways to check or set PYTHONPATH for Java -> Python calls. By default Java passes on the value used from its own environment variables:

```<code>System.out.println("getenv().PYTHONPATH="+System.getenv("PYTHONPATH"));
</code>```

Or set PYTHONPATH just for ProcessBuilder launch:

```<code>String pypath = List.of(Path.of("somedir"), Path.of("anotherdir"))
       .stream().map(Path::toAbsolutePath).map(Path::toString)
       .collect(Collectors.joining(File.pathSeparator));
pb.environment().put("PYTHONPATH", pypath);
System.out.println("environment().PYTHONPATH="+pb.environment().get("PYTHONPATH"));
</code>```

Check the value used in existing python scripts:

```<code># import os
print("PYTHONPATH", os.getenv('PYTHONPATH'))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
To connect Java and Python parts of a pipeline I am experimenting with different methods. Currently I am trying the ProcessBuilder approach using the following code in Java:

import java.io.*;
import java.util.*;

public class Tryout {
    public static void main(String []args) {
        try {
            var processBuilder = new ProcessBuilder("/usr/bin/python3", "tryout.py", "example string for testing purposes");
            processBuilder.redirectErrorStream(true);
            var process = processBuilder.start();
            process.waitFor();
            System.out.println(process);
            try (var reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {

                String line;

                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            }
        }
        catch(IOException e){
            System.out.println(e.getMessage());
        }
        catch(InterruptedException e){
            System.out.println(e.getMessage());
        }
    }
}

And the code for python:

from transformers import BertTokenizer
import sys

print("hello from python!")
input_string = sys.argv[1]
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
tokens = tokenizer(input_string, padding='max_length', max_length=512, truncation=True, return_tensors="np")
print(list(tokens['input_ids'][0]))
print(list(tokens['attention_mask'][0]))

However, this gives me the error: ModuleNotFoundError: No module named 'transformers'.
Before you ask, the transformers package is installed and the python script runs fine when called from the command line.
My question is: How do I include these Modules within the JVM?

I don't fully understand the technical details of ProcessBuilder and assumed it would run in command line using my local python environment, but apparently that is not the case.

Body:
Make sure that PYTHONPATH for JVM launch is same as for python from the shell it is launched from. This will ensure that the environment being used when python runs as a sub-process of Java will match the environment when run directly from your shell / terminal.

Edit

For others with same issue, here are a few ways to check or set PYTHONPATH for Java -> Python calls. By default Java passes on the value used from its own environment variables:

System.out.println("getenv().PYTHONPATH="+System.getenv("PYTHONPATH"));

Or set PYTHONPATH just for ProcessBuilder launch:

String pypath = List.of(Path.of("somedir"), Path.of("anotherdir"))
       .stream().map(Path::toAbsolutePath).map(Path::toString)
       .collect(Collectors.joining(File.pathSeparator));
pb.environment().put("PYTHONPATH", pypath);
System.out.println("environment().PYTHONPATH="+pb.environment().get("PYTHONPATH"));

Check the value used in existing python scripts:

# import os
print("PYTHONPATH", os.getenv('PYTHONPATH'))


问:
Can a custom allocator improve cache locality for lists?
This is a rather hypothetical question.

I only have limited knowledge about how the cpu cache works.

I know a cpu loads subsequent bytes into the cache.

Since a list uses pointers/indirection into random locations in memory, it has relatively bad locality compared to lets say vector or an array.

My question is: If I write an allocator where the data of all nodes is next to each other (via linear allocator), will this improve the cache loading? The indirection is still there but the data for the different nodes are in similar locations.

答:
If I write an allocator where the data of all nodes is next to each other (via linear allocator), will this improve the cache loading?

Yes, if you access the objects in a way that benefits from it. I.e. if you access the elements in a sequence.


问:
How to switch database connection for the job being processed in laravel
I have a Laravel project that interfaces with a react project via APIs. It uses an RDS MySQL instance as the database.

We perform some pre-computation for the user's social feed via jobs processed through SQS. The database instance usage spikes a lot when these jobs are running and ends up affecting live traffic that connects to the same database instance.

I created a read-replica instance of the original and want my jobs to connect to this read-replica for all computation, primarily all queries that would run should connect to the read-replica connection.

The queries I define within the jobs use the on function to specify which connection to use Model::on('mysql_read_replica') where mysql_read_replica is defined in config/database.php.

However, custom attributes within models, helper functions across the codebase continue to use the original connection. This continues to overload the original instance affecting live traffic.

I have looked at the following question and came up with the following solution: I update config and set connection to the read only replica and change it back at the end of the handle method

```<code>public function handle() {
    $mysql_rr = Config::get('database.connections.mysql_rr');
    $mysql = Config::get('database.connections.mysql');
    DB::purge('mysql');
    Config::set('database.connections.mysql', $mysql_rr);

    // job processing code

    DB::purge('mysql');
    Config::set('database.connections.mysql', $mysql);
}
</code>```

I added an event listening callback and I am able to validate all queries are run against the read replica instance using:

```<code>\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
    $sql = $query->sql;
    $time = $query->time;
    $connection = $query->connection->getName();
    $dbName = $query->connection->getDatabaseName();

    Log::info('job query : '.$sql);
    Log::info('job time '.$time);
    Log::info('job connection '.$connection);
    Log::info('job dbName '.$dbName);
});
</code>```

Since these jobs are supposed to be unique for each user. It has a UniqueJobs trait and the issue I see now is that once the job finishes execution, it fails to release the lock stored on cache.
The error log states:

```<code>[2022-02-09 13:43:39] local.ERROR: Call to a member function prepare() on null {"exception":"[object] (Error(code: 0): Call to a member function prepare() on null at vendor\laravel\framework\src\Illuminate\Database\Connection.php:492)
[stacktrace]
#0 vendor\laravel\framework\src\Illuminate\Database\Connection.php(671): Illuminate\Database\Connection->Illuminate\Database\{closure}('delete from `ca...', Array)
#1 vendor\laravel\framework\src\Illuminate\Database\Connection.php(638): Illuminate\Database\Connection->runQueryCallback('delete from `ca...', Array, Object(Closure))
#2 vendor\laravel\framework\src\Illuminate\Database\Connection.php(503): Illuminate\Database\Connection->run('delete from `ca...', Array, Object(Closure))
#3 vendor\laravel\framework\src\Illuminate\Database\Connection.php(448): Illuminate\Database\Connection->affectingStatement('delete from `ca...', Array)
#4 vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php(3043): Illuminate\Database\Connection->delete('delete from `ca...', Array)
#5 vendor\laravel\framework\src\Illuminate\Cache\DatabaseLock.php(127): Illuminate\Database\Query\Builder->delete()
#6 vendor\laravel\framework\src\Illuminate\Queue\CallQueuedHandler.php(211): Illuminate\Cache\DatabaseLock->forceRelease()
#7 vendor\laravel\framework\src\Illuminate\Queue\CallQueuedHandler.php(254): Illuminate\Queue\CallQueuedHandler->ensureUniqueJobLockIsReleased(Object(App\Jobs\GenerateDigest))
#8 vendor\laravel\framework\src\Illuminate\Queue\Jobs\Job.php(213): Illuminate\Queue\CallQueuedHandler->failed(Array, Object(Error), '634f580c-3a6f-4...')
#9 vendor\laravel\framework\src\Illuminate\Queue\Jobs\Job.php(192): Illuminate\Queue\Jobs\Job->failed(Object(Error))
#10 vendor\laravel\framework\src\Illuminate\Queue\Worker.php(548): Illuminate\Queue\Jobs\Job->fail(Object(Error))
#11 vendor\laravel\framework\src\Illuminate\Queue\Worker.php(509): Illuminate\Queue\Worker->failJob(Object(Illuminate\Queue\Jobs\SqsJob), Object(Error))
#12 vendor\laravel\framework\src\Illuminate\Queue\Worker.php(437): Illuminate\Queue\Worker->markJobAsFailedIfWillExceedMaxAttempts('sqs', Object(Illuminate\Queue\Jobs\SqsJob), 1, Object(Error))
#13 vendor\laravel\framework\src\Illuminate\Queue\Worker.php(414): Illuminate\Queue\Worker->handleJobException('sqs', Object(Illuminate\Queue\Jobs\SqsJob), Object(Illuminate\Queue\WorkerOptions), Object(Error))
#14 vendor\laravel\framework\src\Illuminate\Queue\Worker.php(360): Illuminate\Queue\Worker->process('sqs', Object(Illuminate\Queue\Jobs\SqsJob), Object(Illuminate\Queue\WorkerOptions))
#15 vendor\laravel\framework\src\Illuminate\Queue\Worker.php(311): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\SqsJob), 'sqs', Object(Illuminate\Queue\WorkerOptions))
#16 vendor\laravel\framework\src\Illuminate\Queue\Console\WorkCommand.php(117): Illuminate\Queue\Worker->runNextJob('sqs', 'sqs-generation-queue', Object(Illuminate\Queue\WorkerOptions))
#17 vendor\laravel\framework\src\Illuminate\Queue\Console\WorkCommand.php(101): Illuminate\Queue\Console\WorkCommand->runWorker('sqs', 'sqs-generation-queue')
#18 vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(36): Illuminate\Queue\Console\WorkCommand->handle()
#19 vendor\laravel\framework\src\Illuminate\Container\Util.php(40): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#20 vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(93): Illuminate\Container\Util::unwrapIfClosure(Object(Closure))
#21 vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(37): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#22 vendor\laravel\framework\src\Illuminate\Container\Container.php(611): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#23 vendor\laravel\framework\src\Illuminate\Console\Command.php(136): Illuminate\Container\Container->call(Array)
#24 vendor\symfony\console\Command\Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#25 vendor\laravel\framework\src\Illuminate\Console\Command.php(121): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#26 vendor\symfony\console\Application.php(971): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#27 vendor\symfony\console\Application.php(290): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#28 vendor\symfony\console\Application.php(166): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#29 vendor\laravel\framework\src\Illuminate\Console\Application.php(92): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#30 vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php(129): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#31 artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#32 {main}
"}
</code>```

After adding some logging, I find that the getPdo() function in vendor\laravel\framework\src\Illuminate\Database\Connection.php is basically null as the stacktrace says.
If I remove the code to switch connections, the job processes fine and is able to release the lock.

答:
Since we use database as our cache store, I set the connection for cache in config/database to a new connection that contains the connection for the read-write instance.

```<code>        'database' => [
            'driver' => 'database',
            'table' => 'cache',
            // use the read write database connection for cache operations
            'connection' => 'mysql_rw',
        ],
</code>```

This allows the cache to connect to the read-write instance explicitly for handling cache_locks while allowing the jobs to switch the connection as needed.

Body:
I have a Laravel project that interfaces with a react project via APIs. It uses an RDS MySQL instance as the database.

We perform some pre-computation for the user's social feed via jobs processed through SQS. The database instance usage spikes a lot when these jobs are running and ends up affecting live traffic that connects to the same database instance.

I created a read-replica instance of the original and want my jobs to connect to this read-replica for all computation, primarily all queries that would run should connect to the read-replica connection.

The queries I define within the jobs use the on function to specify which connection to use Model::on('mysql_read_replica') where mysql_read_replica is defined in config/database.php.

However, custom attributes within models, helper functions across the codebase continue to use the original connection. This continues to overload the original instance affecting live traffic.

I have looked at the following question and came up with the following solution: I update config and set connection to the read only replica and change it back at the end of the handle method

public function handle() {
    $mysql_rr = Config::get('database.connections.mysql_rr');
    $mysql = Config::get('database.connections.mysql');
    DB::purge('mysql');
    Config::set('database.connections.mysql', $mysql_rr);

    // job processing code

    DB::purge('mysql');
    Config::set('database.connections.mysql', $mysql);
}

I added an event listening callback and I am able to validate all queries are run against the read replica instance using:

\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
    $sql = $query->sql;
    $time = $query->time;
    $connection = $query->connection->getName();
    $dbName = $query->connection->getDatabaseName();

    Log::info('job query : '.$sql);
    Log::info('job time '.$time);
    Log::info('job connection '.$connection);
    Log::info('job dbName '.$dbName);
});

Since these jobs are supposed to be unique for each user. It has a UniqueJobs trait and the issue I see now is that once the job finishes execution, it fails to release the lock stored on cache.
The error log states:

[2022-02-09 13:43:39] local.ERROR: Call to a member function prepare() on null {"exception":"[object] (Error(code: 0): Call to a member function prepare() on null at vendor\laravel\framework\src\Illuminate\Database\Connection.php:492)
[stacktrace]
#0 vendor\laravel\framework\src\Illuminate\Database\Connection.php(671): Illuminate\Database\Connection->Illuminate\Database\{closure}('delete from `ca...', Array)
#1 vendor\laravel\framework\src\Illuminate\Database\Connection.php(638): Illuminate\Database\Connection->runQueryCallback('delete from `ca...', Array, Object(Closure))
#2 vendor\laravel\framework\src\Illuminate\Database\Connection.php(503): Illuminate\Database\Connection->run('delete from `ca...', Array, Object(Closure))
#3 vendor\laravel\framework\src\Illuminate\Database\Connection.php(448): Illuminate\Database\Connection->affectingStatement('delete from `ca...', Array)
#4 vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php(3043): Illuminate\Database\Connection->delete('delete from `ca...', Array)
#5 vendor\laravel\framework\src\Illuminate\Cache\DatabaseLock.php(127): Illuminate\Database\Query\Builder->delete()
#6 vendor\laravel\framework\src\Illuminate\Queue\CallQueuedHandler.php(211): Illuminate\Cache\DatabaseLock->forceRelease()
#7 vendor\laravel\framework\src\Illuminate\Queue\CallQueuedHandler.php(254): Illuminate\Queue\CallQueuedHandler->ensureUniqueJobLockIsReleased(Object(App\Jobs\GenerateDigest))
#8 vendor\laravel\framework\src\Illuminate\Queue\Jobs\Job.php(213): Illuminate\Queue\CallQueuedHandler->failed(Array, Object(Error), '634f580c-3a6f-4...')
#9 vendor\laravel\framework\src\Illuminate\Queue\Jobs\Job.php(192): Illuminate\Queue\Jobs\Job->failed(Object(Error))
#10 vendor\laravel\framework\src\Illuminate\Queue\Worker.php(548): Illuminate\Queue\Jobs\Job->fail(Object(Error))
#11 vendor\laravel\framework\src\Illuminate\Queue\Worker.php(509): Illuminate\Queue\Worker->failJob(Object(Illuminate\Queue\Jobs\SqsJob), Object(Error))
#12 vendor\laravel\framework\src\Illuminate\Queue\Worker.php(437): Illuminate\Queue\Worker->markJobAsFailedIfWillExceedMaxAttempts('sqs', Object(Illuminate\Queue\Jobs\SqsJob), 1, Object(Error))
#13 vendor\laravel\framework\src\Illuminate\Queue\Worker.php(414): Illuminate\Queue\Worker->handleJobException('sqs', Object(Illuminate\Queue\Jobs\SqsJob), Object(Illuminate\Queue\WorkerOptions), Object(Error))
#14 vendor\laravel\framework\src\Illuminate\Queue\Worker.php(360): Illuminate\Queue\Worker->process('sqs', Object(Illuminate\Queue\Jobs\SqsJob), Object(Illuminate\Queue\WorkerOptions))
#15 vendor\laravel\framework\src\Illuminate\Queue\Worker.php(311): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\SqsJob), 'sqs', Object(Illuminate\Queue\WorkerOptions))
#16 vendor\laravel\framework\src\Illuminate\Queue\Console\WorkCommand.php(117): Illuminate\Queue\Worker->runNextJob('sqs', 'sqs-generation-queue', Object(Illuminate\Queue\WorkerOptions))
#17 vendor\laravel\framework\src\Illuminate\Queue\Console\WorkCommand.php(101): Illuminate\Queue\Console\WorkCommand->runWorker('sqs', 'sqs-generation-queue')
#18 vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(36): Illuminate\Queue\Console\WorkCommand->handle()
#19 vendor\laravel\framework\src\Illuminate\Container\Util.php(40): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#20 vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(93): Illuminate\Container\Util::unwrapIfClosure(Object(Closure))
#21 vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(37): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#22 vendor\laravel\framework\src\Illuminate\Container\Container.php(611): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#23 vendor\laravel\framework\src\Illuminate\Console\Command.php(136): Illuminate\Container\Container->call(Array)
#24 vendor\symfony\console\Command\Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#25 vendor\laravel\framework\src\Illuminate\Console\Command.php(121): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#26 vendor\symfony\console\Application.php(971): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#27 vendor\symfony\console\Application.php(290): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#28 vendor\symfony\console\Application.php(166): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#29 vendor\laravel\framework\src\Illuminate\Console\Application.php(92): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#30 vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php(129): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#31 artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#32 {main}
"}

After adding some logging, I find that the getPdo() function in vendor\laravel\framework\src\Illuminate\Database\Connection.php is basically null as the stacktrace says.
If I remove the code to switch connections, the job processes fine and is able to release the lock.

Body:
Since we use database as our cache store, I set the connection for cache in config/database to a new connection that contains the connection for the read-write instance.

        'database' => [
            'driver' => 'database',
            'table' => 'cache',
            // use the read write database connection for cache operations
            'connection' => 'mysql_rw',
        ],

This allows the cache to connect to the read-write instance explicitly for handling cache_locks while allowing the jobs to switch the connection as needed.


问:
What is the correct implementation of Katz index in python?
I am trying to implement Katz index using the following formula

```<code>alpha=0.01

G = nx.karate_club_graph()
A=nx.adjacency_matrix(G).todense()
n=A.shape[0]
I=np.eye(n,n)
result=np.linalg.inv(iden - (alpha * A))-I
print(np.round(result,6))
</code>```

However I am not sure if this implementation is correct, because no iteration (path length is involved). I just directly code this formula inv((I − alpha*A)-I

Any help will be highly appreciated

答: NetworkX library in python uses a power method to implement the Katz index. you can compare result of your algorithm with that</p>

Body:
I am trying to implement Katz index using the following formula

alpha=0.01

G = nx.karate_club_graph()
A=nx.adjacency_matrix(G).todense()
n=A.shape[0]
I=np.eye(n,n)
result=np.linalg.inv(iden - (alpha * A))-I
print(np.round(result,6))

However I am not sure if this implementation is correct, because no iteration (path length is involved). I just directly code this formula inv((I − alpha*A)-I

Any help will be highly appreciated


问:
Is it possible to add tensors of different sizes together in pytorch?
I have an image gradient of size (3, 224, 224) and a patch of (1, 768). is it possible to add this gradient to the patch to get a size of the patch (1, 768)?

Forgive my inquisitiveness. I know pytorch too utilizes broadcasting and I am not sure if I will able to do so with two different tensors in way similar to the line below:

```<code>torch.add(a, b)
</code>```

For example:

The end product would be the same patch on the left with the gradient of an entire image on the right added to it. My understanding is that it’s not possible, but knowledge isn’t bounded.

答: I figured out to do it myself. I divided the image gradient (right) into 16 x 16 patches, created a loop that adds each patch to the original image patch (left). This way, I was able to add a 224 x 224 image gradient into a 16 x 16 patch. I just wanted to see what would happen if I do such

Body:
I have an image gradient of size (3, 224, 224) and a patch of (1, 768). is it possible to add this gradient to the patch to get a size of the patch (1, 768)?

Forgive my inquisitiveness. I know pytorch too utilizes broadcasting and I am not sure if I will able to do so with two different tensors in way similar to the line below:

torch.add(a, b)

For example:

The end product would be the same patch on the left with the gradient of an entire image on the right added to it. My understanding is that it’s not possible, but knowledge isn’t bounded.


问:
Type mismatch: cannot convert from element type Object to int
I'm getting the following error on the line where it says ht.keySet():

Type mismatch: cannot convert from element type Object to int

ht is a LinkedHashMap.

```<code>for (int key : ht.keySet())
{
    if(ht.get(key).size() == 0)
    {
         System.out.println("There is no errors in " + key) ;
    }
    else
    {
        System.out.println("ERROR: there are unexpected errors in " + key);
    }
}
</code>```

答:
Use Integer instead of int and it will probably work.
The keys in the LinkedHashMap must be objects, not primitive types.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm getting the following error on the line where it says ht.keySet():

Type mismatch: cannot convert from element type Object to int

ht is a LinkedHashMap.

for (int key : ht.keySet())
{
    if(ht.get(key).size() == 0)
    {
         System.out.println("There is no errors in " + key) ;
    }
    else
    {
        System.out.println("ERROR: there are unexpected errors in " + key);
    }
}


问:
Update nested array object field in mongodb using spring boot
New to mongodb,
Tring to update multiple array object field of an document.
not getting expected result

Document Structure:

```<code>{
    "_id" : ObjectId("4faaba123412d654fe83hg876"),
    "user_id" : 123456,

    "items" : [{
            Name:{
                    "id":1,
                    "item_name" : "my_item_one",
                    "price" : 20
            },
            Details:{
                    "Date" : "10/02/2022",
                    "Address":"test"
            }}],
            [{
            Name:{
                    "id":2,
                    "item_name" : "my_item_two",
                    "price" : 20
            },
            Details:{
                    "Date" : "10/02/2022",
                    "Address":"test"
            }}]
}
</code>```

Based on id need to update date

Spring boot code

```<code>Query query = new Query(Criteria.where("user_id").is("123456").and("items")
.eleMatch(Criteria.where("items.Name.id").is(1)));
Update update = new Update().set("items.0.Details.Date", "29/01/2022");
mongoOperation.findAndModify(query, update, Items.class);
</code>```

but when I run this query it is returning null
Can any one help on this
Thanks
,
Also tried

```<code>Query query = new Query(Criteria.where("user_id").is("123456").and("items")
.eleMatch(Criteria.where("items.Name.id").is(1)));
Update update = new Update().set("items.Details.Date", "29/01/2022");
mongoOperation.findAndModify(query, update, Items.class);
</code>```

答: i think your query doesn't find anything to update. try running the query as a "find" in java and see which document comes back. my hunch is that the "and eleMatch" part is wrong. just query for the entire document by the user_id, and execute the update on the specific field. also, the syntax on the update you described will update all items, you need to specify the index in the array. perhaps doing the update manually in java would be easier.</p>

Body:
New to mongodb,
Tring to update multiple array object field of an document.
not getting expected result

Document Structure:

{
    "_id" : ObjectId("4faaba123412d654fe83hg876"),
    "user_id" : 123456,

    "items" : [{
            Name:{
                    "id":1,
                    "item_name" : "my_item_one",
                    "price" : 20
            },
            Details:{
                    "Date" : "10/02/2022",
                    "Address":"test"
            }}],
            [{
            Name:{
                    "id":2,
                    "item_name" : "my_item_two",
                    "price" : 20
            },
            Details:{
                    "Date" : "10/02/2022",
                    "Address":"test"
            }}]
}

Based on id need to update date

Spring boot code

Query query = new Query(Criteria.where("user_id").is("123456").and("items")
.eleMatch(Criteria.where("items.Name.id").is(1)));
Update update = new Update().set("items.0.Details.Date", "29/01/2022");
mongoOperation.findAndModify(query, update, Items.class);

but when I run this query it is returning null
Can any one help on this
Thanks
,
Also tried

Query query = new Query(Criteria.where("user_id").is("123456").and("items")
.eleMatch(Criteria.where("items.Name.id").is(1)));
Update update = new Update().set("items.Details.Date", "29/01/2022");
mongoOperation.findAndModify(query, update, Items.class);


问:
SwiftUI ForEach statement iterate the list twice
I've got ForEach loop inside a picker widget, that suppose to iterate a list of items (handler.items).

However, in reality, I get that the tags where not properly set and $arg = $0 instead of $arg = $0.components(separatedBy: " ")[0]

after debugging the problem, it seems that although i see the right number of items according to the list size ... the ForEach iterate all the items twice, thus causing duplicated tags where they suppose to be unique.

here's the code, any idea how come the iteration repeat itself ?

```<code>VStack {
    Picker("items", selection: $arg) {
        ForEach(handler.items , id: \.self, content: {
            Text($0).tag($0.components(separatedBy: " ")[0])
        })
    }
}
</code>```

and here's how handler.items are defined. it's actually a separated object that is visible from the view, and can be changed from swift native methods.

```<code>class myHandler: ObservableObject {
  @Published var items = [String]()
}
</code>```

when setting a breakpoint in the ForEach statement, i could print this object

```<code>(lldb) p handler.items
([String]) $R1 = 2 values {
  [0] = "aaa bbb cc 1.1.1.1"
  [1] = "ddd eee ff 2.2.2.2"
}
</code>```

When i put breakpoint inside the ForEach body, I could see that the breakpoint caught there 4 times, and printing the iterator value i Got this printouts:

```<code>aaa bbb cc 1.1.1.1
ddd eee ff 2.2.2.2
aaa bbb cc 1.1.1.1
ddd eee ff 2.2.2.2
</code>```

EDIT : here's a minimal reproducible example. notice the circled text that clearly shows that the arg didn't get the tag expression but the whole item :

答:
Well I suggest moving the strings to a custom enumeration instead of your ObservableObject. Setting the tag doesn't really need to be done then. And no duplicate entries

Here’s an example from Apple

enum Items: String, CaseIterable, Identifiable {
    case a = "aaa bbb cc 1.1.1.1"
    case b = "ddd eee ff 2.2.2.2"
    var id: Self { self }
}

struct ContentView: View {

    @State var selection = Items.a

    var body: some View {

        Picker("Items", selection: $selection) {
            ForEach(Items.allCases) { item in
                Text(item.rawValue)
            }
        }

    }
}
```

Body:
I've got ForEach loop inside a picker widget, that suppose to iterate a list of items (handler.items).

However, in reality, I get that the tags where not properly set and $arg = $0 instead of $arg = $0.components(separatedBy: " ")[0]

after debugging the problem, it seems that although i see the right number of items according to the list size ... the ForEach iterate all the items twice, thus causing duplicated tags where they suppose to be unique.

here's the code, any idea how come the iteration repeat itself ?

VStack {
    Picker("items", selection: $arg) {
        ForEach(handler.items , id: \.self, content: {
            Text($0).tag($0.components(separatedBy: " ")[0])
        })
    }
}

and here's how handler.items are defined. it's actually a separated object that is visible from the view, and can be changed from swift native methods.

class myHandler: ObservableObject {
  @Published var items = [String]()
}

when setting a breakpoint in the ForEach statement, i could print this object

(lldb) p handler.items
([String]) $R1 = 2 values {
  [0] = "aaa bbb cc 1.1.1.1"
  [1] = "ddd eee ff 2.2.2.2"
}

When i put breakpoint inside the ForEach body, I could see that the breakpoint caught there 4 times, and printing the iterator value i Got this printouts:

aaa bbb cc 1.1.1.1
ddd eee ff 2.2.2.2
aaa bbb cc 1.1.1.1
ddd eee ff 2.2.2.2

EDIT : here's a minimal reproducible example. notice the circled text that clearly shows that the arg didn't get the tag expression but the whole item :


问:
Does AWS Lambda (NodeJS) not allow http.request or https.request?
I am attempting to make a request to another API from a Lambda. I am finding that using the NodeJS http and https modules allow for GET requests but any others (e.g. POST) do not work; POST coincidentally is the only method I need to work for the service I am attempting to call.

Here is a working example of Lambda performing a GET and receiving a 200 response:

const https = require('https')

function handler(event, context, callback) {
    const options = {
        hostname: 'encrypted.google.com'
    }

    https
        .get(options, (res) => {
            console.log('statusCode:', res.statusCode);

            res.on('end', callback.bind(null, null))
        })
        .on('error', callback);
}

exports.handler = handler
```
<p>So that proves that he request is allowed. However, if the script attempts to make the same request using the <code>.request()</code> method of the https (or https) lib/module the request never finishes and the Lambda times out.</p>
<pre class="lang-js prettyprint-override"><code>const https = require('https')

function handler(event, context, callback) {
    const options = {
        hostname: 'encrypted.google.com',
        method: 'GET'
    }

    https
        .request(options, (res) => {
            console.log('statusCode:', res.statusCode);

            res.on('end', callback.bind(null, null))
        })
        .on('error', callback);
}

exports.handler = handler
</code>```

I don't know what I am doing wrong. The call https.request() silently fails - doesn't throw an error - and nothing is reported in the log.

答:
The POST method is done by the request method.

This is the lambda code:

```<code>const https = require('https');

const options = {
  hostname: 'Your host name',
  path: '/api/v1/Login/Login',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body : JSON.stringify({
        'email': 'hassan.uzair9@gmail.com',
        'password': 'Asdf1234.',
  })
};

var result;
try{
    result = await https.request(options);
    console.log("result.....",result);
}catch(err){
    console.log("err......",err);
}
</code>```

Body:
I am attempting to make a request to another API from a Lambda. I am finding that using the NodeJS http and https modules allow for GET requests but any others (e.g. POST) do not work; POST coincidentally is the only method I need to work for the service I am attempting to call.

Here is a working example of Lambda performing a GET and receiving a 200 response:

const https = require('https')

function handler(event, context, callback) {
    const options = {
        hostname: 'encrypted.google.com'
    }

    https
        .get(options, (res) => {
            console.log('statusCode:', res.statusCode);

            res.on('end', callback.bind(null, null))
        })
        .on('error', callback);
}

exports.handler = handler

So that proves that he request is allowed. However, if the script attempts to make the same request using the .request() method of the https (or https) lib/module the request never finishes and the Lambda times out.

const https = require('https')

function handler(event, context, callback) {
    const options = {
        hostname: 'encrypted.google.com',
        method: 'GET'
    }

    https
        .request(options, (res) => {
            console.log('statusCode:', res.statusCode);

            res.on('end', callback.bind(null, null))
        })
        .on('error', callback);
}

exports.handler = handler

I don't know what I am doing wrong. The call https.request() silently fails - doesn't throw an error - and nothing is reported in the log.

Body:
The POST method is done by the request method.

This is the lambda code:

const https = require('https');

const options = {
  hostname: 'Your host name',
  path: '/api/v1/Login/Login',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body : JSON.stringify({
        'email': 'hassan.uzair9@gmail.com',
        'password': 'Asdf1234.',
  })
};

var result;
try{
    result = await https.request(options);
    console.log("result.....",result);
}catch(err){
    console.log("err......",err);
}


问:
Data structure when submitting in Firestore that handles tracking of inventories with product variations
Each product may have variations of sizes and each with its different colors and quantities.

Example:

Product Name: Shirt

Size: Large

Color: Red, Qty: 10

Color: Blue, Qty: 5

Product Name: Cupp

Size: Large

Color: Red, Qty: 10

Color: Blue, Qty: 5

The way I submitted it and what shows in the console:

Code:
Link: https://codesandbox.io/s/form-order-working-4f6g2

Firestore:

答:
Firestore doesn't have the ability to update an existing element in an indexed array. It supports only two methods, arrayUnion() to add an element and arrayRemove() to remove an element from the array as mentioned in the documentation.

As an alternative, you can read the entire array out of the document, make modifications to it in memory, then update the modified array field entirely. This is an error prone and tedious process. You can have a look at this article to know more about it.

I am not sure of your use case, but it seems you can make your database structure more suitable by using maps(nested objects) instead of arrays. Something like this -

By doing this you can update the nested objects by dot notation as mentioned here. Some sample to update the document will look like this -

```<code>async function updateData(color) {
 const docRef = doc(db, 'collectionId', 'documentId');
 await updateDoc(docRef,{
   [`colorStockList.${color}`]:300
 });
}
</code>```

UPDATE

To update the stocks automatically you can implement a method which will get invoked when an order is placed. Within that method you can use the increment() method as described here. The increment() method can increase or decrease the stocks based on the value provided by you. For example if someone places an order for 3 shirts you can pass that number to the increment() method so that it can decrease the stocks by that value. Make sure to use -ve sign with the value when you want to decrease the stocks.

The method should look something like this -

```<code>async function updateData(color,value) {
  const docRef = doc(db, 'collectionId', 'documentId');
 await updateDoc(docRef,{
   [`colorStockList.${color}`]:increment(-value)
 });
}
</code>```

Body:
Firestore doesn't have the ability to update an existing element in an indexed array. It supports only two methods, arrayUnion() to add an element and arrayRemove() to remove an element from the array as mentioned in the documentation.

As an alternative, you can read the entire array out of the document, make modifications to it in memory, then update the modified array field entirely. This is an error prone and tedious process. You can have a look at this article to know more about it.

I am not sure of your use case, but it seems you can make your database structure more suitable by using maps(nested objects) instead of arrays. Something like this -

By doing this you can update the nested objects by dot notation as mentioned here. Some sample to update the document will look like this -

async function updateData(color) {
 const docRef = doc(db, 'collectionId', 'documentId');
 await updateDoc(docRef,{
   [`colorStockList.${color}`]:300
 });
}

UPDATE

To update the stocks automatically you can implement a method which will get invoked when an order is placed. Within that method you can use the increment() method as described here. The increment() method can increase or decrease the stocks based on the value provided by you. For example if someone places an order for 3 shirts you can pass that number to the increment() method so that it can decrease the stocks by that value. Make sure to use -ve sign with the value when you want to decrease the stocks.

The method should look something like this -

async function updateData(color,value) {
  const docRef = doc(db, 'collectionId', 'documentId');
 await updateDoc(docRef,{
   [`colorStockList.${color}`]:increment(-value)
 });
}


问:
HighCharts Line Chart draw y axis line for entire line points and only one line
I tried, combination chart bar and line (ultimately need to develop using react-highcharts)

I have one challenge, need to display highest value drawn line with vertical y-axis

Do we have any option to draw lines(1) for single spline(2) in Highscharts ?

refer image for 1 and 2 (attached image is using excel developed by BA)

答:
You can add a dummy column series with the same data as spline to create those lines.

```<code>{
    type: 'column',
    data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
    showInLegend: false,
    enableMouseTracking: false,
    states: {
      inactive: {
        opacity: 1
      }
    },
    pointWidth: 1,
    color: 'rgb(230, 230, 230)'
  }
</code>```

Demo: https://jsfiddle.net/BlackLabel/tfqrv296/

Body:
You can add a dummy column series with the same data as spline to create those lines.

{
    type: 'column',
    data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
    showInLegend: false,
    enableMouseTracking: false,
    states: {
      inactive: {
        opacity: 1
      }
    },
    pointWidth: 1,
    color: 'rgb(230, 230, 230)'
  }

Demo: https://jsfiddle.net/BlackLabel/tfqrv296/


问:
Running function in IOLoop.current().run_in_executor?
I read the following code

```<code>async def f():
    sc_client = session.client("ec2")
    for id in ids:
        await IOLoop.current().run_in_executor(None, lambda: client.terminate(id))
</code>```

How does it compare to the following code? Will client.terminate be run in parallel? But each execution is awaited?

```<code>    for id in ids:
        client.terminate(id)
</code>```

答:
Will client.terminate be run in parallel?

NO, it still runs as sequence.

IOLoop.current().run_in_executor will run the blocking function in a separate thread and returns an asyncio.Future, while await will wait until the Future which call client.terminate finish, then the loop continue.

The difference the 2 options you given is:

If the program has other coroutine to run, using the 1st option, the other coroutine won't block, while using the 2nd option, the other coroutine will block to wait your for loop finish.

An example to make you understand it (Here, will use loop.run_in_executor to simulate the IOLoop.current().run_in_executor for simple sake):

test.py:

```<code>import asyncio
import concurrent.futures
import time

def client_terminate(id):
    print(f"start terminate {id}")
    time.sleep(5)
    print(f"end terminate {id}")

async def f():
    loop = asyncio.get_running_loop()

    for id in range(2):
        with concurrent.futures.ThreadPoolExecutor() as pool:
            await loop.run_in_executor(pool, client_terminate, id)
        # client_terminate(id)

async def f2():
    await asyncio.sleep(1)
    print("other task")

async def main():
    await asyncio.gather(*[f(), f2()])

asyncio.run(main())
</code>```

The run output is:

```<code>$ python3 test.py
start terminate 0
other task
end terminate 0
start terminate 1
end terminate 1
</code>```

You could see the two client_terminate in for loop still runs in sequence, BUT, the function f2 which print other task inject between them, it won't block asyncio scheduler to schedule f2.

Additional:

If you comment the 2 lines related to await loop.run_in_executor & threadpool, directly call client_terminate(id), the output will be:

```<code>$ python3 test.py
start terminate 0
end terminate 0
start terminate 1
end terminate 1
other task
</code>```

Means if you don't wraps the blocking function in a Future, the other task will have to wait your for loop to finish which waste CPU.

Body:
I read the following code

async def f():
    sc_client = session.client("ec2")
    for id in ids:
        await IOLoop.current().run_in_executor(None, lambda: client.terminate(id))

How does it compare to the following code? Will client.terminate be run in parallel? But each execution is awaited?

    for id in ids:
        client.terminate(id)

Body:
Will client.terminate be run in parallel?

NO, it still runs as sequence.

IOLoop.current().run_in_executor will run the blocking function in a separate thread and returns an asyncio.Future, while await will wait until the Future which call client.terminate finish, then the loop continue.

The difference the 2 options you given is:

If the program has other coroutine to run, using the 1st option, the other coroutine won't block, while using the 2nd option, the other coroutine will block to wait your for loop finish.

An example to make you understand it (Here, will use loop.run_in_executor to simulate the IOLoop.current().run_in_executor for simple sake):

test.py:

import asyncio
import concurrent.futures
import time

def client_terminate(id):
    print(f"start terminate {id}")
    time.sleep(5)
    print(f"end terminate {id}")

async def f():
    loop = asyncio.get_running_loop()

    for id in range(2):
        with concurrent.futures.ThreadPoolExecutor() as pool:
            await loop.run_in_executor(pool, client_terminate, id)
        # client_terminate(id)

async def f2():
    await asyncio.sleep(1)
    print("other task")

async def main():
    await asyncio.gather(*[f(), f2()])

asyncio.run(main())

The run output is:

$ python3 test.py
start terminate 0
other task
end terminate 0
start terminate 1
end terminate 1

You could see the two client_terminate in for loop still runs in sequence, BUT, the function f2 which print other task inject between them, it won't block asyncio scheduler to schedule f2.

Additional:

If you comment the 2 lines related to await loop.run_in_executor & threadpool, directly call client_terminate(id), the output will be:

$ python3 test.py
start terminate 0
end terminate 0
start terminate 1
end terminate 1
other task

Means if you don't wraps the blocking function in a Future, the other task will have to wait your for loop to finish which waste CPU.


问:
Conditionally render a div with vue.js
I am trying to build a quiz which when the user chooses a selection and submits the answer the notification div displays whether choice is correct or not. I have got this logic working however what is happening is the div is disappearing each time the next question is answered. I want to keep the previous question result on the screen and lock the user out of answering the question again and show the correct answer.

Here is what I have so far:

```<code>                  <div
                    class="container"
                    v-for="options in quiz"
                    v-bind:key="options.quizId"
                  >
                    <h3>{{ options.question }}</h3>
                    <div
                      class="control"
                    >
                      <label class="radio">
                        <input
                          type="radio"
                          :value="options.op1"
                          v-model="selectedAnswer"
                        />
                        {{ options.op1 }}
                      </label>
                    </div>
                    <div class="control">
                      <label class="radio">
                        <input
                          type="radio"
                          :value="options.op2"
                          v-model="selectedAnswer"
                        />
                        {{ options.op2 }}
                      </label>
                    </div>
                    <div class="control">
                      <label class="radio">
                        <input
                          type="radio"
                          :value="options.op3"
                          v-model="selectedAnswer"
                        />
                        {{ options.op3 }}
                      </label>
                    </div>
                    <div class="control">
                      <label class="radio">
                        <input
                          type="radio"
                          :value="options.op4"
                          v-model="selectedAnswer"
                        />
                        {{ options.op4 }}
                      </label>
                    </div>
                    <div class="control mt-4" >
                      <button class="button is-link" @click="call(options.id)">
                        Submit
                      </button>
                    </div>
                    <br />
                    <template v-if="options.id === quizId">
                      <template v-if="quizResult == 'correct'">
                         <template v-if="correctAnswer">
                        <div class="notification is-success mt-4">
                          Correct. Well done!
                        </div>
                        </template>
                        <br />

                      </template>
                      <template v-if="quizResult == 'incorrect'">
                        <div class="notification is-danger mt-4">
                          Incorrect. Please try again.
                        </div>
                        <br />
                      </template>
                    </template>
                  </div>

                                </div>
                          </div>
                        </div> <br>
                      </section>
                         </div>
                        </div>

                  <!-- <hr /> -->
                </template>
</code>```
```<code><script>
import axios from "axios";
export default {
  data() {
    return {
      course: {},
      lessons: [],
      comments: [],
      activeLesson: null,
      errors: [],
      showModalFlag1: false,
      okPressed1: false,
      quiz: {},
      questionIndex: 0,
      loading: true,
      quizId: null,
      selectedAnswer: "",
      quizResult: null,
      correctAnswer: false,
      userScore: {
        username: '',
        lesson_id: '',
        lesson_score: '',
      },
      images: [
        {
          photo: "",
        },
      ],
      comment: {
        name: "",
        content: "",
      },
    };
  },
  methods: {

    call(id){
      this.submitQuiz(id);
      console.log('checkid@call',id)
    },
    submitQuiz(e) {
      console.log('check-id@submit', e)
      const quizArray = this.quiz;
      const choice = this.selectedAnswer;
      console.log('chosen: ', choice)

      const result = quizArray.filter( obj => obj.op1 === choice || obj.op2 === choice ||
                                      obj.op3 === choice || obj.op4 === choice)[0];
      console.log('result',result.id);

      for (const prop in result) {
          if ( result.hasOwnProperty(prop) ) {
            if (result.id == e) {
              this.quizId = result.id;
              if (choice == result.answer) {
                  this.quizResult = "correct";
                  this.correctAnswer = true;

              }
         if(choice !== result.answer){
            this.quizId = result.id;
            this.quizResult = "incorrect";
         }
          }
        }
    }

    },

</code>```

答:
I'm seeing conditions with inner conditions for the correct answer notification. So if your quizId is the next one, the outer condition already fails.

It's likely you have an array with questions and thus have an index for the current question. You could save a property a property on that index that shows if the question is correct, so your condition can be extended to also look back for the previous question

Something like this (pseudo code)

```<code><template v-if="showCorrectMsg">
  Good!
  ...
</code>```

and then have a computed showCorrectMsg method something like this (pseudo code):

```<code>if (  questions[currentIndex].quizResult == 'correct' ||
      ( currentIndex > 0 && questions[currentIndex - 1].quizResult == 'correct' )
   ) return true;

return false;
</code>```

So for this to work you will have to store that flag on each answer given (again, pseudo code):

```<code>questions[currentIndex].quizResult = [ theAnswer == theRightAnswer ] ? 'correct' : 'wrong';
</code>```

Title: Conditionally render a div with vue.js

Body:
I am trying to build a quiz which when the user chooses a selection and submits the answer the notification div displays whether choice is correct or not. I have got this logic working however what is happening is the div is disappearing each time the next question is answered. I want to keep the previous question result on the screen and lock the user out of answering the question again and show the correct answer.

Here is what I have so far:

{{ options.question }}

                        <input
                          type="radio"
                          :value="options.op1"
                          v-model="selectedAnswer"
                        />
                        {{ options.op1 }}

                        <input
                          type="radio"
                          :value="options.op2"
                          v-model="selectedAnswer"
                        />
                        {{ options.op2 }}

                        <input
                          type="radio"
                          :value="options.op3"
                          v-model="selectedAnswer"
                        />
                        {{ options.op3 }}

                        <input
                          type="radio"
                          :value="options.op4"
                          v-model="selectedAnswer"
                        />
                        {{ options.op4 }}

                      <button class="button is-link" @click="call(options.id)">
                        Submit
                      </button>

                    <template v-if="options.id === quizId">
                      <template v-if="quizResult == 'correct'">
                         <template v-if="correctAnswer">

                          Correct. Well done!

                        </template>

                      </template>
                      <template v-if="quizResult == 'incorrect'">

                          Incorrect. Please try again.

                      </template>
                    </template>

                </template>

Body:
I'm seeing conditions with inner conditions for the correct answer notification. So if your quizId is the next one, the outer condition already fails.

It's likely you have an array with questions and thus have an index for the current question. You could save a property a property on that index that shows if the question is correct, so your condition can be extended to also look back for the previous question

Something like this (pseudo code)

<template v-if="showCorrectMsg">
  Good!
  ...

and then have a computed showCorrectMsg method something like this (pseudo code):

if (  questions[currentIndex].quizResult == 'correct' ||
      ( currentIndex > 0 && questions[currentIndex - 1].quizResult == 'correct' )
   ) return true;

return false;

So for this to work you will have to store that flag on each answer given (again, pseudo code):

questions[currentIndex].quizResult = [ theAnswer == theRightAnswer ] ? 'correct' : 'wrong';


问:
Get only specific attributes with from Laravel Collection
I've been reviewing the documentation and API for Laravel Collections, but don't seem to find what I am looking for:

I would like to retrieve an array with model data from a collection, but only get specified attributes.

I.e. something like Users::toArray('id','name','email'), where the collection in fact holds all attributes for the users, because they are used elsewhere, but in this specific place I need an array with userdata, and only the specified attributes.

There does not seem to be a helper for this in Laravel? - How can I do this the easiest way?

答:
This is a follow up on the @patricus answer above:

Use the following to return collection of object instead of array so you can use same as models object i.e. $subset[0]->name

```<code>$subset = $users->map(function ($user) {
    return (object) $user->only(['id', 'name', 'email']);
});
</code>```

Body:
This is a follow up on the @patricus answer above:

Use the following to return collection of object instead of array so you can use same as models object i.e. $subset[0]->name

$subset = $users->map(function ($user) {
    return (object) $user->only(['id', 'name', 'email']);
});


问:
Dynamically create textboxes using javascript and insert that text box values into mysql
Hi i have created some text boxes dynamically using javascript according to the no of inputs.
I want to save that textbox values to mysql database. am very new to javascript. Thanks in advance.

Here is my code:

```<code>    <script>

   function add_col()
   {
   var num_box = document.getElementById("num_text").value;
   if(num_box)
   {
   for(var i=0; i<num_box; i++)
   {

   var tableName1 = document.getElementById("uTable");

   var newTR1 = document.getElementById("tr1");

   var newName1 = document.createElement("TD");

   newName1.innerHTML = "<input type='text'  name='site' id='site' value='cell value'>";

   var newTR2 = document.getElementById("tr2");

   var newPhone1 = document.createElement("TD");

   newPhone1.innerHTML = "<input type='text'  name='cell' id='cell' value='site value'>";

   newTR1.appendChild(newName1);

   newTR2.appendChild(newPhone1);

   tableName1.appendChild(newTR1);
   tableName1.appendChild(newTR2);

    document.form1.reset()

    }

   }

   }
   </script>

    <form name="form1" id="form1" method="post">

        <p>
          <input type="text" name="num_text" id="num_text"/>
          <input type="button" name="Submit" value="INPUT" onclick="add_col();" />
        </p>
        <p> </p>
        <table  id="uTable"width="183" border="0">
          <tr id="tr1">
            <td>Name</td>

          </tr>
          <tr id="tr2">
            <td>Phone</td>

          </tr>

      </table>
        <input type="submit" name="Submit2" value="Insert"  />
    </form>
</code>```

答:
What you need to do is to use [] on input names - so that the whole array is passed to your server side:

```<code>newName1.innerHTML = "<input type='text'  name='site[]' id='site' value='cell value'>";
newPhone1.innerHTML = "<input type='text'  name='cell[]' id='cell' value='site value'>";
</code>```

You'll also need to specify the submit target in your html:

```<code><form name="form1" id="form1" method="post" target="myscript.php">
</code>```

Then in your server-side program, you can access the array of submitted values.  You didn't specify what server-side technology you're using; assuming, it's PHP and you're submitting the form, you would do something like this:

```<code>$sites = $_POST['site'];
$cells = $_POST['cell'];
if(count($sites) != count($cells))
{
    // error - number of values don't match
}
elseif(count($sites) == 0)
{
    // no data to insert
}
else
{
    $cnt = count($sites);
    for($i=0; $i<$cnt; $i++)
    {
        //insert into the table pairs ($sites[$i] - $cells[$i])
    }
}
</code>```

Body:
Hi i have created some text boxes dynamically using javascript according to the no of inputs.
I want to save that textbox values to mysql database. am very new to javascript. Thanks in advance.

Here is my code:

    <form name="form1" id="form1" method="post">

          <input type="text" name="num_text" id="num_text"/>
          <input type="button" name="Submit" value="INPUT" onclick="add_col();" />

            Name

            Phone

        <input type="submit" name="Submit2" value="Insert"  />
    </form>

Body:
What you need to do is to use [] on input names - so that the whole array is passed to your server side:

newName1.innerHTML = "<input type='text'  name='site[]' id='site' value='cell value'>";
newPhone1.innerHTML = "<input type='text'  name='cell[]' id='cell' value='site value'>";

You'll also need to specify the submit target in your html:

<form name="form1" id="form1" method="post" target="myscript.php">

Then in your server-side program, you can access the array of submitted values.  You didn't specify what server-side technology you're using; assuming, it's PHP and you're submitting the form, you would do something like this:

$sites = $_POST['site'];
$cells = $_POST['cell'];
if(count($sites) != count($cells))
{
    // error - number of values don't match
}
elseif(count($sites) == 0)
{
    // no data to insert
}
else
{
    $cnt = count($sites);
    for($i=0; $i<$cnt; $i++)
    {
        //insert into the table pairs ($sites[$i] - $cells[$i])
    }
}


问:
How do I prevent users from accidentally deploying to too many tenants in Octopus?
Over the years we’ve had a few instances of Octopus Deploy users accidentally releasing a version to multiple environments, based on a tenant tag.

I usually tell users to check that the Tenant list under ‘Preview and customize’ only contains the 1 environment intended, but we still have some slip through where Octopus deploys to 20+ environments, which I then need to roll back.

Is there a way to alert users when there are more than 1 Tenant in the list, so they can sense check it before proceeding to deploy?

答:
This can be achieved with a PowerShell script, which you add as a deployment step. The script will check for more than one tenant, and alert the user to perform manual intervention if it detects more than 1 target

To have the script work successfully, you must perform the following:

Set a Secret Project Variable named APIKey with the value of an API-Key with access to the deployments within that space.

Change the $octopusURL variable in the Script to match your Octopus Hostname.

Place the Script at the beginning of your deployment inside a "Run A Script" step.

Create a Manual Intervention step as the 2nd process step in your project with the run condition set to: #{Octopus.Action[Run a Script].Output.MultipleTenants}

If you decide to change the name of the step that contains the Script below, be sure to place the step name within the square brackets ([]) on the run condition variable.

```<code>$ErrorActionPreference = "Stop";

# Define working variables
$octopusURL = "http://OctopusURL"
$octopusAPIKey = "$APIKey"
$header = @{ "X-Octopus-ApiKey" = $octopusAPIKey }
$spaceId = $OctopusParameters["Octopus.Space.Id"]

# Get Release Deployment Data
$releaseData = Invoke-RestMethod -method GET -uri "$($octopusURL)/api/$($spaceId)/releases/#{Octopus.Release.Id}/deployments/" -Headers $header

# Get DateTime of Deployment Created
$checkDate = Get-Date $OctopusParameters["Octopus.Deployment.Created"] -format "yyyy-MM-dd HH:mm:ss"

write-host "The following tenants are being deployed to at $($checkDate):"

# Instantiate list
$tenantList = @()

# ForEach Deployment Item inside the Release do the following:
foreach($item in $releaseData.Items){

    # Generate compatible DateTime for comparison with deployment Time
    $date = Get-Date $item.Created.Substring(0,19) -format "yyyy-MM-dd HH:mm:ss"

    # Check date equivalence, if equal then do the following:
    if($date -eq $checkDate){
    write-host "The tenant with ID: $($item.TenantId) is included in this deployment at $($date)."

    # Add tenant to list
    $tenantList = $TenantList + ($item.TenantId)

    # If a release is redeployed, previous tenants may exist in the JSON items, this elseif generates the list of tenants deployed to previously, but not in THIS deployment:
    }elseif($tenantList -notcontains $item.TenantId){
        write-host "The tenant with ID: $($item.TenantId) is not included in this deployment as it was deployed at $($date)."
    }
}

# Condition check list size, create output variable if more than one Tenant.
if($tenantList.Count -gt 1){
Set-OctopusVariable -name "MultipleTenants" -value "True"
}
</code>```

Body:
This can be achieved with a PowerShell script, which you add as a deployment step. The script will check for more than one tenant, and alert the user to perform manual intervention if it detects more than 1 target

To have the script work successfully, you must perform the following:

Set a Secret Project Variable named APIKey with the value of an API-Key with access to the deployments within that space.

Change the $octopusURL variable in the Script to match your Octopus Hostname.

Place the Script at the beginning of your deployment inside a "Run A Script" step.

Create a Manual Intervention step as the 2nd process step in your project with the run condition set to: #{Octopus.Action[Run a Script].Output.MultipleTenants}

If you decide to change the name of the step that contains the Script below, be sure to place the step name within the square brackets ([]) on the run condition variable.

$ErrorActionPreference = "Stop";

# Define working variables
$octopusURL = "http://OctopusURL"
$octopusAPIKey = "$APIKey"
$header = @{ "X-Octopus-ApiKey" = $octopusAPIKey }
$spaceId = $OctopusParameters["Octopus.Space.Id"]

# Get Release Deployment Data
$releaseData = Invoke-RestMethod -method GET -uri "$($octopusURL)/api/$($spaceId)/releases/#{Octopus.Release.Id}/deployments/" -Headers $header

# Get DateTime of Deployment Created
$checkDate = Get-Date $OctopusParameters["Octopus.Deployment.Created"] -format "yyyy-MM-dd HH:mm:ss"

write-host "The following tenants are being deployed to at $($checkDate):"

# Instantiate list
$tenantList = @()

# ForEach Deployment Item inside the Release do the following:
foreach($item in $releaseData.Items){

    # Generate compatible DateTime for comparison with deployment Time
    $date = Get-Date $item.Created.Substring(0,19) -format "yyyy-MM-dd HH:mm:ss"

    # Check date equivalence, if equal then do the following:
    if($date -eq $checkDate){
    write-host "The tenant with ID: $($item.TenantId) is included in this deployment at $($date)."

    # Add tenant to list
    $tenantList = $TenantList + ($item.TenantId)

    # If a release is redeployed, previous tenants may exist in the JSON items, this elseif generates the list of tenants deployed to previously, but not in THIS deployment:
    }elseif($tenantList -notcontains $item.TenantId){
        write-host "The tenant with ID: $($item.TenantId) is not included in this deployment as it was deployed at $($date)."
    }
}

# Condition check list size, create output variable if more than one Tenant.
if($tenantList.Count -gt 1){
Set-OctopusVariable -name "MultipleTenants" -value "True"
}


问:
How to deserialize XML element with package name using Xstream?
I have an xml response and trying to convert it to java object using Xstream library.

```<code><products>
   <com.example.model.ProductModel>
     <productDefinition>
       <productId>1</productId>
       <productType>ASD</productType>
       <price>10</price>
     </productDefinition>
   </com.example.model.ProductModel>
 </products>
</code>```

Here are my java classes for this:

```<code>@XStreamAlias("products")
public class Product {

    @XStreamImplicit(itemFieldName="com.example.model.ProductModel")
    private ProductModel productModel;

    //getters, setters
}

public class ProductModel {

    @XStreamImplicit(itemFieldName="productDefinition")
    private ProductDefinition productDefinition;

    //getters, setters
}
</code>```

When I convert this xml to java object, Product object is not null, but the ProductModel inside of it becomes null. I guess the problem is about the full package name of the xml tag. Any suggestions about how to solve it?

Thanks.

答:
I found the soultion, XStream aliasField method helped me solve it.

```<code>xstream.aliasField("com.example.model.ProductModel", Product.class, "productModel");
</code>```

This simply means, map the "com.example.model.ProductModel" element in the xml to productModel object of Product class.

Body:
I have an xml response and trying to convert it to java object using Xstream library.

<products>
   <com.example.model.ProductModel>
     <productDefinition>
       <productId>1</productId>
       <productType>ASD</productType>
       <price>10</price>
     </productDefinition>
   </com.example.model.ProductModel>
 </products>

Here are my java classes for this:

@XStreamAlias("products")
public class Product {

    @XStreamImplicit(itemFieldName="com.example.model.ProductModel")
    private ProductModel productModel;

    //getters, setters
}

public class ProductModel {

    @XStreamImplicit(itemFieldName="productDefinition")
    private ProductDefinition productDefinition;

    //getters, setters
}

When I convert this xml to java object, Product object is not null, but the ProductModel inside of it becomes null. I guess the problem is about the full package name of the xml tag. Any suggestions about how to solve it?

Thanks.

Body:
I found the soultion, XStream aliasField method helped me solve it.

xstream.aliasField("com.example.model.ProductModel", Product.class, "productModel");

This simply means, map the "com.example.model.ProductModel" element in the xml to productModel object of Product class.


问:
Can I deploy pods in public and private subnets?
I am currently trying to identify the required AWS VPC and Subnet structure for EKS.

However, would like to check whether I can deploy the UI containers (pods) and the Spring Boot based API Gateway pods in public subnet and deploy all other back-end service pods in private subnet.

Is it possible to create such Kubernetes YAML deployment configuration?

答: You deploy the UI containers (pods) and the Spring Boot based API Gateway pods in nodes that run in public subnet, all other back-end service pods in nodes that run in private subnet. Where nodes are really just EC2 instance that runs kubelet that have joined your EKS cluster. Typically, you use nodeSelector or affinity to direct which node for your pod to run.


问:
Could not get unknown property 'flutterRoot' for project ':app' of type org.gradle.api.Project
I have been looking around for solutions to this error, but didn't find any solution. I have a flutter project and I keep getting this error in the app/build.gradle file while trying to build the apk for release.

```<code>Could not get unknown property 'flutterRoot' for project ':app' of type org.gradle.api.Project.
</code>```

Below is my build gradle file.

```<code>    def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new FileNotFoundException ("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
println keystorePropertiesFile
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.develpment.sported_app"
        minSdkVersion 23
        targetSdkVersion 30
        multiDexEnabled true
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    signingConfigs {
       release {
           keyAlias keystoreProperties['keyAlias']
           keyPassword keystoreProperties['keyPassword']
           storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
           storePassword keystoreProperties['storePassword']
       }
   }

    buildTypes {
        release {
            release {
                signingConfig signingConfigs.debug
            }
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "com.android.support:multidex:1.0.3"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
</code>```

It seems there is an issue with my keystore properties.I would like to know where I am going wrong. I have tried invalidating caches and restart but nothing seems to work.

答: Run env in command line and check if there is FLUTTER_ROOT variable. If not set it yourself.

Body:
I have been looking around for solutions to this error, but didn't find any solution. I have a flutter project and I keep getting this error in the app/build.gradle file while trying to build the apk for release.

Could not get unknown property 'flutterRoot' for project ':app' of type org.gradle.api.Project.

Below is my build gradle file.

    def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new FileNotFoundException ("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
println keystorePropertiesFile
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.develpment.sported_app"
        minSdkVersion 23
        targetSdkVersion 30
        multiDexEnabled true
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    signingConfigs {
       release {
           keyAlias keystoreProperties['keyAlias']
           keyPassword keystoreProperties['keyPassword']
           storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
           storePassword keystoreProperties['storePassword']
       }
   }

    buildTypes {
        release {
            release {
                signingConfig signingConfigs.debug
            }
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "com.android.support:multidex:1.0.3"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'

It seems there is an issue with my keystore properties.I would like to know where I am going wrong. I have tried invalidating caches and restart but nothing seems to work.