问:
nestjs / TypeOrm database transaction
Assuming we have 2 services, A and B.
Service A has a function doing the following:

Validate the data

Call a service B function, that makes changes to the database

Do some more stuff

Do changes to the database

Now, let's assume that one of the following, steps 3 or 4 failed.
Since service B made changes in the database, those changes are still there.

Is there any way of rolling the database back in this case? I though about database transactions, but I couldn't find any way to do that in nest js, although it is supported by TypeOrm, it doesn't look natural to nest.
If not, I am now "stuck" with the changes occured by service B, but without the changes should have happen by A.

Thanks a lot.

答:
typeorm-transactional uses CLS (Continuation Local Storage) to handle and propagate transactions between different repositories and service methods.

@Injectable()
export class PostService {
  constructor(
    private readonly authorRepository: AuthorRepository,
    private readonly postRepository: PostRepository,
  ) {}

  @Transactional() // will open a transaction if one doesn't already exist
  async createPost(authorUsername: string, message: string): Promise<Post> {
    const author = await this.authorRepository.create({ username: authorUsername });
    return this.postRepository.save({ message, author_id: author.id });
  }
}
```

Title: nestjs / TypeOrm database transaction


来源: stackexchange

问:
Error: Could not find or load main class CountRows?
Please suggest How can I improve my question

I ran my code but it throws cannot find main class error. I know this error comes when name of class with main method is different from file name. I tried to solve this error for an hour. I need help.

CountRows.java

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

public class CountRows
{
    public static void main(String args[])
    {
        System.out.println("Count number of rows in a specific table!");
        Connection con = null;
        int count = 0;
        try
        {
            //Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial","root","dics");
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}
</code>```

Execution

```<code> >javac -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar" CountRows.java

 E:\user\java\jdbc\test>java -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar" CountRows

Error: Could not find or load main class CountRows
</code>```

Edit: Although the solution works but I still don't understand what was wrong with my way of executing code

答:
Your Code is working perfectly fine there is no issue in it.

I suggest you set classpath initially before using javac and java tools.

Set your classpath via CMD

```<code>set classpath="<EXTERNAL_JAR_FILES_PATH>"
</code>```

I hope this might help you. If you are still facing the same issue you can ping me back. I will be happy to help you.

ContentLicense: CC BY-SA 4.0

Body:
Please suggest How can I improve my question

I ran my code but it throws cannot find main class error. I know this error comes when name of class with main method is different from file name. I tried to solve this error for an hour. I need help.

CountRows.java

import java.io.*;
import java.sql.*;

public class CountRows
{
    public static void main(String args[])
    {
        System.out.println("Count number of rows in a specific table!");
        Connection con = null;
        int count = 0;
        try
        {
            //Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial","root","dics");
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Execution

 >javac -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar" CountRows.java

 E:\user\java\jdbc\test>java -classpath "e:\softwares\java\jar files\mysql-connector-java-8.0.19.jar" CountRows

Error: Could not find or load main class CountRows

Edit: Although the solution works but I still don't understand what was wrong with my way of executing code

Body:
Your Code is working perfectly fine there is no issue in it.

I suggest you set classpath initially before using javac and java tools.

Set your classpath via CMD

set classpath="<EXTERNAL_JAR_FILES_PATH>"

I hope this might help you. If you are still facing the same issue you can ping me back. I will be happy to help you.


问:
Update a dataframe in pandas while iterating row by row
I have a pandas data frame that looks like this (its a pretty big one)

```<code>           date      exer exp     ifor         mat
1092  2014-03-17  American   M  528.205  2014-04-19
1093  2014-03-17  American   M  528.205  2014-04-19
1094  2014-03-17  American   M  528.205  2014-04-19
1095  2014-03-17  American   M  528.205  2014-04-19
1096  2014-03-17  American   M  528.205  2014-05-17
</code>```

now I would like to iterate row by row and as I go through each row, the value of ifor
in each row can change depending on some conditions and I need to lookup another dataframe.

Now, how do I update this as I iterate.
Tried a few things none of them worked.

```<code>for i, row in df.iterrows():
    if <something>:
        row['ifor'] = x
    else:
        row['ifor'] = y

    df.ix[i]['ifor'] = x
</code>```

None of these approaches seem to work. I don't see the values updated in the dataframe.

答:
It's better to use lambda functions using df.apply() -

```<code>df["ifor"] = df.apply(lambda x: {value} if {condition} else x["ifor"], axis=1)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a pandas data frame that looks like this (its a pretty big one)

           date      exer exp     ifor         mat
1092  2014-03-17  American   M  528.205  2014-04-19
1093  2014-03-17  American   M  528.205  2014-04-19
1094  2014-03-17  American   M  528.205  2014-04-19
1095  2014-03-17  American   M  528.205  2014-04-19
1096  2014-03-17  American   M  528.205  2014-05-17

now I would like to iterate row by row and as I go through each row, the value of ifor
in each row can change depending on some conditions and I need to lookup another dataframe.

Now, how do I update this as I iterate.
Tried a few things none of them worked.

for i, row in df.iterrows():
    if <something>:
        row['ifor'] = x
    else:
        row['ifor'] = y

    df.ix[i]['ifor'] = x

None of these approaches seem to work. I don't see the values updated in the dataframe.

Body:
It's better to use lambda functions using df.apply() -

df["ifor"] = df.apply(lambda x: {value} if {condition} else x["ifor"], axis=1)


问:
Develop a userspace read-only disk driver for macOS
I have a special disk image format (compressed and with extra information such as bad blocks) and would like to make that available as a block device (e.g. under /dev/rdisk) in macOS.

I am looking for pointers on how to write a read-only block level userspace driver.

I believe I need to do this with IOKit, but the docs are quite sparse in that area, and provide no sample code for this as far as I can tell.

I've had a look at Amit Singh's Mac OS Internals, but that only goes about filerting existing blocks that get routed through the added driver. But I need to read the data from a separate file, i.e. I need to use the file system, and I also want to do this in a userspace app if possible because making a kext is both hard to debug and is getting deprecated now, too.

Ideally, this should work on current macOS versions, including 10.15, but I'd also be happy with a solution that only works on older macOS versions, starting at 10.6.

Maybe I am still misunderstanding some things here. I was under the impression that it was possible even before 10.15 to write userspace IOKit drivers. But maybe that's not possible with Block Storage devices? Any clarifications would be welcome. I feel quite lost.

Update June 22, 2020

I also asked the question on the OSXFUSE support forum, and got a negative reply there.

答:
Maybe I am still misunderstanding some things here. I was under the impression that it was possible even before 10.15 to write userspace IOKit drivers.

This is a true statement, but it does not mean it's possible to write all types of drivers in userspace, even with 10.15. The confusion likely stems from the fact that "IOKit" is used to mean subtly different things in different contexts:

Fundamentally, it is the (class and inheritance) OOP-based driver stack technology which is built into the XNU kernel (macOS, iOS, etc.), written in C++. Its core data structure is the I/O Kit registry, which is a directed graph of objects representing devices, device (sub-)functions, virtual device, service, drivers, user space client connections, etc. (most of it has properties of it, but nodes can technically have multiple "parent" nodes, and some actually do so on your typical Mac system)

The IOKit user space libraries. (a.k.a. IOKit.framework a.k.a. IOKitLib + various IOCFPlugins) These provide a view of the kernel's I/O Registry to user space programs, and allow them to perform certain interactions with IOKit objects. This is essentially limited to:

Iterating over the registry graph and matching services based on matching rules. Both return handles to specific I/O Registry entries to the user space program.

Getting properties on I/O Registry entries, and if the object explicitly supports it, setting (some) properties.

Creating a user client connection. This is the only way to create an entry in the I/O Registry from regular user space, and these are always IOUserClient subclasses, and only if the parent object specfically permits it.

The IOKit view available to DriverKit based System Extension processes (new in 10.15), which allows instantiation of entirely user space backed registry entry objects, for subclassing a (bounded) selection of super class types.

To answer the question of your specific case:

To implement a driver for a block storage device which will appear to the system as any other, you need to subclass IOStorage or one of its subclasses (typically IOBlockStorageDevice).

IOKit.framework allows you to create user space drivers which will only be used by that user space process or other user space processes. It is therefore not possible to use it to create drivers that will be used by some part of the kernel. For example, it is not possible to create a block device driver which will be used by the kernel's VFS system.

DriverKit as of macOS 10.15.4 SDK does not allow dext-backed subclasses of any of the storage stack's classes. So a dext will not solve the problem on 10.15.
Update: SCSIControllerDriverKit was added with DriverKit 20.4 (macOS 11.4), while BlockStorageDeviceDriverKit came along with DriverKit 21 (macOS 12). I believe these are intended to be used for PCI devices, but it may be possible to build a "virtual" block device with them too. (You may struggle to obtain the necessary DriverKit entitlements for this purpose, and will likely have an even harder time publishing such a driver to the App Store. Moreover, SCSIControllerDriverKit only started providing access to transfer data buffers in the driver from DriverKit 21 onwards, so there's no API availability advantage from the point of view of writing a virtual device driver.)

The only way to do what you're trying to do, as far as I'm aware, is to have a 2-part driver: a kext implementing an IOBlockStorageDevice subclass, as well as a service which offers a user client interface for some user space process to connect to for creating instances of block devices, and which will handle the I/O requests for the device. This is a sort of analog to the FUSE mechanism which works at the VFS layer instead of the block layer.
This is exactly how macOS's built-in disk image mounting system works. Unfortunately, neither the kext nor user space parts of this are open source, documented, or a public API. So unless you reverse engineer it and find a boundary which doesn't enforce the requirement of an Apple code signature, you basically have to reimplement this.

I'm not currently aware of an existing open source system that does this, but I haven't looked very hard. Especially for read-only access, it shouldn't be terribly hard to do if you know what you're doing, but it comes with the usual downsides of developing and distributing kexts.

Note that you could also use FUSE to open your disk image if the block device it represents hosts a file system you wish to mount, and a FUSE implementation for that file system exists.


问:
Google sheets query with sum returning unwanted text
Im not sure where I am making a mistake here. In the following sheet

https://docs.google.com/spreadsheets/d/1h0XR399z6OHqzyX509WwnLBiqHX4nq4FmofaJd-HoAw/edit?usp=sharing

Sheet 1 has the raw data. I am trying to sum the same in sheet based on different criteria but I am getting an issue with a simple query. In sheet order_payment_heads a simple sum query in C2 returns the su but also the text sum amount.
Feels like I am doing something really basic wrong here but any help would be great. query being used is given below

'''=QUERY(Sheet1!A:X,"select SUM(O) where H = '"&A2&"'",1)'''

答:
in a brand new tab, try this in cell A1

```<code>=QUERY(Sheet1!A:X,"select H,V,SUM(O) where H is not null group by H,V label SUM(O)'Price Head'")
</code>```

Hopefully that will get what you're after in one go.  "group by" is really the only reason that query distinguishes itself from other functions.

Body:
in a brand new tab, try this in cell A1

=QUERY(Sheet1!A:X,"select H,V,SUM(O) where H is not null group by H,V label SUM(O)'Price Head'")

Hopefully that will get what you're after in one go.  "group by" is really the only reason that query distinguishes itself from other functions.


问:
Errors with reading from a json file through python program
I am getting errors about the plugin of my program, basically what I am task to do is to extract summaries from a json file which is from a cowrie honeypot, and print it all the countries, like how many countries are written in that json file by using plugins like geoip and geolite2.

Here is the program and the error I am getting, I guess the problem is about the pathing of my program from the source of the file. Any help would really be appreciated

The error I am getting:

My code:

```<code>import glob
import json
import gmplot
from collections import defaultdict
from pprint import pprint
from geoip import geolite2

ips = []
for fn in glob.glob("C:/Users/Bennet/Desktop/Random/forin/cowrie/log/cowrie.json.*"):
 with open(fn, "rt") as f:
    for line in f:
        data = json.loads(line)
        if data['eventid'] == "cowrie.session.connect":
            ips.append(data['src_ip'])

lats = []
longs = []
for ip in ips:
  data = geolite2.lookup(ip)
  if data is None:
    continue
  lats.append(data.location[0])
  longs.append(data.location[1])

gmap = gmplot.GoogleMapPlotter(0,0, 2)
gmap.heatmap(lats, longs)
gmap.draw("mymap.html")
pprint(countries)
</code>```

Cowrie.Json file(logs): Inside of the cowrie logs I need to read from

content of the cowrie logs:

```<code>{"eventid": "cowrie.session.connect", "src_ip": "5.8.32.72", "src_port": 3518, "timestamp": "2018-03-05T00:02:43.158673Z", "message": "New connection: 5.8.32.72:3518 (10.240.0.23:2222) [session: e057e76d0f2a]", "dst_ip": "10.240.0.23", "system": "cowrie.ssh.factory.CowrieSSHFactory", "protocol": "ssh", "isError": 0, "session": "e057e76d0f2a", "dst_port": 2222, "sensor": "garethowenson"}
</code>```

Error after getting the ip address

答:
Unfortunately I don't know the geolite2-module, but if I understand the error message right, the fault is to pass geolite2.lookup() a string (ip), but it requires a bytes-like object.

Did you tried geolite2.lookup(bytes(ip, 'utf-8')) at line 19 already?

Body:
I am getting errors about the plugin of my program, basically what I am task to do is to extract summaries from a json file which is from a cowrie honeypot, and print it all the countries, like how many countries are written in that json file by using plugins like geoip and geolite2.

Here is the program and the error I am getting, I guess the problem is about the pathing of my program from the source of the file. Any help would really be appreciated

The error I am getting:

My code:

import glob
import json
import gmplot
from collections import defaultdict
from pprint import pprint
from geoip import geolite2

ips = []
for fn in glob.glob("C:/Users/Bennet/Desktop/Random/forin/cowrie/log/cowrie.json.*"):
 with open(fn, "rt") as f:
    for line in f:
        data = json.loads(line)
        if data['eventid'] == "cowrie.session.connect":
            ips.append(data['src_ip'])

lats = []
longs = []
for ip in ips:
  data = geolite2.lookup(ip)
  if data is None:
    continue
  lats.append(data.location[0])
  longs.append(data.location[1])

gmap = gmplot.GoogleMapPlotter(0,0, 2)
gmap.heatmap(lats, longs)
gmap.draw("mymap.html")
pprint(countries)

Cowrie.Json file(logs): Inside of the cowrie logs I need to read from

content of the cowrie logs:

{"eventid": "cowrie.session.connect", "src_ip": "5.8.32.72", "src_port": 3518, "timestamp": "2018-03-05T00:02:43.158673Z", "message": "New connection: 5.8.32.72:3518 (10.240.0.23:2222) [session: e057e76d0f2a]", "dst_ip": "10.240.0.23", "system": "cowrie.ssh.factory.CowrieSSHFactory", "protocol": "ssh", "isError": 0, "session": "e057e76d0f2a", "dst_port": 2222, "sensor": "garethowenson"}

Error after getting the ip address


问:
Applet unable to connect to mysql server
I am developing a java applet which connects to mysql database, the applet works fine on local host but when I uploaded it and tried to run, i get an error as "communications link failure the last packet sent successfully to the server was 0 milliseconds ago.
the driver has not recieved any packets from the server"
i tried it on x10hosting and hostable, please help me if anyone knows the solution...</p>

答:
The applet is client-side. If you want to directly connect to a mysql server this would mean each user that opens the applet should either have mysql installed or have access and credentials to the remote database. Even if your firewall allows the access it is a very bad idea to do so. If you do everyone will have access to your database.

So if you want to communicate with a remote database, use some protocol (http would be easiest, via a Servlet) to send requests to the server and receive responses generated based on the database results. For example invoking http://yoursite.com/addRecord?name=foo&email=bar@baz.com could tell the server-side application to open a (local) connection to mysql and insert a record.


问:
simple peer webrtc remote video stream not playing
```<code>peer.on('stream', function (stream) {
            console.log('peer on stream called');
            console.log(stream);
            this.video = document.getElementById("peerVideo");
            this.video.srcObject = stream;
            this.video.play();
          })
          return peer
        }
</code>```

Here I am getting the video stream from a remote machine.
I have logged and checked i am sure that i am getting a remote stream as the stream id at is source is same that i receive here.

this.video.srcObject = stream; this line generates a -> error  Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.

I tried a lot but don't know how to solve this issue.

Thanks for help.

答:
The problem is that the play() function is asynchronous and is loaded while the play function is running. The solution would be to start it after it is loaded.

Adding the autoplay attribute to the video object fixes the problem. And removing the call of video.play().

```<code><video src="somefile.mp4" autoplay></video>
</code>```

Body:
peer.on('stream', function (stream) {
            console.log('peer on stream called');
            console.log(stream);
            this.video = document.getElementById("peerVideo");
            this.video.srcObject = stream;
            this.video.play();
          })
          return peer
        }

Here I am getting the video stream from a remote machine.
I have logged and checked i am sure that i am getting a remote stream as the stream id at is source is same that i receive here.

this.video.srcObject = stream; this line generates a -> error  Uncaught (in promise) DOMException: The play() request was interrupted by a new load request.

I tried a lot but don't know how to solve this issue.

Thanks for help.

Body:
The problem is that the play() function is asynchronous and is loaded while the play function is running. The solution would be to start it after it is loaded.

Adding the autoplay attribute to the video object fixes the problem. And removing the call of video.play().

<video src="somefile.mp4" autoplay></video>


问:
Passing data to a GLSL Vertex Shader
I'm trying to convert a program written in C using legacy OpenGL Fixed Pipeline commands.

I'm stuck trying to pass some data into a Vertex Shader.  I'm trying to use the latest 4.5 commands and I have managed to pass in my array of vertex coordinates "vertices[]" to the Vertex Shader using

```<code>glCreateVertexArrays(1, &vertex_array_object);
glBindVertexArray(vertex_array_object);

glCreateBuffers(1, &vertex_buffer);
glNamedBufferStorage(vertex_buffer, sizeof(verticies), verticies, GL_DYNAMIC_STORAGE_BIT);

glVertexArrayVertexBuffer(vertex_array_object, 0, vertex_buffer, 0, sizeof(float)*3);
glVertexArrayAttribFormat(vertex_array_object,0, 3, GL_FLOAT, GL_FALSE, 0);

glVertexArrayAttribBinding(vertex_array_object,0,0);
glEnableVertexArrayAttrib(vertex_array_object,0);
</code>```

This all works fine and I can render the vertices as points.

As well as passing the vertices I also need to pass an additional block of 4 values for each vertex which I then want to pass from the Vertex Shader to a Geometry Shader.  The values I need to pass are in an array of structures (1 per vertex) where the structure is defined as

```<code>typedef struct {        /* Vertex vector data structure */

unsigned char  v;           /* Scaled magnitude value     "    */
char           x;           /* X Component of direction cosine */
char           y;           /* Y     "      "     "       "    */
char           z;           /* Z     "      "     "       "    */

} NVD;
</code>```

I can't easily change this structure as it's used in lots of other places in the code.

Inside the vertex shader I need the 4 values as integers in the ranges

```<code> v (0->255)
 x,y,z (-127 > 127)
</code>```

答:
I can't easily change this structure as it's used in lots of other places in the code.

Well, you're going to have to because you can't use structs as interface variables between shader stages. You can pass the data along as a single ivec4, with each component storing the value you want. Though really, you should just pass the floating-point values you compute in the shader; it's going to be 128-bits per-vertex either way, so no point in taking the time to quantize the data.

If the size of this data is shown through profiling to be an actual problem (and using a GS at all is far more likely to be the performance problem), you can encode the data in a single uint for passing to the GS, then unpacking it on the other end.

Title: Passing data to a GLSL Vertex Shader

Body:
I'm trying to convert a program written in C using legacy OpenGL Fixed Pipeline commands.

I'm stuck trying to pass some data into a Vertex Shader.  I'm trying to use the latest 4.5 commands and I have managed to pass in my array of vertex coordinates "vertices[]" to the Vertex Shader using

glCreateVertexArrays(1, &vertex_array_object);
glBindVertexArray(vertex_array_object);

glCreateBuffers(1, &vertex_buffer);
glNamedBufferStorage(vertex_buffer, sizeof(verticies), verticies, GL_DYNAMIC_STORAGE_BIT);

glVertexArrayVertexBuffer(vertex_array_object, 0, vertex_buffer, 0, sizeof(float)*3);
glVertexArrayAttribFormat(vertex_array_object,0, 3, GL_FLOAT, GL_FALSE, 0);

glVertexArrayAttribBinding(vertex_array_object,0,0);
glEnableVertexArrayAttrib(vertex_array_object,0);

This all works fine and I can render the vertices as points.

As well as passing the vertices I also need to pass an additional block of 4 values for each vertex which I then want to pass from the Vertex Shader to a Geometry Shader.  The values I need to pass are in an array of structures (1 per vertex) where the structure is defined as

typedef struct {        /* Vertex vector data structure */

unsigned char  v;           /* Scaled magnitude value     "    */
char           x;           /* X Component of direction cosine */
char           y;           /* Y     "      "     "       "    */
char           z;           /* Z     "      "     "       "    */

} NVD;

I can't easily change this structure as it's used in lots of other places in the code.

Inside the vertex shader I need the 4 values as integers in the ranges

 v (0->255)
 x,y,z (-127 > 127)


问:
Stuck with Javascript! - How do I use an If statement to update an element and an array?
I am trying to build a shopping cart function for a project.

This is what I am being asked to do:

Inside the if statement, update the orderTotal element to display Total: $ and the sum of all the prices inside the cartItems array.

1) Under the IF statement I am then entering: orderTotal.innerHTML = "Total: $"
2) At this point I get stuck as I do not know how to add the sum of all prices in the array?

Please help!

var cartItems = [];
var isTotalHidden = true;

var backpack = {
 name: "Backpack",
 price: 400
}

var camera = {
 name: "Camera",
 price: 300
}

function addToCart(item) {
 cartItems.push(item);
 document.getElementById("itemCounter").innerHTML = cartItems.length;
 showTotal();
}

function clickCart() {
 isTotalHidden = !isTotalHidden;
 showTotal();
}

function showTotal() {
 var orderTotal = document.getElementById("orderTotal");
 orderTotal.innerHTML = "";

 if (isTotalHidden === false) {

 }
}```

答:
You need to use Array.reduce like this:

var backpack = {
 name: "Backpack",
 price: 400
}

var camera = {
 name: "Camera",
 price: 300
}

cart = [camera, backpack]
console.log(cart.reduce((agg,cur) => agg + cur.price,0))```

What reduce does in its basic form (which is sufficient for your use case) is takes two arguments callback and starting value (in your case 0). Callback than has two arguments (aggregator and current). You than sum previously aggregated value with the current one in each iteration.

More on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Body:
You need to use Array.reduce like this:

var backpack = {
 name: "Backpack",
 price: 400
}

var camera = {
 name: "Camera",
 price: 300
}

cart = [camera, backpack]
console.log(cart.reduce((agg,cur) => agg + cur.price,0))

What reduce does in its basic form (which is sufficient for your use case) is takes two arguments callback and starting value (in your case 0). Callback than has two arguments (aggregator and current). You than sum previously aggregated value with the current one in each iteration.

More on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce


问:
How can join multiple arraylists
I have two different arraylists. In the first, there are vars (title,author,isbn,date,kind). In the second there are (title,author,isbn,date,kind,field) such as Strings. I dont use super class or subclass.Finally i want these arraylists to populate in common jtable
When i run the program with the first arraylist i take this result 1st_arraylist
When i run the program with the second arraylist i take this result
2st_arraylist
When i run the program both of two arraylists i take this result
both arraylists
I want to view both arraylists in one jtable
My code

```<code>public class LiteraryBookList {
        private ArrayList<LiteraryBook> LibookList;

        public LiteraryBookList() {
            LibookList = new ArrayList<LiteraryBook>();
        }

        public void add(LiteraryBook lb) {
            LibookList.add(lb);
        }

        public ArrayList<LiteraryBook> getBooks() {
            return LibookList;
        }

        public void readFromTxt(String filename) {
            File file = new File(filename);
            FileReader reader = null;
            try {
                reader = new FileReader(file);
            } catch (FileNotFoundException e) {
                System.exit(1);
            }
            BufferedReader infile = new BufferedReader(reader);
            String line = "";
            int counter = 0;
            String title = "";
            String author = "";
            String isbn = "";
            String date = "";
            String kind = "";

            try {
                while ((line = infile.readLine()) != null) {
                     if (line.isEmpty() || line.contains("1")) {
                        continue;
                     }
                    counter++;
                    if (counter == 1) {
                        title = line;
                    } else if (counter == 2) {
                        author = line;
                    } else if (counter == 3) {
                        isbn = line;
                    } else if (counter == 4) {
                        date = line;
                    } else if (counter == 5) {
                        kind = line;
                        LiteraryBook lb = new LiteraryBook(title, author, isbn, date, kind);
                        LibookList.add(lb);
                        counter = 0;

                    }

                }

            } catch (IOException ex) {
                Logger.getLogger(LiteraryBookList.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public Object[][] convert2Data() {
            Object[][] data = new Object[LibookList.size()][5];
            for (int i = 0; i < LibookList.size(); i++) {
                data[i][0] = LibookList.get(i).getTitle();
                data[i][1] = LibookList.get(i).getAuthor();
                data[i][2] = LibookList.get(i).getIsbn();
                data[i][3] = LibookList.get(i).getDate();
                data[i][4] = LibookList.get(i).getKind();
            }
            return data;
        }
    }
</code>```

Also i have..

```<code>public class ScientificBookList {

    private ArrayList<ScientificBook> ScibookList;

    public ScientificBookList() {
        ScibookList = new ArrayList<ScientificBook>();
    }

    public void add(ScientificBook sb) {
        ScibookList.add(sb);
    }

    public ArrayList<ScientificBook> getBooks() {
        return ScibookList;
    }

    public void readFromTxt(String filename) {
        File file = new File(filename);
        FileReader reader = null;
        try {
            reader = new FileReader(file);
        } catch (FileNotFoundException e) {
            System.exit(1);
        }
        BufferedReader infile = new BufferedReader(reader);
        String line = "";
        int counter = 0;
        String sci_title = "";
        String sci_author = "";
        String sci_isbn = "";
        String sci_date = "";
        String sci_kind = "";
        String scientific_field = "";

        try {
            while ((line = infile.readLine()) != null) {
                if (line.isEmpty() || line.contains("2")) {
                    continue;
                }

                counter++;
                if (counter == 1) {
                    sci_title = line;
                } else if (counter == 2) {
                    sci_author = line;
                } else if (counter == 3) {
                    sci_isbn = line;
                } else if (counter == 4) {
                    sci_date = line;
                } else if (counter == 5) {
                    sci_kind = line;
                } else if (counter == 6) {
                    scientific_field = line;

                    ScientificBook sb = new ScientificBook(sci_title, sci_author, sci_isbn, sci_date, sci_kind,scientific_field);
                    ScibookList.add(sb);
                    counter = 0;

                }

            }

        } catch (IOException ex) {
            Logger.getLogger(LiteraryBookList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Object[][] convert2Data() {
        Object[][] data = new Object[ScibookList.size()][6];
        for (int i = 0; i < ScibookList.size(); i++) {
            data[i][0] = ScibookList.get(i).getSci_Title();
            data[i][1] = ScibookList.get(i).getSci_Author();
            data[i][2] = ScibookList.get(i).getSci_Isbn();
            data[i][3] = ScibookList.get(i).getSci_Date();
            data[i][4] = ScibookList.get(i).getSci_Kind();
            data[i][5] = ScibookList.get(i).getScientific_field();

        }
        return data;
    }

}
</code>```

Finally i have

```<code>public class ShowBooks extends JFrame {

    private Object[][] data;
    private String[] columnNames = {"Title", "Author", "Isbn", "Date", "Kind", "Field"};
    private DefaultTableModel tableModel;
    private JTable table;

    private LiteraryBookList myList1;
    private ScientificBookList myList2;

    public ShowBooks() {

        setBounds(10, 10, 400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myList1 = new LiteraryBookList();
        myList2 = new ScientificBookList();

        myList1.readFromTxt("test.txt");
        myList2.readFromTxt("test.txt");

        data = myList1.convert2Data();
        data = myList2.convert2Data();

        tableModel = new DefaultTableModel(data, columnNames);

        table = new JTable(tableModel);
        table.setAutoCreateRowSorter(true);
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setPreferredSize(new Dimension(380, 280));
        JPanel panel = new JPanel();
        panel.add(scrollPane);
        add(panel, BorderLayout.CENTER);
    }

}
</code>```

答:
This could be a dirty solution somewhat duplicating convert2Data methods which should not be called at all:

```<code>// prepare one large array to contain both types of books
data = new Object[myList1.getBooks().size() + myList2.getBooks().size()][6];

int row = 0;
// fill 2D array with scientific books' data
for (ScientificBook book : myList1.getBooks()) {
    data[row][0] = book.getSci_Title();
    data[row][1] = book.getSci_Author();
    data[row][2] = book.getSci_Isbn();
    data[row][3] = book.getSci_Date();
    data[row][4] = book.getSci_Kind();
    data[row][5] = book.getScientific_field();
    row++;
}

// fill 2D array with literary books' data
for (LiteraryBook book : myList2.getBooks()) {
    data[row][0] = book.getTitle();
    data[row][1] = book.getAuthor();
    data[row][2] = book.getIsbn();
    data[row][3] = book.getDate();
    data[row][4] = book.getKind();
    data[row][5] = "";
    row++;
}
</code>```

Though it's highly recommended to redesign your classes and remove duplicated/ unnecessary code.

Title: How can join multiple arraylists

Body:
I have two different arraylists. In the first, there are vars (title,author,isbn,date,kind). In the second there are (title,author,isbn,date,kind,field) such as Strings. I dont use super class or subclass.Finally i want these arraylists to populate in common jtable
When i run the program with the first arraylist i take this result 1st_arraylist
When i run the program with the second arraylist i take this result
2st_arraylist
When i run the program both of two arraylists i take this result
both arraylists
I want to view both arraylists in one jtable
My code

public class LiteraryBookList {
        private ArrayList<LiteraryBook> LibookList;

        public LiteraryBookList() {
            LibookList = new ArrayList<LiteraryBook>();
        }

        public void add(LiteraryBook lb) {
            LibookList.add(lb);
        }

        public ArrayList<LiteraryBook> getBooks() {
            return LibookList;
        }

        public void readFromTxt(String filename) {
            File file = new File(filename);
            FileReader reader = null;
            try {
                reader = new FileReader(file);
            } catch (FileNotFoundException e) {
                System.exit(1);
            }
            BufferedReader infile = new BufferedReader(reader);
            String line = "";
            int counter = 0;
            String title = "";
            String author = "";
            String isbn = "";
            String date = "";
            String kind = "";

            try {
                while ((line = infile.readLine()) != null) {
                     if (line.isEmpty() || line.contains("1")) {
                        continue;
                     }
                    counter++;
                    if (counter == 1) {
                        title = line;
                    } else if (counter == 2) {
                        author = line;
                    } else if (counter == 3) {
                        isbn = line;
                    } else if (counter == 4) {
                        date = line;
                    } else if (counter == 5) {
                        kind = line;
                        LiteraryBook lb = new LiteraryBook(title, author, isbn, date, kind);
                        LibookList.add(lb);
                        counter = 0;

                    }

                }

            } catch (IOException ex) {
                Logger.getLogger(LiteraryBookList.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public Object[][] convert2Data() {
            Object[][] data = new Object[LibookList.size()][5];
            for (int i = 0; i < LibookList.size(); i++) {
                data[i][0] = LibookList.get(i).getTitle();
                data[i][1] = LibookList.get(i).getAuthor();
                data[i][2] = LibookList.get(i).getIsbn();
                data[i][3] = LibookList.get(i).getDate();
                data[i][4] = LibookList.get(i).getKind();
            }
            return data;
        }
    }

Also i have..

public class ScientificBookList {

    private ArrayList<ScientificBook> ScibookList;

    public ScientificBookList() {
        ScibookList = new ArrayList<ScientificBook>();
    }

    public void add(ScientificBook sb) {
        ScibookList.add(sb);
    }

    public ArrayList<ScientificBook> getBooks() {
        return ScibookList;
    }

    public void readFromTxt(String filename) {
        File file = new File(filename);
        FileReader reader = null;
        try {
            reader = new FileReader(file);
        } catch (FileNotFoundException e) {
            System.exit(1);
        }
        BufferedReader infile = new BufferedReader(reader);
        String line = "";
        int counter = 0;
        String sci_title = "";
        String sci_author = "";
        String sci_isbn = "";
        String sci_date = "";
        String sci_kind = "";
        String scientific_field = "";

        try {
            while ((line = infile.readLine()) != null) {
                if (line.isEmpty() || line.contains("2")) {
                    continue;
                }

                counter++;
                if (counter == 1) {
                    sci_title = line;
                } else if (counter == 2) {
                    sci_author = line;
                } else if (counter == 3) {
                    sci_isbn = line;
                } else if (counter == 4) {
                    sci_date = line;
                } else if (counter == 5) {
                    sci_kind = line;
                } else if (counter == 6) {
                    scientific_field = line;

                    ScientificBook sb = new ScientificBook(sci_title, sci_author, sci_isbn, sci_date, sci_kind,scientific_field);
                    ScibookList.add(sb);
                    counter = 0;

                }

            }

        } catch (IOException ex) {
            Logger.getLogger(LiteraryBookList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Object[][] convert2Data() {
        Object[][] data = new Object[ScibookList.size()][6];
        for (int i = 0; i < ScibookList.size(); i++) {
            data[i][0] = ScibookList.get(i).getSci_Title();
            data[i][1] = ScibookList.get(i).getSci_Author();
            data[i][2] = ScibookList.get(i).getSci_Isbn();
            data[i][3] = ScibookList.get(i).getSci_Date();
            data[i][4] = ScibookList.get(i).getSci_Kind();
            data[i][5] = ScibookList.get(i).getScientific_field();

        }
        return data;
    }

}

Finally i have

public class ShowBooks extends JFrame {

    private Object[][] data;
    private String[] columnNames = {"Title", "Author", "Isbn", "Date", "Kind", "Field"};
    private DefaultTableModel tableModel;
    private JTable table;

    private LiteraryBookList myList1;
    private ScientificBookList myList2;

    public ShowBooks() {

        setBounds(10, 10, 400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myList1 = new LiteraryBookList();
        myList2 = new ScientificBookList();

        myList1.readFromTxt("test.txt");
        myList2.readFromTxt("test.txt");

        data = myList1.convert2Data();
        data = myList2.convert2Data();

        tableModel = new DefaultTableModel(data, columnNames);

        table = new JTable(tableModel);
        table.setAutoCreateRowSorter(true);
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setPreferredSize(new Dimension(380, 280));
        JPanel panel = new JPanel();
        panel.add(scrollPane);
        add(panel, BorderLayout.CENTER);
    }

}

Body:
This could be a dirty solution somewhat duplicating convert2Data methods which should not be called at all:

// prepare one large array to contain both types of books
data = new Object[myList1.getBooks().size() + myList2.getBooks().size()][6];

int row = 0;
// fill 2D array with scientific books' data
for (ScientificBook book : myList1.getBooks()) {
    data[row][0] = book.getSci_Title();
    data[row][1] = book.getSci_Author();
    data[row][2] = book.getSci_Isbn();
    data[row][3] = book.getSci_Date();
    data[row][4] = book.getSci_Kind();
    data[row][5] = book.getScientific_field();
    row++;
}

// fill 2D array with literary books' data
for (LiteraryBook book : myList2.getBooks()) {
    data[row][0] = book.getTitle();
    data[row][1] = book.getAuthor();
    data[row][2] = book.getIsbn();
    data[row][3] = book.getDate();
    data[row][4] = book.getKind();
    data[row][5] = "";
    row++;
}

Though it's highly recommended to redesign your classes and remove duplicated/ unnecessary code.


问:
Correct modification of state arrays in React.js
I want to add an element to the end of a state array, is this the correct way to do it?

```<code>this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });
</code>```

I'm concerned that modifying the array in-place with push might cause trouble - is it safe?

The alternative of making a copy of the array, and setStateing that seems wasteful.

答:
Here's a 2020, Reactjs Hook example that I thought could help others. I am using it to add new rows to a Reactjs table. Let me know if I could improve on something.

Adding a new element to a functional state component:

Define the state data:

    const [data, setData] = useState([
        { id: 1, name: 'John', age: 16 },
        { id: 2, name: 'Jane', age: 22 },
        { id: 3, name: 'Josh', age: 21 }
    ]);
```

<p>Have a button trigger a function to add a new element</p>

<pre class="lang-js prettyprint-override"><code><Button
    // pass the current state data to the handleAdd function so we can append to it.
    onClick={() => handleAdd(data)}>
    Add a row
</Button>
</code>```

function handleAdd(currentData) {

        // return last data array element
        let lastDataObject = currentTableData[currentTableData.length - 1]

        // assign last elements ID to a variable.
        let lastID = Object.values(lastDataObject)[0]

        // build a new element with a new ID based off the last element in the array
        let newDataElement = {
            id: lastID + 1,
            name: 'Jill',
            age: 55,
        }

        // build a new state object
        const newStateData = [...currentData, newDataElement ]

        // update the state
        setData(newStateData);

        // print newly updated state
        for (const element of newStateData) {
            console.log('New Data: ' + Object.values(element).join(', '))
        }

}
```

Body:
I want to add an element to the end of a state array, is this the correct way to do it?

this.state.arrayvar.push(newelement);
this.setState({ arrayvar:this.state.arrayvar });

I'm concerned that modifying the array in-place with push might cause trouble - is it safe?

The alternative of making a copy of the array, and setStateing that seems wasteful.

Body:
Here's a 2020, Reactjs Hook example that I thought could help others. I am using it to add new rows to a Reactjs table. Let me know if I could improve on something.

Adding a new element to a functional state component:

Define the state data:

    const [data, setData] = useState([
        { id: 1, name: 'John', age: 16 },
        { id: 2, name: 'Jane', age: 22 },
        { id: 3, name: 'Josh', age: 21 }
    ]);

Have a button trigger a function to add a new element

<Button
    // pass the current state data to the handleAdd function so we can append to it.
    onClick={() => handleAdd(data)}>
    Add a row
</Button>

function handleAdd(currentData) {

        // return last data array element
        let lastDataObject = currentTableData[currentTableData.length - 1]

        // assign last elements ID to a variable.
        let lastID = Object.values(lastDataObject)[0]

        // build a new element with a new ID based off the last element in the array
        let newDataElement = {
            id: lastID + 1,
            name: 'Jill',
            age: 55,
        }

        // build a new state object
        const newStateData = [...currentData, newDataElement ]

        // update the state
        setData(newStateData);

        // print newly updated state
        for (const element of newStateData) {
            console.log('New Data: ' + Object.values(element).join(', '))
        }

}


问:
Laravel SQLSTATE[HY000] [1045] Access denied , using aws EC2 ubuntu
I done,

Connect mysql in terminal by root user which has grant access.

Run php artisan cache:clear && php artisan config:cache.

Created another user & give Grant access.

Connect SQLyog via SSH (using PEM file) & also create db & tables there.

env file multiple times check and typos also.

Still I can not able to receive success response from my API url.

my env files variable

```<code>DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=my_db_name
DB_USERNAME=root
DB_PASSWORD=my_secret_pw
</code>```

Please suggest me, what's the issue or missing something ?

答:
I have fixed this. When I found this question SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) . DB_HOST set to localhost

I have a same situation but didn't find this earlier.

Really thanks to all of them who contribute in above question.

"" (Double Quotes) matter, very!!!

Body:
I done,

Connect mysql in terminal by root user which has grant access.

Run php artisan cache:clear && php artisan config:cache.

Created another user & give Grant access.

Connect SQLyog via SSH (using PEM file) & also create db & tables there.

env file multiple times check and typos also.

Still I can not able to receive success response from my API url.

my env files variable

DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=my_db_name
DB_USERNAME=root
DB_PASSWORD=my_secret_pw

Please suggest me, what's the issue or missing something ?


问:
How to create a background image that is fit to height with blurred backdrop behind it
Is there any way to create a background-image that is fit to height with a blurred backdrop behind it using CSS? I'll use js if I have to (but don't want to).

Example:

答:
You can make it in many ways, but it will always require two images: one behind it blurred and another one on top.

Solution with just CSS (background-image) based on pseudo classes before/after :

.container {
  width: 500px;
  height: 250px;
  position: relative;
  overflow: hidden;
}

.container:before,
.container:after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  background: url(https://peach.blender.org/wp-content/uploads/poster_bunny_small.jpg);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain ;
}

.container:before {
  background-size: cover;
  filter: blur(10px);
  transform: scale(1.1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container"></div></code>```

Solution with two images :

.container {
  width: 500px;
  height: 250px;
  position: relative;
  overflow: hidden;
  text-align: center;
}

.bg {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: -1;
  filter: blur(10px);
  transform: scale(1.1);
}

.image {
  max-width: 100%;
  max-height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <img src="https://peach.blender.org/wp-content/uploads/poster_bunny_small.jpg" class="bg" />
  <img src="https://peach.blender.org/wp-content/uploads/poster_bunny_small.jpg" class="image" />
</div></code>```

Body:
You can make it in many ways, but it will always require two images: one behind it blurred and another one on top.

Solution with just CSS (background-image) based on pseudo classes before/after :

.container {
  width: 500px;
  height: 250px;
  position: relative;
  overflow: hidden;
}

.container:before,
.container:after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  background: url(https://peach.blender.org/wp-content/uploads/poster_bunny_small.jpg);
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain ;
}

.container:before {
  background-size: cover;
  filter: blur(10px);
  transform: scale(1.1);
}

<div class="container"></div>

Solution with two images :

.container {
  width: 500px;
  height: 250px;
  position: relative;
  overflow: hidden;
  text-align: center;
}

.bg {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: -1;
  filter: blur(10px);
  transform: scale(1.1);
}

.image {
  max-width: 100%;
  max-height: 100%;
}

<div class="container">
  <img src="https://peach.blender.org/wp-content/uploads/poster_bunny_small.jpg" class="bg" />
  <img src="https://peach.blender.org/wp-content/uploads/poster_bunny_small.jpg" class="image" />
</div>


问:
Condense multiple combobox coding on Microsoft Excel VBA
I'm trying to condense the following code. I'm thinking a loop function may work, but it also may not because of the difference in VBA item. Any insight?</p>

```<code>If CheckBox1.Value = True _
    Then
    Range("P" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("P" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox2.Value = True _
    Then
    Range("Q" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("Q" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox3.Value = True _
    Then
    Range("R" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("R" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox4.Value = True _
    Then
    Range("S" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("S" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox5.Value = True _
    Then
    Range("T" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("T" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox6.Value = True _
    Then
    Range("U" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("U" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox7.Value = True _
    Then
    Range("V" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("V" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox8.Value = True _
    Then
    Range("W" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("W" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox9.Value = True _
    Then
    Range("X" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("X" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox10.Value = True _
    Then
    Range("Y" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("Y" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox11.Value = True _
    Then
    Range("Z" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("Z" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox12.Value = True _
    Then
    Range("AA" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("AA" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox13.Value = True _
    Then
    Range("AB" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("AB" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox14.Value = True _
    Then
    Range("AC" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("AC" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If
</code>```

答:
Something like this:

```<code>Dim i As Long, ws As Worksheet
Set ws = ActiveSheet 'or whatever
For i = 1 To 14
    ws.Cells(Rows.Count, "P").Offset(0, i - 1).End(xlUp).Value = _
       IIf(Me.Controls("CheckBox" & i).Value = True, "Y", "N")
Next
</code>```

Shouldn't that .Offset(0, 0) be .Offset(1, 0) though?  Or you're just overwriting the value already there.

Body:
I'm trying to condense the following code. I'm thinking a loop function may work, but it also may not because of the difference in VBA item. Any insight?

If CheckBox1.Value = True _
    Then
    Range("P" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("P" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox2.Value = True _
    Then
    Range("Q" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("Q" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox3.Value = True _
    Then
    Range("R" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("R" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox4.Value = True _
    Then
    Range("S" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("S" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox5.Value = True _
    Then
    Range("T" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("T" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox6.Value = True _
    Then
    Range("U" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("U" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox7.Value = True _
    Then
    Range("V" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("V" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox8.Value = True _
    Then
    Range("W" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("W" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox9.Value = True _
    Then
    Range("X" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("X" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox10.Value = True _
    Then
    Range("Y" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("Y" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox11.Value = True _
    Then
    Range("Z" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("Z" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox12.Value = True _
    Then
    Range("AA" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("AA" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox13.Value = True _
    Then
    Range("AB" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("AB" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

If CheckBox14.Value = True _
    Then
    Range("AC" & Rows.Count).End(xlUp).Offset(0, 0).Value = "Y"
    Else
    Range("AC" & Rows.Count).End(xlUp).Offset(0, 0).Value = "N"
End If

Body:
Something like this:

Dim i As Long, ws As Worksheet
Set ws = ActiveSheet 'or whatever
For i = 1 To 14
    ws.Cells(Rows.Count, "P").Offset(0, i - 1).End(xlUp).Value = _
       IIf(Me.Controls("CheckBox" & i).Value = True, "Y", "N")
Next

Shouldn't that .Offset(0, 0) be .Offset(1, 0) though?  Or you're just overwriting the value already there.


问:
React Semantic UI - where documentation on form validation?
I have implemented some form validation in React Semantic UI based on some posts I found on SO - for example, the following:

```<code>     required={true}
     error={this.state.errors["macs"]}
</code>```

My question is, where are these the React Semantic UI documentation? I haven't had any luck finding it so far.

答:
https://react.semantic-ui.com/collections/form/ - specifically in the Form.Field prop.

Field Variations Required Field shows required in use

States Field Error Label shows the Field with the error property set to show a message with a pointer.

Form error state with Messages shows a Message that displays when the form is in an error state.

Body:
I have implemented some form validation in React Semantic UI based on some posts I found on SO - for example, the following:

     required={true}
     error={this.state.errors["macs"]}

My question is, where are these the React Semantic UI documentation? I haven't had any luck finding it so far.


问:
Django filter on prefetch related queryset
I'm using Django 2.2

I have many reverse related models to the User model and I want to get count from each model with different filters.

For example, I have a Relations model like

```<code>status = (
  ('Active', 'active')
  ('Inactive', 'inactive')
)

class Relation(models.Model):
  user = models.ForeignKey(User, related_name='relation')
  status = models.CharField(choices=status, default=ACTIVE)
</code>```

Now I want to get the count and the queryset for each status separately for the user. For that I have defined the model methods inside the User model

```<code>def get_relation():
  return self.relation.all()

def get_active_relation(self):
  return self.relation().filter(status='active')

def get_inactive_relation():
  return self.relation().filter(status='inactive')

def get_active_count():
  return self.get_active_relation().count()

def get_inactive_count():
  return self.get_inactive_relaiton().count()
</code>```

I have the user object as

```<code>user = User.objects.prefetch_related(
  'relation'
).get(pk=request.user.pk)
</code>```

Now when I get the count, it executes an extra query for that

```<code>user.get_active_count()
</code>```

How can I filter on the prefetch_related objects?

I found a use of lambda to get the max value from the prefetch_related in another SOF answer: https://stackoverflow.com/a/12609454/3719167

Is it possible to use lambda to filter the queryset as well?

答:
Have you tried filtering on the attributes of the relation?</p>

```<code>user = User.objects.prefetch_related(
    'relation'
).filter(
    relation__status='active'
).get(pk=request.user.pk)
</code>```

Body:
I'm using Django 2.2

I have many reverse related models to the User model and I want to get count from each model with different filters.

For example, I have a Relations model like

status = (
  ('Active', 'active')
  ('Inactive', 'inactive')
)

class Relation(models.Model):
  user = models.ForeignKey(User, related_name='relation')
  status = models.CharField(choices=status, default=ACTIVE)

Now I want to get the count and the queryset for each status separately for the user. For that I have defined the model methods inside the User model

def get_relation():
  return self.relation.all()

def get_active_relation(self):
  return self.relation().filter(status='active')

def get_inactive_relation():
  return self.relation().filter(status='inactive')

def get_active_count():
  return self.get_active_relation().count()

def get_inactive_count():
  return self.get_inactive_relaiton().count()

I have the user object as

user = User.objects.prefetch_related(
  'relation'
).get(pk=request.user.pk)

Now when I get the count, it executes an extra query for that

user.get_active_count()

How can I filter on the prefetch_related objects?

I found a use of lambda to get the max value from the prefetch_related in another SOF answer: https://stackoverflow.com/a/12609454/3719167

Is it possible to use lambda to filter the queryset as well?

Body:
Have you tried filtering on the attributes of the relation?

user = User.objects.prefetch_related(
    'relation'
).filter(
    relation__status='active'
).get(pk=request.user.pk)


问:
Android Image view border is not showing
I need to show an image border from network image. To test this in offline I have created a view with dummy image. but view shoing fine in android studio editor but in real device the image border is not showing.

this is my editor view

this is my device view

activity_test.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorViolet">

<ImageView
    android:id="@+id/theme"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@id/border_content"
    android:layout_alignTop="@+id/border_content"
    android:layout_alignRight="@id/border_content"
    android:layout_alignBottom="@id/border_content"
    android:src="@drawable/ic_image_border"
    android:scaleType="fitXY"/>

<FrameLayout
    android:id="@+id/border_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="4dp"
        android:background="@drawable/view_border_gradient"
        android:layout_margin="20dp">

        <LinearLayout
            android:id="@+id/background"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageView
            android:id="@+id/image"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="15dp"
            android:layout_marginTop="20dp"
            android:contentDescription="@string/content_desc"
            android:scaleType="fitXY"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:src="@drawable/img_default" />

        <ImageView
            android:id="@+id/aura"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="15dp"
            android:layout_marginTop="20dp"
            android:contentDescription="@string/content_desc"
            android:scaleType="fitXY"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:src="@drawable/img_default" />

        <ImageView
            android:id="@+id/badge"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_marginTop="10dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="30dp"
            android:contentDescription="@string/content_desc"
            android:scaleType="fitXY"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/charms"
            app:layout_constraintStart_toStartOf="@+id/image"
            app:layout_constraintTop_toBottomOf="@+id/image"
            android:src="@drawable/img_default" />

        <ImageView
            android:id="@+id/charms"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_below="@id/image"
            android:layout_marginStart="8dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="30dp"
            android:contentDescription="@string/content_desc"
            android:scaleType="fitXY"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="@+id/image"
            app:layout_constraintStart_toEndOf="@id/badge"
            app:layout_constraintTop_toBottomOf="@+id/image"
            android:src="@drawable/img_default" />

        <TextView
            android:id="@+id/badgeTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="@string/badge"
            android:textColor="@color/colorHint"
            android:textSize="9sp"
            app:layout_constraintEnd_toEndOf="@id/badge"
            app:layout_constraintStart_toStartOf="@id/badge"
            app:layout_constraintTop_toBottomOf="@+id/badge"
            tools:ignore="SmallSp" />

        <TextView
            android:id="@+id/charmTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="@string/charms"
            android:textColor="@color/colorHint"
            android:textSize="9sp"
            app:layout_constraintEnd_toEndOf="@id/charms"
            app:layout_constraintStart_toStartOf="@id/charms"
            app:layout_constraintTop_toBottomOf="@+id/charms"
            tools:ignore="SmallSp" />

        <ImageView
            android:id="@+id/close"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_margin="10dp"
            android:contentDescription="@string/content_desc"
            android:scaleType="fitXY"
            android:tint="@color/colorRed"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/ic_cancel" />

        <TextView
            android:id="@+id/userName"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginEnd="10dp"
            android:textColor="@color/colorFont"
            android:textSize="11sp"
            app:layout_constraintEnd_toStartOf="@+id/close"
            app:layout_constraintStart_toStartOf="@+id/addFriend"
            app:layout_constraintTop_toTopOf="parent"
            tools:ignore="SmallSp"
            android:text="UserName" />

        <TextView
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textColor="@color/colorFont"
            android:textSize="14sp"
            app:layout_constraintEnd_toEndOf="@id/viewProfile"
            app:layout_constraintStart_toStartOf="@+id/addFriend"
            app:layout_constraintTop_toBottomOf="@id/close"
            android:text="User Full Name"
            android:layout_marginTop="5dp"/>

        <RelativeLayout
            android:id="@+id/viewProfile"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:background="@drawable/view_round_sky"
            app:layout_constraintEnd_toEndOf="@id/addFriend"
            app:layout_constraintStart_toStartOf="@+id/addFriend"
            app:layout_constraintTop_toBottomOf="@+id/name">

            <ImageView
                android:id="@+id/imgViewProfile"
                android:layout_width="21dp"
                android:layout_height="15dp"
                android:layout_centerVertical="true"
                android:layout_margin="5dp"
                android:background="@drawable/view_round_white"
                android:contentDescription="@string/content_desc"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                app:srcCompat="@drawable/ic_profile_view" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toEndOf="@+id/imgViewProfile"
                android:paddingStart="5dp"
                android:paddingEnd="15dp"
                android:text="@string/view_profile"
                android:textColor="@color/colorWhite"
                android:textSize="12sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/addFriend"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="15dp"
            android:layout_marginTop="5dp"
            android:layout_marginEnd="15dp"
            android:background="@drawable/view_round_blue"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/image"
            app:layout_constraintTop_toBottomOf="@id/viewProfile">

            <ImageView
                android:id="@+id/imgViewProfileAdd"
                android:layout_width="21dp"
                android:layout_height="15dp"
                android:layout_centerVertical="true"
                android:layout_margin="5dp"
                android:background="@drawable/view_round_white"
                android:contentDescription="@string/content_desc"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                app:srcCompat="@drawable/ic_profile_add" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toEndOf="@+id/imgViewProfileAdd"
                android:paddingStart="5dp"
                android:paddingEnd="15dp"
                android:text="@string/add_as_friend"
                android:textColor="@color/colorWhite"
                android:textSize="12sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/message"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:background="@drawable/view_round_yellow"
            app:layout_constraintEnd_toEndOf="@id/addFriend"
            app:layout_constraintStart_toStartOf="@id/addFriend"
            app:layout_constraintTop_toBottomOf="@id/addFriend">

            <ImageView
                android:id="@+id/imgMessage"
                android:layout_width="21dp"
                android:layout_height="15dp"
                android:layout_centerVertical="true"
                android:layout_margin="5dp"
                android:background="@drawable/view_round_white"
                android:contentDescription="@string/content_desc"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                app:srcCompat="@drawable/ic_profile_message" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toEndOf="@+id/imgMessage"
                android:paddingStart="5dp"
                android:paddingEnd="15dp"
                android:text="@string/messages"
                android:textColor="@color/colorWhite"
                android:textSize="12sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/gift"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:background="@drawable/view_round_orange"
            app:layout_constraintEnd_toEndOf="@id/addFriend"
            app:layout_constraintStart_toStartOf="@id/addFriend"
            app:layout_constraintTop_toBottomOf="@id/message">

            <ImageView
                android:id="@+id/imgGift"
                android:layout_width="21dp"
                android:layout_height="15dp"
                android:layout_centerVertical="true"
                android:layout_margin="5dp"
                android:background="@drawable/view_round_white"
                android:contentDescription="@string/content_desc"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                app:srcCompat="@drawable/ic_profile_gift" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toEndOf="@+id/imgGift"
                android:paddingStart="5dp"
                android:paddingEnd="15dp"
                android:text="@string/gift"
                android:textColor="@color/colorWhite"
                android:textSize="12sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/block"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/view_round_red"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="@id/addFriend"
            app:layout_constraintStart_toStartOf="@id/addFriend"
            app:layout_constraintTop_toBottomOf="@id/gift">

            <ImageView
                android:id="@+id/imgBlock"
                android:layout_width="21dp"
                android:layout_height="15dp"
                android:layout_centerVertical="true"
                android:layout_margin="5dp"
                android:background="@drawable/view_round_white"
                android:contentDescription="@string/content_desc"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                app:srcCompat="@drawable/ic_profile_black" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toEndOf="@+id/imgBlock"
                android:paddingStart="5dp"
                android:paddingEnd="15dp"
                android:text="@string/block"
                android:textColor="@color/colorWhite"
                android:textSize="12sp" />
        </RelativeLayout>

        <androidx.constraintlayout.widget.Group
            android:id="@+id/groupButton"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:constraint_referenced_ids="addFriend,message,gift,block" />

        <androidx.constraintlayout.widget.Group
            android:id="@+id/badge_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="visible"
            app:constraint_referenced_ids="badgeTitle,badge"
            tools:layout_editor_absoluteX="4dp"
            tools:layout_editor_absoluteY="4dp"
            tools:visibility="visible" />

        <androidx.constraintlayout.widget.Group
            android:id="@+id/charms_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="visible"
            app:constraint_referenced_ids="charms,charmTitle"
            tools:layout_editor_absoluteX="4dp"
            tools:layout_editor_absoluteY="4dp"
            tools:visibility="visible" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    </FrameLayout>
    </RelativeLayout>
</code>```

Test.java

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
}
</code>```

}

this is the Border image file to used in the layout file

答: Glide cache is causing the problem. It is now fixed after restarting the app</p>

Body:
I need to show an image border from network image. To test this in offline I have created a view with dummy image. but view shoing fine in android studio editor but in real device the image border is not showing.

this is my editor view

this is my device view

activity_test.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorViolet">

<ImageView
    android:id="@+id/theme"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@id/border_content"
    android:layout_alignTop="@+id/border_content"
    android:layout_alignRight="@id/border_content"
    android:layout_alignBottom="@id/border_content"
    android:src="@drawable/ic_image_border"
    android:scaleType="fitXY"/>

<FrameLayout
    android:id="@+id/border_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="4dp"
        android:background="@drawable/view_border_gradient"
        android:layout_margin="20dp">

        <LinearLayout
            android:id="@+id/background"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageView
            android:id="@+id/image"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="15dp"
            android:layout_marginTop="20dp"
            android:contentDescription="@string/content_desc"
            android:scaleType="fitXY"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:src="@drawable/img_default" />

        <ImageView
            android:id="@+id/aura"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="15dp"
            android:layout_marginTop="20dp"
            android:contentDescription="@string/content_desc"
            android:scaleType="fitXY"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:src="@drawable/img_default" />

        <ImageView
            android:id="@+id/badge"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_marginTop="10dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="30dp"
            android:contentDescription="@string/content_desc"
            android:scaleType="fitXY"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/charms"
            app:layout_constraintStart_toStartOf="@+id/image"
            app:layout_constraintTop_toBottomOf="@+id/image"
            android:src="@drawable/img_default" />

        <ImageView
            android:id="@+id/charms"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_below="@id/image"
            android:layout_marginStart="8dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="30dp"
            android:contentDescription="@string/content_desc"
            android:scaleType="fitXY"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="@+id/image"
            app:layout_constraintStart_toEndOf="@id/badge"
            app:layout_constraintTop_toBottomOf="@+id/image"
            android:src="@drawable/img_default" />

        <TextView
            android:id="@+id/badgeTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="@string/badge"
            android:textColor="@color/colorHint"
            android:textSize="9sp"
            app:layout_constraintEnd_toEndOf="@id/badge"
            app:layout_constraintStart_toStartOf="@id/badge"
            app:layout_constraintTop_toBottomOf="@+id/badge"
            tools:ignore="SmallSp" />

        <TextView
            android:id="@+id/charmTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="@string/charms"
            android:textColor="@color/colorHint"
            android:textSize="9sp"
            app:layout_constraintEnd_toEndOf="@id/charms"
            app:layout_constraintStart_toStartOf="@id/charms"
            app:layout_constraintTop_toBottomOf="@+id/charms"
            tools:ignore="SmallSp" />

        <ImageView
            android:id="@+id/close"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_margin="10dp"
            android:contentDescription="@string/content_desc"
            android:scaleType="fitXY"
            android:tint="@color/colorRed"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/ic_cancel" />

        <TextView
            android:id="@+id/userName"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginEnd="10dp"
            android:textColor="@color/colorFont"
            android:textSize="11sp"
            app:layout_constraintEnd_toStartOf="@+id/close"
            app:layout_constraintStart_toStartOf="@+id/addFriend"
            app:layout_constraintTop_toTopOf="parent"
            tools:ignore="SmallSp"
            android:text="UserName" />

        <TextView
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textColor="@color/colorFont"
            android:textSize="14sp"
            app:layout_constraintEnd_toEndOf="@id/viewProfile"
            app:layout_constraintStart_toStartOf="@+id/addFriend"
            app:layout_constraintTop_toBottomOf="@id/close"
            android:text="User Full Name"
            android:layout_marginTop="5dp"/>

        <RelativeLayout
            android:id="@+id/viewProfile"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:background="@drawable/view_round_sky"
            app:layout_constraintEnd_toEndOf="@id/addFriend"
            app:layout_constraintStart_toStartOf="@+id/addFriend"
            app:layout_constraintTop_toBottomOf="@+id/name">

            <ImageView
                android:id="@+id/imgViewProfile"
                android:layout_width="21dp"
                android:layout_height="15dp"
                android:layout_centerVertical="true"
                android:layout_margin="5dp"
                android:background="@drawable/view_round_white"
                android:contentDescription="@string/content_desc"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                app:srcCompat="@drawable/ic_profile_view" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toEndOf="@+id/imgViewProfile"
                android:paddingStart="5dp"
                android:paddingEnd="15dp"
                android:text="@string/view_profile"
                android:textColor="@color/colorWhite"
                android:textSize="12sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/addFriend"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="15dp"
            android:layout_marginTop="5dp"
            android:layout_marginEnd="15dp"
            android:background="@drawable/view_round_blue"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/image"
            app:layout_constraintTop_toBottomOf="@id/viewProfile">

            <ImageView
                android:id="@+id/imgViewProfileAdd"
                android:layout_width="21dp"
                android:layout_height="15dp"
                android:layout_centerVertical="true"
                android:layout_margin="5dp"
                android:background="@drawable/view_round_white"
                android:contentDescription="@string/content_desc"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                app:srcCompat="@drawable/ic_profile_add" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toEndOf="@+id/imgViewProfileAdd"
                android:paddingStart="5dp"
                android:paddingEnd="15dp"
                android:text="@string/add_as_friend"
                android:textColor="@color/colorWhite"
                android:textSize="12sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/message"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:background="@drawable/view_round_yellow"
            app:layout_constraintEnd_toEndOf="@id/addFriend"
            app:layout_constraintStart_toStartOf="@id/addFriend"
            app:layout_constraintTop_toBottomOf="@id/addFriend">

            <ImageView
                android:id="@+id/imgMessage"
                android:layout_width="21dp"
                android:layout_height="15dp"
                android:layout_centerVertical="true"
                android:layout_margin="5dp"
                android:background="@drawable/view_round_white"
                android:contentDescription="@string/content_desc"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                app:srcCompat="@drawable/ic_profile_message" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toEndOf="@+id/imgMessage"
                android:paddingStart="5dp"
                android:paddingEnd="15dp"
                android:text="@string/messages"
                android:textColor="@color/colorWhite"
                android:textSize="12sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/gift"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:background="@drawable/view_round_orange"
            app:layout_constraintEnd_toEndOf="@id/addFriend"
            app:layout_constraintStart_toStartOf="@id/addFriend"
            app:layout_constraintTop_toBottomOf="@id/message">

            <ImageView
                android:id="@+id/imgGift"
                android:layout_width="21dp"
                android:layout_height="15dp"
                android:layout_centerVertical="true"
                android:layout_margin="5dp"
                android:background="@drawable/view_round_white"
                android:contentDescription="@string/content_desc"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                app:srcCompat="@drawable/ic_profile_gift" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toEndOf="@+id/imgGift"
                android:paddingStart="5dp"
                android:paddingEnd="15dp"
                android:text="@string/gift"
                android:textColor="@color/colorWhite"
                android:textSize="12sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/block"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/view_round_red"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="@id/addFriend"
            app:layout_constraintStart_toStartOf="@id/addFriend"
            app:layout_constraintTop_toBottomOf="@id/gift">

            <ImageView
                android:id="@+id/imgBlock"
                android:layout_width="21dp"
                android:layout_height="15dp"
                android:layout_centerVertical="true"
                android:layout_margin="5dp"
                android:background="@drawable/view_round_white"
                android:contentDescription="@string/content_desc"
                android:paddingStart="3dp"
                android:paddingEnd="3dp"
                app:srcCompat="@drawable/ic_profile_black" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_toEndOf="@+id/imgBlock"
                android:paddingStart="5dp"
                android:paddingEnd="15dp"
                android:text="@string/block"
                android:textColor="@color/colorWhite"
                android:textSize="12sp" />
        </RelativeLayout>

        <androidx.constraintlayout.widget.Group
            android:id="@+id/groupButton"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:constraint_referenced_ids="addFriend,message,gift,block" />

        <androidx.constraintlayout.widget.Group
            android:id="@+id/badge_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="visible"
            app:constraint_referenced_ids="badgeTitle,badge"
            tools:layout_editor_absoluteX="4dp"
            tools:layout_editor_absoluteY="4dp"
            tools:visibility="visible" />

        <androidx.constraintlayout.widget.Group
            android:id="@+id/charms_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="visible"
            app:constraint_referenced_ids="charms,charmTitle"
            tools:layout_editor_absoluteX="4dp"
            tools:layout_editor_absoluteY="4dp"
            tools:visibility="visible" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    </FrameLayout>
    </RelativeLayout>

Test.java

public class Test extends AppCompatActivity {

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

}

this is the Border image file to used in the layout file


问:
Round function is truncating zero at the end in Python
```<code>a = 0.02503
print(round(a,4))
</code>```

Output below when i run the above code in Python 3.0 editor.

```<code>output: 0.025
</code>```

But i want the output to be 0.0250, how to achieve this with proper rounding.

答:
It's a matter of the print formatting, not the rounding:

```<code>a = 0.02503
b = round(a,4)

print(b)          # 0.025
print(f'{b:.4f}') # 0.0250
</code>```

The print(f'{b:.4f}') prints b with for decimal places.

Body:
a = 0.02503
print(round(a,4))

Output below when i run the above code in Python 3.0 editor.

output: 0.025

But i want the output to be 0.0250, how to achieve this with proper rounding.

Body:
It's a matter of the print formatting, not the rounding:

a = 0.02503
b = round(a,4)

print(b)          # 0.025
print(f'{b:.4f}') # 0.0250

The print(f'{b:.4f}') prints b with for decimal places.