问:
Mapping in entity for Self join in Criteria
I wanted to perform self join using criteria query. As it requires a mapping in the entity to refer the attribute(uam_id) by itself. I have done something like this

```<code>@Entity
@Getter
@Setter
@Table(name = "user_order_package_subscription_v1")
public class UserOrderPackageSubscriptionV1 {

    @Id
    @Column(name = "user_order_package_subscription_id", nullable = false, updatable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userOrderPackageSubscriptionId;

    @Column(name = "total_paid_amount", nullable = false)
    private Double totalPaidAmount;

    @Column(name = "purchase_date", nullable = false)
    private LocalDateTime purchaseDate;

    @ManyToOne
    @JoinColumn(name="uam_id", referencedColumnName = "uam_id", insertable=false, updatable=false)
    private UserOrderPackageSubscriptionV1 uopsv1;
}
</code>```

The join segment of the code is as follows

```<code>Root<UserOrderPackageSubscriptionV1> userOrderSubscriptionTableLeft = query.from(UserOrderPackageSubscriptionV1.class);
        Join<UserOrderPackageSubscriptionV1, UserOrderPackageSubscriptionV1> selfJoin = userOrderSubscriptionTableLeft.join("uopsv1", JoinType.LEFT);
        selfJoin.on(
                cb.lessThan(userOrderSubscriptionTableLeft.get("purchaseDate"),
                        selfJoin.get("purchaseDate"))
        );
</code>```

But this results in hibernate creating a unique constraint and automatically tries to make uam_id as foreign key referring the  same table. How do I prevent this from happening ? Also is it possible to perform join directly on the attribute instead of mapping ?

Body:
I wanted to perform self join using criteria query. As it requires a mapping in the entity to refer the attribute(uam_id) by itself. I have done something like this

@Entity
@Getter
@Setter
@Table(name = "user_order_package_subscription_v1")
public class UserOrderPackageSubscriptionV1 {

    @Id
    @Column(name = "user_order_package_subscription_id", nullable = false, updatable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userOrderPackageSubscriptionId;

    @Column(name = "total_paid_amount", nullable = false)
    private Double totalPaidAmount;

    @Column(name = "purchase_date", nullable = false)
    private LocalDateTime purchaseDate;

    @ManyToOne
    @JoinColumn(name="uam_id", referencedColumnName = "uam_id", insertable=false, updatable=false)
    private UserOrderPackageSubscriptionV1 uopsv1;
}

The join segment of the code is as follows

Root<UserOrderPackageSubscriptionV1> userOrderSubscriptionTableLeft = query.from(UserOrderPackageSubscriptionV1.class);
        Join<UserOrderPackageSubscriptionV1, UserOrderPackageSubscriptionV1> selfJoin = userOrderSubscriptionTableLeft.join("uopsv1", JoinType.LEFT);
        selfJoin.on(
                cb.lessThan(userOrderSubscriptionTableLeft.get("purchaseDate"),
                        selfJoin.get("purchaseDate"))
        );

But this results in hibernate creating a unique constraint and automatically tries to make uam_id as foreign key referring the  same table. How do I prevent this from happening ? Also is it possible to perform join directly on the attribute instead of mapping ?


来源: stackexchange

问:
How to eliminate mirroring the records?
I've got GraphQl code like this :

```<code>const queryGraphQL = {
    query: `query {
  products(searchInput: {
    parameters: [{
      id: 915
      values:[4095,4170]
    }
    ]

  },
          settingsInput: {limit:35 }) {
    products {
      producer{
        link
        name
        id
      }
      awardedParameters {
        id
        name
        values {
          name
          link
        }
      }

    }
  }
}`,
}
const fetchData = async () => {
    try {
        const response = await fetch('/graphql/v1/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json',
            },
            body: JSON.stringify(queryGraphQL),
        })
        const dataJson = await response.json()
        return dataJson
    } catch (error) {
        console.error('AJAX fetchDataGraphQL() Error:', error)
        return false
    }
}

const init = async () => {
    const data = await fetchData()

    if(!data) return

    const products = data.data.products.products
    const upcommingContainer = document.querySelector('#main_cms .products.--onstore')

    if(!upcommingContainer) return
    console.log(products)
    const html = products.reduce((prev, curr)=>{
      const date = curr.awardedParameters.find(el=>el.name === 'Kolejna dostawa').values[0].name
      const url = document.querySelector(`.main_producers__wrapper div[id="${curr.producer.id}"]`).dataset['src']
      const link3 = curr.awardedParameters.find(el=>el.name === 'Kolejna dostawa').values[0].link

      if (!url) return ''

      return prev + `<a href="${link3}?filter_producer=${curr.producer.id}" class="col-12 product_link">
      <div class="product mb-2">
          <span class="product__icon_2"><img src="${url}" alt=${curr.producer.name}/></span>
          <span class="producer__name">${curr.producer.name}</span>
          <div class="off_store"></div>

          <div class="product__date">${date}</div>
      </div>
      </a>`
    },'')
   upcommingContainer.innerHTML = html
    return data
}
</code>```

I'm building the template structure with this HTML code :

```<code> <div class="products --onstore d-flex flex-wrap mt-md-5">

                                 <a href="" class="col-12 product_link">
              <div class="product col-12 mb-2">
                  <span class="product__icon_2 skeleton skeleton-image"><img src=""></img></span>
                  <span class="producer__name skeleton skeleton-producer"><span><iai:variable vid="Dostawa marki"/></span></span>
                  <div class="on_store skeleton skeleton-store"><span><iai:variable vid="Na magazynie"/></span></div>
                  <div class="product__date skeleton skeleton-date"></div>
              </div>
              </a>
</div>
</code>```

And my question is, if there is any option to eliminate mirroring the records ? I mean if I have 3 the same result, for example 3 product__date
product 1 12.12.22.
product 2 12.12.22.
product 3 12.12.22.
I want to show only one product with date 12.12.22r. and search for another records with different dates ?

I tried some kind of sort by date, byb this doesn't work. Any ideas how should it looks like?

ContentLicense: CC BY-SA 4.0

Title: How to eliminate mirroring the records?

Body:
I've got GraphQl code like this :

const queryGraphQL = {
    query: `query {
  products(searchInput: {
    parameters: [{
      id: 915
      values:[4095,4170]
    }
    ]

  },
          settingsInput: {limit:35 }) {
    products {
      producer{
        link
        name
        id
      }
      awardedParameters {
        id
        name
        values {
          name
          link
        }
      }

    }
  }
}`,
}
const fetchData = async () => {
    try {
        const response = await fetch('/graphql/v1/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json',
            },
            body: JSON.stringify(queryGraphQL),
        })
        const dataJson = await response.json()
        return dataJson
    } catch (error) {
        console.error('AJAX fetchDataGraphQL() Error:', error)
        return false
    }
}

const init = async () => {
    const data = await fetchData()

    if(!data) return

    const products = data.data.products.products
    const upcommingContainer = document.querySelector('#main_cms .products.--onstore')

    if(!upcommingContainer) return
    console.log(products)
    const html = products.reduce((prev, curr)=>{
      const date = curr.awardedParameters.find(el=>el.name === 'Kolejna dostawa').values[0].name
      const url = document.querySelector(`.main_producers__wrapper div[id="${curr.producer.id}"]`).dataset['src']
      const link3 = curr.awardedParameters.find(el=>el.name === 'Kolejna dostawa').values[0].link

      if (!url) return ''

      return prev + `

          ${curr.producer.name}

${date}

      `
    },'')
   upcommingContainer.innerHTML = html
    return data
}

I'm building the template structure with this HTML code :

                  <iai:variable vid="Dostawa marki"/>

<iai:variable vid="Na magazynie"/>

And my question is, if there is any option to eliminate mirroring the records ? I mean if I have 3 the same result, for example 3 product__date
product 1 12.12.22.
product 2 12.12.22.
product 3 12.12.22.
I want to show only one product with date 12.12.22r. and search for another records with different dates ?

I tried some kind of sort by date, byb this doesn't work. Any ideas how should it looks like?


问:
What archetype is recommended to use in visual studio code, to start with mvc maven and jdbc using servlets and jsp?
I find so many custom archetypes that I don't know which one to use, the java tutorials that I find use neatbeans, eclipse, which create a different structure from the one generated by visual studio code.

So I don't know which archetype to choose, and where to start placing my controllers, views, and models

I will not use any framework for now, please help me

I use mave-archetype-quickstar and maven-archetype-webapp but I don't understand the correct disposition of the files corresponding to the views (jsp) the controllers (servlet) and the models (with jdbc)


问:
openapi generator cli - how to skip generation equals method
We are using the openapi-generator-cli-6.2.1 to generate the APIs and Models from swagger file.
Is it possible to instruct the CLI not to generate any equals() method for the Model classes ?
The reason is because the code generator generates malformed variable names for specific types.

Sample Swagger File

```<code>{
"swagger": "2.0",
"info": {
    "description": "Springfox template project",
    "version": "8.1.0",
    "title": "springfoxtemplate",
    "license": {
        "name": "Some Org"
    }
},
"host": "localhost:7777",
"basePath": "/",
"tags": [
    {
        "name": "main-controller",
        "description": "Main Controller"
    }
],
"paths": {
    "/cart/customer": {
        "get": {
            "tags": [
                "main-controller"
            ],
            "summary": "addCustomer",
            "operationId": "addCustomerUsingGET",
            "produces": [
                "application/json"
            ],
            "parameters": [
                {
                    "in": "body",
                    "name": "customer",
                    "description": "customer",
                    "required": true,
                    "schema": {
                        "$ref": "#/definitions/ShoppingCartRequest«Customer»"
                    }
                }
            ],
            "responses": {
                "200": {
                    "description": "OK",
                    "schema": {
                        "$ref": "#/definitions/ShoppingCartResponse«Customer»"
                    }
                },
                "401": {
                    "description": "Unauthorized"
                },
                "403": {
                    "description": "Forbidden"
                },
                "404": {
                    "description": "Not Found"
                }
            },
            "deprecated": false
        }
    },
    "/cart/nodes": {
        "get": {
            "tags": [
                "main-controller"
            ],
            "summary": "getNodes",
            "operationId": "getNodesUsingGET",
            "produces": [
                "application/json"
            ],
            "responses": {
                "200": {
                    "description": "OK",
                    "schema": {
                        "$ref": "#/definitions/ShoppingCartResponse«List«Nodes»»"
                    }
                },
                "401": {
                    "description": "Unauthorized"
                },
                "403": {
                    "description": "Forbidden"
                },
                "404": {
                    "description": "Not Found"
                }
            },
            "deprecated": false
        }
    }
},
"definitions": {
    "Customer": {
        "type": "object",
        "properties": {
            "id": {
                "type": "string"
            },
            "name": {
                "type": "string"
            },
            "status": {
                "type": "string"
            }
        },
        "title": "Customer"
    },
    "Nodes": {
        "type": "object",
        "properties": {
            "id": {
                "type": "string"
            },
            "name": {
                "type": "string"
            }
        },
        "title": "Nodes"
    },
    "ShoppingCartRequest«Customer»": {
        "type": "object",
        "properties": {
            "cartInstanceID": {
                "type": "string"
            },
            "requestObject": {
                "$ref": "#/definitions/Customer"
            }
        },
        "title": "ShoppingCartRequest«Customer»"
    },
    "ShoppingCartResponse«Customer»": {
        "type": "object",
        "properties": {
            "cartInstanceID": {
                "type": "string"
            },
            "responseObject": {
                "$ref": "#/definitions/Customer"
            },
            "status": {
                "type": "string"
            }
        },
        "title": "ShoppingCartResponse«Customer»"
    },
    "ShoppingCartResponse«List«Nodes»»": {
        "type": "object",
        "properties": {
            "cartInstanceID": {
                "type": "string"
            },
            "responseObject": {
                "type": "array",
                "items": {
                    "$ref": "#/definitions/Nodes"
                }
            },
            "status": {
                "type": "string"
            }
        },
        "title": "ShoppingCartResponse«List«Nodes»»"
    }
}}
</code>```

CLI Command

```<code>java -jar ..\openapi-generator-cli-6.2.1.jar generate --skip-operation-example -g spring --library spring-boot -i local-shoppingcart.json
</code>```

The codegen generates invalid variables in the equals() method

Any suggestion is appreciated

Body:
We are using the openapi-generator-cli-6.2.1 to generate the APIs and Models from swagger file.
Is it possible to instruct the CLI not to generate any equals() method for the Model classes ?
The reason is because the code generator generates malformed variable names for specific types.

Sample Swagger File

{
"swagger": "2.0",
"info": {
    "description": "Springfox template project",
    "version": "8.1.0",
    "title": "springfoxtemplate",
    "license": {
        "name": "Some Org"
    }
},
"host": "localhost:7777",
"basePath": "/",
"tags": [
    {
        "name": "main-controller",
        "description": "Main Controller"
    }
],
"paths": {
    "/cart/customer": {
        "get": {
            "tags": [
                "main-controller"
            ],
            "summary": "addCustomer",
            "operationId": "addCustomerUsingGET",
            "produces": [
                "application/json"
            ],
            "parameters": [
                {
                    "in": "body",
                    "name": "customer",
                    "description": "customer",
                    "required": true,
                    "schema": {
                        "$ref": "#/definitions/ShoppingCartRequest«Customer»"
                    }
                }
            ],
            "responses": {
                "200": {
                    "description": "OK",
                    "schema": {
                        "$ref": "#/definitions/ShoppingCartResponse«Customer»"
                    }
                },
                "401": {
                    "description": "Unauthorized"
                },
                "403": {
                    "description": "Forbidden"
                },
                "404": {
                    "description": "Not Found"
                }
            },
            "deprecated": false
        }
    },
    "/cart/nodes": {
        "get": {
            "tags": [
                "main-controller"
            ],
            "summary": "getNodes",
            "operationId": "getNodesUsingGET",
            "produces": [
                "application/json"
            ],
            "responses": {
                "200": {
                    "description": "OK",
                    "schema": {
                        "$ref": "#/definitions/ShoppingCartResponse«List«Nodes»»"
                    }
                },
                "401": {
                    "description": "Unauthorized"
                },
                "403": {
                    "description": "Forbidden"
                },
                "404": {
                    "description": "Not Found"
                }
            },
            "deprecated": false
        }
    }
},
"definitions": {
    "Customer": {
        "type": "object",
        "properties": {
            "id": {
                "type": "string"
            },
            "name": {
                "type": "string"
            },
            "status": {
                "type": "string"
            }
        },
        "title": "Customer"
    },
    "Nodes": {
        "type": "object",
        "properties": {
            "id": {
                "type": "string"
            },
            "name": {
                "type": "string"
            }
        },
        "title": "Nodes"
    },
    "ShoppingCartRequest«Customer»": {
        "type": "object",
        "properties": {
            "cartInstanceID": {
                "type": "string"
            },
            "requestObject": {
                "$ref": "#/definitions/Customer"
            }
        },
        "title": "ShoppingCartRequest«Customer»"
    },
    "ShoppingCartResponse«Customer»": {
        "type": "object",
        "properties": {
            "cartInstanceID": {
                "type": "string"
            },
            "responseObject": {
                "$ref": "#/definitions/Customer"
            },
            "status": {
                "type": "string"
            }
        },
        "title": "ShoppingCartResponse«Customer»"
    },
    "ShoppingCartResponse«List«Nodes»»": {
        "type": "object",
        "properties": {
            "cartInstanceID": {
                "type": "string"
            },
            "responseObject": {
                "type": "array",
                "items": {
                    "$ref": "#/definitions/Nodes"
                }
            },
            "status": {
                "type": "string"
            }
        },
        "title": "ShoppingCartResponse«List«Nodes»»"
    }
}}

CLI Command

java -jar ..\openapi-generator-cli-6.2.1.jar generate --skip-operation-example -g spring --library spring-boot -i local-shoppingcart.json

The codegen generates invalid variables in the equals() method

Any suggestion is appreciated


问:
RabbitMQ usused error in the application while doing the health checkup, because this update through any rest-api is failing
Currently our application is running on containerised environment, ALl the pods are running fine. but when we do health check of all the pods in the environment could see the below error as "Rabbit mq unused error in the environment' because of this the rest api update to the application is not happening.
Every time we do rest-api update, we need to delete this pod and try to intiate again.

Intersted to know how to clean this rabbit mq in kubernates or any cache needs to be deleted to make this queue clear.
enter image description here

we tried checking the logs of pod and wont see any issue,we have rescaled the pod and increased the replica that also not helping in fixing it.


问:
Is there an R function for Fixed Effect AR(1) Disturbances?
I'm trying to do a Fixed Effect analysis with AR(1) Disturbances.
From research, I found that there was a package called panelAR that incorporated the fixed effect analysis with autoregression disturbances, but the package was removed last year.
Is there a way to conduct the analysis in R?

Accordingly, STATA has a function called xtregar, but I am more comfortable using R so, wish to try with R.

I tried the following code but it says the package does not exist anymore.

```<code>pdata20032020_2 <- panelAR(RDItplusone ~
                         PBA
                       +PAA
                       #+CASH
                       #+COMMON_SHARES_OUTSTANDING
                       +SIC_CODE
                       +MS
                       +HHI
                       +AbsorbedSlack
                       +UnabsorbedSlack
                       +PotentialSlack
                       #+SchumacherSlack_Bromiley
                       #+CURRENT_LIABILITIESTOTAL
                       #+CURRENT_RATIO
                       #+MARKET_VALUE
                       #+NET_INCOME_DOLLAR
                       +NET_SALES_OR_REVENUES
                       #+QUICK_RATIO
                       #+SHORTTERM_INVESTMENTS
                       +TOTAL_ASSETS
                       #+CEO_TOTAL_WRDS
                       #+Analyst_TOTAL_WRDS
                       #+Analyst_CCC_standardized_avg
                       , data=pdata20032020
                       ,timeVar = 'year'
                       ,panelVar = 'company'
                       ,autoCorr = c("ar1","none", "psar1")
                       ,panelCorrMethod = c("none","phet","pcse","pwls", "parks")
                       , rhotype ="breg"
                       , bound.rho = FALSE
                       , rho.na.rm = FALSE
                       , panel.weight = c("t-1", "t")
                       , dof.correction = FALSE
                       , complete.case = FALSE
                       , seq.times = FALSE
                       , singular.ok=TRUE)
</code>```

Body:
I'm trying to do a Fixed Effect analysis with AR(1) Disturbances.
From research, I found that there was a package called panelAR that incorporated the fixed effect analysis with autoregression disturbances, but the package was removed last year.
Is there a way to conduct the analysis in R?

Accordingly, STATA has a function called xtregar, but I am more comfortable using R so, wish to try with R.

I tried the following code but it says the package does not exist anymore.

pdata20032020_2 <- panelAR(RDItplusone ~
                         PBA
                       +PAA
                       #+CASH
                       #+COMMON_SHARES_OUTSTANDING
                       +SIC_CODE
                       +MS
                       +HHI
                       +AbsorbedSlack
                       +UnabsorbedSlack
                       +PotentialSlack
                       #+SchumacherSlack_Bromiley
                       #+CURRENT_LIABILITIESTOTAL
                       #+CURRENT_RATIO
                       #+MARKET_VALUE
                       #+NET_INCOME_DOLLAR
                       +NET_SALES_OR_REVENUES
                       #+QUICK_RATIO
                       #+SHORTTERM_INVESTMENTS
                       +TOTAL_ASSETS
                       #+CEO_TOTAL_WRDS
                       #+Analyst_TOTAL_WRDS
                       #+Analyst_CCC_standardized_avg
                       , data=pdata20032020
                       ,timeVar = 'year'
                       ,panelVar = 'company'
                       ,autoCorr = c("ar1","none", "psar1")
                       ,panelCorrMethod = c("none","phet","pcse","pwls", "parks")
                       , rhotype ="breg"
                       , bound.rho = FALSE
                       , rho.na.rm = FALSE
                       , panel.weight = c("t-1", "t")
                       , dof.correction = FALSE
                       , complete.case = FALSE
                       , seq.times = FALSE
                       , singular.ok=TRUE)


问:
How can I get the program to login a existing user account that created a user account with an image from the camera?
I'm trying to create a chat app with both sign in and user account creation features. Currently the program can only sign in users after they create a new account and not by logging in using an existing account.

After putting and removing various print statements through out the code I've determined that the program appears to be unable to enter a particular code block that handles user authentication when the program's state is set to login via existing user credentials. This is not the desired result as I want the program to be able to login users who provide existing user data instead of just creating new accounts every time they wish to log in as well as being able to login through creating new accounts.

Here's the code needed to reproduce the error.

Main form

```<code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

import './screens/auth_screen.dart';
import './screens/chat_screen.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Chat App',
      theme: ThemeData(
        errorColor: Colors.red,
        primarySwatch: Colors.blue,
        backgroundColor: Colors.blue,
        accentColor: Colors.deepPurple,
        accentColorBrightness: Brightness.dark,
        buttonTheme: ButtonTheme.of(context).copyWith(
          buttonColor: Colors.blue,
          textTheme: ButtonTextTheme.primary,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        ),
      ),
      home: StreamBuilder(
          stream: FirebaseAuth.instance.authStateChanges(),
          builder: (ctx, userSnapshot) {
            if (userSnapshot.hasData) {
              //return ChatScreen();
              print('sucessfully logged in');
            }
            return AuthScreen();
          }),
    );
  }
}
</code>```

Auth screen

```<code>import 'dart:io';

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

import 'package:chat_app2/widgets/auth/auth_form.dart';
import 'package:flutter/services.dart';
import 'package:firebase_storage/firebase_storage.dart';

class AuthScreen extends StatefulWidget {
  @override
  _AuthScreenState createState() => _AuthScreenState();
}

class _AuthScreenState extends State<AuthScreen> {
  final _auth = FirebaseAuth.instance;
  var _isLoading = false;
  void _submitAuthForm(String email, String username, String password,
      File image, bool isLogin, BuildContext ctx) async {
    UserCredential authResult;
    print("isLogin:" + isLogin.toString());
    try {
      setState(() {
        _isLoading = true;
      });

      if (isLogin) {
        authResult = await _auth.signInWithEmailAndPassword(
          email: email,
          password: password,
        );
        print("logged in using an existing email and password");
      } else {
        authResult = await _auth.createUserWithEmailAndPassword(
          email: email,
          password: password,
        );
        print("logged in via account creation");

        final ref = FirebaseStorage.instance
            .ref()
            .child('user_image')
            .child(authResult.user!.uid + '.jpg');

        var uploadTask = ref.putFile(image);
        var storageTaskSnapshot = await uploadTask;
        String url = await storageTaskSnapshot.ref.getDownloadURL();

        await FirebaseFirestore.instance
            .collection('users')
            .doc(authResult.user!.uid)
            .set({
          'username': username,
          'email': email,
          'image_url': url,
        });
      }
    } on PlatformException catch (err) {
      var message = 'An error occured, please check your credentials';
      if (err.message != null) {
        message = err.message!;
      }
      final snackBar = SnackBar(
        content: Text(message),
        backgroundColor: Theme.of(ctx).errorColor,
      );
      ScaffoldMessenger.of(ctx).showSnackBar(snackBar);
      setState(() {
        _isLoading = false;
      });
    } catch (err) {
      final snackBar = SnackBar(
        content: Text(err.toString()),
        backgroundColor: Theme.of(ctx).errorColor,
      );
      ScaffoldMessenger.of(ctx).showSnackBar(snackBar);
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: AuthForm(
        _submitAuthForm,
        _isLoading,
      ),
    );
  }
}

</code>```

Auth form

```<code>import 'dart:io';

import 'package:flutter/material.dart';
import 'package:chat_app2/widgets/pickers/user_image_picker.dart';

class AuthForm extends StatefulWidget {
  AuthForm(this.submitFn, this.isLoading);

  final bool isLoading;
  final void Function(String email, String password, String username,
      File image, bool isLogin, BuildContext ctx) submitFn;

  @override
  _AuthFormState createState() => _AuthFormState();
}

class _AuthFormState extends State<AuthForm> {
  final _formKey = GlobalKey<FormState>();
  var _isLogin = true;
  String _userEmail = '';
  String _userName = '';
  String _userPassword = '';
  File? _userImageFile;

  void _pickedImage(File image) {
    _userImageFile = image;
  }

  void _trySubmit() {
    final isValid = _formKey.currentState?.validate() ?? false;
    FocusScope.of(context).unfocus();

    if (_userImageFile == null && !_isLogin) {
      final snackBar = SnackBar(
        content: Text("please pick an image"),
        backgroundColor: Theme.of(context).errorColor,
      );
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
      return;
    }

    if (isValid && _userImageFile != null && !_isLogin) {
      _formKey.currentState?.save();
      widget.submitFn(
        _userEmail.trim(),
        _userName.trim(),
        _userPassword.trim(),
        _userImageFile!,
        _isLogin,
        context,
      );
    }
    print("Authform submitted");
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Card(
        margin: EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Form(
              key: _formKey,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  if (!_isLogin) UserImagePicker(_pickedImage),
                  TextFormField(
                    key: ValueKey('email'),
                    validator: (value) {
                      if (value!.isEmpty || !value.contains('@')) {
                        return 'Please enter a valid email address';
                      }
                      return null;
                    },
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                      labelText: 'Email address',
                    ),
                    onSaved: (value) {
                      _userEmail = value ?? "";
                    },
                  ),
                  if (!_isLogin)
                    TextFormField(
                      key: ValueKey('userName'),
                      validator: (value) {
                        if (value!.isEmpty || value.length < 4) {
                          return 'Please enter at least four characters';
                        }
                        return null;
                      },
                      decoration: InputDecoration(labelText: 'Username'),
                      onSaved: (value) {
                        _userName = value ?? "";
                      },
                    ),
                  TextFormField(
                    key: ValueKey('password'),
                    validator: (value) {
                      if (value!.isEmpty || value.length < 7) {
                        return 'Password must be at least seven characters long';
                      }
                      return null;
                    },
                    decoration: InputDecoration(labelText: 'Password'),
                    obscureText: true,
                    onSaved: (value) {
                      _userPassword = value ?? "";
                    },
                  ),
                  SizedBox(
                    height: 12,
                  ),
                  if (widget.isLoading) CircularProgressIndicator(),
                  if (!widget.isLoading)
                    ElevatedButton(
                      child: Text(_isLogin ? 'Login' : 'Sign up'),
                      onPressed: _trySubmit,
                      style: ElevatedButton.styleFrom(
                          shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20),
                      )),
                    ),
                  if (!widget.isLoading)
                    TextButton(
                      child: Text(_isLogin
                          ? 'Create new account'
                          : 'I already have an account'),
                      onPressed: () {
                        setState(() {
                          _isLogin = !_isLogin;
                        });
                      },
                      style: TextButton.styleFrom(
                        foregroundColor: Theme.of(context).primaryColor,
                      ),
                    ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

</code>```

Image picker widget

```<code>// ignore_for_file: unnecessary_null_comparison

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class UserImagePicker extends StatefulWidget {
  UserImagePicker(this.imagePickFn);

  final void Function(File pickedImage) imagePickFn;
  @override
  _UserImagePickerState createState() => _UserImagePickerState();
}

class _UserImagePickerState extends State<UserImagePicker> {
  File? _pickedImage;

  void _pickImage() async {
    final pickedImageFile = await ImagePicker.pickImage(
      source: ImageSource.camera,
      imageQuality: 50,
      maxWidth: 150,
    );
    setState(() {
      _pickedImage = pickedImageFile;
    });

    widget.imagePickFn(pickedImageFile);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        CircleAvatar(
          radius: 50,
          backgroundColor: Colors.grey,
          backgroundImage:
              _pickedImage != null ? FileImage(_pickedImage!) : null,
        ),
        TextButton.icon(
            style: TextButton.styleFrom(
              primary: Theme.of(context).primaryColor,
            ),
            onPressed: _pickImage,
            icon: Icon(Icons.image),
            label: Text('Add Image')),
      ],
    );
  }
}

</code>```

the pubspec.yaml

```<code>name: chat_app2
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=2.18.2 <3.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  cloud_firestore: ^4.0.4
  firebase_auth: ^4.1.1
  image_picker: ^0.6.5+3
  firebase_storage: ^11.0.6

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages
</code>```

Body:
I'm trying to create a chat app with both sign in and user account creation features. Currently the program can only sign in users after they create a new account and not by logging in using an existing account.

After putting and removing various print statements through out the code I've determined that the program appears to be unable to enter a particular code block that handles user authentication when the program's state is set to login via existing user credentials. This is not the desired result as I want the program to be able to login users who provide existing user data instead of just creating new accounts every time they wish to log in as well as being able to login through creating new accounts.

Here's the code needed to reproduce the error.

Main form

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

import './screens/auth_screen.dart';
import './screens/chat_screen.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Chat App',
      theme: ThemeData(
        errorColor: Colors.red,
        primarySwatch: Colors.blue,
        backgroundColor: Colors.blue,
        accentColor: Colors.deepPurple,
        accentColorBrightness: Brightness.dark,
        buttonTheme: ButtonTheme.of(context).copyWith(
          buttonColor: Colors.blue,
          textTheme: ButtonTextTheme.primary,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        ),
      ),
      home: StreamBuilder(
          stream: FirebaseAuth.instance.authStateChanges(),
          builder: (ctx, userSnapshot) {
            if (userSnapshot.hasData) {
              //return ChatScreen();
              print('sucessfully logged in');
            }
            return AuthScreen();
          }),
    );
  }
}

Auth screen

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

import 'package:chat_app2/widgets/auth/auth_form.dart';
import 'package:flutter/services.dart';
import 'package:firebase_storage/firebase_storage.dart';

class AuthScreen extends StatefulWidget {
  @override
  _AuthScreenState createState() => _AuthScreenState();
}

class _AuthScreenState extends State<AuthScreen> {
  final _auth = FirebaseAuth.instance;
  var _isLoading = false;
  void _submitAuthForm(String email, String username, String password,
      File image, bool isLogin, BuildContext ctx) async {
    UserCredential authResult;
    print("isLogin:" + isLogin.toString());
    try {
      setState(() {
        _isLoading = true;
      });

      if (isLogin) {
        authResult = await _auth.signInWithEmailAndPassword(
          email: email,
          password: password,
        );
        print("logged in using an existing email and password");
      } else {
        authResult = await _auth.createUserWithEmailAndPassword(
          email: email,
          password: password,
        );
        print("logged in via account creation");

        final ref = FirebaseStorage.instance
            .ref()
            .child('user_image')
            .child(authResult.user!.uid + '.jpg');

        var uploadTask = ref.putFile(image);
        var storageTaskSnapshot = await uploadTask;
        String url = await storageTaskSnapshot.ref.getDownloadURL();

        await FirebaseFirestore.instance
            .collection('users')
            .doc(authResult.user!.uid)
            .set({
          'username': username,
          'email': email,
          'image_url': url,
        });
      }
    } on PlatformException catch (err) {
      var message = 'An error occured, please check your credentials';
      if (err.message != null) {
        message = err.message!;
      }
      final snackBar = SnackBar(
        content: Text(message),
        backgroundColor: Theme.of(ctx).errorColor,
      );
      ScaffoldMessenger.of(ctx).showSnackBar(snackBar);
      setState(() {
        _isLoading = false;
      });
    } catch (err) {
      final snackBar = SnackBar(
        content: Text(err.toString()),
        backgroundColor: Theme.of(ctx).errorColor,
      );
      ScaffoldMessenger.of(ctx).showSnackBar(snackBar);
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: AuthForm(
        _submitAuthForm,
        _isLoading,
      ),
    );
  }
}

Auth form

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:chat_app2/widgets/pickers/user_image_picker.dart';

class AuthForm extends StatefulWidget {
  AuthForm(this.submitFn, this.isLoading);

  final bool isLoading;
  final void Function(String email, String password, String username,
      File image, bool isLogin, BuildContext ctx) submitFn;

  @override
  _AuthFormState createState() => _AuthFormState();
}

class _AuthFormState extends State<AuthForm> {
  final _formKey = GlobalKey<FormState>();
  var _isLogin = true;
  String _userEmail = '';
  String _userName = '';
  String _userPassword = '';
  File? _userImageFile;

  void _pickedImage(File image) {
    _userImageFile = image;
  }

  void _trySubmit() {
    final isValid = _formKey.currentState?.validate() ?? false;
    FocusScope.of(context).unfocus();

    if (_userImageFile == null && !_isLogin) {
      final snackBar = SnackBar(
        content: Text("please pick an image"),
        backgroundColor: Theme.of(context).errorColor,
      );
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
      return;
    }

    if (isValid && _userImageFile != null && !_isLogin) {
      _formKey.currentState?.save();
      widget.submitFn(
        _userEmail.trim(),
        _userName.trim(),
        _userPassword.trim(),
        _userImageFile!,
        _isLogin,
        context,
      );
    }
    print("Authform submitted");
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Card(
        margin: EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Form(
              key: _formKey,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  if (!_isLogin) UserImagePicker(_pickedImage),
                  TextFormField(
                    key: ValueKey('email'),
                    validator: (value) {
                      if (value!.isEmpty || !value.contains('@')) {
                        return 'Please enter a valid email address';
                      }
                      return null;
                    },
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                      labelText: 'Email address',
                    ),
                    onSaved: (value) {
                      _userEmail = value ?? "";
                    },
                  ),
                  if (!_isLogin)
                    TextFormField(
                      key: ValueKey('userName'),
                      validator: (value) {
                        if (value!.isEmpty || value.length < 4) {
                          return 'Please enter at least four characters';
                        }
                        return null;
                      },
                      decoration: InputDecoration(labelText: 'Username'),
                      onSaved: (value) {
                        _userName = value ?? "";
                      },
                    ),
                  TextFormField(
                    key: ValueKey('password'),
                    validator: (value) {
                      if (value!.isEmpty || value.length < 7) {
                        return 'Password must be at least seven characters long';
                      }
                      return null;
                    },
                    decoration: InputDecoration(labelText: 'Password'),
                    obscureText: true,
                    onSaved: (value) {
                      _userPassword = value ?? "";
                    },
                  ),
                  SizedBox(
                    height: 12,
                  ),
                  if (widget.isLoading) CircularProgressIndicator(),
                  if (!widget.isLoading)
                    ElevatedButton(
                      child: Text(_isLogin ? 'Login' : 'Sign up'),
                      onPressed: _trySubmit,
                      style: ElevatedButton.styleFrom(
                          shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20),
                      )),
                    ),
                  if (!widget.isLoading)
                    TextButton(
                      child: Text(_isLogin
                          ? 'Create new account'
                          : 'I already have an account'),
                      onPressed: () {
                        setState(() {
                          _isLogin = !_isLogin;
                        });
                      },
                      style: TextButton.styleFrom(
                        foregroundColor: Theme.of(context).primaryColor,
                      ),
                    ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Image picker widget

// ignore_for_file: unnecessary_null_comparison

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class UserImagePicker extends StatefulWidget {
  UserImagePicker(this.imagePickFn);

  final void Function(File pickedImage) imagePickFn;
  @override
  _UserImagePickerState createState() => _UserImagePickerState();
}

class _UserImagePickerState extends State<UserImagePicker> {
  File? _pickedImage;

  void _pickImage() async {
    final pickedImageFile = await ImagePicker.pickImage(
      source: ImageSource.camera,
      imageQuality: 50,
      maxWidth: 150,
    );
    setState(() {
      _pickedImage = pickedImageFile;
    });

    widget.imagePickFn(pickedImageFile);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        CircleAvatar(
          radius: 50,
          backgroundColor: Colors.grey,
          backgroundImage:
              _pickedImage != null ? FileImage(_pickedImage!) : null,
        ),
        TextButton.icon(
            style: TextButton.styleFrom(
              primary: Theme.of(context).primaryColor,
            ),
            onPressed: _pickImage,
            icon: Icon(Icons.image),
            label: Text('Add Image')),
      ],
    );
  }
}

the pubspec.yaml

name: chat_app2
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=2.18.2 <3.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  cloud_firestore: ^4.0.4
  firebase_auth: ^4.1.1
  image_picker: ^0.6.5+3
  firebase_storage: ^11.0.6

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages


问:
How to draw a grayscale map from a one-dimensional array in matlab
I have a problem when drawing, I need to draw dimensions with value 0 as white and dimensions with value 1 as black. Here is an example where 100 is the length of the 1D array.
enter image description here

I tried the following code, but I don't want to display the y-axis, moreover I'm not sure if this is correct

```<code>myArray = rand(1, 100) > 0.5;
myMatrix = int8(myArray);
myImage = imagesc(myMatrix);
colormap gray;
</code>```

enter image description here

Body:
I have a problem when drawing, I need to draw dimensions with value 0 as white and dimensions with value 1 as black. Here is an example where 100 is the length of the 1D array.
enter image description here

I tried the following code, but I don't want to display the y-axis, moreover I'm not sure if this is correct

myArray = rand(1, 100) > 0.5;
myMatrix = int8(myArray);
myImage = imagesc(myMatrix);
colormap gray;

enter image description here


问:
Banners managed by Google Ad Manager don't display in another domain
we use Google Ad Manager to manage all the banners on our website. It used to be working on two domains: www.enfsolar.com, and www.enfrecycling.com, but it stopped working on www.enfrecycling.com a few months ago.
Anyone knows how to fix it?

Eg. this two pages have the exact same code, enfsolar.com can display the banner normally but the other one doesn't:
https://www.enfsolar.com/about?dev=1
https://www.enfrecycling.com/?dev=1

Settings for the two domains is exactly the same, but it still doesn't work.


问:
Configure Gradle task arguments in Visual Studio Code
I'm trying to use Visual Studio Code for my gradle build projects and run tasks with arguments.

I have installed the Gradle extension and opened a gradle project in visual studio code.
I see the project's tasks are listed under Gradle icon with an option to run (play button).

However I wanted to run each of the tasks with an argument, for which I chose 'Run Task With Args' and passed the arguments. This worked as expected.

I'm trying to automate this for all tasks, so I tried configuring the arguments in launch.json and tasks.json so that I need not pass the arguments each time, but neither of the options work.

tasks.json looks like below:

```<code>{
    "version": "2.0.0",
    "command": "gradle",
    "isShellCommaand": true,
    "args": ["-path"]
}
</code>```

launch.json looks like below:

Gradle is not being recognized as a type.

launch.json

Body:
I'm trying to use Visual Studio Code for my gradle build projects and run tasks with arguments.

I have installed the Gradle extension and opened a gradle project in visual studio code.
I see the project's tasks are listed under Gradle icon with an option to run (play button).

However I wanted to run each of the tasks with an argument, for which I chose 'Run Task With Args' and passed the arguments. This worked as expected.

I'm trying to automate this for all tasks, so I tried configuring the arguments in launch.json and tasks.json so that I need not pass the arguments each time, but neither of the options work.

tasks.json looks like below:

{
    "version": "2.0.0",
    "command": "gradle",
    "isShellCommaand": true,
    "args": ["-path"]
}

launch.json looks like below:

Gradle is not being recognized as a type.

launch.json


问:
How to code a pixel-based GUI drawing system + scaling the size in Roblox Luau
I wish to create a drawing system that turns whatever shape you draw into an array looking like

```<code>local Drawing = { -- Simple box drawing
   "11111",
   "10001",
   "10001",
   "10001",
   "11111",
}
</code>```

If you are interested in full use case:
I am trying to make a symbol-recognizing system (not neural networking, isn't fast enough for me needs) with template-matching algorithms like sum of absolute differences or normalized cross correlation. I make a answer symbol with the 0s and 1s like the drawing above, then compare them to each to see whichever is closest. (Sorry if this should be another topic, but if you know a more performant/efficient way of comparing them I am all ears!)

However the problem I currently having is making a grid-based drawing system and scaling the drawing.

I thought of having a bunch of frame in a grid, then detect when the mouse hovers over each (with the mouseHover event). I also thought of just rounding the mouse position. This is mostly sorted out for me, however I was wondering how others would implement this kind of system.

I want the drawing to be converted no matter its size, into a designated size, like 5x5 or 10x10 to fit the original drawing template. I thought of finding the boundary box of the drawing, then trying to "compress" (divide) each individual mouse position I would cache while moving the mouse. However this would need me to use a ton of memory and I doubt it is extremely optimal, especially if you just keep the mouse down to play the event for a very long time. Also, would there be a way to possibly stop "outliers" from occurring? A small line outside the draw-line could potentially break it. Is there an alternative algorithm I can use?

Thank you for reading, also let me know if any formatting here is incorrect I am new to stack-overflow.

Body:
I wish to create a drawing system that turns whatever shape you draw into an array looking like

local Drawing = { -- Simple box drawing
   "11111",
   "10001",
   "10001",
   "10001",
   "11111",
}

If you are interested in full use case:
I am trying to make a symbol-recognizing system (not neural networking, isn't fast enough for me needs) with template-matching algorithms like sum of absolute differences or normalized cross correlation. I make a answer symbol with the 0s and 1s like the drawing above, then compare them to each to see whichever is closest. (Sorry if this should be another topic, but if you know a more performant/efficient way of comparing them I am all ears!)

However the problem I currently having is making a grid-based drawing system and scaling the drawing.

I thought of having a bunch of frame in a grid, then detect when the mouse hovers over each (with the mouseHover event). I also thought of just rounding the mouse position. This is mostly sorted out for me, however I was wondering how others would implement this kind of system.

I want the drawing to be converted no matter its size, into a designated size, like 5x5 or 10x10 to fit the original drawing template. I thought of finding the boundary box of the drawing, then trying to "compress" (divide) each individual mouse position I would cache while moving the mouse. However this would need me to use a ton of memory and I doubt it is extremely optimal, especially if you just keep the mouse down to play the event for a very long time. Also, would there be a way to possibly stop "outliers" from occurring? A small line outside the draw-line could potentially break it. Is there an alternative algorithm I can use?

Thank you for reading, also let me know if any formatting here is incorrect I am new to stack-overflow.


问:
Torch CUDA to CPU. Convert these lines "torch.cuda.current_device()","torch.cuda.get_device_properties()","torch.cuda.device_count()" for CPU?
I want to rewrite the script in Python. It uses torch.cuda . As far as I know, torch.cuda is for GPUs that support CUDA. I do not have such a GPU, I want to use the CPU instead of the GPU.

How can I rewrite these lines:

```<code>torch.cuda.current_device()
torch.cuda.get_device_properties()
torch.cuda.device_count()
</code>```

so that these operations use CPU instead of GPU?

Thank you for your attention.

Here is part of code:

```<code>if not torch.cuda.is_available():
        print("Your PyTorch installation is not configured to use CUDA. If you have a GPU ready "
              "for deep learning, ensure that the drivers are properly installed, and that your "
              "CUDA version matches your PyTorch installation. CPU-only inference is currently "
              "not supported.", file=sys.stderr)
        quit(-1) #он видит что у меня нет видюхи которая поддерживает Cuda и выходит (quit)

    device_id = torch.cuda.current_device()
    gpu_properties = torch.cuda.get_device_properties(device_id)
    print("Found %d GPUs available. Using GPU %d (%s) of compute capability %d.%d with "
          "%.1fGb total memory.\n" %
          (torch.cuda.device_count(),
           device_id,
           gpu_properties.name,
           gpu_properties.major,
           gpu_properties.minor,
           gpu_properties.total_memory / 1e9))

    ## Load the models one by one.
    print("Preparing the encoder, the synthesizer and the vocoder...")
    encoder.load_model(args.enc_model_fpath)
    print("args.enc_model_fpath:")
    print(args.enc_model_fpath)
    synthesizer = Synthesizer(args.syn_model_dir.joinpath("taco_pretrained"), low_mem=args.low_mem)

    vocoder.load_model(args.voc_model_fpath)
    print("args.voc_model_fpath:")
    print(args.voc_model_fpath)
</code>```

Whole code: https://github.com/solidsnake777999/py/blob/main/demo_cli.py

Body:
I want to rewrite the script in Python. It uses torch.cuda . As far as I know, torch.cuda is for GPUs that support CUDA. I do not have such a GPU, I want to use the CPU instead of the GPU.

How can I rewrite these lines:

torch.cuda.current_device()
torch.cuda.get_device_properties()
torch.cuda.device_count()

so that these operations use CPU instead of GPU?

Thank you for your attention.

Here is part of code:

if not torch.cuda.is_available():
        print("Your PyTorch installation is not configured to use CUDA. If you have a GPU ready "
              "for deep learning, ensure that the drivers are properly installed, and that your "
              "CUDA version matches your PyTorch installation. CPU-only inference is currently "
              "not supported.", file=sys.stderr)
        quit(-1) #он видит что у меня нет видюхи которая поддерживает Cuda и выходит (quit)

    device_id = torch.cuda.current_device()
    gpu_properties = torch.cuda.get_device_properties(device_id)
    print("Found %d GPUs available. Using GPU %d (%s) of compute capability %d.%d with "
          "%.1fGb total memory.\n" %
          (torch.cuda.device_count(),
           device_id,
           gpu_properties.name,
           gpu_properties.major,
           gpu_properties.minor,
           gpu_properties.total_memory / 1e9))

    ## Load the models one by one.
    print("Preparing the encoder, the synthesizer and the vocoder...")
    encoder.load_model(args.enc_model_fpath)
    print("args.enc_model_fpath:")
    print(args.enc_model_fpath)
    synthesizer = Synthesizer(args.syn_model_dir.joinpath("taco_pretrained"), low_mem=args.low_mem)

    vocoder.load_model(args.voc_model_fpath)
    print("args.voc_model_fpath:")
    print(args.voc_model_fpath)

Whole code: https://github.com/solidsnake777999/py/blob/main/demo_cli.py


问:
Gdalwarp validation
I was resizing a Tiff file resolution from 0.08 to 0.5 using gdalwarp

```<code>#gdalwrap 'outputfile', 'inputfile'
</code>```

Then transform the tiff file to csv file.
However, in the end. I need to validate the result 0.5.csv compared with 0.08.csv.
Some area have not resulting good projection.

I need several reason or maybe references about how gdalwarp works and how is it working result (validation).

Thank you.

Title: Gdalwarp validation

Body:
I was resizing a Tiff file resolution from 0.08 to 0.5 using gdalwarp

#gdalwrap 'outputfile', 'inputfile'

Then transform the tiff file to csv file.
However, in the end. I need to validate the result 0.5.csv compared with 0.08.csv.
Some area have not resulting good projection.

I need several reason or maybe references about how gdalwarp works and how is it working result (validation).

Thank you.


问:
Possible to animate a View inside a ViewGroup inside a LinearLayout?
I have a class that extends LinearLayout defined in main.xml. Programmatically I create x number of classes that extend ViewGroup. I have overridden canAnimate() to return true. Inside of that there are some more views also created programmatically. What I am trying to do is tap on one of those nested child views and have it animate (y-axis rotation ObjectAnimator). At the end of animation I hide the tapped view in the onAnimationEnd listener.

The touch event works, and I can see the view that was tapped hide after the given duration of the animation. The problem is that the view doesn't actually animate. If I use the same animation code on the ViewGroup extension, I can see that animate as you would expect.

What it seems like is that you can't animate child views that are nested more than 2 levels deep. Can anyone confirm this or give an example of how to animate a View of a ViewGroup of a LinearLayout?

This is in Honeycomb.

Thanks.

Update:
I can nest 4 LinearLayouts and a View in XML and see it animate. I changed the class that extends ViewGroup to extend LinearLayout but still no animation with the child view. What could be set inflating a view that I'm not setting programmatically to allow animation of children?

```<code>public class MyViewGroup extends ViewGroup implements ViewGroup.OnTouchListener {

    private View viewToAnimate;

    public MyViewGroup(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setup(context);
    }

    public MyViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        setup(context);
    }

    public MyViewGroup(Context context) {
        super(context);
        setup(context);
    }

    private void setup(Context context)
    {
        viewToAnimate = new View(context);
        viewToAnimate.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
        viewToAnimate.setBackgroundColor(Color.YELLOW);
        viewToAnimate.setOnTouchListener(this);
        addView(viewToAnimate);
    }

    @Override
    protected boolean canAnimate()
    {
        return true;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // Left out for brevity
    }

    public boolean onTouch(View v, MotionEvent event)
    {
        animateViewRotation();
        return true;
    }

    private Interpolator accelerator = new AccelerateInterpolator();
    private Interpolator decelerator = new DecelerateInterpolator();
    private void animateViewRotation()
    {
            // Tried all of the following:
        /*
        ObjectAnimator rotationY = ObjectAnimator.ofFloat(viewToAnimate, "rotationY", 0f, 90f);
        AnimatorSet translations = new AnimatorSet();
        translations.setDuration(1000);
        translations.play(rotationY);
        translations.start();
        */

        /*
        RotateAnimation ta = new RotateAnimation(0f, 90f, 0, 100);
        ta.setDuration(1000);
        viewToAnimate.startAnimation(ta);
        */

        // Copied/adapted from API Demos code
        ObjectAnimator animation = ObjectAnimator.ofFloat(viewToAnimate, "rotationY", 0f, 90f);
        animation.setDuration(1000);
        //animation.setInterpolator(accelerator);
        animation.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator anim) {
                viewToAnimate.setVisibility(View.GONE);
            }
        });

        animation.start();
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a class that extends LinearLayout defined in main.xml. Programmatically I create x number of classes that extend ViewGroup. I have overridden canAnimate() to return true. Inside of that there are some more views also created programmatically. What I am trying to do is tap on one of those nested child views and have it animate (y-axis rotation ObjectAnimator). At the end of animation I hide the tapped view in the onAnimationEnd listener.

The touch event works, and I can see the view that was tapped hide after the given duration of the animation. The problem is that the view doesn't actually animate. If I use the same animation code on the ViewGroup extension, I can see that animate as you would expect.

What it seems like is that you can't animate child views that are nested more than 2 levels deep. Can anyone confirm this or give an example of how to animate a View of a ViewGroup of a LinearLayout?

This is in Honeycomb.

Thanks.

Update:
I can nest 4 LinearLayouts and a View in XML and see it animate. I changed the class that extends ViewGroup to extend LinearLayout but still no animation with the child view. What could be set inflating a view that I'm not setting programmatically to allow animation of children?

public class MyViewGroup extends ViewGroup implements ViewGroup.OnTouchListener {

    private View viewToAnimate;

    public MyViewGroup(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setup(context);
    }

    public MyViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        setup(context);
    }

    public MyViewGroup(Context context) {
        super(context);
        setup(context);
    }

    private void setup(Context context)
    {
        viewToAnimate = new View(context);
        viewToAnimate.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
        viewToAnimate.setBackgroundColor(Color.YELLOW);
        viewToAnimate.setOnTouchListener(this);
        addView(viewToAnimate);
    }

    @Override
    protected boolean canAnimate()
    {
        return true;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // Left out for brevity
    }

    public boolean onTouch(View v, MotionEvent event)
    {
        animateViewRotation();
        return true;
    }

    private Interpolator accelerator = new AccelerateInterpolator();
    private Interpolator decelerator = new DecelerateInterpolator();
    private void animateViewRotation()
    {
            // Tried all of the following:
        /*
        ObjectAnimator rotationY = ObjectAnimator.ofFloat(viewToAnimate, "rotationY", 0f, 90f);
        AnimatorSet translations = new AnimatorSet();
        translations.setDuration(1000);
        translations.play(rotationY);
        translations.start();
        */

        /*
        RotateAnimation ta = new RotateAnimation(0f, 90f, 0, 100);
        ta.setDuration(1000);
        viewToAnimate.startAnimation(ta);
        */

        // Copied/adapted from API Demos code
        ObjectAnimator animation = ObjectAnimator.ofFloat(viewToAnimate, "rotationY", 0f, 90f);
        animation.setDuration(1000);
        //animation.setInterpolator(accelerator);
        animation.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator anim) {
                viewToAnimate.setVisibility(View.GONE);
            }
        });

        animation.start();
    }

}


问:
WS2812b simulation with Stm32 in Proteus
I am an Embedded Engineer, working on the Simulation of WS2812B (12-RGB LEDs Strip) with Stm32F401RE in Proteus. But I can't simulate it. It's working with Arduino properly but not with Stm32.

Did I do something wrong? The frequency for the PWM is 84MHz and I have set the same Frequency for Stm32F401RE in proteus.

Please guide me on how to properly simulate it or share a proteus simulation file with me if you have?

Thank you!!!


问:
How to populate column values in one data frame from column values of another data frame based on key if the exist
I have two dataframes df and df1 as shown below. The key for populating the value is Name

df

```<code>ID Name   City  Country_Code
1  Rahul
2  Rachel
3  Mathew
4  James
5  Rose
6  David
</code>```

df1

```<code>Name   City_Name  CC
Rahul  Delhi      IND
Rachel Munich     GR
Mathew
James  Paris      FR
David  London     GB
</code>```

Expected Result

df

```<code>ID Name   City       Country_Code
1  Rahul   Delhi     IND
2  Rachel  Munich    GR
3  Mathew
4  James    Paris    FR
5  Rose
6  David   London    GB
</code>```

How can this be done in python?

Body:
I have two dataframes df and df1 as shown below. The key for populating the value is Name

df

ID Name   City  Country_Code
1  Rahul
2  Rachel
3  Mathew
4  James
5  Rose
6  David

df1

Name   City_Name  CC
Rahul  Delhi      IND
Rachel Munich     GR
Mathew
James  Paris      FR
David  London     GB

Expected Result

df

ID Name   City       Country_Code
1  Rahul   Delhi     IND
2  Rachel  Munich    GR
3  Mathew
4  James    Paris    FR
5  Rose
6  David   London    GB

How can this be done in python?


问:
How to read feature importance for censored data?

```<code>                  event.1   event.2
AMOUNT              0.2455    0.0108
INSTALL_RATE        0.0535    0.0239
FOREIGN             0.0413    0.0640
PROPERTY            0.0390    0.0016
HISTORY             0.0278    0.0279
AGE                 0.0169    0.0323
NUM_CREDITS         0.0168    0.0156
OTHER_INSTALL       0.0136   -0.0174
RESIDENCE           0.0096   -0.0105
GUARANTOR           0.0095    0.0094
JOB                 0.0087    0.0087
CHK_ACCT            0.0079   -0.0035
PRESENT_RESIDENT    0.0070   -0.0086
NUM_DEPENDENTS      0.0062    0.0018
COAPPLICANT         0.0054    0.0072
EMPLOYMENT          0.0037    0.0014
PURPOSE             0.0021    0.0071
TELEPHONE           0.0010    0.0148
SEX                 0.0009    0.0141
SAV_ACCT           -0.0014   -0.0093
</code>```

Does event 1 belong to outcome 0? Or does it belong to outcome 1 (failure)?

I made a feature importance chart recently. I want to make sure I am reading it correctly in R.

```<code>fit <- rfsrc(Surv(DURATION,DEFAULT) ~ .,
             data = CD,
             ntree = 500,
             importance = TRUE,
             nsplit = 5)

plot(fit)
</code>```

Body:
                  event.1   event.2
AMOUNT              0.2455    0.0108
INSTALL_RATE        0.0535    0.0239
FOREIGN             0.0413    0.0640
PROPERTY            0.0390    0.0016
HISTORY             0.0278    0.0279
AGE                 0.0169    0.0323
NUM_CREDITS         0.0168    0.0156
OTHER_INSTALL       0.0136   -0.0174
RESIDENCE           0.0096   -0.0105
GUARANTOR           0.0095    0.0094
JOB                 0.0087    0.0087
CHK_ACCT            0.0079   -0.0035
PRESENT_RESIDENT    0.0070   -0.0086
NUM_DEPENDENTS      0.0062    0.0018
COAPPLICANT         0.0054    0.0072
EMPLOYMENT          0.0037    0.0014
PURPOSE             0.0021    0.0071
TELEPHONE           0.0010    0.0148
SEX                 0.0009    0.0141
SAV_ACCT           -0.0014   -0.0093

Does event 1 belong to outcome 0? Or does it belong to outcome 1 (failure)?

I made a feature importance chart recently. I want to make sure I am reading it correctly in R.

fit <- rfsrc(Surv(DURATION,DEFAULT) ~ .,
             data = CD,
             ntree = 500,
             importance = TRUE,
             nsplit = 5)

plot(fit)


问:
Unable To See the "Folder' Option on the Pane
I want to change the folder size font and I am unable to see the Folder option next to the Workspace option. I have highlighted the same in red circle. Can somebody help me get the Folder option?

enter image description here

I tried clicking on the settings on the left corner pane of VS code, tried closing the window and reopening the settings by clicking the cogwheel. However I couldn't find the Folder option in the pane next to 'User' and 'Workspace'. Need help.


问:
Expected 2D array, got scalar array instead. Reshape your data either using array.reshape(-1, 1)
I have problem with my python, here is my code
I'm trying to classify data that will be inputted later through the Python GUI, and when it's applied there are problems that come out, I need help

```<code>from tkinter import ttk
from tkinter.messagebox import showinfo

#Variabel and function
JUMLAH_ART = tk.StringVar()
STATUS_BANGUNAN = tk.StringVar()
STATUS_LAHAN = tk.StringVar()
LANTAI_TERLUAS = tk.StringVar()
DINDING_TERLUAS = tk.StringVar()
ATAP_TERLUAS = tk.StringVar()
SUMBER_AIR_MINUM = tk.StringVar()
CARA_MEMPEROLEH_AIR_MINUM = tk.StringVar()
SUMBER_PENERANGAN_UTAMA = tk.StringVar()
JENIS_KLOSET = tk.StringVar()
KEPEMILIKAN_SEPEDA_MOTOR = tk.StringVar()
KEPEMILIKAN_ASET_TIDAK_BERGERAK = tk.StringVar()
PROSES = tk.StringVar()

def button_klasifikasi():
    '''function'''
    Data_Testing =[[JUMLAH_ART.get(),STATUS_BANGUNAN.get(),STATUS_LAHAN.get(),LANTAI_TERLUAS.get(),DINDING_TERLUAS.get(),ATAP_TERLUAS.get(),SUMBER_AIR_MINUM.get(),CARA_MEMPEROLEH_AIR_MINUM.get(),SUMBER_PENERANGAN_UTAMA.get(),JENIS_KLOSET.get(),KEPEMILIKAN_SEPEDA_MOTOR.get(),KEPEMILIKAN_ASET_TIDAK_BERGERAK.get()]]

    Data = map(float, Data_Testing)
    y_pred = classifier.predict(Data)
    if y_pred == 0:
        hasil = "Tidak"
    else:
        hasil = "Ya"

    pesan = f"Hasil Keikutsertaan Bansos ", Data_Testing
    showinfo(title="HASIL", message=pesan)

#Frame Input
input_frame = ttk.Frame(window)
input_frame.pack(padx = 10, pady = 10, fill="x", expand=True)

#Komponen
#Input X1
Jumlah_ART = ttk.Label(input_frame, text="Jumlah Anggota Keluarga")
Jumlah_ART.pack(padx = 10, fill="x", expand=True)
#Enter X1
Jumlah_ART = ttk.Entry(input_frame, textvariable=JUMLAH_ART)
Jumlah_ART.pack(padx = 10, fill="x", expand=True)
#Input X2
Status_bangunan = ttk.Label(input_frame, text="Status Bangunan")
Status_bangunan.pack(padx = 10, fill="x", expand=True)
#Enter X2
Status_bangunan = ttk.Entry(input_frame, textvariable=STATUS_BANGUNAN)
Status_bangunan.pack(padx = 10, fill="x", expand=True)
#Input X3
Status_lahan = ttk.Label(input_frame, text="Status Lahan")
Status_lahan.pack(padx = 10, fill="x", expand=True)
#Enter X3
Status_lahan = ttk.Entry(input_frame, textvariable=STATUS_LAHAN)
Status_lahan.pack(padx = 10, fill="x", expand=True)
#Input X4
Lantai_terluas = ttk.Label(input_frame, text="Lantai Terluas")
Lantai_terluas.pack(padx = 10, fill="x", expand=True)
#Enter X4
Lantai_terluas = ttk.Entry(input_frame, textvariable=LANTAI_TERLUAS)
Lantai_terluas.pack(padx = 10, fill="x", expand=True)
#Input X5
Dinding_terluas = ttk.Label(input_frame, text="Dinding Terluas")
Dinding_terluas.pack(padx = 10, fill="x", expand=True)
#Enter X5
Dinding_terluas = ttk.Entry(input_frame, textvariable=DINDING_TERLUAS)
Dinding_terluas.pack(padx = 10, fill="x", expand=True)
#Input X6
Atap_terluas = ttk.Label(input_frame, text="Atap Terluas")
Atap_terluas.pack(padx = 10, fill="x", expand=True)
#Enter X6
Atap_terluas = ttk.Entry(input_frame, textvariable=ATAP_TERLUAS)
Atap_terluas.pack(padx = 10, fill="x", expand=True)
#Input X7
Sumber_air_minum = ttk.Label(input_frame, text="Sumber Air Minum")
Sumber_air_minum.pack(padx = 10, fill="x", expand=True)
#Enter X7
Sumber_air_minum = ttk.Entry(input_frame, textvariable=SUMBER_AIR_MINUM)
Sumber_air_minum.pack(padx = 10, fill="x", expand=True)
#Input X8
Cara_memperoleh_air_minum = ttk.Label(input_frame, text="Cara Memperoleh Air Minum")
Cara_memperoleh_air_minum.pack(padx = 10, fill="x", expand=True)
#Enter X8
Cara_memperoleh_air_minum = ttk.Entry(input_frame, textvariable=CARA_MEMPEROLEH_AIR_MINUM)
Cara_memperoleh_air_minum.pack(padx = 10, fill="x", expand=True)
#Input X9
Sumber_penerangan_utama = ttk.Label(input_frame, text="Sumber Penerangan Utama")
Sumber_penerangan_utama.pack(padx = 10, fill="x", expand=True)
#Enter X9
Sumber_penerangan_utama = ttk.Entry(input_frame, textvariable=SUMBER_PENERANGAN_UTAMA)
Sumber_penerangan_utama.pack(padx = 10, fill="x", expand=True)
#Input X10
Jenis_kloset = ttk.Label(input_frame, text="Jenis Kloset")
Jenis_kloset.pack(padx = 10, fill="x", expand=True)
#Enter X10
Jenis_kloset = ttk.Entry(input_frame, textvariable=JENIS_KLOSET)
Jenis_kloset.pack(padx = 10, fill="x", expand=True)
#Input X11
Kepemilikan_sepeda_motor = ttk.Label(input_frame, text="Kepemilikan Sepeda Motor")
Kepemilikan_sepeda_motor.pack(padx = 10, fill="x", expand=True)
#Enter X11
Kepemilikan_sepeda_motor = ttk.Entry(input_frame, textvariable=KEPEMILIKAN_SEPEDA_MOTOR)
Kepemilikan_sepeda_motor.pack(padx = 10, fill="x", expand=True)
#Input X12
Kepemilikan_aset_tidak_bergerak  = ttk.Label(input_frame, text="Kepemilikan Aset Tidak Bergerak")
Kepemilikan_aset_tidak_bergerak.pack(padx = 10, fill="x", expand=True)
#Enter X12
Kepemilikan_aset_tidak_bergerak  = ttk.Entry(input_frame, textvariable=KEPEMILIKAN_ASET_TIDAK_BERGERAK)
Kepemilikan_aset_tidak_bergerak.pack(padx = 10, fill="x", expand=True)

#Button
button_proses  = ttk.Button(input_frame, text="Proses", command=button_klasifikasi)
button_proses.pack(padx = 10, pady = 10, fill="x", expand=True)

#Main Loop Window
window.mainloop()
</code>```

and here the result

ValueError: Expected 2D array, got scalar array instead:
array=<map object at 0x0000026E3E600BE0>.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

i need help to solve this.I'm still confused, because this is the first time I've retrieved the data entered.

Body:
I have problem with my python, here is my code
I'm trying to classify data that will be inputted later through the Python GUI, and when it's applied there are problems that come out, I need help

from tkinter import ttk
from tkinter.messagebox import showinfo

#Variabel and function
JUMLAH_ART = tk.StringVar()
STATUS_BANGUNAN = tk.StringVar()
STATUS_LAHAN = tk.StringVar()
LANTAI_TERLUAS = tk.StringVar()
DINDING_TERLUAS = tk.StringVar()
ATAP_TERLUAS = tk.StringVar()
SUMBER_AIR_MINUM = tk.StringVar()
CARA_MEMPEROLEH_AIR_MINUM = tk.StringVar()
SUMBER_PENERANGAN_UTAMA = tk.StringVar()
JENIS_KLOSET = tk.StringVar()
KEPEMILIKAN_SEPEDA_MOTOR = tk.StringVar()
KEPEMILIKAN_ASET_TIDAK_BERGERAK = tk.StringVar()
PROSES = tk.StringVar()

def button_klasifikasi():
    '''function'''
    Data_Testing =[[JUMLAH_ART.get(),STATUS_BANGUNAN.get(),STATUS_LAHAN.get(),LANTAI_TERLUAS.get(),DINDING_TERLUAS.get(),ATAP_TERLUAS.get(),SUMBER_AIR_MINUM.get(),CARA_MEMPEROLEH_AIR_MINUM.get(),SUMBER_PENERANGAN_UTAMA.get(),JENIS_KLOSET.get(),KEPEMILIKAN_SEPEDA_MOTOR.get(),KEPEMILIKAN_ASET_TIDAK_BERGERAK.get()]]

    Data = map(float, Data_Testing)
    y_pred = classifier.predict(Data)
    if y_pred == 0:
        hasil = "Tidak"
    else:
        hasil = "Ya"

    pesan = f"Hasil Keikutsertaan Bansos ", Data_Testing
    showinfo(title="HASIL", message=pesan)

#Frame Input
input_frame = ttk.Frame(window)
input_frame.pack(padx = 10, pady = 10, fill="x", expand=True)

#Komponen
#Input X1
Jumlah_ART = ttk.Label(input_frame, text="Jumlah Anggota Keluarga")
Jumlah_ART.pack(padx = 10, fill="x", expand=True)
#Enter X1
Jumlah_ART = ttk.Entry(input_frame, textvariable=JUMLAH_ART)
Jumlah_ART.pack(padx = 10, fill="x", expand=True)
#Input X2
Status_bangunan = ttk.Label(input_frame, text="Status Bangunan")
Status_bangunan.pack(padx = 10, fill="x", expand=True)
#Enter X2
Status_bangunan = ttk.Entry(input_frame, textvariable=STATUS_BANGUNAN)
Status_bangunan.pack(padx = 10, fill="x", expand=True)
#Input X3
Status_lahan = ttk.Label(input_frame, text="Status Lahan")
Status_lahan.pack(padx = 10, fill="x", expand=True)
#Enter X3
Status_lahan = ttk.Entry(input_frame, textvariable=STATUS_LAHAN)
Status_lahan.pack(padx = 10, fill="x", expand=True)
#Input X4
Lantai_terluas = ttk.Label(input_frame, text="Lantai Terluas")
Lantai_terluas.pack(padx = 10, fill="x", expand=True)
#Enter X4
Lantai_terluas = ttk.Entry(input_frame, textvariable=LANTAI_TERLUAS)
Lantai_terluas.pack(padx = 10, fill="x", expand=True)
#Input X5
Dinding_terluas = ttk.Label(input_frame, text="Dinding Terluas")
Dinding_terluas.pack(padx = 10, fill="x", expand=True)
#Enter X5
Dinding_terluas = ttk.Entry(input_frame, textvariable=DINDING_TERLUAS)
Dinding_terluas.pack(padx = 10, fill="x", expand=True)
#Input X6
Atap_terluas = ttk.Label(input_frame, text="Atap Terluas")
Atap_terluas.pack(padx = 10, fill="x", expand=True)
#Enter X6
Atap_terluas = ttk.Entry(input_frame, textvariable=ATAP_TERLUAS)
Atap_terluas.pack(padx = 10, fill="x", expand=True)
#Input X7
Sumber_air_minum = ttk.Label(input_frame, text="Sumber Air Minum")
Sumber_air_minum.pack(padx = 10, fill="x", expand=True)
#Enter X7
Sumber_air_minum = ttk.Entry(input_frame, textvariable=SUMBER_AIR_MINUM)
Sumber_air_minum.pack(padx = 10, fill="x", expand=True)
#Input X8
Cara_memperoleh_air_minum = ttk.Label(input_frame, text="Cara Memperoleh Air Minum")
Cara_memperoleh_air_minum.pack(padx = 10, fill="x", expand=True)
#Enter X8
Cara_memperoleh_air_minum = ttk.Entry(input_frame, textvariable=CARA_MEMPEROLEH_AIR_MINUM)
Cara_memperoleh_air_minum.pack(padx = 10, fill="x", expand=True)
#Input X9
Sumber_penerangan_utama = ttk.Label(input_frame, text="Sumber Penerangan Utama")
Sumber_penerangan_utama.pack(padx = 10, fill="x", expand=True)
#Enter X9
Sumber_penerangan_utama = ttk.Entry(input_frame, textvariable=SUMBER_PENERANGAN_UTAMA)
Sumber_penerangan_utama.pack(padx = 10, fill="x", expand=True)
#Input X10
Jenis_kloset = ttk.Label(input_frame, text="Jenis Kloset")
Jenis_kloset.pack(padx = 10, fill="x", expand=True)
#Enter X10
Jenis_kloset = ttk.Entry(input_frame, textvariable=JENIS_KLOSET)
Jenis_kloset.pack(padx = 10, fill="x", expand=True)
#Input X11
Kepemilikan_sepeda_motor = ttk.Label(input_frame, text="Kepemilikan Sepeda Motor")
Kepemilikan_sepeda_motor.pack(padx = 10, fill="x", expand=True)
#Enter X11
Kepemilikan_sepeda_motor = ttk.Entry(input_frame, textvariable=KEPEMILIKAN_SEPEDA_MOTOR)
Kepemilikan_sepeda_motor.pack(padx = 10, fill="x", expand=True)
#Input X12
Kepemilikan_aset_tidak_bergerak  = ttk.Label(input_frame, text="Kepemilikan Aset Tidak Bergerak")
Kepemilikan_aset_tidak_bergerak.pack(padx = 10, fill="x", expand=True)
#Enter X12
Kepemilikan_aset_tidak_bergerak  = ttk.Entry(input_frame, textvariable=KEPEMILIKAN_ASET_TIDAK_BERGERAK)
Kepemilikan_aset_tidak_bergerak.pack(padx = 10, fill="x", expand=True)

#Button
button_proses  = ttk.Button(input_frame, text="Proses", command=button_klasifikasi)
button_proses.pack(padx = 10, pady = 10, fill="x", expand=True)

#Main Loop Window
window.mainloop()

and here the result

ValueError: Expected 2D array, got scalar array instead:
array=<map object at 0x0000026E3E600BE0>.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

i need help to solve this.I'm still confused, because this is the first time I've retrieved the data entered.


问:
docker environment, can't access webcam
Trying to capture some frames with a USB camera. I'm using Docker so this application is containerized, but I have mapped /dev/ttyUSB0 correctly, so inside the container I am able to communicate (via serial commands) to the camera with no issue.

My current issue stems from my attempt at capturing frames using OpenCV.

In my capture function, I have:

```<code>using namespace cv;
using namespace std;

std::string filename;
std::string file_extension = "mp4";

SPDLOG_INFO("Creating video capture filename.");
create_filename(filename, capture_sequence_number, file_extension);

// Create a VideoCapture object.
VideoCapture cap("/dev/ttyUSB0");

// Check if camera opened successfully
if(!cap.isOpened()){
    SPDLOG_ERROR("Failed to open video stream.");
    return;
}
</code>```

The isOpened() is returning false, as the "Failed to open video stream" log statement is printed, and none of the subsequent capturing code executes.

Is there a decent way to diagnose this? I can preview the camera (using some hardware I have here), so I know it is outputting frames, and I can communicate with it over serial, so I know it's connected within the container (communicating via /dev/ttyUSB0). I am just not sure how to go about diagnosing why the VideoCapture object is not opening. My camera is connected to a CameraLink to GigE converter, I have an ethernet cord from that GigE converter into my laptop, so I'm not sure if there's potentially some networking aspect I'm missing?

Title: docker environment, can't access webcam

Body:
Trying to capture some frames with a USB camera. I'm using Docker so this application is containerized, but I have mapped /dev/ttyUSB0 correctly, so inside the container I am able to communicate (via serial commands) to the camera with no issue.

My current issue stems from my attempt at capturing frames using OpenCV.

In my capture function, I have:

using namespace cv;
using namespace std;

std::string filename;
std::string file_extension = "mp4";

SPDLOG_INFO("Creating video capture filename.");
create_filename(filename, capture_sequence_number, file_extension);

// Create a VideoCapture object.
VideoCapture cap("/dev/ttyUSB0");

// Check if camera opened successfully
if(!cap.isOpened()){
    SPDLOG_ERROR("Failed to open video stream.");
    return;
}

The isOpened() is returning false, as the "Failed to open video stream" log statement is printed, and none of the subsequent capturing code executes.

Is there a decent way to diagnose this? I can preview the camera (using some hardware I have here), so I know it is outputting frames, and I can communicate with it over serial, so I know it's connected within the container (communicating via /dev/ttyUSB0). I am just not sure how to go about diagnosing why the VideoCapture object is not opening. My camera is connected to a CameraLink to GigE converter, I have an ethernet cord from that GigE converter into my laptop, so I'm not sure if there's potentially some networking aspect I'm missing?


问:
Does mongoose findOne fetch a reference to the document or just value?
[Screenshot image] 1In line 103, findOne method is used which is fetching a document.
In the fetched document, when a field is changed(i.e added an item to the field "items" in this case),
and it is saved to the database again, does it get added as a new document or
it updates the original document that was fetched?

I thought that the save method was like insertOne.
I was expecting it to be saved as a new document but I think it is updating the original document?

I wonder if the fetched document is reference to the original document or just a copy of it;


问:
typescript issue when using plain jsdoc types
Hi Im not using typescript or tsconfig.json
but JSDoc types as understood by vscode // @tscheck
I am looking for a Javscript-only solution with JSDoc type comments.

I followed the ideas in https://medium.com/@trukrs/type-safe-javascript-with-jsdoc-7a2a63209b76
and it's been working well generally but:

node   v16.17.0, vscode 1.74.0

```<code>    // @tscheck

    /** @type {string} myTestString */
    const myTestString = ("2022-01-12").replaceAll("-", "")
</code>```

Error:
Property 'replaceAll' does not exist on type 'string'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2021' or later.ts(2550)

How to fix this message without a build step?
First I removed the // tscheck.  which killed the message,
but want to keep the type checking if possible.

In pure typescript there seems to be this suggestion
https://pinoria.com/how-to-fix-the-property-replaceall-does-not-exist-on-type-string-error-with-typescript/

but how to do similar without a build step?

Body:
Hi Im not using typescript or tsconfig.json
but JSDoc types as understood by vscode // @tscheck
I am looking for a Javscript-only solution with JSDoc type comments.

I followed the ideas in https://medium.com/@trukrs/type-safe-javascript-with-jsdoc-7a2a63209b76
and it's been working well generally but:

node   v16.17.0, vscode 1.74.0

    // @tscheck

    /** @type {string} myTestString */
    const myTestString = ("2022-01-12").replaceAll("-", "")

Error:
Property 'replaceAll' does not exist on type 'string'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2021' or later.ts(2550)

How to fix this message without a build step?
First I removed the // tscheck.  which killed the message,
but want to keep the type checking if possible.

In pure typescript there seems to be this suggestion
https://pinoria.com/how-to-fix-the-property-replaceall-does-not-exist-on-type-string-error-with-typescript/

but how to do similar without a build step?


问:
Error in element_line(linewidth = 1, colour = "black") : unused argument (linewidth = 1)
using r library SmartEDA
getting this error

```<code>Error in element_line(linewidth = 1, colour = "black") :
  unused argument (linewidth = 1)
</code>```

reintall the package but still facing this issue

Body:
using r library SmartEDA
getting this error

Error in element_line(linewidth = 1, colour = "black") :
  unused argument (linewidth = 1)

reintall the package but still facing this issue


Title: I combined 2 .csv files with 5 rows each and converted it into a df in Databricks Comm edition .But one column is having all null values in the df

Body:
+----------+---------+-------------+----------+-------+--------+-------+------+------------+------+
|Invoice ID|     City|Customer type|Unit price| Tax 5%|   Total|Payment|  cogs|gross income|Rating|
+----------+---------+-------------+----------+-------+--------+-------+------+------------+------+
| 750678428|   Yangon|       Member|     74.69|26.1415|548.9715|   null|522.83|     26.1415|   9.1|
| 226313081|Naypyitaw|       Normal|     15.28|   3.82|   80.22|   null|  76.4|        3.82|   9.6|
| 631413108|   Yangon|       Normal|     46.33|16.2155|340.5255|   null|324.31|     16.2155|   7.4|
| 123191176|   Yangon|       Member|     58.22| 23.288| 489.048|   null|465.76|      23.288|   8.4|
| 373737910|   Yangon|       Normal|     86.31|30.2085|634.3785|   null|604.17|     30.2085|   5.3|
| 750678428|   Yangon|       Member|     74.69|26.1415|548.9715|   null|522.83|     26.1415|   9.1|
| 226313081|Naypyitaw|       Normal|     15.28|   3.82|   80.22|   null|  76.4|        3.82|   9.6|
| 631413108|   Yangon|       Normal|     46.33|16.2155|340.5255|   null|324.31|     16.2155|   7.4|
| 123191176|   Yangon|       Member|     58.22| 23.288| 489.048|   null|465.76|      23.288|   8.4|
| 373737910|   Yangon|       Normal|     86.31|30.2085|634.3785|   null|604.17|     30.2085|   5.3|
+----------+---------+-------------+----------+-------+--------+-------+------+------------+------+

The payment column is completely NULL; but  indeed there is data in the input CSV files. How do I rectify this ?