问:
The overlay state seems to not update Even when wrapped inside a blocbuilder
I am unable to update the overlay widget with search results which I got from an api. The overlay and the text field are in a separate widget called search widget. The search widget is wrapped inside a bloc builder. All the other widgets under the bloc builder seems to be working fine while the

main screen

```<code>BlocBuilder<MainScreenBloc,MainScreenState>(
builder: (context, state){

Scaffold(

body:Column(
children:[

//toggle button...

Container(
               margin: EdgeInsets.fromLTRB(20, 15, 20, 0),
                              child: SearchWidget(
                                focusNode: focusNode,
                                searchResults: _Bloc
                                    .searchResult,
                                controller: searchController,
                                isLoading: state is LoadingSearchResultsState,
                                createSearchResultItem: _searchResultWidget,
                              ),
                            ),

//name field...

//title field...

// address field...
]

);

);

}
)

</code>```

Search widget

```<code>class SearchWidget extends StatefulWidget {
  SearchWidget({
    Key? key,
    required this.searchResults,
    required this.focusNode,
    required this.controller,
    required this.isLoading,
    required this.createSearchResultItem,
  }) : super(key: key);
  final List<dynamic>? searchResults;
  final TextEditingController controller;
  final FocusNode focusNode;
  final bool isLoading;
  final Widget Function(dynamic) createSearchResultItem;
  @override
  State<SearchWidget> createState() => _SearchWidgetState();
}
class _SearchWidgetState extends State<SearchWidget> {
  OverlayEntry? _overlayEntry;
  final LayerLink _layerLink = LayerLink();
  @override
  void initState() {
    super.initState();
    OverlayState? overlayState = Overlay.of(context);
    widget.focusNode.addListener(() {
      if (widget.focusNode.hasFocus) {
        _overlayEntry = _createOverlay();
        overlayState!.insert(_overlayEntry!);
      } else {
        _overlayEntry!.remove();
      }
    });
  }
  OverlayEntry _createOverlay() {
    RenderBox renderBox = context.findRenderObject() as RenderBox;
    var size = renderBox.size;
    return OverlayEntry(
        builder: (context) => Positioned(
              width: size.width,
              child: CompositedTransformFollower(
                link: _layerLink,
                showWhenUnlinked: false,
                offset: Offset(0.0, size.height),
                child: Material(
                  elevation: 5.0,
                  child: Container(
                      constraints: BoxConstraints(
                        maxHeight: 200,
                      ),
                      child: (widget.searchResults != null &&
                              widget.searchResults?.length != 0)
                          ? Container(
                              constraints: BoxConstraints(maxHeight: 300),
                              child: ListView.builder(
                                shrinkWrap: true,
                                itemCount: widget.searchResults?.length,
                                itemBuilder: ((context, index) {
                                  // if (widget.searchResultItems[index] == null) {
                                  //   return Container();
                                  // }
                                  return widget.createSearchResultItem(
                                      widget.searchResults?[index] ?? []);
                                }),
                              ),
                            )
                          : widget.isLoading
                              ? Container(
                                  height: 300,
                                  width: 75,
                                  child: Center(
                                      child:
                                          CircularProgressIndicator.adaptive()),
                                )
                              :
                              Container(
                                  height: 300,
                                  width: 75,
                                  child: Center(
                                    child: Text(‘No Results Found’),
                                  ),
                                )),
                ),
              ),
            ));
  }
  @override
  Widget build(BuildContext context) {
    return CompositedTransformTarget(
      link: _layerLink,
      child: TextFormField(
        focusNode: widget.focusNode,
        controller: widget.controller,
        style: Style.textMediumBold(
          TSColor.black(context),
        ),
        keyboardType: TextInputType.text,
        textInputAction: TextInputAction.next,
        decoration: InputDecoration(
          hintText: “Add Items”,
          focusedBorder: InputBorder.none,
          border: InputBorder.none,
          filled: true,
          fillColor: hexToColor(“#F0F2F3"),
        ),
      ),
    );
  }
}

</code>```

Body:
I am unable to update the overlay widget with search results which I got from an api. The overlay and the text field are in a separate widget called search widget. The search widget is wrapped inside a bloc builder. All the other widgets under the bloc builder seems to be working fine while the

main screen

BlocBuilder<MainScreenBloc,MainScreenState>(
builder: (context, state){

Scaffold(

body:Column(
children:[

//toggle button...

Container(
               margin: EdgeInsets.fromLTRB(20, 15, 20, 0),
                              child: SearchWidget(
                                focusNode: focusNode,
                                searchResults: _Bloc
                                    .searchResult,
                                controller: searchController,
                                isLoading: state is LoadingSearchResultsState,
                                createSearchResultItem: _searchResultWidget,
                              ),
                            ),

//name field...

//title field...

// address field...
]

);

);

}
)

Search widget

class SearchWidget extends StatefulWidget {
  SearchWidget({
    Key? key,
    required this.searchResults,
    required this.focusNode,
    required this.controller,
    required this.isLoading,
    required this.createSearchResultItem,
  }) : super(key: key);
  final List<dynamic>? searchResults;
  final TextEditingController controller;
  final FocusNode focusNode;
  final bool isLoading;
  final Widget Function(dynamic) createSearchResultItem;
  @override
  State<SearchWidget> createState() => _SearchWidgetState();
}
class _SearchWidgetState extends State<SearchWidget> {
  OverlayEntry? _overlayEntry;
  final LayerLink _layerLink = LayerLink();
  @override
  void initState() {
    super.initState();
    OverlayState? overlayState = Overlay.of(context);
    widget.focusNode.addListener(() {
      if (widget.focusNode.hasFocus) {
        _overlayEntry = _createOverlay();
        overlayState!.insert(_overlayEntry!);
      } else {
        _overlayEntry!.remove();
      }
    });
  }
  OverlayEntry _createOverlay() {
    RenderBox renderBox = context.findRenderObject() as RenderBox;
    var size = renderBox.size;
    return OverlayEntry(
        builder: (context) => Positioned(
              width: size.width,
              child: CompositedTransformFollower(
                link: _layerLink,
                showWhenUnlinked: false,
                offset: Offset(0.0, size.height),
                child: Material(
                  elevation: 5.0,
                  child: Container(
                      constraints: BoxConstraints(
                        maxHeight: 200,
                      ),
                      child: (widget.searchResults != null &&
                              widget.searchResults?.length != 0)
                          ? Container(
                              constraints: BoxConstraints(maxHeight: 300),
                              child: ListView.builder(
                                shrinkWrap: true,
                                itemCount: widget.searchResults?.length,
                                itemBuilder: ((context, index) {
                                  // if (widget.searchResultItems[index] == null) {
                                  //   return Container();
                                  // }
                                  return widget.createSearchResultItem(
                                      widget.searchResults?[index] ?? []);
                                }),
                              ),
                            )
                          : widget.isLoading
                              ? Container(
                                  height: 300,
                                  width: 75,
                                  child: Center(
                                      child:
                                          CircularProgressIndicator.adaptive()),
                                )
                              :
                              Container(
                                  height: 300,
                                  width: 75,
                                  child: Center(
                                    child: Text(‘No Results Found’),
                                  ),
                                )),
                ),
              ),
            ));
  }
  @override
  Widget build(BuildContext context) {
    return CompositedTransformTarget(
      link: _layerLink,
      child: TextFormField(
        focusNode: widget.focusNode,
        controller: widget.controller,
        style: Style.textMediumBold(
          TSColor.black(context),
        ),
        keyboardType: TextInputType.text,
        textInputAction: TextInputAction.next,
        decoration: InputDecoration(
          hintText: “Add Items”,
          focusedBorder: InputBorder.none,
          border: InputBorder.none,
          filled: true,
          fillColor: hexToColor(“#F0F2F3"),
        ),
      ),
    );
  }
}


来源: stackexchange

问:
Why is the user being set to null after I refresh the Web page from the browser?
I have been working on authentication for a React - Redux based app and facing an issue with state persistence.

When I login, the user gets set correctly, however, when I refresh the browser, the user goes to null, even though it is present in the localStorage.

This problem occured after I did some tweaks with this useEffect hook:

```<code>const [tempCode, setTempCode] = useState(null)
const { user, isSuccess, message } = useSelector((state) => state.auth)

  useEffect(() => {
    if (isSuccess && user) {
      dispatch(reset())
      navigate("/")
    } else {
      const queryString = window.location.search
      const urlParams = new URLSearchParams(queryString)
      const codeExists = urlParams.get("code")

      if (codeExists) {
        setTempCode({ code: codeExists })
      }
      dispatch(login(tempCode))
      navigate("/")
    }
  }, [tempCode])
</code>```

Here's the initial state from auth slice:

```<code>const initialState = {
  isSuccess: false,
  user: JSON.parse(localStorage.getItem("user")) || null,
  isLoading: false,
  isError: false,
  message: "",
}
</code>```

Here's the reset action from the auth reducer:

```<code>export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    reset: (state) => {
      state.isLoading = false
      state.isError = false
      state.isSuccess = false
      state.message = ""
    },
</code>```

Why is the user being reset to null when it's still present in local storage? It was working fine previously.

ContentLicense: CC BY-SA 4.0

Body:
I have been working on authentication for a React - Redux based app and facing an issue with state persistence.

When I login, the user gets set correctly, however, when I refresh the browser, the user goes to null, even though it is present in the localStorage.

This problem occured after I did some tweaks with this useEffect hook:

const [tempCode, setTempCode] = useState(null)
const { user, isSuccess, message } = useSelector((state) => state.auth)

  useEffect(() => {
    if (isSuccess && user) {
      dispatch(reset())
      navigate("/")
    } else {
      const queryString = window.location.search
      const urlParams = new URLSearchParams(queryString)
      const codeExists = urlParams.get("code")

      if (codeExists) {
        setTempCode({ code: codeExists })
      }
      dispatch(login(tempCode))
      navigate("/")
    }
  }, [tempCode])

Here's the initial state from auth slice:

const initialState = {
  isSuccess: false,
  user: JSON.parse(localStorage.getItem("user")) || null,
  isLoading: false,
  isError: false,
  message: "",
}

Here's the reset action from the auth reducer:

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    reset: (state) => {
      state.isLoading = false
      state.isError = false
      state.isSuccess = false
      state.message = ""
    },

Why is the user being reset to null when it's still present in local storage? It was working fine previously.


问:
Could not parse the Android Application Module's Gradle config resolve Gradle build issues and resync in Firebase?
how to solve this problem

android {
namespace 'user.eight.real'
compileSdk 33

```<code>defaultConfig {
    applicationId "user.eight.real"
    minSdk 24
    targetSdk 33
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildToolsVersion '30.0.3'
</code>```

}

dependencies
{
implementation fileTree(include: ['*.jar'],dir: 'libs')

```<code>         implementation 'androidx.appcompat:appcompat-v7:26.1.0'
        implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
        implementation 'androidx.legacy:legacy-support-v4:1.0.0'
        testImplementation 'junit:junit:4.13.2'
        androidTestImplementation 'androidx.test.ext:junit:1.1.4'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
         implementation 'com.google.android.material:material:1.7.0'
        implementation 'com.github.bumptech.glide:glide:4.14.2'
        annotationProcessor 'com.github.bumptech.glide:compiler:4.14.2'
        implementation'com.github.mohammadatif:Animatoo:master'
        implementation 'org.jsoup:jsoup:1.10.2'

    }
</code>```
```<code></code>```

Body:
how to solve this problem

android {
namespace 'user.eight.real'
compileSdk 33

defaultConfig {
    applicationId "user.eight.real"
    minSdk 24
    targetSdk 33
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildToolsVersion '30.0.3'

}

dependencies
{
implementation fileTree(include: ['*.jar'],dir: 'libs')

         implementation 'androidx.appcompat:appcompat-v7:26.1.0'
        implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
        implementation 'androidx.legacy:legacy-support-v4:1.0.0'
        testImplementation 'junit:junit:4.13.2'
        androidTestImplementation 'androidx.test.ext:junit:1.1.4'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
         implementation 'com.google.android.material:material:1.7.0'
        implementation 'com.github.bumptech.glide:glide:4.14.2'
        annotationProcessor 'com.github.bumptech.glide:compiler:4.14.2'
        implementation'com.github.mohammadatif:Animatoo:master'
        implementation 'org.jsoup:jsoup:1.10.2'

    }


问:
Generating Error "errors": [ { "message": "There is no current event loop in thread 'Thread-5'." using graphql and django
this is the error I'm getting while fetching comments in graphql [

model I have created in django
schema I have created is here]3


问:
Facing issue in Code Splitting || import written in return statement
I am facing problem in code splitting which I just learn from YouTube. I'm stuck in this error not able to print any message from API component with Import("./API) but if I write a code like <API /> then its working properly

The reason I asked this question is because if there is a button and I want to click on that then only its load the components.

This is just a simple code I'm trying.

App.js

```<code>const App = () => {
    return (
        <div className="App">
            <h1>Hello API</h1>
            {() =>
                import("./API")
                    .then((module) => module.API())
                    .catch((error) => console.log(error))
            }
        </div>
    );
};

export default App;
</code>```

API.js

```<code>import Data from "./Constant.json";

export default function API() {
    let time = new Date().getHours() + 1;
    const checkTime =
        time < 2 && time > 0 ? (
            <h1>{Data.MAINTENANCE_ISSUE}</h1>
        ) : (
            <h1>{Data.API_CALL_IS_RUNNING}</h1>
        );
    return checkTime;
}
</code>```

If I run this below code then its working properly, I'm just confuse the import written in return statement.

App.js

```<code>const App = () => {
    return (
        <div className="App">
            <h1>Hello API</h1>
            <API />
        </div>
    );
};

export default App;
</code>```

API.js

```<code>import Data from "./Constant.json";

export default function API() {
    let time = new Date().getHours() + 1;
    const checkTime =
        time < 2 && time > 0 ? (
            <h1>{Data.MAINTENANCE_ISSUE}</h1>
        ) : (
            <h1>{Data.API_CALL_IS_RUNNING}</h1>
        );
    return checkTime;
}
</code>```

Body:
I am facing problem in code splitting which I just learn from YouTube. I'm stuck in this error not able to print any message from API component with Import("./API) but if I write a code like <API /> then its working properly

The reason I asked this question is because if there is a button and I want to click on that then only its load the components.

This is just a simple code I'm trying.

App.js

const App = () => {
    return (

Hello API

            {() =>
                import("./API")
                    .then((module) => module.API())
                    .catch((error) => console.log(error))
            }

    );
};

export default App;

API.js

import Data from "./Constant.json";

export default function API() {
    let time = new Date().getHours() + 1;
    const checkTime =
        time < 2 && time > 0 ? (

{Data.MAINTENANCE_ISSUE}

        ) : (

{Data.API_CALL_IS_RUNNING}

        );
    return checkTime;
}

If I run this below code then its working properly, I'm just confuse the import written in return statement.

App.js

const App = () => {
    return (

Hello API

            <API />

    );
};

export default App;

API.js

import Data from "./Constant.json";

export default function API() {
    let time = new Date().getHours() + 1;
    const checkTime =
        time < 2 && time > 0 ? (

{Data.MAINTENANCE_ISSUE}

        ) : (

{Data.API_CALL_IS_RUNNING}

        );
    return checkTime;
}


问:
Can not add uniqueidentifier type column in columnstore non-clustered index
Im trying  to create non-clustered COLUMNSTORE  index on my fact table including some key columns.... but when selecting columns of table to add in index  i don't see all of the columns which are uniqueidentifier type. There are all column types exept uids in menu.

Is it possible to add uniqueidentifier type in non-clustered COLUMNSTORE  index ?


问:
Shell context menu without NEW option
I´m developing an application to manage folders and files, and I'm showing the context menu for folders but it doesn't show the "NEW" option.

When I show the context menu for a folder the option "NEW" doesn't show.

Can anybody tell me what I'm doing wrong?

```<code>iShellFolder.GetUIObjectOf(IntPtr.Zero,
                           System.Convert.ToUInt32(apidl.Length),
                           apidl,
                           (riid),
                           (rgfReserved),
                           obj2)

If (Me.ContextMenu2 IsNot Nothing) Then
    ' Si ya hay un ContextMenu2 lo elimina
    Marshal.ReleaseComObject(Me.ContextMenu2)
    Me.ContextMenu2 = Nothing
End If
' Crea el ContextMenu2
Me.ContextMenu2 = TryCast(obj2, Win32.IContextMenu2)

If (Me.ContextMenu2 IsNot Nothing) Then
    ' Si lo creó
    Dim mousePosition As Point = Control.MousePosition
    Dim uFlags As UInt32 = FirstCMFFlag
    If uFlags <> CMF.CMF_NOVERBS Then
        If pidlList.Count = 1 Then
            uFlags = uFlags Or CMF.CMF_CANRENAME Or CMF.CMF_EXPLORE
        End If
        If (Control.ModifierKeys And Keys.Shift) = Keys.Shift Then
            uFlags = uFlags Or CMF.CMF_EXTENDEDVERBS    ' 256
        End If
    End If

    ' Presenta y lee la opción del ContextMenu
    Me.ContextMenu2.QueryContextMenu(menu.Handle, 0, 1, &H7FFF, uFlags)
    Dim menuResult As UInt32 = 0
    If FirstMenuResult = 0 Then   ' No trae ningún valor a ejecutar
        Dim flg As UInt32 = &H100   '  returncmd (&h100)
        menuResult = Win32.TrackPopupMenu(menu.Handle, flg,
                                                    mousePosition.X, mousePosition.Y,
                                                    0, parent, IntPtr.Zero)
    Else
        menuResult = FirstMenuResult
    End If
</code>```

Title: Shell context menu without NEW option

Body:
I´m developing an application to manage folders and files, and I'm showing the context menu for folders but it doesn't show the "NEW" option.

When I show the context menu for a folder the option "NEW" doesn't show.

Can anybody tell me what I'm doing wrong?

iShellFolder.GetUIObjectOf(IntPtr.Zero,
                           System.Convert.ToUInt32(apidl.Length),
                           apidl,
                           (riid),
                           (rgfReserved),
                           obj2)

If (Me.ContextMenu2 IsNot Nothing) Then
    ' Si ya hay un ContextMenu2 lo elimina
    Marshal.ReleaseComObject(Me.ContextMenu2)
    Me.ContextMenu2 = Nothing
End If
' Crea el ContextMenu2
Me.ContextMenu2 = TryCast(obj2, Win32.IContextMenu2)

If (Me.ContextMenu2 IsNot Nothing) Then
    ' Si lo creó
    Dim mousePosition As Point = Control.MousePosition
    Dim uFlags As UInt32 = FirstCMFFlag
    If uFlags <> CMF.CMF_NOVERBS Then
        If pidlList.Count = 1 Then
            uFlags = uFlags Or CMF.CMF_CANRENAME Or CMF.CMF_EXPLORE
        End If
        If (Control.ModifierKeys And Keys.Shift) = Keys.Shift Then
            uFlags = uFlags Or CMF.CMF_EXTENDEDVERBS    ' 256
        End If
    End If

    ' Presenta y lee la opción del ContextMenu
    Me.ContextMenu2.QueryContextMenu(menu.Handle, 0, 1, &H7FFF, uFlags)
    Dim menuResult As UInt32 = 0
    If FirstMenuResult = 0 Then   ' No trae ningún valor a ejecutar
        Dim flg As UInt32 = &H100   '  returncmd (&h100)
        menuResult = Win32.TrackPopupMenu(menu.Handle, flg,
                                                    mousePosition.X, mousePosition.Y,
                                                    0, parent, IntPtr.Zero)
    Else
        menuResult = FirstMenuResult
    End If


问:
Data is not saving in database session table
I am using laravel and I need to save some data in session with database drive.

So I have:

SESSION_DRIVER=database

Migration:

```<code>Schema::create('sessions', function (Blueprint $table) {
            $table->string('id')->primary();
            $table->string('session_id')->nullable()->index();
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->longText('payload');
            $table->timestamp('created_at')->nullable();
});
</code>```

And in the controller I have two endpoints to register a new user (so in this point there is no user logged).

In this endpoint I want to store data in database:

```<code>public function sendEmailValidationCode(RegisterRequest $request)
    {
        $validationCode = randomNumber(4);

        $ip = $request->ip();
        $userAgent = $request->header('user-agent');

        $userData = [
            'first_name' => $request->input('first_name'),
            'last_name' => $request->input('last_name'),
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password')),
            'validation_code' => $validationCode
        ];

        $dataToEncrypt = json_encode([
            'email' => $userData['email'],
            'validation_code' => $validationCode
        ]);

        $encryptedData =  $this->encryptService->encrypt($dataToEncrypt);

        session([
            'session_id' => session()->getId(),
            'ip_address' => $ip,
            'user_agent' => $userAgent,
            'payload' => json_encode($userData),
            'created_at' => Carbon::now()
        ]);

        return AuthResource::make([
            'session_id' => session()->getId(),
            'validation_id' => $encryptedData
        ]);
    }
</code>```

after run this method in the database I have an empty session table.

And in the other method I want to get this data but of course it is empty:

```<code> public function register(Request $request)
 {
        return session()->all();
 }
</code>```

Body:
I am using laravel and I need to save some data in session with database drive.

So I have:

SESSION_DRIVER=database

Migration:

Schema::create('sessions', function (Blueprint $table) {
            $table->string('id')->primary();
            $table->string('session_id')->nullable()->index();
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->longText('payload');
            $table->timestamp('created_at')->nullable();
});

And in the controller I have two endpoints to register a new user (so in this point there is no user logged).

In this endpoint I want to store data in database:

public function sendEmailValidationCode(RegisterRequest $request)
    {
        $validationCode = randomNumber(4);

        $ip = $request->ip();
        $userAgent = $request->header('user-agent');

        $userData = [
            'first_name' => $request->input('first_name'),
            'last_name' => $request->input('last_name'),
            'email' => $request->input('email'),
            'password' => bcrypt($request->input('password')),
            'validation_code' => $validationCode
        ];

        $dataToEncrypt = json_encode([
            'email' => $userData['email'],
            'validation_code' => $validationCode
        ]);

        $encryptedData =  $this->encryptService->encrypt($dataToEncrypt);

        session([
            'session_id' => session()->getId(),
            'ip_address' => $ip,
            'user_agent' => $userAgent,
            'payload' => json_encode($userData),
            'created_at' => Carbon::now()
        ]);

        return AuthResource::make([
            'session_id' => session()->getId(),
            'validation_id' => $encryptedData
        ]);
    }

after run this method in the database I have an empty session table.

And in the other method I want to get this data but of course it is empty:

 public function register(Request $request)
 {
        return session()->all();
 }


问:
Android SwipeRefreshLayout with WebView Vertical Scrolling Issue
When using SwipeRefreshLayout with WebView (as child view), scrolling upwards on a website does not work since the swipe down to refresh action is being triggert instead.

Every solution I have found online does not seem to work for me. I have tried using NestedScrollView, ViewTreeObserver OnScrollChangedListener and CanChildScrollUpCallback. The last solution seems to be the most recommended one so I would prefer a solution using the callback method. Here is how I tried to implement it:

```<code>
swipeRefreshLayout.setOnChildScrollUpCallback((parent, child) -> webView.canScrollVertically(-1));

</code>```

But I can't get it to work and I don't know why. Any help is appreciated.

Here is the rest of the code that goes along with it:

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

        <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            android:id="@+id/swipe_refresh_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <WebView
                android:id="@+id/web_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

        </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</RelativeLayout>
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_refresh_layout);
        webView = findViewById(R.id.web_view);

        swipeRefreshLayout.setOnChildScrollUpCallback((parent, child) -> webView.canScrollVertically(-1));

        swipeRefreshLayout.setOnRefreshListener(
                () -> {
                    webView.reload();
                    swipeRefreshLayout.setRefreshing(false);
                }
        );

        webView.setWebViewClient(new WebViewClient());
        CookieManager.getInstance().setAcceptCookie(true);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        String url = "https://WEBSITE";
        webView.loadUrl(url);

    }
}

</code>```

Body:
When using SwipeRefreshLayout with WebView (as child view), scrolling upwards on a website does not work since the swipe down to refresh action is being triggert instead.

Every solution I have found online does not seem to work for me. I have tried using NestedScrollView, ViewTreeObserver OnScrollChangedListener and CanChildScrollUpCallback. The last solution seems to be the most recommended one so I would prefer a solution using the callback method. Here is how I tried to implement it:

swipeRefreshLayout.setOnChildScrollUpCallback((parent, child) -> webView.canScrollVertically(-1));

But I can't get it to work and I don't know why. Any help is appreciated.

Here is the rest of the code that goes along with it:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

        <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            android:id="@+id/swipe_refresh_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <WebView
                android:id="@+id/web_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

        </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</RelativeLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_refresh_layout);
        webView = findViewById(R.id.web_view);

        swipeRefreshLayout.setOnChildScrollUpCallback((parent, child) -> webView.canScrollVertically(-1));

        swipeRefreshLayout.setOnRefreshListener(
                () -> {
                    webView.reload();
                    swipeRefreshLayout.setRefreshing(false);
                }
        );

        webView.setWebViewClient(new WebViewClient());
        CookieManager.getInstance().setAcceptCookie(true);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        String url = "https://WEBSITE";
        webView.loadUrl(url);

    }
}


问:
How to instantiate a custom instance of a class in app module in nestjs?
I have a eventbusService which uses aws sns and aws sqs under the hood. Now I want to dynamically instantiate new instance of eventbus service by passing values of sns topic arn and sqs queue url. I have tried multiple solutions using useFactory, but cant seem to understand how it works. Please help by providing any suggestions/code examples.

I tried creating a useFactory inside of appModule and passed it provide : EventBusService. Inside the useFactory I passed topicArn and queueUrl. I was expecting a new instance of class eventService when I passed values inside factory function, but it keeps showing error..eventBusFactory is not a function.


问:
AWS java sdk - SqsClient.create() fails without throwing an exception
I'm having an issue with my call to SqsClient.create() failing.  In one case, I was able to recreate this by setting the wrong AWS_SECRET_ACCESS_KEY value in my environmental vars.  In other cases, I don't know why it fails.  The issue is, instead of throwing an exception, it seems to just fail silently and I end up getting some other problems down the road because of it. And I can't troubleshoot it because it never goes into the catch block! I orignally was just catching AwsServiceException and SdkClientException, but after my initial problems, I added a catch-all Exception as well to my try-catch block, but even then, when it fails it still doesn't go into the last Exception catch block for some reason.  What can be the cause of this?  I am scratching my head trying to figure it out.</p>
```<code>      try {
         sqsClient = SqsClient.create();
         snsClient = SnsClient.create();

      } catch (final AwsServiceException ex) {
         //do something
      } catch (final SdkClientException ex) {
         //do something
      } catch (Exception e) {
         //do something
      }
</code>```

Body:
I'm having an issue with my call to SqsClient.create() failing.  In one case, I was able to recreate this by setting the wrong AWS_SECRET_ACCESS_KEY value in my environmental vars.  In other cases, I don't know why it fails.  The issue is, instead of throwing an exception, it seems to just fail silently and I end up getting some other problems down the road because of it. And I can't troubleshoot it because it never goes into the catch block! I orignally was just catching AwsServiceException and SdkClientException, but after my initial problems, I added a catch-all Exception as well to my try-catch block, but even then, when it fails it still doesn't go into the last Exception catch block for some reason.  What can be the cause of this?  I am scratching my head trying to figure it out.

      try {
         sqsClient = SqsClient.create();
         snsClient = SnsClient.create();

      } catch (final AwsServiceException ex) {
         //do something
      } catch (final SdkClientException ex) {
         //do something
      } catch (Exception e) {
         //do something
      }


问:
Printing on Bixolon SPP-R410 - C#
I have a question about the print length on the printer Bixolon SPP-R410.
I developed the code in C# for printing using their SDK, but I'm having trouble adjusting the length of the print on the paper.

I set the area to be printed using the code below, but when i have more text to print and set the height parameter above 3000 the printer doesn't accept it and prints the text up to about 2600.

```<code>BxlPrint.SetPrintAreaInPM(0, 0, 879, 3000);
</code>```

How can i set it to print longer texts than 3000 height?

Note: the code was developed for the Windows operating system.

I tried with changes to the printer driver, various changes in the code but to no avail.

Title: Printing on Bixolon SPP-R410 - C#

Body:
I have a question about the print length on the printer Bixolon SPP-R410.
I developed the code in C# for printing using their SDK, but I'm having trouble adjusting the length of the print on the paper.

I set the area to be printed using the code below, but when i have more text to print and set the height parameter above 3000 the printer doesn't accept it and prints the text up to about 2600.

BxlPrint.SetPrintAreaInPM(0, 0, 879, 3000);

How can i set it to print longer texts than 3000 height?

Note: the code was developed for the Windows operating system.

I tried with changes to the printer driver, various changes in the code but to no avail.


问:
Web scraping with python from a website that uses microsoft login
It's been 6 hours that I have been trying to extract the grades from my school website.
My code is working perfectly, I have just a problem...
I cannot get connected through the Microsoft login page.
The only way to get connected is by getting my cookies and pasting them into the code.
This is not what I want. I want to put my email and my password and get connected.

This is my code:

```<code>from bs4 import BeautifulSoup
import requests
import csv

'''
publishedGrade[x]
    1 = ID
    3 = grade
'''

cookies = {
    'SERVERID': 'XXXXXXXXXXX',
    'JSESSIONID': 'XXXXXXXXXXX',
}

# Start the session
session = requests.Session()

# Create the payload
payload = {'loginfmt':'XXXXXXXX',
          'passwd':'XXXXXXXX'
         }

# Post the payload to the site to log in
s = session.post("https://login.microsoftonline.com/08983daf-5aca-4f44-bc65-c23ce32d46ec/oauth2/authorize?response_type=code&client_id=dcd45342-6b22-4490-aaa6-39e6199c2bf6&scope=openid&redirect_uri=https%3A%2F%2Faurion.ieseg.fr%2Fopenid_connect_login&nonce=XXXXXX&state=XXXXXXXX&sso_reload=true", data=payload, cookies=cookies)

# Navigate to the next page and scrape the data
soup = session.get('https://aurion.ieseg.fr/faces/LearnerNotationListPage.xhtml', cookies=cookies)
soup = BeautifulSoup(soup.text, 'html.parser')
results = soup.find(id="form:dataTableFavori_data")
elements = results.find_all("tr", role="row")

allIDs=[]
allGrades=[]

#Getting each published grade
for i, element in enumerate(elements):
    publishedGrade = element.find_all("td", role="gridcell")

    #Extracting only the course name
    ID=publishedGrade[1].text.split("_")

    #Appending course ID and the grade
    #Extractin the digit ID
    #example XXX_XXX_XXX_ID_XXX
    allIDs.append(ID[len(ID)-2])
    allGrades.append(publishedGrade[3].text)

#Saving all in a CSV file
with open('text.csv', 'w', encoding='UTF-8', newline='') as f:
        writer = csv.writer(f)
        for w in range(len(elements)):
            writer.writerow([allIDs[w], allGrades[w]])
</code>```

In this code I just censored cookies password email and the end of the url of the microsoft login page.

I tried to use Selenium, but it is not optimal. Because I plan to integrate the code in an html page with Django.

I extracted the html page showed when I tried to get connected with my email. When I try to show it in a browser page, it redirects me to https://login.microsoftonline.com/cookiesdisabled.

This is what I see

Body:
It's been 6 hours that I have been trying to extract the grades from my school website.
My code is working perfectly, I have just a problem...
I cannot get connected through the Microsoft login page.
The only way to get connected is by getting my cookies and pasting them into the code.
This is not what I want. I want to put my email and my password and get connected.

This is my code:

from bs4 import BeautifulSoup
import requests
import csv

'''
publishedGrade[x]
    1 = ID
    3 = grade
'''

cookies = {
    'SERVERID': 'XXXXXXXXXXX',
    'JSESSIONID': 'XXXXXXXXXXX',
}

# Start the session
session = requests.Session()

# Create the payload
payload = {'loginfmt':'XXXXXXXX',
          'passwd':'XXXXXXXX'
         }

# Post the payload to the site to log in
s = session.post("https://login.microsoftonline.com/08983daf-5aca-4f44-bc65-c23ce32d46ec/oauth2/authorize?response_type=code&client_id=dcd45342-6b22-4490-aaa6-39e6199c2bf6&scope=openid&redirect_uri=https%3A%2F%2Faurion.ieseg.fr%2Fopenid_connect_login&nonce=XXXXXX&state=XXXXXXXX&sso_reload=true", data=payload, cookies=cookies)

# Navigate to the next page and scrape the data
soup = session.get('https://aurion.ieseg.fr/faces/LearnerNotationListPage.xhtml', cookies=cookies)
soup = BeautifulSoup(soup.text, 'html.parser')
results = soup.find(id="form:dataTableFavori_data")
elements = results.find_all("tr", role="row")

allIDs=[]
allGrades=[]

#Getting each published grade
for i, element in enumerate(elements):
    publishedGrade = element.find_all("td", role="gridcell")

    #Extracting only the course name
    ID=publishedGrade[1].text.split("_")

    #Appending course ID and the grade
    #Extractin the digit ID
    #example XXX_XXX_XXX_ID_XXX
    allIDs.append(ID[len(ID)-2])
    allGrades.append(publishedGrade[3].text)

#Saving all in a CSV file
with open('text.csv', 'w', encoding='UTF-8', newline='') as f:
        writer = csv.writer(f)
        for w in range(len(elements)):
            writer.writerow([allIDs[w], allGrades[w]])

In this code I just censored cookies password email and the end of the url of the microsoft login page.

I tried to use Selenium, but it is not optimal. Because I plan to integrate the code in an html page with Django.

I extracted the html page showed when I tried to get connected with my email. When I try to show it in a browser page, it redirects me to https://login.microsoftonline.com/cookiesdisabled.

This is what I see


问:
Allowing inline assembly on cmake build
I'm trying to build an exe using cmake and no IDE for this project https://github.com/cyberquarks/fubi

This is the cmake file:

```<code>cmake_minimum_required(VERSION 3.10)
project(Fubi)

set(SOURCES DbgHelpDll.cpp Fubi.cpp SysExports.cpp fubimain.cpp stdafx.cpp)
add_executable(Fubi ${SOURCES})
target_link_libraries(Fubi PRIVATE DbgHelp)

set_property(TARGET Fubi PROPERTY ENTRY_POINT "fubimain.cpp")

include_directories("C:/local/boost_1_73_0")
link_directories(C:/local/boost_1_73_0/lib64-msvc-14.2)

set(CMAKE_SYSTEM_VERSION 6.0)
</code>```

While I build it with:

```<code>$ mkdir build
$ cd build
$ cmake -G "Visual Studio 16 2019" ..
$ cmake --build .
</code>```

During the build process it throws this error:

```<code>Fubi.cpp
C:\fubi\Fubi.cpp(40,5): error C4235: nonstandard extension used: '__asm' keyword not supported on this architecture [C:\fubi\build\Fubi.vcxproj]
</code>```

Which is this code:

```<code>DWORD Fubi::Call_cdecl( const void* args, size_t sz, DWORD func )
{
    DWORD rc;
    __asm
    {
    // ...
    }
    return ( rc );
}
</code>```

How can I use cmake to build the executable and allow the inline assembly code to compile also?

Update:

The same project works when using CLion IDE to build and run it.

Toolchains:

Debug config:

Cmake settings:

Run config:

Title: Allowing inline assembly on cmake build

Body:
I'm trying to build an exe using cmake and no IDE for this project https://github.com/cyberquarks/fubi

This is the cmake file:

cmake_minimum_required(VERSION 3.10)
project(Fubi)

set(SOURCES DbgHelpDll.cpp Fubi.cpp SysExports.cpp fubimain.cpp stdafx.cpp)
add_executable(Fubi ${SOURCES})
target_link_libraries(Fubi PRIVATE DbgHelp)

set_property(TARGET Fubi PROPERTY ENTRY_POINT "fubimain.cpp")

include_directories("C:/local/boost_1_73_0")
link_directories(C:/local/boost_1_73_0/lib64-msvc-14.2)

set(CMAKE_SYSTEM_VERSION 6.0)

While I build it with:

$ mkdir build
$ cd build
$ cmake -G "Visual Studio 16 2019" ..
$ cmake --build .

During the build process it throws this error:

Fubi.cpp
C:\fubi\Fubi.cpp(40,5): error C4235: nonstandard extension used: '__asm' keyword not supported on this architecture [C:\fubi\build\Fubi.vcxproj]

Which is this code:

DWORD Fubi::Call_cdecl( const void* args, size_t sz, DWORD func )
{
    DWORD rc;
    __asm
    {
    // ...
    }
    return ( rc );
}

How can I use cmake to build the executable and allow the inline assembly code to compile also?

Update:

The same project works when using CLion IDE to build and run it.

Toolchains:

Debug config:

Cmake settings:

Run config:


问:
Pyspark type mismatch in nested JSON structure stops schema validation
I'm reading a json file with PySpark and validating the schema against a predefined data schema.

the data schema:

```<code>testschema = StructType([
    StructField("_corrupt_record", StringType(), True),
    StructField("a", StringType(), True),
    StructField("b", StringType(), True),
    StructField("c", StringType(), True),
    StructField("d", StringType(), True),
    StructField("e", StructType([
        StructField("e_1", IntegerType(), True)
    ]), True)
])
</code>```

The JSON file:

```<code>{
    "e": {
        "e_1": "2"
    },
    "a": "a",
    "b": "b",
    "c": "c",
    "d": "d"
}
</code>```

after reading the JSON file and validating the structure against the testschema definition  using the following code:

```<code>peopleDF = spark.read.json(json_input, schema=testschema, multiLine=True)

peopleDF.createOrReplaceTempView("people")

teenagerNamesDF = spark.sql("SELECT * FROM people")
display(teenagerNamesDF)
</code>```

Given the JSON file, i expect a null value for e_1 due to the type mismatch (e.g. checking for integer but given string). However, this also causes all other values to be null also.

result:
[![enter image description here][1]][1]

However, when I move this nested 'e' block down in the structure, it appears that is able to populate the fields before the block where the type mismatch occurs. E.g.

```<code>{
    "a": "a",
    "b": "b",
    "c": "c",
    "d": "d",
    "e": {
        "e_1": "2"
    }

}
</code>```

result:
[![enter image description here][2]][2]

It seems that type mismatching in nested JSON structures stop/halts schema validation. How can this be solved?

Body:
I'm reading a json file with PySpark and validating the schema against a predefined data schema.

the data schema:

testschema = StructType([
    StructField("_corrupt_record", StringType(), True),
    StructField("a", StringType(), True),
    StructField("b", StringType(), True),
    StructField("c", StringType(), True),
    StructField("d", StringType(), True),
    StructField("e", StructType([
        StructField("e_1", IntegerType(), True)
    ]), True)
])

The JSON file:

{
    "e": {
        "e_1": "2"
    },
    "a": "a",
    "b": "b",
    "c": "c",
    "d": "d"
}

after reading the JSON file and validating the structure against the testschema definition  using the following code:

peopleDF = spark.read.json(json_input, schema=testschema, multiLine=True)

peopleDF.createOrReplaceTempView("people")

teenagerNamesDF = spark.sql("SELECT * FROM people")
display(teenagerNamesDF)

Given the JSON file, i expect a null value for e_1 due to the type mismatch (e.g. checking for integer but given string). However, this also causes all other values to be null also.

result:
[![enter image description here][1]][1]

However, when I move this nested 'e' block down in the structure, it appears that is able to populate the fields before the block where the type mismatch occurs. E.g.

{
    "a": "a",
    "b": "b",
    "c": "c",
    "d": "d",
    "e": {
        "e_1": "2"
    }

}

result:
[![enter image description here][2]][2]

It seems that type mismatching in nested JSON structures stop/halts schema validation. How can this be solved?


问:
Difference between using Flink addDefaultKryoSerializer and registerTypeWithKryoSerializer
A few questions regarding serialization in Flink. In order to ensure Flink state to evolve safely and in a backwards compatible way, I decided to represent all non-primitive state types as Protobuf messages.

Question 1: are there any downsides to representing state with Protobufs? It looks like POJO might be faster / more efficient, but that performance hit is okay for my use case. Tradeoff is towards safety since there's better tooling available to ensure only compatible changes are made to Protobuf message schemas.

Question 2: is it sufficient to just using the interface type (eg. Message.class) when specifying serializers? Or, should I be adding/registering each concrete message type? Just the interface seems to work, but I'm not sure if there are gotchas here that I should consider.

Question 3: Does it matter how I specify ProtobufSerializer with Flink, addDefaultKryoSerializer or registerTypeWithKryoSerializer? I understand there's this mostly impacts Kryo's reference IDs, but I also understand the IDs are re-calculated within an object graph. So, do the IDs really matter in that case? Are there any situations where the same object graph would see classes in different orders?

Code sample of the various options described above:

```<code>javaEnv.addDefaultKryoSerializer(Message.class, ProtobufSerializer.class); // Option 1

javaEnv.registerTypeWithKryoSerializer(Message.class, ProtobufSerializer.class); // Option 2

javaEnv.addDefaultKryoSerializer(FooPb.class, ProtobufSerializer.class); // Option 3

javaEnv.registerTypeWithKryoSerializer(FooPb.class, ProtobufSerializer.class); // Option 4
</code>```

Body:
A few questions regarding serialization in Flink. In order to ensure Flink state to evolve safely and in a backwards compatible way, I decided to represent all non-primitive state types as Protobuf messages.

Question 1: are there any downsides to representing state with Protobufs? It looks like POJO might be faster / more efficient, but that performance hit is okay for my use case. Tradeoff is towards safety since there's better tooling available to ensure only compatible changes are made to Protobuf message schemas.

Question 2: is it sufficient to just using the interface type (eg. Message.class) when specifying serializers? Or, should I be adding/registering each concrete message type? Just the interface seems to work, but I'm not sure if there are gotchas here that I should consider.

Question 3: Does it matter how I specify ProtobufSerializer with Flink, addDefaultKryoSerializer or registerTypeWithKryoSerializer? I understand there's this mostly impacts Kryo's reference IDs, but I also understand the IDs are re-calculated within an object graph. So, do the IDs really matter in that case? Are there any situations where the same object graph would see classes in different orders?

Code sample of the various options described above:

javaEnv.addDefaultKryoSerializer(Message.class, ProtobufSerializer.class); // Option 1

javaEnv.registerTypeWithKryoSerializer(Message.class, ProtobufSerializer.class); // Option 2

javaEnv.addDefaultKryoSerializer(FooPb.class, ProtobufSerializer.class); // Option 3

javaEnv.registerTypeWithKryoSerializer(FooPb.class, ProtobufSerializer.class); // Option 4


问:
Vuex state property does not update
I'm developing a simple social media at the moment. I have a problem. token state property doesn't update at all, even when there is a token item in the localStorage. Here is my unfinished project on Github. And here is the store where the token property is stored (path: resources/js/store/modules/middleware.js):

const state = {
    user: {
        loggedIn: false,
        isSubscribed: false,
        token: localStorage.getItem('token') || ''
    },
}
const actions = {}
const mutations = {}
const getters = {
    auth(state) {
        return state.user
    }
}

export default {
    namespaced: false,
    state,
    actions,
    mutations,
    getters
}
```
<p>At first I thought that the state just updates before <code>token</code> item appears. So I decided to print the token in the console after 10 seconds (path of the file below: <code>resources/js/middleware/auth.js</code>):</p>
<pre class="lang-js prettyprint-override"><code>export default function ({ next, store }) {
    if (!store.getters.auth.token) {
        console.log(store.getters.auth.token);
        setTimeout(() => {
            console.log(store.getters.auth.token);
        }, 10000)
        return next('login')
    }
    return next()
}
</code>```

But the token was still an empty string. Here is how the console looks:

If you need something else to understand my question, feel free to ask!

Title: Vuex state property does not update

Body:
I'm developing a simple social media at the moment. I have a problem. token state property doesn't update at all, even when there is a token item in the localStorage. Here is my unfinished project on Github. And here is the store where the token property is stored (path: resources/js/store/modules/middleware.js):

const state = {
    user: {
        loggedIn: false,
        isSubscribed: false,
        token: localStorage.getItem('token') || ''
    },
}
const actions = {}
const mutations = {}
const getters = {
    auth(state) {
        return state.user
    }
}

export default {
    namespaced: false,
    state,
    actions,
    mutations,
    getters
}

At first I thought that the state just updates before token item appears. So I decided to print the token in the console after 10 seconds (path of the file below: resources/js/middleware/auth.js):

export default function ({ next, store }) {
    if (!store.getters.auth.token) {
        console.log(store.getters.auth.token);
        setTimeout(() => {
            console.log(store.getters.auth.token);
        }, 10000)
        return next('login')
    }
    return next()
}

But the token was still an empty string. Here is how the console looks:

If you need something else to understand my question, feel free to ask!


问:
Is nest js microservices(EventPattern) the same as websockets?
I try to make a nest.js server, that publishes events, and it doesn't know his subscribers. As far as I concerned, microservices in nest.js works in the same way as websockets. But I've met some problems. Looks like all microservices must know about each other. So I can't make a microservice-server (server_A), that emits events and microservices-clients, that subscribes events of server_A.
Using websockets, it is possible. Is it possible to do it, using microservices?

I tryied to create microservice (server_A) on localhost, then I created a subscriber on localhost also. I made them work on localhost as expected. But when I try to deploy server_A on remote server, I can't connect my microservice-subscriber from localhost, even if I fill correct host and ip.
There is the error: Error: listen EADDRNOTAVAIL: address not available x.x.x.x:port (real ip is masked)
But I think, if I make server_A a websocket server, and then subscribe by another nest.js application, it will work no matter wherefrom will I connect


问:
Supabase file uploading occasionally fails
Sometimes I can upload a file and sometimes I get this error:

```<code>{statusCode: '403', error: '', message: 'new row violates row-level security policy (USING expression) for table "objects"'}
</code>```

I got the uploading code from this page. I duplicated the component with different bucket names and only changed htmlFor, id, accept and bucket url, both with the same policies but sometimes the other works/fails or both. One is for image upload and the other video, both have worked at some point so idk why I keep getting the error. And none of the files exceeds the max upload size(50mb). Heres SQL snippet I used:

```<code>insert into storage.buckets (id, name)
  values ('avatars', 'avatars');

create policy "Avatar images are publicly accessible." on storage.objects
  for select using (bucket_id = 'avatars');

create policy "Anyone can upload an avatar." on storage.objects
  for insert with check (bucket_id = 'avatars');
</code>```

Also I'm using Typescript and no error in my code.

Body:
Sometimes I can upload a file and sometimes I get this error:

{statusCode: '403', error: '', message: 'new row violates row-level security policy (USING expression) for table "objects"'}

I got the uploading code from this page. I duplicated the component with different bucket names and only changed htmlFor, id, accept and bucket url, both with the same policies but sometimes the other works/fails or both. One is for image upload and the other video, both have worked at some point so idk why I keep getting the error. And none of the files exceeds the max upload size(50mb). Heres SQL snippet I used:

insert into storage.buckets (id, name)
  values ('avatars', 'avatars');

create policy "Avatar images are publicly accessible." on storage.objects
  for select using (bucket_id = 'avatars');

create policy "Anyone can upload an avatar." on storage.objects
  for insert with check (bucket_id = 'avatars');

Also I'm using Typescript and no error in my code.


问:
Bullet (Sprite) cant figure out how to collide with list variable
I am making a game where you have to shoot asteroids before they hit you, but I cant figure out how to collide my Bullet(sprite) with a list variable.

Here is my Bullet Class:

```<code>class Bullets(pg.sprite.Sprite):
    def __init__(self, x, y):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.image.load("Asteroid shootout/pixel_laser_red.png")
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y
        self.rect.center = [self.x, self.y]

    def update(self):
        self.rect.y -= 5

</code>```

Here is my Asteroid info:

```<code>asteroid_size = 40
asteroid_pos = [random.randint(0, width-asteroid_size), 0]
asteroid_list = [asteroid_pos]
</code>```

and I couldnt figure out how to collide these two, any help?

Body:
I am making a game where you have to shoot asteroids before they hit you, but I cant figure out how to collide my Bullet(sprite) with a list variable.

Here is my Bullet Class:

class Bullets(pg.sprite.Sprite):
    def __init__(self, x, y):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.image.load("Asteroid shootout/pixel_laser_red.png")
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y
        self.rect.center = [self.x, self.y]

    def update(self):
        self.rect.y -= 5

Here is my Asteroid info:

asteroid_size = 40
asteroid_pos = [random.randint(0, width-asteroid_size), 0]
asteroid_list = [asteroid_pos]

and I couldnt figure out how to collide these two, any help?


问:
how to use a diffential form dy/dx in a custom loss function - keras
I am writing a custom loss function for a keras sequential neural net model. I am trying to find the change of y (here as dk) with respect to x (here as dx) and z (here as ds). Something similar to dy/dx and dy/dz.

y_pred is the output from the model.

dk, dx, and ds are the dy, dx, and dz variables.

I am trying to find dk/dx>0 and dk/ds>0 and penalizing if it is NOT true. In short, similar to a monotonic function.

I tried to run the code using the following code, however the code gives an error while fitting. Please note that the Y_pred is the tensor output from the code.

This is the custom function.

```<code>def custom_loss(y_true, y_pred):

    mse = tf.keras.losses.MeanSquaredError()

    penalty = 50
    dk = [x - y_pred[i - 1] for i, x in enumerate(y_pred)][1:]
    ds = [x - snw[i - 1] for i, x in enumerate(snw)][1:]
    dk_ds = [x / y for x, y in zip(dk, ds)]

    dx = [x - xnw[i - 1] for i, x in enumerate(xnw)][1:]
    dk_dx = [x / y for x, y in zip(dk, dx)]

    # penalize the loss heavily if the differentials are less than 0 (i.e. not increasing)
    loss = tf.where(tf.logical_or(tf.greater_equal(dk_ds, 0.0), tf.greater_equal(dk_dx, 0.0)),
                   x=mse(y_true, y_pred), y=mse(y_true, y_pred)* penalty)

    return loss
</code>```

This is the model fitting:

history = model.fit(
    X_tr, Y_tr, epochs=500, sample_weight=weight_new, validation_split=0.10, verbose=0
)
```
<p>This is the error:</p>
<blockquote>
<p>File "C:\Program
Files\Anaconda3-2021\lib\site-packages\keras\engine\training.py", line
1249, in train_function  *
return step_function(self, iterator)
<br/><br/> File "C:\Users\sxm6402\AppData\Local\Temp/ipykernel_29432/3615420274.py",
line 7, in custom_loss  *
dk = [x - y_pred[i - 1] for i, x in enumerate(y_pred)][1:]</p>
```OperatorNotAllowedInGraphError: Iterating over a symbolic `tf.Tensor` is
not allowed: AutoGraph did convert this function. This might indicate
you are trying to use an unsupported feature.
```

Can anyone help me with this please?

Body:
I am writing a custom loss function for a keras sequential neural net model. I am trying to find the change of y (here as dk) with respect to x (here as dx) and z (here as ds). Something similar to dy/dx and dy/dz.

y_pred is the output from the model.

dk, dx, and ds are the dy, dx, and dz variables.

I am trying to find dk/dx>0 and dk/ds>0 and penalizing if it is NOT true. In short, similar to a monotonic function.

I tried to run the code using the following code, however the code gives an error while fitting. Please note that the Y_pred is the tensor output from the code.

This is the custom function.

def custom_loss(y_true, y_pred):

    mse = tf.keras.losses.MeanSquaredError()

    penalty = 50
    dk = [x - y_pred[i - 1] for i, x in enumerate(y_pred)][1:]
    ds = [x - snw[i - 1] for i, x in enumerate(snw)][1:]
    dk_ds = [x / y for x, y in zip(dk, ds)]

    dx = [x - xnw[i - 1] for i, x in enumerate(xnw)][1:]
    dk_dx = [x / y for x, y in zip(dk, dx)]

    # penalize the loss heavily if the differentials are less than 0 (i.e. not increasing)
    loss = tf.where(tf.logical_or(tf.greater_equal(dk_ds, 0.0), tf.greater_equal(dk_dx, 0.0)),
                   x=mse(y_true, y_pred), y=mse(y_true, y_pred)* penalty)

    return loss

This is the model fitting:

history = model.fit(
    X_tr, Y_tr, epochs=500, sample_weight=weight_new, validation_split=0.10, verbose=0
)

This is the error:

File "C:\Program
Files\Anaconda3-2021\lib\site-packages\keras\engine\training.py", line
1249, in train_function  *
return step_function(self, iterator)

 File "C:\Users\sxm6402\AppData\Local\Temp/ipykernel_29432/3615420274.py",
line 7, in custom_loss  *
dk = [x - y_pred[i - 1] for i, x in enumerate(y_pred)][1:]

OperatorNotAllowedInGraphError: Iterating over a symbolic `tf.Tensor` is
not allowed: AutoGraph did convert this function. This might indicate
you are trying to use an unsupported feature.

Can anyone help me with this please?


问:
Where is ${applicationName}?
```<code>./android/app/src/main/AndroidManifest.xml:
</code>```
```<code><application
    android:label="Flutter"
    android:name="${applicationName}"
    android:icon="@mipmap/ic_launcher">
</code>```

There is a variable called "applicationName" being referenced from the given file. Where is the declaration of such variable?

Title: Where is ${applicationName}?

Body:
./android/app/src/main/AndroidManifest.xml:

<application
    android:label="Flutter"
    android:name="${applicationName}"
    android:icon="@mipmap/ic_launcher">

There is a variable called "applicationName" being referenced from the given file. Where is the declaration of such variable?


问:
Draw scrollbar over RecyclerView.ItemDecoration sticky header
I am extending RecyclerView.ItemDecoration to define a class that enables a RecyclerView to make header view's sticky when they are at the top of the RecyclerView. For this, I need to override onDrawOver() to draw the sticky header , since I need to draw the sticky header on top of all the other RecyclerView view's. This has the unfortunate side effect of also drawing the sticky header on top of the RecyclerView's scrollbar. I am wondering if there is some way I can easily get the RecyclerView to draw it's scrollbar over this sticky header?

I've tried doing the following already:

Mess around with android:scrollbarStyle XML tag on RecyclerView. Setting this to outsideOverlay does not draw the scrollbar over the sticky header.

Move sticky header drawing logic to onDraw() instead of onDrawOver(). Doing this draws the sticky header underneath the scrollbar, but also draws it underneath the RecyclerView's other views.

Any feedback is helpful. Thanks.


问:
RTK query with multiple parameters and skip option
I am trying to make a conditional query with RTK query. In my api slice I have the following query:

```<code> retrieveAppointmentsPublic:builder.query({
      query:({id,date="2022-12-25"})=>({
        url:`/shops/public/appointments/${id}/${date}`,
        method:'GET',
       })
    })
</code>```

For now the date is a place holder. In my front end I am using the useRetrieveAppointmentsPublicQuery hook in the following way :

```<code>    const date="2022-12-25"
  const {
    data: apps,
    isLoading: isAppsLoading,
    isUninitialized:isAppsUninitialized,
    isSuccess: isAppsSuccess,
    isError: isAppError,
    error: appError,
  } = useRetrieveAppointmentsPublicQuery({id,date},{skipAppsQuery})
</code>```

According to rtk query documentation you can pass a skip option to the hook so when its true it will skip the query untill it is set to false. This does not work for me as the query happens as soon as the component mounts.

What am I doing wrong and what would be the right way to do this ?
Can anyone explain ? Thanks in advance :)

PS i need the id parameter to select the shop that I need from the db and the date parameters to select the appointments from that specific shop for that date. It works perfectly on the back end. I just need this to happen when the front end user makes a specific action -> skipAppsQuery = false

Body:
I am trying to make a conditional query with RTK query. In my api slice I have the following query:

 retrieveAppointmentsPublic:builder.query({
      query:({id,date="2022-12-25"})=>({
        url:`/shops/public/appointments/${id}/${date}`,
        method:'GET',
       })
    })

For now the date is a place holder. In my front end I am using the useRetrieveAppointmentsPublicQuery hook in the following way :

    const date="2022-12-25"
  const {
    data: apps,
    isLoading: isAppsLoading,
    isUninitialized:isAppsUninitialized,
    isSuccess: isAppsSuccess,
    isError: isAppError,
    error: appError,
  } = useRetrieveAppointmentsPublicQuery({id,date},{skipAppsQuery})

According to rtk query documentation you can pass a skip option to the hook so when its true it will skip the query untill it is set to false. This does not work for me as the query happens as soon as the component mounts.

What am I doing wrong and what would be the right way to do this ?
Can anyone explain ? Thanks in advance :)

PS i need the id parameter to select the shop that I need from the db and the date parameters to select the appointments from that specific shop for that date. It works perfectly on the back end. I just need this to happen when the front end user makes a specific action -> skipAppsQuery = false


问:
How to make scrollview's height dynamic with SwiftUi
I have a scroll view with an image at the top, then three sections with textfields below it.
code
How I want the UI to work is, when the user inputs more text, the section grows, pushing the any section below it downwards.

When more than 3 lines of text is entered, they start to stack on top of each other.

Though most responses have said to use TextView, the code actually works with textfields... Except when I comment out the top image, giving more space to the 3 sections.
commented
How can I make the scrollview work so that when a section increases in size, the scrollview expands?


问:
Is it possible to check the group affiliation in custom permissions (BasePermission)?
Let's say I want to fetch a user profile. I want to allow it to the profile owners or users belonging to the administrator group. I know how to do these two things separately.
For owners:

```<code>class IsOwner(BasePermission):
    def has_permission(self, request, view):
        return True

    def has_object_permission(self, request, view, object):
        if request.user.is_authenticated:
            return object.name == request.user.name
        return False
</code>```

And for the admin group:

```<code>from django.contrib.auth.mixins import PermissionRequiredMixin
class MyView(PermissionRequiredMixin, View):
permission_required = ('polls.can_open', 'polls.can_edit')
</code>```

But how to allow either of the above? Is it possible to check user groups and permissions inside the has_object_permission method, without additional database calls?

Body:
Let's say I want to fetch a user profile. I want to allow it to the profile owners or users belonging to the administrator group. I know how to do these two things separately.
For owners:

class IsOwner(BasePermission):
    def has_permission(self, request, view):
        return True

    def has_object_permission(self, request, view, object):
        if request.user.is_authenticated:
            return object.name == request.user.name
        return False

And for the admin group:

from django.contrib.auth.mixins import PermissionRequiredMixin
class MyView(PermissionRequiredMixin, View):
permission_required = ('polls.can_open', 'polls.can_edit')

But how to allow either of the above? Is it possible to check user groups and permissions inside the has_object_permission method, without additional database calls?


问:
Mysql.connector.connect() functions doesn't work in one of my python projects and im confused
```<code>import mysql.connector

db = mysql.connector.connect(
  host="localhost",
  user="root",
  password="root",
  database="testdatabase"
)
</code>```

This is my code, I use this basic skeleton to connect to the database in all my code, in this particular project I was using flask to create a python webpage, and this code doesn't seem to run. Even if I try to run this code alone separately on a different file it still doesn't work, but only for this project. I have installed mysql-connector and mysql-connector-python and the file are there in site packages it show the error at the mysql.connector.connect() function but I don't know why. Please help!

Even if I try to run this code alone separately on a different file it still doesn't work, but only for this project. I have installed mysql-connector and mysql-connector-python and the file are there in site packages.

It shows this error:

```<code>Traceback (most recent call last):
  File "C:\Users\chezh\PycharmProjects\pythonProject3\venv\test.py", line 4, in <module>
    db = mysql.connector.connect(
         ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\chezh\PycharmProjects\pythonProject3\venv\Lib\site-packages\mysql\connector\__init__.py", line 179, in connect
    return MySQLConnection(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

Body:
import mysql.connector

db = mysql.connector.connect(
  host="localhost",
  user="root",
  password="root",
  database="testdatabase"
)

This is my code, I use this basic skeleton to connect to the database in all my code, in this particular project I was using flask to create a python webpage, and this code doesn't seem to run. Even if I try to run this code alone separately on a different file it still doesn't work, but only for this project. I have installed mysql-connector and mysql-connector-python and the file are there in site packages it show the error at the mysql.connector.connect() function but I don't know why. Please help!

Even if I try to run this code alone separately on a different file it still doesn't work, but only for this project. I have installed mysql-connector and mysql-connector-python and the file are there in site packages.

It shows this error:

Traceback (most recent call last):
  File "C:\Users\chezh\PycharmProjects\pythonProject3\venv\test.py", line 4, in <module>
    db = mysql.connector.connect(
         ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\chezh\PycharmProjects\pythonProject3\venv\Lib\site-packages\mysql\connector\__init__.py", line 179, in connect
    return MySQLConnection(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


问:
How to deploy Azure function with pnpm and rush?
How do you deploy an Azure function app with pnpm?

I'm using a rush monorepo and the rush deploy task which works great locally. The problem is that I'm unable to get ALL of my pnpm node_modules dependencies AND get my Azure function started in the cloud runtime environment

Min repro project here: https://github.com/luisnaranjo733/pnpm-rush-azure-functions

After running rush deploy, I get a nice ready to deploy project at the common/deploy path. When I try to deploy the commmon/apps/functions directory which contains the package.json for my functions project, Azure Functions mostly works except for when I import a dependency that itself has a dependency on something else.

This makes sense because of the way pnpm node_modules works, but in this case it's causing a huge headache with Azure Functions. See screenshot below for more details

The green highlighted node_modules is the one that only contains the dependencies declared by my project. As expected, only @azure/service-bus is there because that is the only dependency my functions project is using.

The orange highlighted node_modules is the pnpm global content adressable module store. This is where the dependencies of @azure/service-bus end up such a @azure/core-amqp.

When running locally via npm run start, my function is able to resolve the import to @azure/service-bus from the green node_modules and its internal dependencies from the orange node_modules. When running on the cloud runtime environment, this doesn't work :(

I can deploy the common/deploy/apps/functions project which works fine on the cloud runtime until I try to import @azure/service-bus which fails because it can't find its internal dependencies such as @azure/core-amqp.

Example cloud runtime file system when deploying the common/deploy/apps/functions folder

I see a few possible paths forward, but no clear winner

Revert back to npm, which sucks because I really wanted to use pnpm+rush.

Configure pnpm to copy and flatten my common/deploy/apps/functions/node_modules indistinguishable from a npm or yarn one (no symlinks to global content addressable module store). But this kind of negates the whole point of pnpm

Configure Azure Functions cloud runtime environment to use some kind of pnpm mode and figure out what's happening and solve it for me

Has anyone trodden this path or have any words of wisdom?
Thanks,
Luis


问:
Keep Track of Rolling out of a Log file using Serilog
I am using the Serilog for Logging and I have configured it roll out every day,
but I want to add a specific log line as a last line of every log file for which I have to keep track when the file is rolling out and new file is created.

Any one have any idea about how to achieve this.


问:
Saving deque to file minding performance and portability
I have a while loop that collects data from a microphone (replaced here for np.random.random() to make it more reproducible). I do some operations, let's say I take the abs().mean() here because my output will be a one dimensional array.

This loop is going to run for a LONG time (e.g., once a second for a week) and I am wondering my options to save this. My main concerns are saving the data with acceptable performance and having the result being portable (e.g, .csv beats .npy).

The simple way: just append things into a .txt file. Could be replaced by csv.gz maybe? Maybe using np.savetxt()? Would it be worth it?

The hdf5 way: this should be a nicer way, but reading the whole dataset to append to it doesn't seem like good practice or better performing than dumping into a text file. Is there another way to append to hdf5 files?

The npy way (code not shown): I could save this into a .npy file but I would rather make it portable using a format that could be read from any program.

```<code>from collections import deque
import numpy as np
import h5py
amplitudes = deque(maxlen=save_interval_sec)
# Read from the microphone in a continuous stream
while True:
    data = np.random.random(100)
    amplitude = np.abs(data).mean()
    print(amplitude, end="\r")
    amplitudes.append(amplitude)

    # Save the amplitudes to a file every n iterations
    if len(amplitudes) == save_interval:
        with open("amplitudes.txt", "a") as f:
            for amp in amplitudes:
                f.write(str(amp) + "\n")
        amplitudes.clear()

    # Save the amplitudes to an HDF5 file every n iterations
    if len(amplitudes) == save_interval:
        # Convert the deque to a Numpy array
        amplitudes_array = np.array(amplitudes)

        # Open an HDF5 file
        with h5py.File("amplitudes.h5", "a") as f:
            # Get the existing dataset or create a new one if it doesn't exist
            dset = f.get("amplitudes")
            if dset is None:
                dset = f.create_dataset("amplitudes", data=amplitudes_array, dtype=np.float32,
                                        maxshape=(None,), chunks=True, compression="gzip")
            else:
                # Get the current size of the dataset
                current_size = dset.shape[0]

                # Resize the dataset to make room for the new data
                dset.resize((current_size + save_interval,))

                # Write the new data to the dataset
                dset[current_size:] = amplitudes_array
        # Clear the deque
        amplitudes.clear()
    # For debug only
    if len(amplitudes)>3:
        break
</code>```

Update

I get that the answer might depend a bit on the sampling frequency (once a second might be too slow) and the data dimensions (single column might be too little). I guess I asked because anything can work, but I always just dump to text. I am not sure where the breaking points are that tip the decision into one or the other method.

Body:
I have a while loop that collects data from a microphone (replaced here for np.random.random() to make it more reproducible). I do some operations, let's say I take the abs().mean() here because my output will be a one dimensional array.

This loop is going to run for a LONG time (e.g., once a second for a week) and I am wondering my options to save this. My main concerns are saving the data with acceptable performance and having the result being portable (e.g, .csv beats .npy).

The simple way: just append things into a .txt file. Could be replaced by csv.gz maybe? Maybe using np.savetxt()? Would it be worth it?

The hdf5 way: this should be a nicer way, but reading the whole dataset to append to it doesn't seem like good practice or better performing than dumping into a text file. Is there another way to append to hdf5 files?

The npy way (code not shown): I could save this into a .npy file but I would rather make it portable using a format that could be read from any program.

from collections import deque
import numpy as np
import h5py
amplitudes = deque(maxlen=save_interval_sec)
# Read from the microphone in a continuous stream
while True:
    data = np.random.random(100)
    amplitude = np.abs(data).mean()
    print(amplitude, end="\r")
    amplitudes.append(amplitude)

    # Save the amplitudes to a file every n iterations
    if len(amplitudes) == save_interval:
        with open("amplitudes.txt", "a") as f:
            for amp in amplitudes:
                f.write(str(amp) + "\n")
        amplitudes.clear()

    # Save the amplitudes to an HDF5 file every n iterations
    if len(amplitudes) == save_interval:
        # Convert the deque to a Numpy array
        amplitudes_array = np.array(amplitudes)

        # Open an HDF5 file
        with h5py.File("amplitudes.h5", "a") as f:
            # Get the existing dataset or create a new one if it doesn't exist
            dset = f.get("amplitudes")
            if dset is None:
                dset = f.create_dataset("amplitudes", data=amplitudes_array, dtype=np.float32,
                                        maxshape=(None,), chunks=True, compression="gzip")
            else:
                # Get the current size of the dataset
                current_size = dset.shape[0]

                # Resize the dataset to make room for the new data
                dset.resize((current_size + save_interval,))

                # Write the new data to the dataset
                dset[current_size:] = amplitudes_array
        # Clear the deque
        amplitudes.clear()
    # For debug only
    if len(amplitudes)>3:
        break

Update

I get that the answer might depend a bit on the sampling frequency (once a second might be too slow) and the data dimensions (single column might be too little). I guess I asked because anything can work, but I always just dump to text. I am not sure where the breaking points are that tip the decision into one or the other method.


问:
Flutter nearby connections on IOS
I want to make chat app using nearby connections/bluetooth. I was using flutter_nearby_connection pack, which should work on both platform (ios + android), but it works only on IOS emulator. Real device is calling methods flutter -> swift.

I gave a lot of permissions (info.plist / permission handler/NSBonjourServices key). Right now I have a error [Core Bluetooth] XPC connection invalid . NSBluetoothPeripheralUsageDescription is added to plist and sandbox is off.

Did someone try this on real IOS? Documentation only has tests on IOS emulator, so idk if its problem by my side. Can u recommend other pack that will allow me to chat between Android - IOS?

MacOs 12.6.2, Xcode 14.2, IOS 15.7.1

Title: Flutter nearby connections on IOS


问:
No Output on DOM after adding Redux Logic
I was trying out react redux, but each time I add redux logic in my App component, I don't get any output on the browser window.

I have three files:

App.js

```<code>import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { increment } from './counterSlice';

function App() {
  const count = useSelector((state) => state.counter.value)
  const dispatch = useDispatch()

  return (
    <div>
      <h1>Values is {count}</h1>
      <button onClick={() => dispatch(increment)}>Plus</button>
    </div>
  );
}

export default App;
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import store from './store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

</code>```

counterSlice.js

```<code>import { createSlice } from "@reduxjs/toolkit";

const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    increment: state => {
      state.value++;
    },
    decrement: state => {
      state.value--;
    }
  }
});

export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer
</code>```

And finally the store.js

```<code>import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counterSlice";

const store = configureStore({
  reducer: counterReducer
})

export default store;
</code>```

What could be the problem?

I tried to run the code using npm start and was expecting to see the initial state value stored in the counter slice display in the browser window.

Body:
I was trying out react redux, but each time I add redux logic in my App component, I don't get any output on the browser window.

I have three files:

App.js

import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { increment } from './counterSlice';

function App() {
  const count = useSelector((state) => state.counter.value)
  const dispatch = useDispatch()

  return (

Values is {count}

      <button onClick={() => dispatch(increment)}>Plus</button>

  );
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import store from './store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

counterSlice.js

import { createSlice } from "@reduxjs/toolkit";

const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    increment: state => {
      state.value++;
    },
    decrement: state => {
      state.value--;
    }
  }
});

export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer

And finally the store.js

import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counterSlice";

const store = configureStore({
  reducer: counterReducer
})

export default store;

What could be the problem?

I tried to run the code using npm start and was expecting to see the initial state value stored in the counter slice display in the browser window.


问:
symfony process external data
In my symfony project, I regularly need to download data from a git repository, and then importing it in to the database. I think the best way to do this will be a console command which is called by a cronjob.

My question, what would be best practice: Do it all in a console command, or having a controller which does the work and the command is just the interface for the cronjob?

Title: symfony process external data


问:
Why is the headers property of an http.IncomingMessage non-enumerable?
Say I create a node server with the following:

```<code>const server = http.createServer((req, res) => {
  // req is an IncomingMessage
}
</code>```

I believe the first param, req, is an instance of IncomingMessage

I know this instance has a headers property.

If I do Object.keys(req), however, I do not see the headers key.  I assume this is because this the headers property is non-enumerable.

Question is - why?  Why is headers not enumerable whereas rawHeaders is?  Is this just how it is, or is there a specific reason / benefit to this?

Thanks!

Body:
Say I create a node server with the following:

const server = http.createServer((req, res) => {
  // req is an IncomingMessage
}

I believe the first param, req, is an instance of IncomingMessage

I know this instance has a headers property.

If I do Object.keys(req), however, I do not see the headers key.  I assume this is because this the headers property is non-enumerable.

Question is - why?  Why is headers not enumerable whereas rawHeaders is?  Is this just how it is, or is there a specific reason / benefit to this?

Thanks!


问:
dynamic web priject is missing on eclipse version 2021-09
I download Eclipse version 2021.09, and i don't have Dynamic Web project option.
I tried to install it with Help => install new software => select Web,XML, JavaEE ... and restart Eclipse.
After restart Eclipse, i still don't hava web dynamic project option.

How can i set this option ?