问:
I Can't request a @Put in my android app with Retrofit
i'm trying to call a RestWebService using Retrofit, i can do the @get method but when i try the @PUT i don't have a response. My Restservice use x-www-form.

I try do use Logger but when the rest service is called I don’t have a answer so I can’t have a answer. Also I remove @FormURLEncoded and I try do send by query but I have the same answer

```<code>   private void saveData(String idFirebase, String firstName, String lastName, String licenseCard) {

        userRestService.getInstance().putUser("25yw345iHNbq8rmO8VOKhkKqv9M2", "Teste")
                .enqueue(new Callback<MessageResponse>() {
                    @Override
                    public void onResponse(Call<MessageResponse> call, Response<MessageResponse> response) {
                        if (response.isSuccessful()) {
                            logger.info("Webservice is working" + response.body().getMessage());
                        }
                    }
                    @Override
                    public void onFailure(Call<MessageResponse> call, Throwable t) {

                    }
                });

    }
}
</code>```
```<code>public interface userRestServiceInterface {
    @GET("api/user")
        Call<userResponse> getUser(@Query("xifirebaseid") String firebaseId);

    @FormUrlEncoded
    @PUT("api/user/{xifirebaseid}")
    Call<MessageResponse> putUser(@Path("xifirebaseid") String idFireBaseUser, @Field("xsnome") String firstName);
}
</code>```
```<code>if (INSTANCE == null) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://MyIP:3000/")
                .addConverterFactory(MoshiConverterFactory.create())
                .build();

        INSTANCE = retrofit.create(userRestServiceInterface.class);
        logger.info("Calling the Rest"+ INSTANCE);
    }
    return INSTANCE;
}
</code>```

I try to change the invocation method, and i use Postman with success.
I Android Studio give me this message

```<code>2022-12-29 21:36:35.168 12780-12810/com.swerve D/EGL_emulation: app_time_stats: avg=521.57ms min=514.41ms max=528.73ms count=2
2022-12-29 21:36:36.680 12780-12810/com.swerve D/EGL_emulation: app_time_stats: avg=504.05ms min=498.82ms max=512.63ms count=3
2022-12-29 21:36:37.704 12780-12810/com.swerve D/EGL_emulation: app_time_stats: avg=512.04ms min=511.06ms max=513.03ms count=2
2022-12-29 21:36:38.727 12780-12810/com.swerve D/EGL_emulation: app_time_stats: avg=511.20ms min=510.81ms max=511.59ms count=2
</code>```

I try do do debug but without success, the service don't give any error message.. I try with and without x-www-form

Body:
i'm trying to call a RestWebService using Retrofit, i can do the @get method but when i try the @PUT i don't have a response. My Restservice use x-www-form.

I try do use Logger but when the rest service is called I don’t have a answer so I can’t have a answer. Also I remove @FormURLEncoded and I try do send by query but I have the same answer

   private void saveData(String idFirebase, String firstName, String lastName, String licenseCard) {

        userRestService.getInstance().putUser("25yw345iHNbq8rmO8VOKhkKqv9M2", "Teste")
                .enqueue(new Callback<MessageResponse>() {
                    @Override
                    public void onResponse(Call<MessageResponse> call, Response<MessageResponse> response) {
                        if (response.isSuccessful()) {
                            logger.info("Webservice is working" + response.body().getMessage());
                        }
                    }
                    @Override
                    public void onFailure(Call<MessageResponse> call, Throwable t) {

                    }
                });

    }
}

public interface userRestServiceInterface {
    @GET("api/user")
        Call<userResponse> getUser(@Query("xifirebaseid") String firebaseId);

    @FormUrlEncoded
    @PUT("api/user/{xifirebaseid}")
    Call<MessageResponse> putUser(@Path("xifirebaseid") String idFireBaseUser, @Field("xsnome") String firstName);
}

if (INSTANCE == null) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://MyIP:3000/")
                .addConverterFactory(MoshiConverterFactory.create())
                .build();

        INSTANCE = retrofit.create(userRestServiceInterface.class);
        logger.info("Calling the Rest"+ INSTANCE);
    }
    return INSTANCE;
}

I try to change the invocation method, and i use Postman with success.
I Android Studio give me this message

2022-12-29 21:36:35.168 12780-12810/com.swerve D/EGL_emulation: app_time_stats: avg=521.57ms min=514.41ms max=528.73ms count=2
2022-12-29 21:36:36.680 12780-12810/com.swerve D/EGL_emulation: app_time_stats: avg=504.05ms min=498.82ms max=512.63ms count=3
2022-12-29 21:36:37.704 12780-12810/com.swerve D/EGL_emulation: app_time_stats: avg=512.04ms min=511.06ms max=513.03ms count=2
2022-12-29 21:36:38.727 12780-12810/com.swerve D/EGL_emulation: app_time_stats: avg=511.20ms min=510.81ms max=511.59ms count=2

I try do do debug but without success, the service don't give any error message.. I try with and without x-www-form


来源: stackexchange

问:
How do I highlight a camelCase word in WebStorm?
I am trying to highlight a camelCase word in WebStorm, For example, firstName.
However, It's doesn't highlight the entire word, highlight a portion of it, first or Name.
How can I select or highlight the entire word?
I am using WebStorm 2022.3 version.

ContentLicense: CC BY-SA 4.0


问:
How to summarise multiple arrays of time series data based on the data deviation in python?
I have multiple arrays of varying time series data, all starting at the same place but having different outcomes.

I want to summarise them as a single plot highlighting the most typical routes taken, if there are multiple directions I'd want it to show distinct routes but with some parameter suggesting its uncertain, such as thinner or fainter lines.

I'm imagining it like a tree branch - The main path is the thickest and less likely paths getting smaller. Alternativley if the data is moving entirly in one direction the plot would show one intense line in that direction.

I've looked at k-means clustering, which isn't so great with time series, and DTW (Dynamic time wrapping) which doesn't offer multiple routes based on data deviation.


问:
Cannot read properties of undefined in CSS Module
I am having a component of a form and I am adding classNames that have variables inside of them, the variables type is string and I am having this error in the console
SearchInput.js:9 Uncaught TypeError: Cannot read properties of undefined (reading 'Hamburger')
Here is my code:

```<code>import React from 'react'
import SearchIcon from '../../images/search.svg'
import appCSS from '../CSS/App.module.css';

export default function SearchInput({requestedBy, navStatus}) {

  return (
    <form className={`${appCSS.searchbarForm[requestedBy]} ${appCSS.searchbarForm[navStatus]}`}>
      <input type="text" placeholder='Search for courses or teachers'/>
      <button type='submit'>
        <img src={SearchIcon} alt="search icon" />
      </button>
    </form>

  )
}
</code>```

I am running the latest version of react with "react-scripts": "5.0.1", and "css-loader": "^6.7.3"

in the CSS all classNames are checked, they are all correct

Body:
I am having a component of a form and I am adding classNames that have variables inside of them, the variables type is string and I am having this error in the console
SearchInput.js:9 Uncaught TypeError: Cannot read properties of undefined (reading 'Hamburger')
Here is my code:

import React from 'react'
import SearchIcon from '../../images/search.svg'
import appCSS from '../CSS/App.module.css';

export default function SearchInput({requestedBy, navStatus}) {

  return (
    <form className={`${appCSS.searchbarForm[requestedBy]} ${appCSS.searchbarForm[navStatus]}`}>
      <input type="text" placeholder='Search for courses or teachers'/>
      <button type='submit'>

      </button>
    </form>

  )
}

I am running the latest version of react with "react-scripts": "5.0.1", and "css-loader": "^6.7.3"

in the CSS all classNames are checked, they are all correct


问:
comparison between pointer and integer
So I am trying to write a lotto program where the user input is two integers 0-36 or two colors. After that compare them and if the choose to put numbers and it's a match then it should print 36 else if they choose to put colors and matches it should print 2ggr.

Now I get this error comparison between pointer and integer.

I am new to programming so I would be happy to get some help.

```<code>#include <stdio.h>
#include <string.h>

int main()
{
    char a[10];
    char b[10];

    scanf("%s %s", a, b);

    if (a >= 0 && a <= 36 && b >= 0 && b <= 36)
    {
        if (a == b)
        {
            printf("36ggr");
        }
        else if (
               a == 'Red'
            || a == 'green'
            || a == 'black'
            && b == 'Red'
            || b == 'green'
            || b == 'black'
        )
        {
            if (a == b)
            {
                printf("2ggr");
            }
        }
        else
        {
            printf("Inget vinst");
        }
    }

    return 0;
}

</code>```

Title: comparison between pointer and integer

Body:
So I am trying to write a lotto program where the user input is two integers 0-36 or two colors. After that compare them and if the choose to put numbers and it's a match then it should print 36 else if they choose to put colors and matches it should print 2ggr.

Now I get this error comparison between pointer and integer.

I am new to programming so I would be happy to get some help.

#include <stdio.h>
#include <string.h>

int main()
{
    char a[10];
    char b[10];

    scanf("%s %s", a, b);

    if (a >= 0 && a <= 36 && b >= 0 && b <= 36)
    {
        if (a == b)
        {
            printf("36ggr");
        }
        else if (
               a == 'Red'
            || a == 'green'
            || a == 'black'
            && b == 'Red'
            || b == 'green'
            || b == 'black'
        )
        {
            if (a == b)
            {
                printf("2ggr");
            }
        }
        else
        {
            printf("Inget vinst");
        }
    }

    return 0;
}


问:
Client Using VPN(Cisco OpenConenct) breaks TCP connection. C#. SuperSimpleTCP
I'm using C# .Net with SuperSimpleTCP Library to make a simple messaging app.
The App works just fine in Normal circumstances. But if the client is connected to a VPN(cisco openconnect) Client will fail to communicate with the server. not only messages will fail to successfully transmit to the server, but the server will fail to register the Client's disconnection in the event of the Client closing the app

Minimalist Client Code:

```<code>private void Client_Form_Load(object sender, EventArgs e)
{
       IPAddress iPAddress = IPAddress.Parse(IP_Address);
       client = new SimpleTcpClient(iPAddress,25565);
       client.Connect();
}

private void btnSend_Click(object sender, EventArgs e)
{
         if(!client.IsConnected)return;
            if (string.IsNullOrEmpty(txtMessage.Text)) return;
            client.Send(Message);
}
</code>```

Minimalist Server Code:

```<code> private void Server_Form_Load(object sender, EventArgs e)
        {
            server = new SimpleTcpServer(txtIP.Text);
         server.Start();
            client.Events.Connected += Events_Connected;
            client.Events.Disconnected += Events_Disconnected;
            client.Events.DataReceived += Events_DataReceived;

        }
private void Events_ClientConnected(object? sender, ConnectionEventArgs e)
        {
        this.Invoke((MethodInvoker)delegate
            {
                txtInfo.Text += $"{e.IpPort}: Connected...{Environment.NewLine}";
            });
     }

private void Events_ClientDisconnected(object? sender, ConnectionEventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                txtInfo.Text += $"{e.IpPort}: Disconnected...{Environment.NewLine}";
            });
        }
private void Events_DataReceived(object? sender, DataReceivedEventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                txtInfo.Text += $"{e.IpPort}: {Encoding.UTF8.GetString(e.Data)}{Environment.NewLine}";
            });

        }
</code>```

I don't know what about using a VPN causes the issue and how to fix it.

Edit: It is important that my app can't run with a VPN running in the background cause I live in Iran. and using VPN is almost necessary while using the internet in any way

Body:
I'm using C# .Net with SuperSimpleTCP Library to make a simple messaging app.
The App works just fine in Normal circumstances. But if the client is connected to a VPN(cisco openconnect) Client will fail to communicate with the server. not only messages will fail to successfully transmit to the server, but the server will fail to register the Client's disconnection in the event of the Client closing the app

Minimalist Client Code:

private void Client_Form_Load(object sender, EventArgs e)
{
       IPAddress iPAddress = IPAddress.Parse(IP_Address);
       client = new SimpleTcpClient(iPAddress,25565);
       client.Connect();
}

private void btnSend_Click(object sender, EventArgs e)
{
         if(!client.IsConnected)return;
            if (string.IsNullOrEmpty(txtMessage.Text)) return;
            client.Send(Message);
}

Minimalist Server Code:

 private void Server_Form_Load(object sender, EventArgs e)
        {
            server = new SimpleTcpServer(txtIP.Text);
         server.Start();
            client.Events.Connected += Events_Connected;
            client.Events.Disconnected += Events_Disconnected;
            client.Events.DataReceived += Events_DataReceived;

        }
private void Events_ClientConnected(object? sender, ConnectionEventArgs e)
        {
        this.Invoke((MethodInvoker)delegate
            {
                txtInfo.Text += $"{e.IpPort}: Connected...{Environment.NewLine}";
            });
     }

private void Events_ClientDisconnected(object? sender, ConnectionEventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                txtInfo.Text += $"{e.IpPort}: Disconnected...{Environment.NewLine}";
            });
        }
private void Events_DataReceived(object? sender, DataReceivedEventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                txtInfo.Text += $"{e.IpPort}: {Encoding.UTF8.GetString(e.Data)}{Environment.NewLine}";
            });

        }

I don't know what about using a VPN causes the issue and how to fix it.

Edit: It is important that my app can't run with a VPN running in the background cause I live in Iran. and using VPN is almost necessary while using the internet in any way


问:
Using local project installs (also called editable installs) with root user
Using git submodules I put the library my-pkg into a subfolder of my scripts. In my-pkg there is a valid package structure for a package my_pkg.

```<code>my-pkg/
├─ setup.cfg
├─ setup.py
├─ my_pkg
|  ├─ __init__.py
...
</code>```

It is possible to pip install -e my-pkg when not using the root user (in a testing environment where it is possible to use other users). How can I debug or solve this for the root user in the target environment?

There is no error message, the only feedback is:

```<code>Installing collected packages: my-pkg
  Running setup.py develop for my-pkg
Successfully installed my-pkg
</code>```

The statement has no effect when using the root user. When using the statement with other users, my-pkg becomes importable.

It is possible there are other differences between the environment where the local project install works and where it doesn't. But the user thing is the most obvious. Everything else runs with all versions and files fixed using Docker.

Some additional information:

version of setuptools (I tried several other as well): 65.6.3

It does not make a difference if python -m pip or absolute paths are used for pip or python3

Body:
Using git submodules I put the library my-pkg into a subfolder of my scripts. In my-pkg there is a valid package structure for a package my_pkg.

my-pkg/
├─ setup.cfg
├─ setup.py
├─ my_pkg
|  ├─ __init__.py
...

It is possible to pip install -e my-pkg when not using the root user (in a testing environment where it is possible to use other users). How can I debug or solve this for the root user in the target environment?

There is no error message, the only feedback is:

Installing collected packages: my-pkg
  Running setup.py develop for my-pkg
Successfully installed my-pkg

The statement has no effect when using the root user. When using the statement with other users, my-pkg becomes importable.

It is possible there are other differences between the environment where the local project install works and where it doesn't. But the user thing is the most obvious. Everything else runs with all versions and files fixed using Docker.

Some additional information:

version of setuptools (I tried several other as well): 65.6.3

It does not make a difference if python -m pip or absolute paths are used for pip or python3


问:
SQLAlchemy doesn't create tables in a Flask application
I've been trying to create a first web application using Flask. The problem is I can't get around creating the database.db file, or even the tables within the database, when the file already exists using create_all() function.

Here's my init module:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path

db = SQLAlchemy()
DB_NAME = "database.db"

def create_app():
app = Flask(__name__)
app.config\["SECRET_KEY"\] = "yfytf345fg34y5t"
app.config\['SQLALCHEMY_DATABASE_URI'\] = f'sqlite:///{DB_NAME}'
db.init_app(app)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')

    with app.app_context():
        from .models import Note, User
        db.create_all()
        db.session.commit()

    return app

```
<p>And here are the models created:</p>
<pre class="lang-py prettyprint-override"><code>from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.String(10000))
    date = db.Column(db.DateTime(timezone=True), default=func.now())
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    firstName = db.Column(db.String(150))
    notes = db.relationship('Note')

</code>```

I've been following a 3-year old youtube tutorial on flask, I accounted for changes in SQLAlchemy docummentation, used app context and basically went through all of the recent similar questions asked, but got no solution.

Body:
I've been trying to create a first web application using Flask. The problem is I can't get around creating the database.db file, or even the tables within the database, when the file already exists using create_all() function.

Here's my init module:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path

db = SQLAlchemy()
DB_NAME = "database.db"

def create_app():
app = Flask(__name__)
app.config\["SECRET_KEY"\] = "yfytf345fg34y5t"
app.config\['SQLALCHEMY_DATABASE_URI'\] = f'sqlite:///{DB_NAME}'
db.init_app(app)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')

    with app.app_context():
        from .models import Note, User
        db.create_all()
        db.session.commit()

    return app

And here are the models created:

from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    data = db.Column(db.String(10000))
    date = db.Column(db.DateTime(timezone=True), default=func.now())
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    firstName = db.Column(db.String(150))
    notes = db.relationship('Note')

I've been following a 3-year old youtube tutorial on flask, I accounted for changes in SQLAlchemy docummentation, used app context and basically went through all of the recent similar questions asked, but got no solution.


问:
Ionic Angular: Date Picker Type error: TypeError: Cannot read properties of undefined (reading ‘options’)
I have a angular ionic application (Capacitor) and have the following date picker:

```<code>  <ion-item>
    <ion-label>Date</ion-label>
    <ion-input
      value="{{ date | date: 'dd-MMM-yyyy' }}"
      id="date"
      class="ion-text-end"
      readonly="true"
    ></ion-input>
    <ion-popover trigger="date" size="cover">
      <ng-template>
        <ion-datetime [showDefaultButtons]="true"
                      #popoverDatetime
                      presentation="date" value="{{date}}"
                      (ionChange)="date = popoverDatetime.value;">
        </ion-datetime>
      </ng-template>
    </ion-popover>
  </ion-item>

</code>```

now whenever I click the date picker to open it I get the following error logs:

```<code>TypeError: Cannot read properties of undefined (reading 'options')
  at PickerColumnCmp.refresh @ http://localhost/node_modules_ionic_core_dist_esm_ion-datetime_3_entry_js.js:2934:24
  at PickerColumnCmp.componentDidLoad @ http://localhost/node_modules_ionic_core_dist_esm_ion-datetime_3_entry_js.js:2686:10
  at safeCall @ http://localhost/vendor.js:21810:30
  at postUpdateComponent @ http://localhost/vendor.js:21730:7
  at postUpdate @ http://localhost/vendor.js:21660:32
  at push.3279._ZoneDelegate.invoke @ http://localhost/polyfills.js:422:30
  at push.3279.Zone.run @ http://localhost/polyfills.js:182:47
  at <anonymous> @ http://localhost/polyfills.js:1339:38
  at push.3279._ZoneDelegate.invokeTask @ http://localhost/polyfills.js:456:35
  at push.3279.Zone.runTask @ http://localhost/polyfills.js:227:51
</code>```
```<code>TypeError: Cannot read properties of undefined (reading 'align') <error: unable to serialize object>
TypeError: Cannot read properties of undefined (reading 'align')
at PickerColumnCmp.render @ http://localhost/node_modules_ionic_core_dist_esm_ion-datetime_3_entry_js.js:2974:38
at callRender @ http://localhost/vendor.js:21681:44
at <anonymous> @ http://localhost/vendor.js:21644:7
at Generator.next @ <anonymous>
at asyncGeneratorStep @ http://localhost/vendor.js:200079:24
at _next @ http://localhost/vendor.js:200101:9
at <anonymous> @ http://localhost/vendor.js:200108:7
at new ZoneAwarePromise @ http://localhost/polyfills.js:1364:25
at <anonymous> @ http://localhost/vendor.js:200097:12
at updateComponent @ http://localhost/vendor.js:21675:17
</code>```

this is in my live environment and my logs are flooded with them, wondering if anyone can help me out here.

Thanks

Body:
I have a angular ionic application (Capacitor) and have the following date picker:

  <ion-item>
    <ion-label>Date</ion-label>
    <ion-input
      value="{{ date | date: 'dd-MMM-yyyy' }}"
      id="date"
      class="ion-text-end"
      readonly="true"
    ></ion-input>
    <ion-popover trigger="date" size="cover">
      <ng-template>
        <ion-datetime [showDefaultButtons]="true"
                      #popoverDatetime
                      presentation="date" value="{{date}}"
                      (ionChange)="date = popoverDatetime.value;">
        </ion-datetime>
      </ng-template>
    </ion-popover>
  </ion-item>

now whenever I click the date picker to open it I get the following error logs:

TypeError: Cannot read properties of undefined (reading 'options')
  at PickerColumnCmp.refresh @ http://localhost/node_modules_ionic_core_dist_esm_ion-datetime_3_entry_js.js:2934:24
  at PickerColumnCmp.componentDidLoad @ http://localhost/node_modules_ionic_core_dist_esm_ion-datetime_3_entry_js.js:2686:10
  at safeCall @ http://localhost/vendor.js:21810:30
  at postUpdateComponent @ http://localhost/vendor.js:21730:7
  at postUpdate @ http://localhost/vendor.js:21660:32
  at push.3279._ZoneDelegate.invoke @ http://localhost/polyfills.js:422:30
  at push.3279.Zone.run @ http://localhost/polyfills.js:182:47
  at <anonymous> @ http://localhost/polyfills.js:1339:38
  at push.3279._ZoneDelegate.invokeTask @ http://localhost/polyfills.js:456:35
  at push.3279.Zone.runTask @ http://localhost/polyfills.js:227:51

TypeError: Cannot read properties of undefined (reading 'align') <error: unable to serialize object>
TypeError: Cannot read properties of undefined (reading 'align')
at PickerColumnCmp.render @ http://localhost/node_modules_ionic_core_dist_esm_ion-datetime_3_entry_js.js:2974:38
at callRender @ http://localhost/vendor.js:21681:44
at <anonymous> @ http://localhost/vendor.js:21644:7
at Generator.next @ <anonymous>
at asyncGeneratorStep @ http://localhost/vendor.js:200079:24
at _next @ http://localhost/vendor.js:200101:9
at <anonymous> @ http://localhost/vendor.js:200108:7
at new ZoneAwarePromise @ http://localhost/polyfills.js:1364:25
at <anonymous> @ http://localhost/vendor.js:200097:12
at updateComponent @ http://localhost/vendor.js:21675:17

this is in my live environment and my logs are flooded with them, wondering if anyone can help me out here.

Thanks


问:
snapshot of FutureBuilder is null in flutter
this code uses data.dart class but gets snapshot.data as null, when I implement the second code in dart code with a simple main function this error doesnt arise. how to avoid snapshot getting null.

```<code>import 'package:flutter/material.dart';
import 'package:flutter_application_1/data.dart';

void main() {
   getStudents();
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomeScreen(),
    );
  }
}
class HomeScreen extends StatelessWidget{
 const HomeScreen({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Android Expert'),),
      body:FutureBuilder<List<StudentData>?>(future: getStudents(), builder:(context, snapshot) {
        if(snapshot.hasData){
          return ListView.builder(
            itemCount: snapshot.data!.length,
            itemBuilder: (context, index) {
              return Container(height: 84, color: Colors.red, margin:EdgeInsets.fromLTRB(8, 4, 8, 4));
            },
          );
        }
        else{
          return Center(child:CircularProgressIndicator(),);
        }
      },)
    );
  }
}
</code>```

data.dart class is the following. In this code JSON information is read and pass to a real student. an error that arise in debug console is Error: DioError [DioErrorType.response]: XMLHttpRequest error.

```<code>    import 'package:dio/dio.dart';

    class StudentData{
      final int id;
      final String firstName;
      final String lastName;
      final String course;
      final int score;
      final String createdAt;
      final String updatedAt;

      StudentData(this.id, this.firstName, this.lastName, this.course, this.score,
      this.createdAt, this.updatedAt);
  StudentData.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        firstName = json['first_name'],
        lastName = json['last_name'],
        course = json['course'],
        score = json['score'],
        createdAt = json['created_at'],
        updatedAt = json['created_at'];
    }

    class HttpClient{
      static Dio instance=Dio(BaseOptions(baseUrl: 'http://expertdevelopers.ir/api/v1/'));
    }

    Future<List<StudentData>?> getStudents()async{
      final response=await HttpClient.instance.get('experts/student');

      final List<StudentData> students=[];
      if (response.data is List<dynamic>){
        (response.data as List<dynamic>).forEach((element) {
          students.add(StudentData.fromJson(element));
        });
      }
      //print(students.toString());
      return students;
    }
</code>```

Body:
this code uses data.dart class but gets snapshot.data as null, when I implement the second code in dart code with a simple main function this error doesnt arise. how to avoid snapshot getting null.

import 'package:flutter/material.dart';
import 'package:flutter_application_1/data.dart';

void main() {
   getStudents();
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomeScreen(),
    );
  }
}
class HomeScreen extends StatelessWidget{
 const HomeScreen({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Android Expert'),),
      body:FutureBuilder<List<StudentData>?>(future: getStudents(), builder:(context, snapshot) {
        if(snapshot.hasData){
          return ListView.builder(
            itemCount: snapshot.data!.length,
            itemBuilder: (context, index) {
              return Container(height: 84, color: Colors.red, margin:EdgeInsets.fromLTRB(8, 4, 8, 4));
            },
          );
        }
        else{
          return Center(child:CircularProgressIndicator(),);
        }
      },)
    );
  }
}

data.dart class is the following. In this code JSON information is read and pass to a real student. an error that arise in debug console is Error: DioError [DioErrorType.response]: XMLHttpRequest error.

    import 'package:dio/dio.dart';

    class StudentData{
      final int id;
      final String firstName;
      final String lastName;
      final String course;
      final int score;
      final String createdAt;
      final String updatedAt;

      StudentData(this.id, this.firstName, this.lastName, this.course, this.score,
      this.createdAt, this.updatedAt);
  StudentData.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        firstName = json['first_name'],
        lastName = json['last_name'],
        course = json['course'],
        score = json['score'],
        createdAt = json['created_at'],
        updatedAt = json['created_at'];
    }

    class HttpClient{
      static Dio instance=Dio(BaseOptions(baseUrl: 'http://expertdevelopers.ir/api/v1/'));
    }

    Future<List<StudentData>?> getStudents()async{
      final response=await HttpClient.instance.get('experts/student');

      final List<StudentData> students=[];
      if (response.data is List<dynamic>){
        (response.data as List<dynamic>).forEach((element) {
          students.add(StudentData.fromJson(element));
        });
      }
      //print(students.toString());
      return students;
    }


问:
How to set a value to a declared variable from a function call in MySQL?
Let's say, I want to generate token and return it to user. I declare a variable new_token and I tried to pass it a value from procedure generate_token().
It might not work with procedures, because they are not allowed to be used in expressions.
But it does not work with functions either way.

Code:

DECLARE new_token varchar(255);
SET new_token = CALL generate_token(lg);
```

I tried to assign to a local variable from a function call and from procedure, but neither of them did work. Can you help me out?

Body:
Let's say, I want to generate token and return it to user. I declare a variable new_token and I tried to pass it a value from procedure generate_token().
It might not work with procedures, because they are not allowed to be used in expressions.
But it does not work with functions either way.

Code:

DECLARE new_token varchar(255);
SET new_token = CALL generate_token(lg);

I tried to assign to a local variable from a function call and from procedure, but neither of them did work. Can you help me out?


问:
MVN package. NA data management
Trying to run normality test with MVN package. {MVN}
https://cran.r-project.org/web/packages/MVN/index.html

I always receive the same answer, i´ve tried several ways to omit these values in the analysis: na.omit, is.na, na.exclude etc.

```<code>***mvn(data, univariateTest ="SW", desc = TRUE)
Error in qr.default(S) : NA/NaN/Inf in foreign function call (arg 1)***
</code>```

Would anyone know how to do the test without the NA values within each column?

Thank you very much

Title: MVN package. NA data management

Body:
Trying to run normality test with MVN package. {MVN}
https://cran.r-project.org/web/packages/MVN/index.html

I always receive the same answer, i´ve tried several ways to omit these values in the analysis: na.omit, is.na, na.exclude etc.

***mvn(data, univariateTest ="SW", desc = TRUE)
Error in qr.default(S) : NA/NaN/Inf in foreign function call (arg 1)***

Would anyone know how to do the test without the NA values within each column?

Thank you very much


问:
Java JList How To Handle Different Model Classes?
I have a Jlist and it's model class can differ. And I want to take action according to JList's model class. I tried something like this:

```<code>        private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
        Object selectedObject = jList1.getModel().getClass();
        switch (selectedObject) {

        case ResponsePlayerSearch.class:
            //do something with this class. for example run get player function from this class:
            selectedObject.getPlayerName();
            break;
        case ResponseLeagueSearch.class:
            //do something with this class
            break;
        case ResponseTeamSearch.class:
            //do something with this class
            break;
        case ResponseCoachSearch.class:
            //do something with this class
            break;
        default:

    }

}
</code>```

But ide throws an error : patterns in switch statements are a preview feature and are disabled by default. (use --enable-preview to enable patterns in switch statements)

How should I handle a situation like this? Should I use switch case or something else? Or how should I use switch case for handling different classes?

Edit(To give more details) :
Basically what I'm doing is searching some values from an api. First, users have to select a type(team,player,league or coach) and according to this type they can search any word they want. So as an example, let's say user searched for a team. Then program makes the call and getting the response. Then this response is converting to a model. Which is ResponseTeamSearch for this type. After that JList's model class is changing according to this model. Then JList is getting populated by the values of response.

By the way this is the creation code of Jlist:

```<code>jList1 = new javax.swing.JList();
 jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTIO;

jList1.addListSelectionListener(new
javax.swing.event.ListSelectionListener() {
  public void valueChanged(javax.swing.event.ListSelectionEvent
evt)
{
    jList1ValueChanged(evt);
  }
    });

  jScrollPane1.setViewportView(jList1);
</code>```

Body:
I have a Jlist and it's model class can differ. And I want to take action according to JList's model class. I tried something like this:

        private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
        Object selectedObject = jList1.getModel().getClass();
        switch (selectedObject) {

        case ResponsePlayerSearch.class:
            //do something with this class. for example run get player function from this class:
            selectedObject.getPlayerName();
            break;
        case ResponseLeagueSearch.class:
            //do something with this class
            break;
        case ResponseTeamSearch.class:
            //do something with this class
            break;
        case ResponseCoachSearch.class:
            //do something with this class
            break;
        default:

    }

}

But ide throws an error : patterns in switch statements are a preview feature and are disabled by default. (use --enable-preview to enable patterns in switch statements)

How should I handle a situation like this? Should I use switch case or something else? Or how should I use switch case for handling different classes?

Edit(To give more details) :
Basically what I'm doing is searching some values from an api. First, users have to select a type(team,player,league or coach) and according to this type they can search any word they want. So as an example, let's say user searched for a team. Then program makes the call and getting the response. Then this response is converting to a model. Which is ResponseTeamSearch for this type. After that JList's model class is changing according to this model. Then JList is getting populated by the values of response.

By the way this is the creation code of Jlist:

jList1 = new javax.swing.JList();
 jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTIO;

jList1.addListSelectionListener(new
javax.swing.event.ListSelectionListener() {
  public void valueChanged(javax.swing.event.ListSelectionEvent
evt)
{
    jList1ValueChanged(evt);
  }
    });

  jScrollPane1.setViewportView(jList1);


问:
Exposing host devices during docker build
My docker build will be greatly facilitated by having my computer's GPU available to it during build time via the normal devices like /dev/kfd. How can I do this?

Here is what I have tried so far, after much research on the internet.

I am using docker buildx like this

```<code>docker buildx create --driver-opt image=moby/buildkit:master  \
                     --use --name insecure-builder \
                     --buildkitd-flags '--allow-insecure-entitlement security.insecure' \
                     --config ./buildkitd.toml
docker buildx use insecure-builder
docker buildx build --load --allow security.insecure . -t myimage
</code>```

And the contents of the buildkitd.toml file is this:

```<code># Define the builder to use for the build
builder = "docker"

# Define the context for the build
[context]
  # Use the current directory as the context
  local = ["."]
  # Map the /dev/kfd device to the container
  devices = ["/dev/kfd"]

# Define the steps for the build
[[steps]]
  # Use the Dockerfile in the context to build the image
  use = "./Dockerfile"
  # Tag the image with the specified name and tag
  image = "my-image:latest"
</code>```

Inside the Dockerfile I have a line like this:

```<code>RUN --security=insecure  /load-deps.sh
</code>```

Inside the script I test for the availability of /dev/kfd - and it's not there, then only device I can find is '/dev/pts'

Body:
My docker build will be greatly facilitated by having my computer's GPU available to it during build time via the normal devices like /dev/kfd. How can I do this?

Here is what I have tried so far, after much research on the internet.

I am using docker buildx like this

docker buildx create --driver-opt image=moby/buildkit:master  \
                     --use --name insecure-builder \
                     --buildkitd-flags '--allow-insecure-entitlement security.insecure' \
                     --config ./buildkitd.toml
docker buildx use insecure-builder
docker buildx build --load --allow security.insecure . -t myimage

And the contents of the buildkitd.toml file is this:

# Define the builder to use for the build
builder = "docker"

# Define the context for the build
[context]
  # Use the current directory as the context
  local = ["."]
  # Map the /dev/kfd device to the container
  devices = ["/dev/kfd"]

# Define the steps for the build
[[steps]]
  # Use the Dockerfile in the context to build the image
  use = "./Dockerfile"
  # Tag the image with the specified name and tag
  image = "my-image:latest"

Inside the Dockerfile I have a line like this:

RUN --security=insecure  /load-deps.sh

Inside the script I test for the availability of /dev/kfd - and it's not there, then only device I can find is '/dev/pts'


问:
How to add legend to Radar chart in Python
I would like to add a legend to the Radar chart. That shows score changes over time.Sp I want each line in the chart to be categorized based on a specific date.

The code is as follows:

```<code>import plotly.graph_objects as go

categories = ['GAD-7','PHQ-9','Likert-Insomnia','Likert-Depression','Likert-Anxiety']

fig = go.Figure()

fig.add_trace(go.Scatterpolar(
      r=Survey['GAD7Score'],
      theta=categories,
      #fill='toself',
      name='GAD-7'
))
fig.add_trace(go.Scatterpolar(
      r=Survey['PHQ9Score'],
      theta=categories,
      #fill='toself',
      name='PHQ-9'
))

fig.add_trace(go.Scatterpolar(
      r=Survey['Likert-Insomnia'],
      theta=categories,
      #fill='toself',
      name='Likert-Insomnia'
))

fig.add_trace(go.Scatterpolar(
      r=Survey['Likert-Depression'],
      theta=categories,
      #fill='toself',
      name='Likert-Depression'
))

fig.add_trace(go.Scatterpolar(
      r=Survey['Likert-Anxiety'],
      theta=categories,
      #fill='toself',
      name='Likert-Anxiety'

))

fig.update_layout(
  polar=dict(
    radialaxis=dict(
      visible=True,
      range=[0, 7]
    )),
  showlegend=True
)

fig.show()
</code>```

The displayed figure gives the legend for the categories while the legend should be the date column

enter image description here

Body:
I would like to add a legend to the Radar chart. That shows score changes over time.Sp I want each line in the chart to be categorized based on a specific date.

The code is as follows:

import plotly.graph_objects as go

categories = ['GAD-7','PHQ-9','Likert-Insomnia','Likert-Depression','Likert-Anxiety']

fig = go.Figure()

fig.add_trace(go.Scatterpolar(
      r=Survey['GAD7Score'],
      theta=categories,
      #fill='toself',
      name='GAD-7'
))
fig.add_trace(go.Scatterpolar(
      r=Survey['PHQ9Score'],
      theta=categories,
      #fill='toself',
      name='PHQ-9'
))

fig.add_trace(go.Scatterpolar(
      r=Survey['Likert-Insomnia'],
      theta=categories,
      #fill='toself',
      name='Likert-Insomnia'
))

fig.add_trace(go.Scatterpolar(
      r=Survey['Likert-Depression'],
      theta=categories,
      #fill='toself',
      name='Likert-Depression'
))

fig.add_trace(go.Scatterpolar(
      r=Survey['Likert-Anxiety'],
      theta=categories,
      #fill='toself',
      name='Likert-Anxiety'

))

fig.update_layout(
  polar=dict(
    radialaxis=dict(
      visible=True,
      range=[0, 7]
    )),
  showlegend=True
)

fig.show()

The displayed figure gives the legend for the categories while the legend should be the date column

enter image description here


问:
SequelizeAssociationError in One to many relationships in Sequelize Postgres

I have two models project and stages. while retrieving the first time I get the response. when trying to retrieve the next time I get SequelizeAssociationError.
here project have many stages

stack

```<code>SequelizeAssociationError: You have used the alias stage in two separate associations. Aliased associations must have
unique aliases.
at new Association (D:\one to many example\node_modules\sequelize\lib\associations\base.js:13:13)
at new HasMany (D:\one to many example\node_modules\sequelize\lib\associations\has-many.js:28:5)
at create_project.hasMany (D:\one to many example\node_modules\sequelize\lib\associations\mixin.js:22:25)
at D:\one to many example\controllers\listStages.js:13:17
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

</code>```

createStageModel

```<code>const createStagesModel = {
  id: {
    type: new DataTypes.INTEGER(),
    autoIncrement: true,
    primaryKey: true,
  },
  stages_name: {
    type: new DataTypes.STRING(),
    allowNull: false,
  },
  stages_code: {
    type: new DataTypes.STRING(200),
    allowNull: false,
  },
  project_id: {
    type: new DataTypes.INTEGER(),
    allowNull: true,
  },
  isActive: {
    type: new DataTypes.INTEGER(),
    defaultValue: 1,
  },
};

</code>```

listStages

```<code>const { initStagesModel } = require("../models/stageModel");
const { initProjectModel } = require("../models/projectModel");

router.get("/:id", async (req, res) => {
  try {
    const stageData = await initStagesModel();
    const projectData = await initProjectModel();
    const id = req.params.id;

    projectData.hasMany(stageData, {
      foreignKey: "project_id",
      as: "stage",
    });

    stageData.belongsTo(projectData, {
      foreignKey: "project_id",
      as: "project",
    });

    data = await projectData.findAll({
      include: [
        {
          model: stageData,
          as: "stage",
        },
      ],
      where: { id: id },
    });

    return res.status(200).send(data);
  } catch (err) {
    return res.status(400).send(err.stack);
  }
});
</code>```

Body:
I have two models project and stages. while retrieving the first time I get the response. when trying to retrieve the next time I get SequelizeAssociationError.
here project have many stages

stack

SequelizeAssociationError: You have used the alias stage in two separate associations. Aliased associations must have
unique aliases.
at new Association (D:\one to many example\node_modules\sequelize\lib\associations\base.js:13:13)
at new HasMany (D:\one to many example\node_modules\sequelize\lib\associations\has-many.js:28:5)
at create_project.hasMany (D:\one to many example\node_modules\sequelize\lib\associations\mixin.js:22:25)
at D:\one to many example\controllers\listStages.js:13:17
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

createStageModel

const createStagesModel = {
  id: {
    type: new DataTypes.INTEGER(),
    autoIncrement: true,
    primaryKey: true,
  },
  stages_name: {
    type: new DataTypes.STRING(),
    allowNull: false,
  },
  stages_code: {
    type: new DataTypes.STRING(200),
    allowNull: false,
  },
  project_id: {
    type: new DataTypes.INTEGER(),
    allowNull: true,
  },
  isActive: {
    type: new DataTypes.INTEGER(),
    defaultValue: 1,
  },
};

listStages

const { initStagesModel } = require("../models/stageModel");
const { initProjectModel } = require("../models/projectModel");

router.get("/:id", async (req, res) => {
  try {
    const stageData = await initStagesModel();
    const projectData = await initProjectModel();
    const id = req.params.id;

    projectData.hasMany(stageData, {
      foreignKey: "project_id",
      as: "stage",
    });

    stageData.belongsTo(projectData, {
      foreignKey: "project_id",
      as: "project",
    });

    data = await projectData.findAll({
      include: [
        {
          model: stageData,
          as: "stage",
        },
      ],
      where: { id: id },
    });

    return res.status(200).send(data);
  } catch (err) {
    return res.status(400).send(err.stack);
  }
});


问:
How to suppress a Doxygen warning
Is there a way to suppress the "documented symbol 'x' was not declared or defined" Doxygen warning for certain parts of the code?

I know similar questions have been asked at least here and here but I did not find the answers posted to those questions helpful for my case so I wanted to check if there were any solutions or ideas that would help in this use case.

So first of all, I need to have WARN_AS_ERROR=FAIL_ON_WARNINGS so that Doxygen exit code will be non-zero when there are (valid) warnings so that my pull request checker can detect issues correctly. In this case, however, Doxygen incorrectly claims that some documented symbols are not declared because it's unable to parse their declarations due to the way their declarations come from external library code (see below). So I would need that particular warning to be suppressed for the definitions of those particular functions. The documentation for those functions should still be processed and warnings about any other issues in that processing are very desired. Hence, to my understanding, @cond does not solve this. Is there anything that does?

For reference, this is where the undesired warning originates from although I don't think it should matter for the question:
in file c.h:

```<code>//! blabla
namespace A
{
  //! blabla
  namespace B
  {
    //! blabla
    class C
    {
#include "lib.h" // This is where the function declarations are but Doxygen does not figure it
    };
  }
}
</code>```

in file c.cpp:

```<code>using namespace A::B;

/*! The declaration of this function was in lib.h. I may document something additional here but Doxygen collects this function without that also, which is desired.
*/
void C::foo()
{
}
</code>```

Title: How to suppress a Doxygen warning

Body:
Is there a way to suppress the "documented symbol 'x' was not declared or defined" Doxygen warning for certain parts of the code?

I know similar questions have been asked at least here and here but I did not find the answers posted to those questions helpful for my case so I wanted to check if there were any solutions or ideas that would help in this use case.

So first of all, I need to have WARN_AS_ERROR=FAIL_ON_WARNINGS so that Doxygen exit code will be non-zero when there are (valid) warnings so that my pull request checker can detect issues correctly. In this case, however, Doxygen incorrectly claims that some documented symbols are not declared because it's unable to parse their declarations due to the way their declarations come from external library code (see below). So I would need that particular warning to be suppressed for the definitions of those particular functions. The documentation for those functions should still be processed and warnings about any other issues in that processing are very desired. Hence, to my understanding, @cond does not solve this. Is there anything that does?

For reference, this is where the undesired warning originates from although I don't think it should matter for the question:
in file c.h:

//! blabla
namespace A
{
  //! blabla
  namespace B
  {
    //! blabla
    class C
    {
#include "lib.h" // This is where the function declarations are but Doxygen does not figure it
    };
  }
}

in file c.cpp:

using namespace A::B;

/*! The declaration of this function was in lib.h. I may document something additional here but Doxygen collects this function without that also, which is desired.
*/
void C::foo()
{
}


问:
Adding boundaries to scaling/panning image viewer in react-native
I have an image (sometimes squared, sometimes different width/height), and I want to create a square image of it. But I want the user to choose which part of the image is in the new image (not necessarily the center part). So I created a image viewer with gesture-handler and reanimated to scale and pan an image within a rectangle. I have created a working example: expo snack

The problem is, now you can pan the image without boundaries, so sometimes the black background is visible. I don't want this.

I have tried this for 3 days calculating the boundaries based on the translateX/Y and the scale, but I cannot find the solution. Can anyone point me in the right direction?


问:
Integrating adb in a web page
I am trying to use adb features from the web without installing anything locally.

For eg. Just like app.webadb.com
Works.

Any help would be appreciated

I even researched a lot on this topic that how is webadb working and found no clue of that.

Title: Integrating adb in a web page


问:
Debugging struct with recursive pointers
I have implemented a sort of tree structure for a filesystem thingy.

```<code>struct FileSystemNode{
    current_directory_path: String,
    current_directory_name: String,
    //we need mutable and immutable access to a node
    // (from here to child and from child's child to parent)
    parent_directory: Option<Rc<RefCell<FileSystemNode>>>,
    children: Vec<Rc<RefCell<FileSystemNode>>>,
    //if size is 0, this is a directory
    size: usize
}
</code>```

I'm parsing a file that says which directories and files exist and then generate the new nodes on the fly and add them to my structure. Somewhere I have a bug, so now I want to debug this. Since IntelliJ community has no Rust debugger, I'm trying to use rust dgb.

Now when I have my root node created but it has no children, I can print the root node just fine:

```<code>$1 = Rc(strong=1, weak=0) = {value = RefCell(borrow=0) = {
    value = advent_of_code_2022::day7::FileSystemNode {
    current_directory_path: "/",
    current_directory_name: "",
    parent_directory: core::option::Option<alloc::rc::Rc<core::cell::RefCell<advent_of_code_2022::day7::FileSystemNode>>>::none,
    children: Vec(size=0),
    size: 0},
    borrow = 0},
    strong = 1, weak = 0}
</code>```

However, as soon as I add a second node and set the child / parent members accordingly, the print will try to follow all these parents and children (I assume), so there is a recursive call to print leading to an error in gdb I cannot even break. The following spams my gdb log:

Python Exception <class 'RecursionError'>: maximum recursion depth exceeded while calling a Python object

Python Exception <class 'RecursionError'>: maximum recursion depth exceeded while getting the str of an object

Is there any way for me to prevent this recursion from taking place? Ideally for the parent_directory and children it would print just the current_directory_path or current_directory_name and size members, but for it would also help if it just gave me an address instead of following it or leaving it out altogether.

Here is a minimal working example, just build it, start in gdb, move to line let node ..., print root (it works) and then move to line `println!...", print root again, it spams the errors.

```<code>use std::cell::RefCell;
use std::rc::Rc;

struct FileSystemNode{
    current_directory_path: String,
    current_directory_name: String,
    //we need mutable and immutable access to a node
    // (from here to child and from child's child to parent)
    parent_directory: Option<Rc<RefCell<FileSystemNode>>>,
    children: Vec<Rc<RefCell<FileSystemNode>>>,
    //if size is 0, this is a directory
    size: usize
}

impl FileSystemNode {
    pub fn new() -> FileSystemNode {
        return FileSystemNode {
            current_directory_path: String::from(""),
            current_directory_name: String::from(""),
            parent_directory: None,
            children: Vec::new(),
            size: 0
        };
    }
}

pub fn main(){
    let root = Rc::new(RefCell::new(FileSystemNode::new()));
    root.borrow_mut().current_directory_path = String::from("/");

    let node = Rc::new(RefCell::new(FileSystemNode::new()));
    node.borrow_mut().current_directory_path = String::from("/test/");
    node.borrow_mut().current_directory_name = String::from("test");
    node.borrow_mut().parent_directory = Some(Rc::clone(&root));

    root.borrow_mut().children.push(Rc::clone(&node));

    println!("");
}
</code>```

Body:
I have implemented a sort of tree structure for a filesystem thingy.

struct FileSystemNode{
    current_directory_path: String,
    current_directory_name: String,
    //we need mutable and immutable access to a node
    // (from here to child and from child's child to parent)
    parent_directory: Option<Rc<RefCell<FileSystemNode>>>,
    children: Vec<Rc<RefCell<FileSystemNode>>>,
    //if size is 0, this is a directory
    size: usize
}

I'm parsing a file that says which directories and files exist and then generate the new nodes on the fly and add them to my structure. Somewhere I have a bug, so now I want to debug this. Since IntelliJ community has no Rust debugger, I'm trying to use rust dgb.

Now when I have my root node created but it has no children, I can print the root node just fine:

$1 = Rc(strong=1, weak=0) = {value = RefCell(borrow=0) = {
    value = advent_of_code_2022::day7::FileSystemNode {
    current_directory_path: "/",
    current_directory_name: "",
    parent_directory: core::option::Option<alloc::rc::Rc<core::cell::RefCell<advent_of_code_2022::day7::FileSystemNode>>>::none,
    children: Vec(size=0),
    size: 0},
    borrow = 0},
    strong = 1, weak = 0}

However, as soon as I add a second node and set the child / parent members accordingly, the print will try to follow all these parents and children (I assume), so there is a recursive call to print leading to an error in gdb I cannot even break. The following spams my gdb log:

Python Exception <class 'RecursionError'>: maximum recursion depth exceeded while calling a Python object

Python Exception <class 'RecursionError'>: maximum recursion depth exceeded while getting the str of an object

Is there any way for me to prevent this recursion from taking place? Ideally for the parent_directory and children it would print just the current_directory_path or current_directory_name and size members, but for it would also help if it just gave me an address instead of following it or leaving it out altogether.

Here is a minimal working example, just build it, start in gdb, move to line let node ..., print root (it works) and then move to line `println!...", print root again, it spams the errors.

use std::cell::RefCell;
use std::rc::Rc;

struct FileSystemNode{
    current_directory_path: String,
    current_directory_name: String,
    //we need mutable and immutable access to a node
    // (from here to child and from child's child to parent)
    parent_directory: Option<Rc<RefCell<FileSystemNode>>>,
    children: Vec<Rc<RefCell<FileSystemNode>>>,
    //if size is 0, this is a directory
    size: usize
}

impl FileSystemNode {
    pub fn new() -> FileSystemNode {
        return FileSystemNode {
            current_directory_path: String::from(""),
            current_directory_name: String::from(""),
            parent_directory: None,
            children: Vec::new(),
            size: 0
        };
    }
}

pub fn main(){
    let root = Rc::new(RefCell::new(FileSystemNode::new()));
    root.borrow_mut().current_directory_path = String::from("/");

    let node = Rc::new(RefCell::new(FileSystemNode::new()));
    node.borrow_mut().current_directory_path = String::from("/test/");
    node.borrow_mut().current_directory_name = String::from("test");
    node.borrow_mut().parent_directory = Some(Rc::clone(&root));

    root.borrow_mut().children.push(Rc::clone(&node));

    println!("");
}


问:
Rails Simple form: Unable to render validation messages
I have an application with 3 models; for all those models, I have used the simple_form gem to render the form.

Initially, my goal was to render inline validation messages under their respective fields, and I had never tried that before so I made a google search to find out how it's done, and then I found out about the simple_form gem.

So I followed the RailsCasts tutorial and its GitHub page to set up the gem in my application and used it for all of the models in my application. It was working perfectly fine showing the default error message at the top and the validation message at the bottom of their respective fields.

I also implemented test suites using RSpec and Capybara to check if validation messages show up when a user fills in an invalid detail and it would work as expected.

A couple of days went by and I was continuing to build my application and was running all the test suites every now and then and everything was working as expected. Then for some reason, I manually wanted to create a user with invalid details and expect to show validation messages but it wouldn't. I was completely shocked. I mean it wasn't creating it either but it wasn't showing in the view. I know this because I gave a debugger in the controller to see if it actually passes validation messages and it was. But it just wasn't showing in the view. And this scenario happens to all of the models. It is able to create instances with valid values but not show error messages for invalid ones. And same is true with the RSpec test suites as it expects the message to show but it's not able to find it.

I have been trying to debug this problem for days but have just not been able to. I mean I can give my own code to show-up validations but why isn't it showing now as it was showing then?

I also tried to see if I had implemented any code in the past few days that was interrupting the gems' process somehow. So I browsed through the commit history and checked out the commit where I thought it could have affected to raise this error. But was unlucky in the process. In fact, I went back to that commit where I had initialized the gem, and it still wasn't working.

I also inspected the bootstrap files of simple_form that it installs to see if it's working and it does. I then implemented bootstrap styles to the form and it is working perfectly fine.

I also tried the trick to re-install the gem in case I unintentionally messed up some code in their initializer files. But it didn't work, it just works the same out of the box too.

I would like your help in this, wondering if you have faced such issues. I am just not able to find what is causing the issue, so I can debug it.

If you're curious, I am running the Rails 7.0.4 with Ruby 3.1.2 and simple_form 5.1.0 version with JS (esbuild) & CSS (Bootstrap 5.2)

Gemfile:

```<code>source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby "3.1.2"

gem "rails", "~> 7.0.4"

gem "sprockets-rails"

gem "pg", "~> 1.1"

gem "puma", "~> 5.0"

gem "jsbundling-rails"

gem "turbo-rails"

gem "stimulus-rails"

gem "cssbundling-rails"

gem "jbuilder"

gem "redis", "~> 4.0"

# gem "bcrypt", "~> 3.1.7"

gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ]

gem "bootsnap", require: false

group :development, :test do
  gem "debug", platforms: %i[ mri mingw x64_mingw ]
  gem "rspec-rails"
  gem 'factory_bot_rails'
  gem 'capybara'
end

group :development do
  gem "web-console"
end

group :test do
  gem 'simplecov', require: false
  gem "shoulda-matchers", git: 'https://github.com/thoughtbot/shoulda-matchers.git'
  gem 'shoulda-callback-matchers', '~> 1.1.1'
  gem 'rails-controller-testing'
end

gem 'validates_email_format_of'

gem 'faker'

gem 'friendly_id'

gem "simple_form", "~> 5.1"

gem 'ransack'

gem "humanize", "~> 2.5"
</code>```

My model:

```<code><% its_message = "must be exactly 8 characters long" %>
<% mobile_message = "without the country code" %>

<%= simple_form_for @sabeel do |f| %>
    <%= f.error_notification %>
    <%= f.input :its, hint: its_message %>
    <%= f.input :hof_name, placeholder: "Shk. Fakruddin Nakhudawala" %>
    <%= f.input :apartment, collection: Sabeel.apartments.keys.map{ |apartment| [apartment.titleize, apartment] }, include_blank: false %>
    <%= f.input :flat_no %>
    <%= f.input :mobile, hint: mobile_message, placeholder: "9876543210" %>
    <%= f.input :email, input_html: { class: "mb-5" }%>
    <%= f.button :submit %>
<% end %>
</code>```

I am using the default vertical wrapper for my simple_form, simple_form_bootstrap.rb file:

```<code>  # vertical default_wrapper
  config.wrappers :vertical_form, tag: 'div', class: 'form-group col-md-4 offset-md-4 mb-3', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b|
    b.use :html5
    b.use :placeholder
    b.optional :maxlength
    b.optional :minlength
    b.optional :pattern
    b.optional :min_max
    b.optional :readonly
    b.use :label, class: 'fw-normal fs-5'
    b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid'
    b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' }
    b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' }
  end
</code>```

I am not able to find the error class form-group-invalid in both simple_form files in the config/initializers dir. I don't know if that's necessary, but if it is expected to be given somewhere then where would it be?

Initially, I did say that I used the simple_form gem to implement inline validations but after knowing its simplicity and ease of use I want to use simple_form only unless there's some other gem that's much better!

Thanks! :)

Body:
I have an application with 3 models; for all those models, I have used the simple_form gem to render the form.

Initially, my goal was to render inline validation messages under their respective fields, and I had never tried that before so I made a google search to find out how it's done, and then I found out about the simple_form gem.

So I followed the RailsCasts tutorial and its GitHub page to set up the gem in my application and used it for all of the models in my application. It was working perfectly fine showing the default error message at the top and the validation message at the bottom of their respective fields.

I also implemented test suites using RSpec and Capybara to check if validation messages show up when a user fills in an invalid detail and it would work as expected.

A couple of days went by and I was continuing to build my application and was running all the test suites every now and then and everything was working as expected. Then for some reason, I manually wanted to create a user with invalid details and expect to show validation messages but it wouldn't. I was completely shocked. I mean it wasn't creating it either but it wasn't showing in the view. I know this because I gave a debugger in the controller to see if it actually passes validation messages and it was. But it just wasn't showing in the view. And this scenario happens to all of the models. It is able to create instances with valid values but not show error messages for invalid ones. And same is true with the RSpec test suites as it expects the message to show but it's not able to find it.

I have been trying to debug this problem for days but have just not been able to. I mean I can give my own code to show-up validations but why isn't it showing now as it was showing then?

I also tried to see if I had implemented any code in the past few days that was interrupting the gems' process somehow. So I browsed through the commit history and checked out the commit where I thought it could have affected to raise this error. But was unlucky in the process. In fact, I went back to that commit where I had initialized the gem, and it still wasn't working.

I also inspected the bootstrap files of simple_form that it installs to see if it's working and it does. I then implemented bootstrap styles to the form and it is working perfectly fine.

I also tried the trick to re-install the gem in case I unintentionally messed up some code in their initializer files. But it didn't work, it just works the same out of the box too.

I would like your help in this, wondering if you have faced such issues. I am just not able to find what is causing the issue, so I can debug it.

If you're curious, I am running the Rails 7.0.4 with Ruby 3.1.2 and simple_form 5.1.0 version with JS (esbuild) & CSS (Bootstrap 5.2)

Gemfile:

source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby "3.1.2"

gem "rails", "~> 7.0.4"

gem "sprockets-rails"

gem "pg", "~> 1.1"

gem "puma", "~> 5.0"

gem "jsbundling-rails"

gem "turbo-rails"

gem "stimulus-rails"

gem "cssbundling-rails"

gem "jbuilder"

gem "redis", "~> 4.0"

# gem "bcrypt", "~> 3.1.7"

gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ]

gem "bootsnap", require: false

group :development, :test do
  gem "debug", platforms: %i[ mri mingw x64_mingw ]
  gem "rspec-rails"
  gem 'factory_bot_rails'
  gem 'capybara'
end

group :development do
  gem "web-console"
end

group :test do
  gem 'simplecov', require: false
  gem "shoulda-matchers", git: 'https://github.com/thoughtbot/shoulda-matchers.git'
  gem 'shoulda-callback-matchers', '~> 1.1.1'
  gem 'rails-controller-testing'
end

gem 'validates_email_format_of'

gem 'faker'

gem 'friendly_id'

gem "simple_form", "~> 5.1"

gem 'ransack'

gem "humanize", "~> 2.5"

My model:

<% its_message = "must be exactly 8 characters long" %>
<% mobile_message = "without the country code" %>

<%= simple_form_for @sabeel do |f| %>
    <%= f.error_notification %>
    <%= f.input :its, hint: its_message %>
    <%= f.input :hof_name, placeholder: "Shk. Fakruddin Nakhudawala" %>
    <%= f.input :apartment, collection: Sabeel.apartments.keys.map{ |apartment| [apartment.titleize, apartment] }, include_blank: false %>
    <%= f.input :flat_no %>
    <%= f.input :mobile, hint: mobile_message, placeholder: "9876543210" %>
    <%= f.input :email, input_html: { class: "mb-5" }%>
    <%= f.button :submit %>
<% end %>

I am using the default vertical wrapper for my simple_form, simple_form_bootstrap.rb file:

  # vertical default_wrapper
  config.wrappers :vertical_form, tag: 'div', class: 'form-group col-md-4 offset-md-4 mb-3', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b|
    b.use :html5
    b.use :placeholder
    b.optional :maxlength
    b.optional :minlength
    b.optional :pattern
    b.optional :min_max
    b.optional :readonly
    b.use :label, class: 'fw-normal fs-5'
    b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid'
    b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' }
    b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' }
  end

I am not able to find the error class form-group-invalid in both simple_form files in the config/initializers dir. I don't know if that's necessary, but if it is expected to be given somewhere then where would it be?

Initially, I did say that I used the simple_form gem to implement inline validations but after knowing its simplicity and ease of use I want to use simple_form only unless there's some other gem that's much better!

Thanks! :)


问:
Error: A required parameter (postSlug) was not provided as a string in getStaticPaths for /blogs/[postSlug]
enter image description here Just find where am I missing a typescript fulfillment</p>


问:
XAMPP is not loading my JS file and just loads 'index of /' (NodeJS)
I have been having trouble with XAMPP and localhost.
This is my code at the moment, inside a JavaScript file named 'app':

```<code>
</code>```
```<code>const express = require("express");

const app = express();

app.get("/", (req, res, next) => {
    res.send("<h1>Hello World</h1>");
});

app.listen(8080);
</code>```
```<code>
</code>```

I'm working with express and I'm following a tutorial of freeCodeCamp about authentication (timestamp of the exact part of the video where I got stuck) and at the start a problem appeared for me. The problem is that when I want to execute my code in the browser to see it in localhost, then I go to localhost:8080 and instead of visualizing the app.js that has to show an h1, I end up seeing the "Index of /".
This appears when I load my localhost:8080, instead of visualizing the site I'm expected to see
But I would like to see the "
Hello World
" as I'm supposed to do.

If I directly go to my file from 'Index of /' and I load my 'app.js' file, it literally loads the code itself. It doesn't execute it.
An image of what appears
(The comment is a memo that I made for me)

What am I doing wrong? I'm a beginner so that may contribute to the problem.

I used to have another problem where webs will not load at all and it would throw me an error. I fixed that changing the ports of my Apache server and I set them to 8080. I even reinstalled XAMPP. And, in the past, instead of loading the index of /, it constantly loaded XAMPP dashboard site. I watched several tutorials to solve this and they all said that I needed to delete index.php file from folders. I did that and now is why instead of appearing XAMPP dashboard, appears index of /.
But, my main problem persists... I keep seeing Index of / instead of just seeing the "
Hello World
" as the man in the tutorial has.
What should appear to me (from the video) but doesn't appear

Body:
I have been having trouble with XAMPP and localhost.
This is my code at the moment, inside a JavaScript file named 'app':

const express = require("express");

const app = express();

app.get("/", (req, res, next) => {
    res.send("
Hello World
");
});

app.listen(8080);

I'm working with express and I'm following a tutorial of freeCodeCamp about authentication (timestamp of the exact part of the video where I got stuck) and at the start a problem appeared for me. The problem is that when I want to execute my code in the browser to see it in localhost, then I go to localhost:8080 and instead of visualizing the app.js that has to show an h1, I end up seeing the "Index of /".
This appears when I load my localhost:8080, instead of visualizing the site I'm expected to see
But I would like to see the "
Hello World
" as I'm supposed to do.

If I directly go to my file from 'Index of /' and I load my 'app.js' file, it literally loads the code itself. It doesn't execute it.
An image of what appears
(The comment is a memo that I made for me)

What am I doing wrong? I'm a beginner so that may contribute to the problem.

I used to have another problem where webs will not load at all and it would throw me an error. I fixed that changing the ports of my Apache server and I set them to 8080. I even reinstalled XAMPP. And, in the past, instead of loading the index of /, it constantly loaded XAMPP dashboard site. I watched several tutorials to solve this and they all said that I needed to delete index.php file from folders. I did that and now is why instead of appearing XAMPP dashboard, appears index of /.
But, my main problem persists... I keep seeing Index of / instead of just seeing the "
Hello World
" as the man in the tutorial has.
What should appear to me (from the video) but doesn't appear


问:
Codeigniter 3 - issue with add global function
I try count rows in table (total notifications put in header admin panel).

```<code>  public function index()
    {
        $data['title'] = trans("admin_panel");

        $data['notification_count'] = $this->order_admin_model->get_all_notifications_count();

        $this->load->view('admin/includes/_header', $data);
        $this->load->view('admin/index');
        $this->load->view('admin/includes/_footer');
    }
</code>```

This working correct when I'm stay in "home page" admin.  But when I open  another page in admin panel then I get issue with undefinied variable.

Header is visible on all pages. So I think I need add this variable as global ?

If yes I try add in helper and then I autoload this helper:

```<code>//get notifications count
if(!function_exists('notifications_count')) {
  function notifications_count($data) {
    $data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
  }
}
</code>```

But when I put this above code then still I get this issue.

Body:
I try count rows in table (total notifications put in header admin panel).

  public function index()
    {
        $data['title'] = trans("admin_panel");

        $data['notification_count'] = $this->order_admin_model->get_all_notifications_count();

        $this->load->view('admin/includes/_header', $data);
        $this->load->view('admin/index');
        $this->load->view('admin/includes/_footer');
    }

This working correct when I'm stay in "home page" admin.  But when I open  another page in admin panel then I get issue with undefinied variable.

Header is visible on all pages. So I think I need add this variable as global ?

If yes I try add in helper and then I autoload this helper:

//get notifications count
if(!function_exists('notifications_count')) {
  function notifications_count($data) {
    $data['notification_count'] = $this->order_admin_model->get_all_notifications_count();
  }
}

But when I put this above code then still I get this issue.


问:
SPM modules not found in test target
I'm struggling with the SPM modules in the unit test target. Simply adding @testable import MyApp and then running UTs ends up with an error saying that an SPM module has not been found.

To be more explicit, those are the error lines:

/MyApp-cxdzdpxkuamerffyiosojkxpvujl/Build/Intermediates.noindex/MyApp.build/Debug-iphoneos/MyAppTests.build/Objects-normal/arm64/MyAppTests.swiftdoc: No such file or directory

/MyApp-cxdzdpxkuamerffyiosojkxpvujl/Build/Intermediates.noindex/MyApp.build/Debug-iphoneos/MyAppTests.build/Objects-normal/arm64/MyAppTests.abi.json: No such file or directory

/MyApp-cxdzdpxkuamerffyiosojkxpvujl/Build/Intermediates.noindex/MyApp.build/Debug-iphoneos/MyAppTests.build/Objects-normal/arm64/MyAppTests.swiftmodule: No such file or directory

/MyApp-cxdzdpxkuamerffyiosojkxpvujl/Build/Intermediates.noindex/MyApp.build/Debug-iphoneos/MyAppTests.build/Objects-normal/arm64/MyAppTests.swiftsourceinfo: No such file or directory

I've checked the folder and those files aren't indeed there.

What I've tried and more details:

the only package I've added to the project is Firebase (9.6.0) and as I mentioned, it was added via SPM

no Cocoapods or Carthage was ever used in this project, so I'm using just the xcodeproj file.

Enable testability is set to true for Debug configuration in both targets (the main and the test)

the scheme is set up to launch the tests with Debug conf

the get the same results when I run the tests in a host app or not

I've also tried to remove the test target and add it again, but no change

Xcode 14.1 and M1 machine

Title: SPM modules not found in test target


问:
How to display app logs in nginx-unit docker?
I am using the official nginx unit docker image, And I would like to run a hello world wsgi application, and being able to print stuff on docker-compose output.

How can I do that ?

Here the hello world:

```<code>print('DURING INITIAL SETUP')

def application(environ, start_response):
  print('DURING REQUEST')
  start_response('200 OK', [('Content-Type', 'text/plain')])
  yield b'Hello, World!\n'

</code>```

But nothing is ever written to the output... (I also tried writing directly to /proc/1/fd/1, but missing permissions)

Body:
I am using the official nginx unit docker image, And I would like to run a hello world wsgi application, and being able to print stuff on docker-compose output.

How can I do that ?

Here the hello world:

print('DURING INITIAL SETUP')

def application(environ, start_response):
  print('DURING REQUEST')
  start_response('200 OK', [('Content-Type', 'text/plain')])
  yield b'Hello, World!\n'

But nothing is ever written to the output... (I also tried writing directly to /proc/1/fd/1, but missing permissions)


问:
Data fetching using Spring Data JPA Stream From DB2 Database
Trying to implement Stream in Spring Data JPA to stream a resultSet from the DB2 table, but getting an error as below - (I am following this SO answer: https://stackoverflow.com/a/66792134/9884497, and a blog - https://www.geekyhacker.com/2019/03/26/high-performance-data-fetching-using-spring-data-jpa-stream/ )

I am using spring-boot-starter-data-jpa:2.5.8

```<code>  org.hibernate.exception.GenericJDBCException: Could not determine if resultset is empty due to exception calling isBeforeFirst or isAfterLast()
at
.....
org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.ibm.db2.jcc.am.SqlException: [jcc][t4][10179][10900][4.24.92] This method should only be called on ResultSet objects that are scrollable (type TYPE_SCROLL_SENSITIVE or TYPE_SCROLL_INSENSITIVE). ERRORCODE=-4476, SQLSTATE=null
</code>```

I can see this problem listed at https://hibernate.atlassian.net/browse/HHH-13556 which was supposed to be solved at 5.3 Hibernate ORM Version but spring-boot-starter-data-jpa:2.5.8 already packed with Hibernate-core:5.4.33

Tried to find a solution but could not see any if we can use Stream in Spring Data JPA with DB2 Databases. Looked at the documentation as well but sadly no success. Posting here if anyone has used/is aware of the solution for DB2 Database.

So my questions are:

Does DB2 supports Spring Data JPA Stream which can return Stream?

What are the required configurations eg: the value of HINT_FETCH_SIZE

How to get a Scrollable Result Set using Spring Data JPA Stream for DB2.

Meanwhile - I am able to solve this problem by StatelessSession but here looking if Spring Data JPA Stream works for DB2.

Body:
Trying to implement Stream in Spring Data JPA to stream a resultSet from the DB2 table, but getting an error as below - (I am following this SO answer: https://stackoverflow.com/a/66792134/9884497, and a blog - https://www.geekyhacker.com/2019/03/26/high-performance-data-fetching-using-spring-data-jpa-stream/ )

I am using spring-boot-starter-data-jpa:2.5.8

  org.hibernate.exception.GenericJDBCException: Could not determine if resultset is empty due to exception calling isBeforeFirst or isAfterLast()
at
.....
org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.ibm.db2.jcc.am.SqlException: [jcc][t4][10179][10900][4.24.92] This method should only be called on ResultSet objects that are scrollable (type TYPE_SCROLL_SENSITIVE or TYPE_SCROLL_INSENSITIVE). ERRORCODE=-4476, SQLSTATE=null

I can see this problem listed at https://hibernate.atlassian.net/browse/HHH-13556 which was supposed to be solved at 5.3 Hibernate ORM Version but spring-boot-starter-data-jpa:2.5.8 already packed with Hibernate-core:5.4.33

Tried to find a solution but could not see any if we can use Stream in Spring Data JPA with DB2 Databases. Looked at the documentation as well but sadly no success. Posting here if anyone has used/is aware of the solution for DB2 Database.

So my questions are:

Does DB2 supports Spring Data JPA Stream which can return Stream?

What are the required configurations eg: the value of HINT_FETCH_SIZE

How to get a Scrollable Result Set using Spring Data JPA Stream for DB2.

Meanwhile - I am able to solve this problem by StatelessSession but here looking if Spring Data JPA Stream works for DB2.


问:
write or update a special row in SQL table - C#
I design a company profile form in Visual studio 2019 and I save data in a table in SQL, I want to save information just in one row because it is my customer info and it is unique
I can not write and update this row
first of all I select Whole data from table to check is it null or not?
then if it is null it means this is first time => I insert data
else => user wants to update => I Update data

this is my code:

private void btnSave_Click(object sender, EventArgs e)
{
    cmd = new SqlCommand("select * from CompanyProfile where id=@N", con);
    cmd.Parameters.AddWithValue("@N", "1");
    if (cmd.Connection.State == ConnectionState.Open)
    {
        cmd.Connection.Close();
    }
    con.Open();
    dr = cmd.ExecuteReader();
    if (dr.Read())
    {
        if (dr["CompanyName"].ToString() == null)
        {
            con.Close();
            SqlCommand cmd = new SqlCommand("insert into CompanyProfile(ComanyName,RegNo,RegDate,NID,EID,WorkShopCode,WebSite,CEOName,Tel,Mobile,Fax,ZipCode,Email,Address,Logo)values(@a,@b,@c,@d,@e,@f,@g,@h,@i,@j,@k,@l,@m,@n,@o)", con);
            if (PBLogo.Image == null)
            {
                MessageBox.Show("please insert PIC");
                return;
            }
            if (cmd.Connection.State == ConnectionState.Open)
            {
                cmd.Connection.Close();
            }
            con.Open();
            byte[] ar = File.ReadAllBytes(PBLogo.ImageLocation);

            cmd.Parameters.AddWithValue("@a", txtCompanyName.Text);
            cmd.Parameters.AddWithValue("@b", txtRegNo.Text);
            cmd.Parameters.AddWithValue("@c", txtRegDate.Text);
            cmd.Parameters.AddWithValue("@d", txtNID.Text);
            cmd.Parameters.AddWithValue("@e", txtEID.Text);
            cmd.Parameters.AddWithValue("@f", txtWorkShopCode.Text);
            cmd.Parameters.AddWithValue("@g", txtWebSite.Text);
            cmd.Parameters.AddWithValue("@h", txtCEOName.Text);
            cmd.Parameters.AddWithValue("@i", txtTel.Text);
            cmd.Parameters.AddWithValue("@j", txtMobile.Text);
            cmd.Parameters.AddWithValue("@k", txtFax.Text);
            cmd.Parameters.AddWithValue("@l", txtZipCode.Text);
            cmd.Parameters.AddWithValue("@m", txtEmail.Text);
            cmd.Parameters.AddWithValue("@n", txtAddress.Text);
            cmd.Parameters.AddWithValue("@o", SqlDbType.VarBinary).Value = ar;
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("form saved");
        }
        else
        {
            con.Close();
            MemoryStream ms1 = new MemoryStream();
            try
            {
                byte[] arrPic = ms1.GetBuffer();
                ms1.Close();
                cmd.Parameters.Clear();
                cmd.Connection = con;
                string Updatetable = "Update CompanyProfile set CompanyName='" + txtCompanyName.Text + "',RegNo='" + txtRegNo.Text + "',RegDate='" + txtCompanyName.Text + "',NID='" + txtNID.Text + "',EID='" + txtEID.Text + "',WorkShopCode='" + txtWorkShopCode.Text + "',Website='" + txtWebSite.Text + "',CEOName='" + txtCEOName.Text + "',Tel='" + txtTel.Text + "',Mobile='" + txtMobile.Text + "',Fax='" + txtFax.Text + "',ZipCode='" + txtZipCode.Text + "',Email='" + txtEmail.Text + "',Address='" + txtAddress.Text + "',Pic=@Pic where id=@Y";

                cmd.Parameters.AddWithValue("@Y", "1");
                SqlCommand com = new SqlCommand(Updatetable, con);
                com.Parameters.AddWithValue("@Pic", arrPic);
                con.Open();
                com.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("form updated");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
```

this error occurred : System.IndexOutOfRangeException: 'CompanyName'

what is the problem and how can I fix it?

is this a suitable method to write or update just one row?

Body:
I design a company profile form in Visual studio 2019 and I save data in a table in SQL, I want to save information just in one row because it is my customer info and it is unique
I can not write and update this row
first of all I select Whole data from table to check is it null or not?
then if it is null it means this is first time => I insert data
else => user wants to update => I Update data

this is my code:

private void btnSave_Click(object sender, EventArgs e)
{
    cmd = new SqlCommand("select * from CompanyProfile where id=@N", con);
    cmd.Parameters.AddWithValue("@N", "1");
    if (cmd.Connection.State == ConnectionState.Open)
    {
        cmd.Connection.Close();
    }
    con.Open();
    dr = cmd.ExecuteReader();
    if (dr.Read())
    {
        if (dr["CompanyName"].ToString() == null)
        {
            con.Close();
            SqlCommand cmd = new SqlCommand("insert into CompanyProfile(ComanyName,RegNo,RegDate,NID,EID,WorkShopCode,WebSite,CEOName,Tel,Mobile,Fax,ZipCode,Email,Address,Logo)values(@a,@b,@c,@d,@e,@f,@g,@h,@i,@j,@k,@l,@m,@n,@o)", con);
            if (PBLogo.Image == null)
            {
                MessageBox.Show("please insert PIC");
                return;
            }
            if (cmd.Connection.State == ConnectionState.Open)
            {
                cmd.Connection.Close();
            }
            con.Open();
            byte[] ar = File.ReadAllBytes(PBLogo.ImageLocation);

            cmd.Parameters.AddWithValue("@a", txtCompanyName.Text);
            cmd.Parameters.AddWithValue("@b", txtRegNo.Text);
            cmd.Parameters.AddWithValue("@c", txtRegDate.Text);
            cmd.Parameters.AddWithValue("@d", txtNID.Text);
            cmd.Parameters.AddWithValue("@e", txtEID.Text);
            cmd.Parameters.AddWithValue("@f", txtWorkShopCode.Text);
            cmd.Parameters.AddWithValue("@g", txtWebSite.Text);
            cmd.Parameters.AddWithValue("@h", txtCEOName.Text);
            cmd.Parameters.AddWithValue("@i", txtTel.Text);
            cmd.Parameters.AddWithValue("@j", txtMobile.Text);
            cmd.Parameters.AddWithValue("@k", txtFax.Text);
            cmd.Parameters.AddWithValue("@l", txtZipCode.Text);
            cmd.Parameters.AddWithValue("@m", txtEmail.Text);
            cmd.Parameters.AddWithValue("@n", txtAddress.Text);
            cmd.Parameters.AddWithValue("@o", SqlDbType.VarBinary).Value = ar;
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("form saved");
        }
        else
        {
            con.Close();
            MemoryStream ms1 = new MemoryStream();
            try
            {
                byte[] arrPic = ms1.GetBuffer();
                ms1.Close();
                cmd.Parameters.Clear();
                cmd.Connection = con;
                string Updatetable = "Update CompanyProfile set CompanyName='" + txtCompanyName.Text + "',RegNo='" + txtRegNo.Text + "',RegDate='" + txtCompanyName.Text + "',NID='" + txtNID.Text + "',EID='" + txtEID.Text + "',WorkShopCode='" + txtWorkShopCode.Text + "',Website='" + txtWebSite.Text + "',CEOName='" + txtCEOName.Text + "',Tel='" + txtTel.Text + "',Mobile='" + txtMobile.Text + "',Fax='" + txtFax.Text + "',ZipCode='" + txtZipCode.Text + "',Email='" + txtEmail.Text + "',Address='" + txtAddress.Text + "',Pic=@Pic where id=@Y";

                cmd.Parameters.AddWithValue("@Y", "1");
                SqlCommand com = new SqlCommand(Updatetable, con);
                com.Parameters.AddWithValue("@Pic", arrPic);
                con.Open();
                com.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("form updated");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

this error occurred : System.IndexOutOfRangeException: 'CompanyName'

what is the problem and how can I fix it?

is this a suitable method to write or update just one row?


问:
Architecture: Organizing and accessing 1..n optional instances of an interface in a single struct
Let's say I have an Interface Animal, instances of which are saved in a separate struct Human. There are multiple types of animals that implement the interface. Each human can have 1..n of these Animals. Access from the human to the animals should be as simple as possible. My initial idea was to have a map [string]Animal with a constant for each animal. I feel like this is a bit clunky. Is there a better way of doing this?

Here's a simplified example of what I currently have. The code I'm working on has 20+ types that implement the interface, while each instance of the parent only has a couple.

https://go.dev/play/p/Rw4iMjHbMQF

```<code>package main

import (
   "fmt"
)

const (
   COW = "Cow"
   DOG = "Dog"
   CAT = "Cat"
)

func main() {
   h1 := Human{Animals: map[string]Animal{
      COW: Cow{},
      DOG: Dog{},
      CAT: Cat{},
   }}

   h2 := Human{Animals: map[string]Animal{
      CAT: Cat{},
   }}

   if cow, ok := h1.Animals[COW]; ok {
      cow.(Cow).EatGrass()
   }

   if cow, ok := h2.Animals[CAT]; ok {
      cow.(Cat).Scratch("bingo")
   }
}

type Human struct {
   Animals map[string]Animal
}

type Animal interface {
   Speak()
}

type Cow struct {
}

func (c Cow) Speak() {
   fmt.Println("moo")
}

func (c Cow) EatGrass() {
   fmt.Println("munch")
}

type Dog struct {
}

func (d Dog) Speak() {
   fmt.Println("bark")
}

func (d Dog) Fetch(ball string) string {
   return ball
}

type Cat struct {
}

func (c Cat) Speak() {
   fmt.Println("meow")
}

func (c Cat) Scratch(human string) {
   fmt.Println(human + ": ouch")
}

</code>```

Body:
Let's say I have an Interface Animal, instances of which are saved in a separate struct Human. There are multiple types of animals that implement the interface. Each human can have 1..n of these Animals. Access from the human to the animals should be as simple as possible. My initial idea was to have a map [string]Animal with a constant for each animal. I feel like this is a bit clunky. Is there a better way of doing this?

Here's a simplified example of what I currently have. The code I'm working on has 20+ types that implement the interface, while each instance of the parent only has a couple.

https://go.dev/play/p/Rw4iMjHbMQF

package main

import (
   "fmt"
)

const (
   COW = "Cow"
   DOG = "Dog"
   CAT = "Cat"
)

func main() {
   h1 := Human{Animals: map[string]Animal{
      COW: Cow{},
      DOG: Dog{},
      CAT: Cat{},
   }}

   h2 := Human{Animals: map[string]Animal{
      CAT: Cat{},
   }}

   if cow, ok := h1.Animals[COW]; ok {
      cow.(Cow).EatGrass()
   }

   if cow, ok := h2.Animals[CAT]; ok {
      cow.(Cat).Scratch("bingo")
   }
}

type Human struct {
   Animals map[string]Animal
}

type Animal interface {
   Speak()
}

type Cow struct {
}

func (c Cow) Speak() {
   fmt.Println("moo")
}

func (c Cow) EatGrass() {
   fmt.Println("munch")
}

type Dog struct {
}

func (d Dog) Speak() {
   fmt.Println("bark")
}

func (d Dog) Fetch(ball string) string {
   return ball
}

type Cat struct {
}

func (c Cat) Speak() {
   fmt.Println("meow")
}

func (c Cat) Scratch(human string) {
   fmt.Println(human + ": ouch")
}


问:
Unreal Engine 4 : Problem when making my won skybox material
I'm using UE4.27. I'm following a video (https://www.youtube.com/watch?v=K8UhqxKKCz4&t=420s) to make my own skybox material and I have an error since I binded Normalize to my HDRI Parameter :

```<code>(Node TextureSamplePArameter2D) Coercion failed: MaterialFloat3 Local4 = (Local1/Local3);
</code>```

Can someone explain how to resolve it please ?
Thanks a lot for answers

Body:
I'm using UE4.27. I'm following a video (https://www.youtube.com/watch?v=K8UhqxKKCz4&t=420s) to make my own skybox material and I have an error since I binded Normalize to my HDRI Parameter :

(Node TextureSamplePArameter2D) Coercion failed: MaterialFloat3 Local4 = (Local1/Local3);

Can someone explain how to resolve it please ?
Thanks a lot for answers