问:
Best way to accept multiple tcp clients?
I have a client/server infrastructure. At present they use a TcpClient and TcpListener to send a receive data between all the clients and server.

What I currently do is when data is received (on it's own thread), it is put in a queue for another thread to process in order to free the socket so it is ready and open to receive new data.

```<code>                // Enter the listening loop.
                while (true)
                {
                    Debug.WriteLine("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    using (client = server.AcceptTcpClient())
                    {
                        data = new List<byte>();

                        // Get a stream object for reading and writing
                        using (NetworkStream stream = client.GetStream())
                        {
                            // Loop to receive all the data sent by the client.
                            int length;

                            while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                            {
                                var copy = new byte[length];
                                Array.Copy(bytes, 0, copy, 0, length);
                                data.AddRange(copy);
                            }
                        }
                    }

                    receivedQueue.Add(data);
                }
</code>```

However I wanted to find out if there is a better way to do this. For example if there are 10 clients and they all want to send data to the server at the same time, one will get through while all the others will fail.Or if one client has a slow connection and hogs the socket all other communication will halt.

Is there not some way to be able to receive data from all clients at the same time and add the received data in the queue for processing when it has finished downloading?

答: You should use asynchronous socket programming to achieve this. Take a look at the example provided by MSDN. </p>

Body:
I have a client/server infrastructure. At present they use a TcpClient and TcpListener to send a receive data between all the clients and server.

What I currently do is when data is received (on it's own thread), it is put in a queue for another thread to process in order to free the socket so it is ready and open to receive new data.

                // Enter the listening loop.
                while (true)
                {
                    Debug.WriteLine("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    using (client = server.AcceptTcpClient())
                    {
                        data = new List<byte>();

                        // Get a stream object for reading and writing
                        using (NetworkStream stream = client.GetStream())
                        {
                            // Loop to receive all the data sent by the client.
                            int length;

                            while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                            {
                                var copy = new byte[length];
                                Array.Copy(bytes, 0, copy, 0, length);
                                data.AddRange(copy);
                            }
                        }
                    }

                    receivedQueue.Add(data);
                }

However I wanted to find out if there is a better way to do this. For example if there are 10 clients and they all want to send data to the server at the same time, one will get through while all the others will fail.Or if one client has a slow connection and hogs the socket all other communication will halt.

Is there not some way to be able to receive data from all clients at the same time and add the received data in the queue for processing when it has finished downloading?


来源: stackexchange

问:
Spring Data JPA (H2 database) is returning DDL error during table creation
I have a Spring boot application where I have H2 as database. I have just one entity which is User. When I run the application, I keep getting DDL errors when creating the table in memory. If I try to access the H2 console via the browser (localhost:8080/h2-console), it won't connect. I believe this is because the table wasn't created successfully.

So far, I have only added @Entity, @Id, @GeneratedValue annotations to my User entity. I even tried changing the fields name from (id,name) to (userId, userName) using @Column(name="user_id") / @Column(name="user_name") because I thought that id and name might be reserved words. However, I keep getting the same DDL errors

Error:

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in
SQL statement "DROP TABLE IF EXISTS USER[*] CASCADE "; expected
"identifier"; SQL statement: drop table if exists user CASCADE
[42001-206]

2022-01-21 14:28:13.618  WARN 20700 --- [  restartedMain]
o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget
encountered exception accepting command : Error executing DDL "create
table user (id integer not null, birth_date timestamp, name
varchar(255), primary key (id))" via JDBC Statement

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error
executing DDL "create table user (id integer not null, birth_date
timestamp, name varchar(255), primary key (id))" via JDBC Statement

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in
SQL statement "CREATE TABLE USER[*] (ID INTEGER NOT NULL, BIRTH_DATE
TIMESTAMP, NAME VARCHAR(255), PRIMARY KEY (ID))"; expected
"identifier"; SQL statement: create table user (id integer not null,
birth_date timestamp, name varchar(255), primary key (id)) [42001-206]
at
org.h2.message.DbException.getJdbcSQLException(DbException.java:521)
~[h2-2.0.206.jar:2.0.206]

User class

```<code>import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(description="some description here")
@Entity
public class User {
    @Id
    @GeneratedValue
    private Integer id;

    @Size(min=2, message="Name should have at least 2 characters")
    @ApiModelProperty(notes="Name should have at least 2 characters")
    private String name;

    @Past
    @ApiModelProperty(notes="Birthdate should be in the past")
    @Column(name="birth_date")
    private Date birthDate;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", birthDate=" + birthDate + "]";
    }

    public User() {}

    public User(Integer id, String name, Date birthDate) {
        super();
        this.id = id;
        this.name = name;
        this.birthDate = birthDate;
    }
}
</code>```

pom.xml dependency

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <!-- <version>2.6.2</version> -->
    <version>2.5.2</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.0.206</version>
    <scope>runtime</scope>
</dependency>
</code>```

application.properties

```<code>logging.level.org.springframework = info
spring.jackson.serialization.write-dates-as-timestamps=false
management.endpoints.web.exposure.include=*

spring.security.user.name=someusername
spring.security.user.password=somepassword

spring.jpa.show-sql=true
spring.h2.console.enabled=true
</code>```

答: i think table name "USER" is reserved. it would work if you change it to "_USER" or "CUSTOM_USER" by using @Table(name="") annotation.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a Spring boot application where I have H2 as database. I have just one entity which is User. When I run the application, I keep getting DDL errors when creating the table in memory. If I try to access the H2 console via the browser (localhost:8080/h2-console), it won't connect. I believe this is because the table wasn't created successfully.

So far, I have only added @Entity, @Id, @GeneratedValue annotations to my User entity. I even tried changing the fields name from (id,name) to (userId, userName) using @Column(name="user_id") / @Column(name="user_name") because I thought that id and name might be reserved words. However, I keep getting the same DDL errors

Error:

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in
SQL statement "DROP TABLE IF EXISTS USER[*] CASCADE "; expected
"identifier"; SQL statement: drop table if exists user CASCADE
[42001-206]

2022-01-21 14:28:13.618  WARN 20700 --- [  restartedMain]
o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget
encountered exception accepting command : Error executing DDL "create
table user (id integer not null, birth_date timestamp, name
varchar(255), primary key (id))" via JDBC Statement

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error
executing DDL "create table user (id integer not null, birth_date
timestamp, name varchar(255), primary key (id))" via JDBC Statement

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in
SQL statement "CREATE TABLE USER[*] (ID INTEGER NOT NULL, BIRTH_DATE
TIMESTAMP, NAME VARCHAR(255), PRIMARY KEY (ID))"; expected
"identifier"; SQL statement: create table user (id integer not null,
birth_date timestamp, name varchar(255), primary key (id)) [42001-206]
at
org.h2.message.DbException.getJdbcSQLException(DbException.java:521)
~[h2-2.0.206.jar:2.0.206]

User class

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(description="some description here")
@Entity
public class User {
    @Id
    @GeneratedValue
    private Integer id;

    @Size(min=2, message="Name should have at least 2 characters")
    @ApiModelProperty(notes="Name should have at least 2 characters")
    private String name;

    @Past
    @ApiModelProperty(notes="Birthdate should be in the past")
    @Column(name="birth_date")
    private Date birthDate;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", birthDate=" + birthDate + "]";
    }

    public User() {}

    public User(Integer id, String name, Date birthDate) {
        super();
        this.id = id;
        this.name = name;
        this.birthDate = birthDate;
    }
}

pom.xml dependency

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>

    <version>2.5.2</version>
    <relativePath />
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.0.206</version>
    <scope>runtime</scope>
</dependency>

application.properties

logging.level.org.springframework = info
spring.jackson.serialization.write-dates-as-timestamps=false
management.endpoints.web.exposure.include=*

spring.security.user.name=someusername
spring.security.user.password=somepassword

spring.jpa.show-sql=true
spring.h2.console.enabled=true


问:
Unable to install dplyr on R-4.0.5
Trying to install dplyr on R-4.0.5

When I do install.packages("dplyr"),

I get the following error,

```<code>Installing package into ‘C:/Users/Pragyaditya Das/Documents/R/win-library/4.0’
(as ‘lib’ is unspecified)
also installing the dependencies ‘purrr’, ‘generics’, ‘tidyselect’

  There is a binary version available but the source version is later:
      binary source needs_compilation
dplyr  1.0.5  1.0.6              TRUE

trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/purrr_0.3.4.zip'
Content type 'application/zip' length 429582 bytes (419 KB)
downloaded 419 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/generics_0.1.0.zip'
Content type 'application/zip' length 71044 bytes (69 KB)
downloaded 69 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/tidyselect_1.1.1.zip'
Content type 'application/zip' length 204234 bytes (199 KB)
downloaded 199 KB

package ‘purrr’ successfully unpacked and MD5 sums checked
package ‘generics’ successfully unpacked and MD5 sums checked
package ‘tidyselect’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\Pragyaditya Das\AppData\Local\Temp\RtmpOAwWYv\downloaded_packages
installing the source package ‘dplyr’

trying URL 'https://cran.rstudio.com/src/contrib/dplyr_1.0.6.tar.gz'
Content type 'application/x-gzip' length 954401 bytes (932 KB)
downloaded 932 KB

* installing *source* package 'dplyr' ...
** package 'dplyr' successfully unpacked and MD5 sums checked
** using staged installation
** libs

*** arch - i386
"c:/rtools40/mingw32/bin/"g++ -std=gnu++11  -I"C:/PROGRA~1/R/R-40~1.5/include" -DNDEBUG          -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign -c chop.cpp -o chop.o
sh: c:/rtools40/mingw32/bin/g++: No such file or directory
make: *** [C:/PROGRA~1/R/R-40~1.5/etc/i386/Makeconf:229: chop.o] Error 127
ERROR: compilation failed for package 'dplyr'
* removing 'C:/Users/Pragyaditya Das/Documents/R/win-library/4.0/dplyr'
Warning in install.packages :
  installation of package ‘dplyr’ had non-zero exit status

The downloaded source packages are in
    ‘C:\Users\Pragyaditya Das\AppData\Local\Temp\RtmpOAwWYv\downloaded_packages’
</code>```

Please help me. TIA.

答:
More specifically, rename C:\RTools to C:\RTools40
and rename C:\Rtools40\ming_w64 to C:\Rtools40\mingw64 (not sure this is necessary since the root folder is already renamed)

After these changes, I was able to install the dplyr package and load the library.

Title: Unable to install dplyr on R-4.0.5

Body:
Trying to install dplyr on R-4.0.5

When I do install.packages("dplyr"),

I get the following error,

Installing package into ‘C:/Users/Pragyaditya Das/Documents/R/win-library/4.0’
(as ‘lib’ is unspecified)
also installing the dependencies ‘purrr’, ‘generics’, ‘tidyselect’

  There is a binary version available but the source version is later:
      binary source needs_compilation
dplyr  1.0.5  1.0.6              TRUE

trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/purrr_0.3.4.zip'
Content type 'application/zip' length 429582 bytes (419 KB)
downloaded 419 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/generics_0.1.0.zip'
Content type 'application/zip' length 71044 bytes (69 KB)
downloaded 69 KB

trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/tidyselect_1.1.1.zip'
Content type 'application/zip' length 204234 bytes (199 KB)
downloaded 199 KB

package ‘purrr’ successfully unpacked and MD5 sums checked
package ‘generics’ successfully unpacked and MD5 sums checked
package ‘tidyselect’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\Pragyaditya Das\AppData\Local\Temp\RtmpOAwWYv\downloaded_packages
installing the source package ‘dplyr’

trying URL 'https://cran.rstudio.com/src/contrib/dplyr_1.0.6.tar.gz'
Content type 'application/x-gzip' length 954401 bytes (932 KB)
downloaded 932 KB

* installing *source* package 'dplyr' ...
** package 'dplyr' successfully unpacked and MD5 sums checked
** using staged installation
** libs

*** arch - i386
"c:/rtools40/mingw32/bin/"g++ -std=gnu++11  -I"C:/PROGRA~1/R/R-40~1.5/include" -DNDEBUG          -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign -c chop.cpp -o chop.o
sh: c:/rtools40/mingw32/bin/g++: No such file or directory
make: *** [C:/PROGRA~1/R/R-40~1.5/etc/i386/Makeconf:229: chop.o] Error 127
ERROR: compilation failed for package 'dplyr'
* removing 'C:/Users/Pragyaditya Das/Documents/R/win-library/4.0/dplyr'
Warning in install.packages :
  installation of package ‘dplyr’ had non-zero exit status

The downloaded source packages are in
    ‘C:\Users\Pragyaditya Das\AppData\Local\Temp\RtmpOAwWYv\downloaded_packages’

Please help me. TIA.


问:
How to encapsulate the H.264 bitstream of video file in C++
I'm trying to convert a video file (.mp4) to a Dicom file.

I have succeeded to do it by storing single images (one per frame of the video) in the Dicom,
but the result is a too large file, it's not good for me.

Instead I want to encapsulate the H.264 bitstream as it is stored in the video file, into the Dicom file.

I've tried to get the bytes of the file as follows:

```<code>std::ifstream inFile(file_name, std::ifstream::binary);

inFile.seekg(0, inFile.end);
std::streampos length = inFile.tellg();
inFile.seekg(0, inFile.beg);

std::vector<unsigned char> bytes(length);

inFile.read((char*)&bytes[0], length);
</code>```

but I think I have missed something like encapsulating for the read bytes because the result Dicom file was a black image.

In python I would use pydicom.encaps.encapsulate function for this purpose:

https://pydicom.github.io/pydicom/dev/reference/generated/pydicom.encaps.encapsulate.html

```<code>with open(videofile, 'rb') as f:
    dataset.PixelData = encapsulate([f.read()])
</code>```

Is there anything in C ++ that is equivalent to the encapsulate function?

or any different way to get the encapsulated pixel data of video at one stream and not frame by frame?

This is the code of initializing the Dcmdataset, using the bytes extracted:

```<code>VideoFileStream* vfs = new VideoFileStream();
vfs->setFilename(file_name);
if (!vfs->open())
    return false;

DcmDataset* dataset = new DcmDataset();
dataset->putAndInsertOFStringArray(DCM_SeriesInstanceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_SERIES_UID_ROOT));
dataset->putAndInsertOFStringArray(DCM_SOPInstanceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_INSTANCE_UID_ROOT));
dataset->putAndInsertOFStringArray(DCM_StudyInstanceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_STUDY_UID_ROOT));
dataset->putAndInsertOFStringArray(DCM_MediaStorageSOPInstanceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_UID_ROOT));
dataset->putAndInsertString(DCM_MediaStorageSOPClassUID, UID_VideoPhotographicImageStorage);
dataset->putAndInsertString(DCM_SOPClassUID, UID_VideoPhotographicImageStorage);
dataset->putAndInsertOFStringArray(DCM_TransferSyntaxUID, UID_MPEG4HighProfileLevel4_1TransferSyntax);
dataset->putAndInsertOFStringArray(DCM_PatientID, "987655");
dataset->putAndInsertOFStringArray(DCM_StudyDate, "20050509");
dataset->putAndInsertOFStringArray(DCM_Modality, "ES");
dataset->putAndInsertOFStringArray(DCM_PhotometricInterpretation, "YBR_PARTIAL_420");
dataset->putAndInsertUint16(DCM_SamplesPerPixel, 3);
dataset->putAndInsertUint16(DCM_BitsAllocated, 8);
dataset->putAndInsertUint16(DCM_BitsStored, 8);
dataset->putAndInsertUint16(DCM_HighBit, 7);
dataset->putAndInsertUint16(DCM_Rows, vfs->height());
dataset->putAndInsertUint16(DCM_Columns, vfs->width());
dataset->putAndInsertUint16(DCM_CineRate, vfs->framerate());
dataset->putAndInsertUint16(DCM_FrameTime, 1000.0 * 1 / vfs->framerate());
const Uint16* arr = new Uint16[]{ 0x18,0x00, 0x63, 0x10 };
dataset->putAndInsertUint16Array(DCM_FrameIncrementPointer, arr, 4);
dataset->putAndInsertString(DCM_NumberOfFrames, std::to_string(vfs->numFrames()).c_str());
dataset->putAndInsertOFStringArray(DCM_FrameOfReferenceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_UID_ROOT));
dataset->putAndInsertUint16(DCM_PixelRepresentation, 0);
dataset->putAndInsertUint16(DCM_PlanarConfiguration, 0);
dataset->putAndInsertOFStringArray(DCM_ImageType, "ORIGINAL");
dataset->putAndInsertOFStringArray(DCM_LossyImageCompression, "01");
dataset->putAndInsertOFStringArray(DCM_LossyImageCompressionMethod, "ISO_14496_10");
dataset->putAndInsertUint16(DCM_LossyImageCompressionRatio, 30);
dataset->putAndInsertUint8Array(DCM_PixelData, (const Uint8 *)bytes.data(), length);

DJ_RPLossy repParam;
dataset->chooseRepresentation(EXS_MPEG4HighProfileLevel4_1, &repParam);
dataset->updateOriginalXfer();

DcmFileFormat fileformat(dataset);
OFCondition status = fileformat.saveFile("C://temp//videoTest", EXS_LittleEndianExplicit);
</code>```

答:
The trick is to redirect the value of the attribute PixelData to a file stream. With this, the video is loaded in chunks and on demand (i.e. when the attribute is accessed).
But you have to create the whole structure explicitly, that is:

The Pixel Data element

The Pixel Sequence with...

...the offset table

...a single item containing the contents of the MPEG file

Code

```<code>// set length to the size of the video file
DcmInputFileStream dcmFileStream(videofile.c_str(), 0);
DcmPixelSequence* pixelSequence = new DcmPixelSequence(DCM_PixelSequenceTag));
DcmPixelItem* offsetTable = new DcmPixelItem(DCM_PixelItemTag);
pixelSequence->insert(offsetTable);
DcmPixelItem* frame = new DcmPixelItem(DCM_PixelItemTag);
frame->createValueFromTempFile(dcmFileStream.newFactory(), OFstatic_cast(Uint32, length), EBO_LittleEndian);
pixelSequence->insert(frame);
DcmPixelData* pixelData = new DcmPixeldata(DCM_PixelData);
pixelData->putOriginalRepresentation(EXS_MPEG4HighProfileLevel4_1, nullptr, pixelSequence);
dataset->insert(pixelData, true);
DcmFileFormat fileformat(dataset);
OFCondition status = fileformat.saveFile("C://temp//videoTest");
</code>```

Note that you "destroy" the compression if you save the file in VR Implicit Little Endian.

As mentioned above and obvious in the code, the whole MPEG file is wrapped into a single item in the PixelData. This is DICOM conformant but you may want to encapsulate single frames each in one item.

Note : No error handling presented here

Body:
I'm trying to convert a video file (.mp4) to a Dicom file.

I have succeeded to do it by storing single images (one per frame of the video) in the Dicom,
but the result is a too large file, it's not good for me.

Instead I want to encapsulate the H.264 bitstream as it is stored in the video file, into the Dicom file.

I've tried to get the bytes of the file as follows:

std::ifstream inFile(file_name, std::ifstream::binary);

inFile.seekg(0, inFile.end);
std::streampos length = inFile.tellg();
inFile.seekg(0, inFile.beg);

std::vector<unsigned char> bytes(length);

inFile.read((char*)&bytes[0], length);

but I think I have missed something like encapsulating for the read bytes because the result Dicom file was a black image.

In python I would use pydicom.encaps.encapsulate function for this purpose:

https://pydicom.github.io/pydicom/dev/reference/generated/pydicom.encaps.encapsulate.html

with open(videofile, 'rb') as f:
    dataset.PixelData = encapsulate([f.read()])

Is there anything in C ++ that is equivalent to the encapsulate function?

or any different way to get the encapsulated pixel data of video at one stream and not frame by frame?

This is the code of initializing the Dcmdataset, using the bytes extracted:

VideoFileStream* vfs = new VideoFileStream();
vfs->setFilename(file_name);
if (!vfs->open())
    return false;

DcmDataset* dataset = new DcmDataset();
dataset->putAndInsertOFStringArray(DCM_SeriesInstanceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_SERIES_UID_ROOT));
dataset->putAndInsertOFStringArray(DCM_SOPInstanceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_INSTANCE_UID_ROOT));
dataset->putAndInsertOFStringArray(DCM_StudyInstanceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_STUDY_UID_ROOT));
dataset->putAndInsertOFStringArray(DCM_MediaStorageSOPInstanceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_UID_ROOT));
dataset->putAndInsertString(DCM_MediaStorageSOPClassUID, UID_VideoPhotographicImageStorage);
dataset->putAndInsertString(DCM_SOPClassUID, UID_VideoPhotographicImageStorage);
dataset->putAndInsertOFStringArray(DCM_TransferSyntaxUID, UID_MPEG4HighProfileLevel4_1TransferSyntax);
dataset->putAndInsertOFStringArray(DCM_PatientID, "987655");
dataset->putAndInsertOFStringArray(DCM_StudyDate, "20050509");
dataset->putAndInsertOFStringArray(DCM_Modality, "ES");
dataset->putAndInsertOFStringArray(DCM_PhotometricInterpretation, "YBR_PARTIAL_420");
dataset->putAndInsertUint16(DCM_SamplesPerPixel, 3);
dataset->putAndInsertUint16(DCM_BitsAllocated, 8);
dataset->putAndInsertUint16(DCM_BitsStored, 8);
dataset->putAndInsertUint16(DCM_HighBit, 7);
dataset->putAndInsertUint16(DCM_Rows, vfs->height());
dataset->putAndInsertUint16(DCM_Columns, vfs->width());
dataset->putAndInsertUint16(DCM_CineRate, vfs->framerate());
dataset->putAndInsertUint16(DCM_FrameTime, 1000.0 * 1 / vfs->framerate());
const Uint16* arr = new Uint16[]{ 0x18,0x00, 0x63, 0x10 };
dataset->putAndInsertUint16Array(DCM_FrameIncrementPointer, arr, 4);
dataset->putAndInsertString(DCM_NumberOfFrames, std::to_string(vfs->numFrames()).c_str());
dataset->putAndInsertOFStringArray(DCM_FrameOfReferenceUID, dcmGenerateUniqueIdentifier(new char[100], SITE_UID_ROOT));
dataset->putAndInsertUint16(DCM_PixelRepresentation, 0);
dataset->putAndInsertUint16(DCM_PlanarConfiguration, 0);
dataset->putAndInsertOFStringArray(DCM_ImageType, "ORIGINAL");
dataset->putAndInsertOFStringArray(DCM_LossyImageCompression, "01");
dataset->putAndInsertOFStringArray(DCM_LossyImageCompressionMethod, "ISO_14496_10");
dataset->putAndInsertUint16(DCM_LossyImageCompressionRatio, 30);
dataset->putAndInsertUint8Array(DCM_PixelData, (const Uint8 *)bytes.data(), length);

DJ_RPLossy repParam;
dataset->chooseRepresentation(EXS_MPEG4HighProfileLevel4_1, &repParam);
dataset->updateOriginalXfer();

DcmFileFormat fileformat(dataset);
OFCondition status = fileformat.saveFile("C://temp//videoTest", EXS_LittleEndianExplicit);

Body:
The trick is to redirect the value of the attribute PixelData to a file stream. With this, the video is loaded in chunks and on demand (i.e. when the attribute is accessed).
But you have to create the whole structure explicitly, that is:

The Pixel Data element

The Pixel Sequence with...

...the offset table

...a single item containing the contents of the MPEG file

Code

// set length to the size of the video file
DcmInputFileStream dcmFileStream(videofile.c_str(), 0);
DcmPixelSequence* pixelSequence = new DcmPixelSequence(DCM_PixelSequenceTag));
DcmPixelItem* offsetTable = new DcmPixelItem(DCM_PixelItemTag);
pixelSequence->insert(offsetTable);
DcmPixelItem* frame = new DcmPixelItem(DCM_PixelItemTag);
frame->createValueFromTempFile(dcmFileStream.newFactory(), OFstatic_cast(Uint32, length), EBO_LittleEndian);
pixelSequence->insert(frame);
DcmPixelData* pixelData = new DcmPixeldata(DCM_PixelData);
pixelData->putOriginalRepresentation(EXS_MPEG4HighProfileLevel4_1, nullptr, pixelSequence);
dataset->insert(pixelData, true);
DcmFileFormat fileformat(dataset);
OFCondition status = fileformat.saveFile("C://temp//videoTest");

Note that you "destroy" the compression if you save the file in VR Implicit Little Endian.

As mentioned above and obvious in the code, the whole MPEG file is wrapped into a single item in the PixelData. This is DICOM conformant but you may want to encapsulate single frames each in one item.

Note : No error handling presented here


问:
CSS image in percentage sized container
I have the following code:

https://codepen.io/rctneil/pen/NWwGQyr?editors=1100

Basically my issue revolves around the .card-logo elements.

I will be putting a variety of logo images in this location.  I need them to be a maximum width of 50% of the parent card and a maximum height of 50% of the width of the parent card.

That itself wouldn't be too difficult, but I also need them to be less than that if the aspect of the image requires it.  Eg, if it's a portrait image then the height should be 50% of the width of the card but the width of the logo needs to just be whatever it ends up being naturally.

Any ideas?

答:
Here is my solution : https://codepen.io/Woralie/pen/dyZvzRP

You'll need to add a container for each logo image.

```<code>  .card-logo {
    position: absolute;
    display: block;
    max-width: 50%;
    max-height: 100%;
    margin-top: 0.75rem;
    padding: 0.75rem;
    background-color: white;
  }

  .card-logo-container {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    margin-top: -25%;
    margin-bottom: 0.75rem;
    padding: 25%;
    min-width: 100%;
  }
</code>```

The trick is to make the container position: relative with padding: 25% and the image position: absolute with max-width: 50%. The container's top and bottom paddings take 2*25% of the total width, so when its height is 0, the image's height at max-height: 100% takes a maximum of 50% of the container's total width.

Title: CSS image in percentage sized container

Body:
Here is my solution : https://codepen.io/Woralie/pen/dyZvzRP

You'll need to add a container for each logo image.

  .card-logo {
    position: absolute;
    display: block;
    max-width: 50%;
    max-height: 100%;
    margin-top: 0.75rem;
    padding: 0.75rem;
    background-color: white;
  }

  .card-logo-container {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    margin-top: -25%;
    margin-bottom: 0.75rem;
    padding: 25%;
    min-width: 100%;
  }

The trick is to make the container position: relative with padding: 25% and the image position: absolute with max-width: 50%. The container's top and bottom paddings take 2*25% of the total width, so when its height is 0, the image's height at max-height: 100% takes a maximum of 50% of the container's total width.


问:
How to get data from a child in Firebase Database?
I am struggling to get data from a child in my Database to settext in a TextView.

Here is my Database:
Database

I think the problem is that I don't have the Uid right after Ansatte but the name instead.
If I take away name, and just have Ansatte,Uid, and the rest of the data it works.

Here is my code for getting data:

```<code> databaseReference = FirebaseDatabase.getInstance("").getReference("Ansatte");
    btnadd = (findViewById(R.id.btn_leggtilansatt));

    mAuth = FirebaseAuth.getInstance();
    currentid = mAuth.getCurrentUser().getUid();

    tvtest = findViewById(R.id.tvtest);

    databaseReference.child(currentid).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {

            if (snapshot.exists()){
                String user = snapshot.child("name").getValue().toString();

                tvtest.setText(user);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
</code>```

And here is the code for storing:

```<code>private void add() {
    String name = editText1.getText().toString().trim();
    String email = editText2.getText().toString().trim();
    String storage = editText3.getText().toString().trim();
    String password = tv.getText().toString().trim();

    if (!TextUtils.isEmpty(name)){

        mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if (task.isSuccessful()){

                    Ansatt ansatt = new Ansatt (name, email, storage);

                    databaseAnsatt.child(name).child(mAuth.getUid()).setValue(ansatt);

                    Toast.makeText(getApplicationContext(), "Hei" , Toast.LENGTH_LONG).toString().trim();
                    Intent intent = new Intent(AddEmployeeActivity.this, MainActivity.class);
                    startActivity(intent);
                }
            }
        });

    }
</code>```

答:
To be able to get the value of the name field that exists under the following location:

```<code>root/Ansatte/Name/$uid
</code>```

Please use the following lines of code:

```<code>String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = db.child("Ansatte").child("Name").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            String name = snapshot.child("name").getValue(String.class);
            tvtest.setText(name);
            Log.d("TAG", name);
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});
</code>```

The result in the logcat will be:

```<code>name
</code>```

And this value will be also set to your tvtest TextView.

P.S. Don't forget to have set the proper security rules.

Body:
I am struggling to get data from a child in my Database to settext in a TextView.

Here is my Database:
Database

I think the problem is that I don't have the Uid right after Ansatte but the name instead.
If I take away name, and just have Ansatte,Uid, and the rest of the data it works.

Here is my code for getting data:

 databaseReference = FirebaseDatabase.getInstance("").getReference("Ansatte");
    btnadd = (findViewById(R.id.btn_leggtilansatt));

    mAuth = FirebaseAuth.getInstance();
    currentid = mAuth.getCurrentUser().getUid();

    tvtest = findViewById(R.id.tvtest);

    databaseReference.child(currentid).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {

            if (snapshot.exists()){
                String user = snapshot.child("name").getValue().toString();

                tvtest.setText(user);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

And here is the code for storing:

private void add() {
    String name = editText1.getText().toString().trim();
    String email = editText2.getText().toString().trim();
    String storage = editText3.getText().toString().trim();
    String password = tv.getText().toString().trim();

    if (!TextUtils.isEmpty(name)){

        mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if (task.isSuccessful()){

                    Ansatt ansatt = new Ansatt (name, email, storage);

                    databaseAnsatt.child(name).child(mAuth.getUid()).setValue(ansatt);

                    Toast.makeText(getApplicationContext(), "Hei" , Toast.LENGTH_LONG).toString().trim();
                    Intent intent = new Intent(AddEmployeeActivity.this, MainActivity.class);
                    startActivity(intent);
                }
            }
        });

    }

Body:
To be able to get the value of the name field that exists under the following location:

root/Ansatte/Name/$uid

Please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = db.child("Ansatte").child("Name").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            String name = snapshot.child("name").getValue(String.class);
            tvtest.setText(name);
            Log.d("TAG", name);
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

The result in the logcat will be:

name

And this value will be also set to your tvtest TextView.

P.S. Don't forget to have set the proper security rules.


问:
I am struggling to figure out how to compare the two instances in Java
My task is as follows:

Create a Java class called SalesPerson with following properties:

sales id - data type int

sales amount - data type double

Write a default constructor to initialize each of the properties.

Code getters and setters for each property.

In the main method, instantiate two instances of SalesPerson type.

Using setters, set the id and sales amount for each sales person. Then compare each sales person's sales amount and display the id of the sales person with higher sales amount.

I believe I have correctly written everything so far but I am at a loss for how to compare "amount1" and "amount2". The instructions I was given are pasted above if that helps at all. My current code is this:

```<code>public class SalesPerson {
    public int salesId;
    public double salesAmount;

    public SalesPerson() {
        salesId = 101;
        salesAmount = 1002.36;
    }

    public void setSalesId(int i) {
        salesId = i;
    }

    public void setSalesAmount(double a) {
        salesAmount = a;
    }

    public int getSalesId() {
        return salesId;
    }

    public double getSalesAmount() {
        return salesAmount;
    }

    public static void main(String[] args) {
        SalesPerson amount1 = new SalesPerson();
        SalesPerson amount2 = new SalesPerson();
        System.out.println("ID is: " + amount1.getSalesId());
        System.out.println("Sale amount is: " + amount1.getSalesAmount());
        amount2.setSalesId(254);
        amount2.setSalesAmount(1563.58);
        System.out.println("ID is: " + amount2.getSalesId());
        System.out.println("Sale amount is: " + amount2.getSalesAmount());
        if(amount2 > amount1) {

        }
    }
}
</code>```

答: You could write your code like that, but in order to compare to instances of the same class, that class must implement the Comparable interface. See here https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html. After doing so you will be able to store SalesPerson objects in sorted structures like TreeSet or TreeMap if need be.</p>

Body:
My task is as follows:

Create a Java class called SalesPerson with following properties:

sales id - data type int

sales amount - data type double

Write a default constructor to initialize each of the properties.

Code getters and setters for each property.

In the main method, instantiate two instances of SalesPerson type.

Using setters, set the id and sales amount for each sales person. Then compare each sales person's sales amount and display the id of the sales person with higher sales amount.

I believe I have correctly written everything so far but I am at a loss for how to compare "amount1" and "amount2". The instructions I was given are pasted above if that helps at all. My current code is this:

public class SalesPerson {
    public int salesId;
    public double salesAmount;

    public SalesPerson() {
        salesId = 101;
        salesAmount = 1002.36;
    }

    public void setSalesId(int i) {
        salesId = i;
    }

    public void setSalesAmount(double a) {
        salesAmount = a;
    }

    public int getSalesId() {
        return salesId;
    }

    public double getSalesAmount() {
        return salesAmount;
    }

    public static void main(String[] args) {
        SalesPerson amount1 = new SalesPerson();
        SalesPerson amount2 = new SalesPerson();
        System.out.println("ID is: " + amount1.getSalesId());
        System.out.println("Sale amount is: " + amount1.getSalesAmount());
        amount2.setSalesId(254);
        amount2.setSalesAmount(1563.58);
        System.out.println("ID is: " + amount2.getSalesId());
        System.out.println("Sale amount is: " + amount2.getSalesAmount());
        if(amount2 > amount1) {

        }
    }
}


问:
Sum two columns to a third one of DataGridView. How?
How can I sum the values of two dataGridView columns and store the result in a third column for each row ? </p>

答:
As you haven't given any code I am going to assume you are putting data straight into the DataGridView. As @Arun suggests below the calculations should be done in the underlying data layer then bind that to the DataGridView with a 'Binding Source'.

Are you using SQL? If so;

```<code>Select (Order.qty) as Quantity , (Product.Price) as Price,(Order.qty * Product.price) as             total from Order
Inner Join Product on Order.Pid = Product.PID
</code>```

Otherwise here are some useful links I found, sorry I don't have time to copy and paste in some content from these websites;

A GridView Control with Subtotals

DataTable.Compute Method

ContentLicense: CC BY-SA 3.0

Body:
As you haven't given any code I am going to assume you are putting data straight into the DataGridView. As @Arun suggests below the calculations should be done in the underlying data layer then bind that to the DataGridView with a 'Binding Source'.

Are you using SQL? If so;

Select (Order.qty) as Quantity , (Product.Price) as Price,(Order.qty * Product.price) as             total from Order
Inner Join Product on Order.Pid = Product.PID

Otherwise here are some useful links I found, sorry I don't have time to copy and paste in some content from these websites;

A GridView Control with Subtotals

DataTable.Compute Method


问:
how to get only one value from array data and convert it into comma separted values. using javascript without template literals
i have array data in the format given below

```<code>const data=  [
  {
    name: "productname",
    id: "1356",
    price: "0.00",
    category: "Health",
    position: "1",
    list: "New Products",
    stocklevel: "20",
    brand: "Health"
  },
  {
    name: "productname2",
    id: "5263",
    price: "0",
    category: "Hair",
    position: "2",
    list: "New Products",
    stocklevel: "",
    brand: "Hair"
  }]
</code>```

from this data i want only product name of each product by difference of product1 , product2.
for example i want the data in format of string by comma separated values like given below:-

```<code>product1name: "productname",
product2name: "productname2",
...
</code>```

i tried using map function but not able to take only one or two values from whole array data.
here is the code what i tried

```<code>    var dataByComa = '';

  var Values = data
  .map(function (p, i) {
    return Object.keys(data[i]).map(function (k) {
      return "prod" +" " + ": " + JSON.stringify(data[i][k]);
    });
  }).map(function (v) {
    return v.join(",\n"); });
  var commaValues = Values.join(",\n");
return commaValues;
</code>```

with this code i can able to convert array data into comma separated values but i want only productnames.

Note :- Without using template template literals.

答:
You can iterate through the data and assign the value to an external variable like this:</p>
```<code>    let finalData = {}
    data.forEach((item, index) => {
       finalData[`product${index+1}name`] = item.name
    })
</code>```

Body:
i have array data in the format given below

const data=  [
  {
    name: "productname",
    id: "1356",
    price: "0.00",
    category: "Health",
    position: "1",
    list: "New Products",
    stocklevel: "20",
    brand: "Health"
  },
  {
    name: "productname2",
    id: "5263",
    price: "0",
    category: "Hair",
    position: "2",
    list: "New Products",
    stocklevel: "",
    brand: "Hair"
  }]

from this data i want only product name of each product by difference of product1 , product2.
for example i want the data in format of string by comma separated values like given below:-

product1name: "productname",
product2name: "productname2",
...

i tried using map function but not able to take only one or two values from whole array data.
here is the code what i tried

    var dataByComa = '';

  var Values = data
  .map(function (p, i) {
    return Object.keys(data[i]).map(function (k) {
      return "prod" +" " + ": " + JSON.stringify(data[i][k]);
    });
  }).map(function (v) {
    return v.join(",\n"); });
  var commaValues = Values.join(",\n");
return commaValues;

with this code i can able to convert array data into comma separated values but i want only productnames.

Note :- Without using template template literals.

Body:
You can iterate through the data and assign the value to an external variable like this:

    let finalData = {}
    data.forEach((item, index) => {
       finalData[`product${index+1}name`] = item.name
    })


问:
React multiple checkbox with one check at a time
Hello I have question about how I can make user select one checkbox at a time. So for example, if there is three checkbox(none are selected when page loads) on react component and user select one checkbox, the other checkbox will not be checked unless user uncheck it. I am trying to use useref to make it to work... but seems like it is not working..

```<code>const refCheckBoxOne = useRef(null);
const refCheckBoxTwo = useRef(null);
const refCheckBoxThree = useRef(null);

const onchangefunction = (propertyname, value) => {

if(refcheckBoxOne.current.check){
refcheckBoxOne.current.check = false;
refcheckBoxOne.current.check = false;
}

}

<input id="one" ref={refCheckBoxOne} userefonchange={(e) => onchangefunction("checkboxOne",e.target.value) }/>
<input id="two" ref={refCheckBoxTwo} onchange={(e) => onchangefunction("checkboxTwo",e.target.value) }/>
<input id="three" ref={refCheckBoxThree} onchange={(e) => onchangefunction("checkboxThree",e.target.value) }/>
</code>```

I have tried many ways to do it... but cant get it to work. I would be really appreciated if anyone can give me an idea on how to approach this kind of issue.

Thank you

答:
If two items you can use this

```<code>const App = () => {
  const [checked, setChecked] = React.useState(false);
  const handleChange = () => {
    setChecked(!checked);
  };
  return (
    <div>
      <label>
        <input
          type="checkbox"
          checked={checked}
          onChange={handleChange}
        />
      </label>
    </div>
  );
};
</code>```

If multiple  value then use it

```<code>export default function App() {
  const [checkedState, setCheckedState] = useState(
    [false,false,false]
  );

  const handleOnChange = (position) => {
    const updatedCheckedState = checkedState.map((item, index) =>
     index === position ? !item : item
   );

   setCheckedState(updatedCheckedState);
};

return (
 <div className="App">
  <h3>Select Toppings</h3>
  <ul className="toppings-list">
        <li key=0>
          <div className="toppings-list-item">
            <div className="left-section">
              <input
                type="checkbox"
                id=`custom-checkbox-1`
                checked={checkedState[0]}
                onChange={() => handleOnChange(0)}
              />
            </div>
          </div>
        </li>
        <li key=1>
          <div className="toppings-list-item">
            <div className="left-section">
              <input
                type="checkbox"
                id=`custom-checkbox-1`
                checked={checkedState[1]}
                onChange={() => handleOnChange(1)}
              />
            </div>
          </div>
        </li>
        <li key=2>
          <div className="toppings-list-item">
            <div className="left-section">
              <input
                type="checkbox"
                id=`custom-checkbox-2`
                checked={checkedState[2]}
                onChange={() => handleOnChange(2)}
              />
            </div>
          </div>
        </li>
   </ul>
 </div>
</code>```

If you have any question , Comment below here .

Body:
Hello I have question about how I can make user select one checkbox at a time. So for example, if there is three checkbox(none are selected when page loads) on react component and user select one checkbox, the other checkbox will not be checked unless user uncheck it. I am trying to use useref to make it to work... but seems like it is not working..

const refCheckBoxOne = useRef(null);
const refCheckBoxTwo = useRef(null);
const refCheckBoxThree = useRef(null);

const onchangefunction = (propertyname, value) => {

if(refcheckBoxOne.current.check){
refcheckBoxOne.current.check = false;
refcheckBoxOne.current.check = false;
}

}

<input id="one" ref={refCheckBoxOne} userefonchange={(e) => onchangefunction("checkboxOne",e.target.value) }/>
<input id="two" ref={refCheckBoxTwo} onchange={(e) => onchangefunction("checkboxTwo",e.target.value) }/>
<input id="three" ref={refCheckBoxThree} onchange={(e) => onchangefunction("checkboxThree",e.target.value) }/>

I have tried many ways to do it... but cant get it to work. I would be really appreciated if anyone can give me an idea on how to approach this kind of issue.

Thank you

Body:
If two items you can use this

const App = () => {
  const [checked, setChecked] = React.useState(false);
  const handleChange = () => {
    setChecked(!checked);
  };
  return (
    <div>
      <label>
        <input
          type="checkbox"
          checked={checked}
          onChange={handleChange}
        />
      </label>
    </div>
  );
};

If multiple  value then use it

export default function App() {
  const [checkedState, setCheckedState] = useState(
    [false,false,false]
  );

  const handleOnChange = (position) => {
    const updatedCheckedState = checkedState.map((item, index) =>
     index === position ? !item : item
   );

   setCheckedState(updatedCheckedState);
};

return (
 <div className="App">
  <h3>Select Toppings</h3>
  <ul className="toppings-list">
        <li key=0>
          <div className="toppings-list-item">
            <div className="left-section">
              <input
                type="checkbox"
                id=`custom-checkbox-1`
                checked={checkedState[0]}
                onChange={() => handleOnChange(0)}
              />
            </div>
          </div>
        </li>
        <li key=1>
          <div className="toppings-list-item">
            <div className="left-section">
              <input
                type="checkbox"
                id=`custom-checkbox-1`
                checked={checkedState[1]}
                onChange={() => handleOnChange(1)}
              />
            </div>
          </div>
        </li>
        <li key=2>
          <div className="toppings-list-item">
            <div className="left-section">
              <input
                type="checkbox"
                id=`custom-checkbox-2`
                checked={checkedState[2]}
                onChange={() => handleOnChange(2)}
              />
            </div>
          </div>
        </li>
   </ul>
 </div>

If you have any question , Comment below here .


问:
Turns thousands of dummy variables into multinomial variable
I have a dataframe of the following sort:

```<code>    a<-c('q','w')
    b<-c(T,T)
    d<-c(F,F)
    .e<-c(T,F)
    .f<-c(F,F)
    .g<-c(F,T)
    h<-c(F,F)
    i<-c(F,T)
    j<-c(T,T)

    df<-data.frame(a,b,d,.e,.f,.g,h,i,j)
</code>```
```<code>      a    b     d    .e    .f    .g     h     i    j
    1 q TRUE FALSE  TRUE FALSE FALSE FALSE FALSE TRUE
    2 w TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE TRUE
</code>```

I want to turn all variables starting with periods at the start into a single multinomial variable called Index such that the second row would have a value 1 for the Index column, the third row would have a value 2, etc. :

```<code>df$Index<-c('e','g')
</code>```
```<code>  a    b     d    .e    .f    .g     h     i    j Index
1 q TRUE FALSE  TRUE FALSE FALSE FALSE FALSE TRUE     e
2 w TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE TRUE     g
</code>```

Although many rows can have a T for any of period-initial variable, each row can be T for only ONE period-initial variable.

If it were just a few items id do an ifelse statement:

df$Index <- ifelse(df$_10000, '10000',...

But there are 12000 of these. The names for all dummy variables begin with underscores, so I feel like there must be a better way. In pseudocode I would say something like:

```<code>for every row:
    for every column beginning with '_':
        if value == T:
            assign the name of the column without '_' to a Column 'Index'
</code>```

Thanks in advance

答:
Sample data:

df <- cbind(a = letters[1:10], b = LETTERS[1:10],
            data.frame(diag(10) == 1))
names(df)[-(1:2)] <- paste0("_", 1:10)
set.seed(42)
df <- df[sample(nrow(df)),]
head(df,3)
#    a b    _1    _2    _3    _4    _5    _6    _7    _8    _9   _10
# 1  a A  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# 5  e E FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
# 10 j J FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
```
<p>Execution:</p>
<pre class="lang-r prettyprint-override"><code>df$Index <- apply(subset(df, select = grepl("^_", names(df))), 1,
                  function(z) which(z)[1])
df
#    a b    _1    _2    _3    _4    _5    _6    _7    _8    _9   _10 Index
# 1  a A  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE     1
# 5  e E FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE     5
# 10 j J FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE    10
# 8  h H FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE     8
# 2  b B FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE     2
# 4  d D FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE     4
# 6  f F FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE     6
# 9  i I FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE     9
# 7  g G FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE     7
# 3  c C FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE     3
</code>```

If there are more than one TRUE in a row of _-columns, the first found will be used, the remainder silently ignored. If there are none, Index will be NA for that row.

Body:
I have a dataframe of the following sort:

    a<-c('q','w')
    b<-c(T,T)
    d<-c(F,F)
    .e<-c(T,F)
    .f<-c(F,F)
    .g<-c(F,T)
    h<-c(F,F)
    i<-c(F,T)
    j<-c(T,T)

    df<-data.frame(a,b,d,.e,.f,.g,h,i,j)

      a    b     d    .e    .f    .g     h     i    j
    1 q TRUE FALSE  TRUE FALSE FALSE FALSE FALSE TRUE
    2 w TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE TRUE

I want to turn all variables starting with periods at the start into a single multinomial variable called Index such that the second row would have a value 1 for the Index column, the third row would have a value 2, etc. :

df$Index<-c('e','g')

  a    b     d    .e    .f    .g     h     i    j Index
1 q TRUE FALSE  TRUE FALSE FALSE FALSE FALSE TRUE     e
2 w TRUE FALSE FALSE FALSE  TRUE FALSE  TRUE TRUE     g

Although many rows can have a T for any of period-initial variable, each row can be T for only ONE period-initial variable.

If it were just a few items id do an ifelse statement:

df$Index <- ifelse(df$_10000, '10000',...

But there are 12000 of these. The names for all dummy variables begin with underscores, so I feel like there must be a better way. In pseudocode I would say something like:

for every row:
    for every column beginning with '_':
        if value == T:
            assign the name of the column without '_' to a Column 'Index'

Thanks in advance

Body:
Sample data:

df <- cbind(a = letters[1:10], b = LETTERS[1:10],
            data.frame(diag(10) == 1))
names(df)[-(1:2)] <- paste0("_", 1:10)
set.seed(42)
df <- df[sample(nrow(df)),]
head(df,3)
#    a b    _1    _2    _3    _4    _5    _6    _7    _8    _9   _10
# 1  a A  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# 5  e E FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
# 10 j J FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE

Execution:

df$Index <- apply(subset(df, select = grepl("^_", names(df))), 1,
                  function(z) which(z)[1])
df
#    a b    _1    _2    _3    _4    _5    _6    _7    _8    _9   _10 Index
# 1  a A  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE     1
# 5  e E FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE     5
# 10 j J FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE    10
# 8  h H FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE     8
# 2  b B FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE     2
# 4  d D FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE     4
# 6  f F FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE     6
# 9  i I FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE     9
# 7  g G FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE     7
# 3  c C FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE     3

If there are more than one TRUE in a row of _-columns, the first found will be used, the remainder silently ignored. If there are none, Index will be NA for that row.


问:
problem understanding c++ namespace and using-declaration in terms of inheritance
```<code>struct A { int i; };
struct B: A {};
struct C: A {};
struct D: B, C {
    using B::i;
    void f() {
        i = 0;
    }
};
</code>```

It seems like I specified to use i from A from B, but compiler says

error: 'A' is an ambiguous base of 'D'

To be honest, I don't really understand what using B::i does. As far as I know, it brings i from namespace B, to namespace D. But does namespace B contain i because it inherits i from A, or is it only namespace A that contains i? If latter, why

```<code>//A, B, C is same with above
struct D: B, C {
    void f() {
        B::i = 0;
    }
};
</code>```

this just compiles with no problem?

As you can see, I'm confusing with whole concept of namespaces in terms of class inheritance. Can anyone explain how rules of namespaces, inheritance, etc. works with these examples?

答:
Keyword using got multiple meanings depending on context. And C++ class scope is a namespace in terms of name resolution, but is not exactly like a namespace - a statement which deserves attention. Using declaration in class scope is related to inheritance and inheritance isn't a namespace feature. On other hand, class scope cannot be expanded by later declarations while a namespace can be.

A using statement in a namespace scope can be a using-directive if used on a namespace, a using-declaration for namespace members and type alias and alias template declaration. In C++20 it can be used for enums.

A using in a class scope is a using-declaration and it refers to a name of base class member into derived class definition. This may allow to chance access mode, such as to expose a protected member of base class as a public member of derived. If the derived class already contains a member with the same name, parameter list and qualifications, the derived class member hides or overrides one that is introduced from the base class.

If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using C::C), all constructors of that base  are made visible.

Obviously for that the name it refers should be unambiguous, which isn't the case in your example. Class D contains class A twice, once as a base of class B and once as a base of class C. Fully qualified names for those will be B::A::i and C::A::i, shorthanded to B::i and C::i. Now there is a question: which of those your statement must be hiding and which one exposing as per what was said above? The C::A::i is a different name, so B::i is allowed to conflict with it. In addition to that, with all your access being default to public, any using-declaration in class-scope is superfluous.

If using is in a code block scope, it got same meaning as namespace using-declaration.

```<code>void f() {
    B::i = 0;
}
</code>```

would be same as

```<code>void f() {
    using B::i;
    i = 0;
}
</code>```

provided B is a namespace. B isn't a namespace and the second case would be ill-formed. QED, class scope isn't exactly a namespace.

Body:
struct A { int i; };
struct B: A {};
struct C: A {};
struct D: B, C {
    using B::i;
    void f() {
        i = 0;
    }
};

It seems like I specified to use i from A from B, but compiler says

error: 'A' is an ambiguous base of 'D'

To be honest, I don't really understand what using B::i does. As far as I know, it brings i from namespace B, to namespace D. But does namespace B contain i because it inherits i from A, or is it only namespace A that contains i? If latter, why

//A, B, C is same with above
struct D: B, C {
    void f() {
        B::i = 0;
    }
};

this just compiles with no problem?

As you can see, I'm confusing with whole concept of namespaces in terms of class inheritance. Can anyone explain how rules of namespaces, inheritance, etc. works with these examples?

Body:
Keyword using got multiple meanings depending on context. And C++ class scope is a namespace in terms of name resolution, but is not exactly like a namespace - a statement which deserves attention. Using declaration in class scope is related to inheritance and inheritance isn't a namespace feature. On other hand, class scope cannot be expanded by later declarations while a namespace can be.

A using statement in a namespace scope can be a using-directive if used on a namespace, a using-declaration for namespace members and type alias and alias template declaration. In C++20 it can be used for enums.

A using in a class scope is a using-declaration and it refers to a name of base class member into derived class definition. This may allow to chance access mode, such as to expose a protected member of base class as a public member of derived. If the derived class already contains a member with the same name, parameter list and qualifications, the derived class member hides or overrides one that is introduced from the base class.

If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using C::C), all constructors of that base  are made visible.

Obviously for that the name it refers should be unambiguous, which isn't the case in your example. Class D contains class A twice, once as a base of class B and once as a base of class C. Fully qualified names for those will be B::A::i and C::A::i, shorthanded to B::i and C::i. Now there is a question: which of those your statement must be hiding and which one exposing as per what was said above? The C::A::i is a different name, so B::i is allowed to conflict with it. In addition to that, with all your access being default to public, any using-declaration in class-scope is superfluous.

If using is in a code block scope, it got same meaning as namespace using-declaration.

void f() {
    B::i = 0;
}

would be same as

void f() {
    using B::i;
    i = 0;
}

provided B is a namespace. B isn't a namespace and the second case would be ill-formed. QED, class scope isn't exactly a namespace.


问:
Building different images for each environment with Gitlab-CI AutoDevOps
Dockerfiles accept ENV variables via --build-args. These vars are mandatory for NextJS, used for static pages (to call remote APIs) and are "Hard coded" within the built image.

Gitlab-CI AutoDevOps has an ENV var to pass these args (AUTO_DEVOPS_BUILD_IMAGE_EXTRA_ARGS). But this is only consumeable if you are using one environment/image. When multiple environments (staging and production) needed, the URLs differ (https://staging.exmpl.com and https://www.exmpl.com).

How do I have to modify the Gitlab AutoDevOps to have two different images built?

In the CI/CD Settings my AUTO_DEVOPS_BUILD_IMAGE_EXTRA_ARGS are set:

```<code>--build-arg=API_URL=https://staging.exmpl.at/backend --build-arg=NEXT_PUBLIC_API_URL=https://staging.exmpl.at/backend
# as well $NEXT_PUBLIC_API_URL is set there
</code>```

Currently this is my complete gitlab-ci.yml:

include:
  - template: Auto-DevOps.gitlab-ci.yml

# added vars for build
build:
  stage: build
  variables:
    API_URL: $NEXT_PUBLIC_API_URL
    NEXT_PUBLIC_API_URL: $NEXT_PUBLIC_API_URL

```

How can I build two images, without "leaving" AutoDevOps? I assume I have to customize the build stage.

Another idea is to create a second Git repository called production with production URL set for $NEXT_PUBLIC_API_URL:

Staging get build and runs tests.

if successful it gets published

Staging repo content will be copied to the production repo

Production repo gets build (with production URL) and tested and then published too

Then I have two images.

Has someone please a better idea?

Thank you in advance

答:
Maybe a couple way you can do this. It's pretty easy if you only care about the build job.

One way would be to make a second job which extends: from build

build:
  variables:
    MY_ENV: staging

build production:
  extends: build
  variables:
    MY_ENV: production
```
<p>Another way might be to add a <code>parallel:matrix:</code> key to the <code>build</code> job</p>
<pre class="lang-yaml prettyprint-override"><code>build:
  parallel:
    matrix:
      - MY_ENV: staging
      - MY_ENV: production
</code>```

Keep in mind, however, if any jobs downstream of build depends on its artifacts, you'll need to manage those as well.

For example:

build:
  variables:
    MY_ENV: staging

build production:
  extends: build
  variables:
    MY_ENV: production

# some other job inherited from a template that depends on `build`
# we also want two of these jobs for each environment
downstream:
  variables:
    MY_ENV: staging

# extend it for production
downstream production:
  extends: downstream
  dependencies:  # make sure we get artifacts from correct upstream build job
    - build production
  variables:
    MY_ENV: production
```

Body:
Dockerfiles accept ENV variables via --build-args. These vars are mandatory for NextJS, used for static pages (to call remote APIs) and are "Hard coded" within the built image.

Gitlab-CI AutoDevOps has an ENV var to pass these args (AUTO_DEVOPS_BUILD_IMAGE_EXTRA_ARGS). But this is only consumeable if you are using one environment/image. When multiple environments (staging and production) needed, the URLs differ (https://staging.exmpl.com and https://www.exmpl.com).

How do I have to modify the Gitlab AutoDevOps to have two different images built?

In the CI/CD Settings my AUTO_DEVOPS_BUILD_IMAGE_EXTRA_ARGS are set:

--build-arg=API_URL=https://staging.exmpl.at/backend --build-arg=NEXT_PUBLIC_API_URL=https://staging.exmpl.at/backend
# as well $NEXT_PUBLIC_API_URL is set there

Currently this is my complete gitlab-ci.yml:

include:
  - template: Auto-DevOps.gitlab-ci.yml

# added vars for build
build:
  stage: build
  variables:
    API_URL: $NEXT_PUBLIC_API_URL
    NEXT_PUBLIC_API_URL: $NEXT_PUBLIC_API_URL

How can I build two images, without "leaving" AutoDevOps? I assume I have to customize the build stage.

Another idea is to create a second Git repository called production with production URL set for $NEXT_PUBLIC_API_URL:

Staging get build and runs tests.

if successful it gets published

Staging repo content will be copied to the production repo

Production repo gets build (with production URL) and tested and then published too

Then I have two images.

Has someone please a better idea?

Thank you in advance

Body:
Maybe a couple way you can do this. It's pretty easy if you only care about the build job.

One way would be to make a second job which extends: from build

build:
  variables:
    MY_ENV: staging

build production:
  extends: build
  variables:
    MY_ENV: production

Another way might be to add a parallel:matrix: key to the build job

build:
  parallel:
    matrix:
      - MY_ENV: staging
      - MY_ENV: production

Keep in mind, however, if any jobs downstream of build depends on its artifacts, you'll need to manage those as well.

For example:

build:
  variables:
    MY_ENV: staging

build production:
  extends: build
  variables:
    MY_ENV: production

# some other job inherited from a template that depends on `build`
# we also want two of these jobs for each environment
downstream:
  variables:
    MY_ENV: staging

# extend it for production
downstream production:
  extends: downstream
  dependencies:  # make sure we get artifacts from correct upstream build job
    - build production
  variables:
    MY_ENV: production


问:
Is there a way to extend the Spring Actuator logger and invoke it from my own controller?
Is there a way to extend the Spring Actuator logger and invoke it from my own controller, so that I can do some security validations? For example, something like this:</p>
```<code>@RestController
public class MyLoggingController {

    @Autowired
    private ActuatorLogger logger; // not sure what the actual class name is

    @PostMapping("/loggers")
    public String setLoggeringLevel( @RequestBody String body ) {

        // do security validations

        // set logging level
        logger.setLoggingLevel( ... ); // not sure what the actual method signature is

        return response;
    }

}
</code>```

答:
Check out the actual implementation here.
You can change it according to your requirements. For example:

```<code>@Component
public class LoggingConfiguration {

    private final LoggingSystem loggingSystem;

    private final LoggerGroups loggerGroups;

    public LoggingConfiguration(LoggingSystem loggingSystem, LoggerGroups loggerGroups) {
        Assert.notNull(loggingSystem, "LoggingSystem must not be null");
        Assert.notNull(loggerGroups, "LoggerGroups must not be null");
        this.loggingSystem = loggingSystem;
        this.loggerGroups = loggerGroups;
    }

    public void configureLogLevel(String packageName, LogLevel configuredLevel) {
        Assert.notNull(packageName, "Name must not be empty");
        LoggerGroup group = loggerGroups.get(packageName);
        if (group != null && group.hasMembers()) {
            group.configureLogLevel(configuredLevel, loggingSystem::setLogLevel);
            return;
        }
        loggingSystem.setLogLevel(packageName, configuredLevel);
    }
}
</code>```

Now you can use the LoggingConfiguration's instance however you want.

```<code>@RestController
public class MyLoggingController {

    @Autowired
    private LoggingConfiguration loggingConfiguration;

    @PostMapping("/loggers")
    public String setLoggeringLevel( @RequestBody String body ) {

        // do security validations

        // set logging level
        loggingConfiguration.configureLogLevel( ... );

        return response;
    }

}
</code>```

Body:
Is there a way to extend the Spring Actuator logger and invoke it from my own controller, so that I can do some security validations? For example, something like this:

@RestController
public class MyLoggingController {

    @Autowired
    private ActuatorLogger logger; // not sure what the actual class name is

    @PostMapping("/loggers")
    public String setLoggeringLevel( @RequestBody String body ) {

        // do security validations

        // set logging level
        logger.setLoggingLevel( ... ); // not sure what the actual method signature is

        return response;
    }

}

Body:
Check out the actual implementation here.
You can change it according to your requirements. For example:

@Component
public class LoggingConfiguration {

    private final LoggingSystem loggingSystem;

    private final LoggerGroups loggerGroups;

    public LoggingConfiguration(LoggingSystem loggingSystem, LoggerGroups loggerGroups) {
        Assert.notNull(loggingSystem, "LoggingSystem must not be null");
        Assert.notNull(loggerGroups, "LoggerGroups must not be null");
        this.loggingSystem = loggingSystem;
        this.loggerGroups = loggerGroups;
    }

    public void configureLogLevel(String packageName, LogLevel configuredLevel) {
        Assert.notNull(packageName, "Name must not be empty");
        LoggerGroup group = loggerGroups.get(packageName);
        if (group != null && group.hasMembers()) {
            group.configureLogLevel(configuredLevel, loggingSystem::setLogLevel);
            return;
        }
        loggingSystem.setLogLevel(packageName, configuredLevel);
    }
}

Now you can use the LoggingConfiguration's instance however you want.

@RestController
public class MyLoggingController {

    @Autowired
    private LoggingConfiguration loggingConfiguration;

    @PostMapping("/loggers")
    public String setLoggeringLevel( @RequestBody String body ) {

        // do security validations

        // set logging level
        loggingConfiguration.configureLogLevel( ... );

        return response;
    }

}


问:
How to UICollectionReusableView stretch to Safe Area
I am trying to show HeaderView in my UICollectionView class and I use UICollectionReusableView class for that.

Actually I am showing HeaderView in my CollectionView but It does not reach to safe area.

I use auto layout programmatically and I wrote extension to do that.

Here is my class and extensions that I use in my code:

```<code>import Foundation
import UIKit

private let headerIdentifer = "HeaderCell"

class ProfileController: UICollectionViewController {
    //MARK: - Properties

    //MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        configureProfileCollectionView()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.isHidden = true

    }

    //MARK: - Helpers

    func configureProfileCollectionView() {
        collectionView.backgroundColor = .white
        collectionView.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifer)
    }
}

extension ProfileController {
    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifer, for: indexPath) as! HeaderView
        return header
    }
}

extension ProfileController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

        return CGSize(width: view.frame.width, height: 300)
    }
}

</code>```
```<code>import Foundation
import UIKit

class HeaderView: UICollectionReusableView {

    //MARK: - Properties

    private lazy var containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .systemBlue

        view.addSubview(backButton)
        backButton.anchor(top: view.topAnchor, left: view.leftAnchor,
                          paddingTop: 42, paddingLeft: 16)
        backButton.setDimensions(width: 30, height: 30)
        return view
    }()

    private lazy var backButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(UIImage(named: "baseline_arrow_back_white_24dp")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        return button
    }()

    //MARK: - Lifecyle
    override init(frame: CGRect) {

        super.init(frame: frame)

        addSubview(containerView)
        containerView.anchor(top: topAnchor, left: leftAnchor, right: rightAnchor, height: 108)

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK: - Selectors

    @objc func backButtonTapped() {

    }
}
</code>```
```<code>import UIKit

extension UIView {
    func anchor(top: NSLayoutYAxisAnchor? = nil,
                left: NSLayoutXAxisAnchor? = nil,
                bottom: NSLayoutYAxisAnchor? = nil,
                right: NSLayoutXAxisAnchor? = nil,
                paddingTop: CGFloat = 0,
                paddingLeft: CGFloat = 0,
                paddingBottom: CGFloat = 0,
                paddingRight: CGFloat = 0,
                width: CGFloat? = nil,
                height: CGFloat? = nil) {

        translatesAutoresizingMaskIntoConstraints = false

        if let top = top {
            topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
        }

        if let left = left {
            leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true
        }

        if let bottom = bottom {
            bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
        }

        if let right = right {
            rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
        }

        if let width = width {
            widthAnchor.constraint(equalToConstant: width).isActive = true
        }

        if let height = height {
            heightAnchor.constraint(equalToConstant: height).isActive = true
        }
    }

    func center(inView view: UIView, yConstant: CGFloat? = 0) {
        translatesAutoresizingMaskIntoConstraints = false
        centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: yConstant!).isActive = true
    }

    func centerX(inView view: UIView, topAnchor: NSLayoutYAxisAnchor? = nil, paddingTop: CGFloat? = 0) {
        translatesAutoresizingMaskIntoConstraints = false
        centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

        if let topAnchor = topAnchor {
            self.topAnchor.constraint(equalTo: topAnchor, constant: paddingTop!).isActive = true
        }
    }

    func centerY(inView view: UIView, leftAnchor: NSLayoutXAxisAnchor? = nil, paddingLeft: CGFloat? = nil, constant: CGFloat? = 0) {
        translatesAutoresizingMaskIntoConstraints = false

        centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: constant!).isActive = true

        if let leftAnchor = leftAnchor, let padding = paddingLeft {
            self.leftAnchor.constraint(equalTo: leftAnchor, constant: padding).isActive = true
        }
    }

    func setDimensions(width: CGFloat, height: CGFloat) {
        translatesAutoresizingMaskIntoConstraints = false
        widthAnchor.constraint(equalToConstant: width).isActive = true
        heightAnchor.constraint(equalToConstant: height).isActive = true
    }

    func addConstraintsToFillView(_ view: UIView) {
        translatesAutoresizingMaskIntoConstraints = false
        anchor(top: view.topAnchor, left: view.leftAnchor,
               bottom: view.bottomAnchor, right: view.rightAnchor)
    }

}
</code>```

答:
The UICollectionReusableView is set up fine I believe and I think an automatic inset is applied to the UICollectionView because of the safe area.

Try one of the two options below in your viewDidLoad and it might work

```<code>// Option 1
// Get the inset applied at the top and negate the applied inset
if let top
    = UIApplication.shared.windows.first?.safeAreaInsets.top
{
    collectionView.contentInset.top = -top
}

// Option 2
// Request the collection view to ignore the default behavior
// to add an inset for safe area
collectionView.contentInsetAdjustmentBehavior = .never
</code>```

Body:
I am trying to show HeaderView in my UICollectionView class and I use UICollectionReusableView class for that.

Actually I am showing HeaderView in my CollectionView but It does not reach to safe area.

I use auto layout programmatically and I wrote extension to do that.

Here is my class and extensions that I use in my code:

import Foundation
import UIKit

private let headerIdentifer = "HeaderCell"

class ProfileController: UICollectionViewController {
    //MARK: - Properties

    //MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        configureProfileCollectionView()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.isHidden = true

    }

    //MARK: - Helpers

    func configureProfileCollectionView() {
        collectionView.backgroundColor = .white
        collectionView.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifer)
    }
}

extension ProfileController {
    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifer, for: indexPath) as! HeaderView
        return header
    }
}

extension ProfileController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

        return CGSize(width: view.frame.width, height: 300)
    }
}

import Foundation
import UIKit

class HeaderView: UICollectionReusableView {

    //MARK: - Properties

    private lazy var containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .systemBlue

        view.addSubview(backButton)
        backButton.anchor(top: view.topAnchor, left: view.leftAnchor,
                          paddingTop: 42, paddingLeft: 16)
        backButton.setDimensions(width: 30, height: 30)
        return view
    }()

    private lazy var backButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(UIImage(named: "baseline_arrow_back_white_24dp")?.withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        return button
    }()

    //MARK: - Lifecyle
    override init(frame: CGRect) {

        super.init(frame: frame)

        addSubview(containerView)
        containerView.anchor(top: topAnchor, left: leftAnchor, right: rightAnchor, height: 108)

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK: - Selectors

    @objc func backButtonTapped() {

    }
}

import UIKit

extension UIView {
    func anchor(top: NSLayoutYAxisAnchor? = nil,
                left: NSLayoutXAxisAnchor? = nil,
                bottom: NSLayoutYAxisAnchor? = nil,
                right: NSLayoutXAxisAnchor? = nil,
                paddingTop: CGFloat = 0,
                paddingLeft: CGFloat = 0,
                paddingBottom: CGFloat = 0,
                paddingRight: CGFloat = 0,
                width: CGFloat? = nil,
                height: CGFloat? = nil) {

        translatesAutoresizingMaskIntoConstraints = false

        if let top = top {
            topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
        }

        if let left = left {
            leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true
        }

        if let bottom = bottom {
            bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
        }

        if let right = right {
            rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
        }

        if let width = width {
            widthAnchor.constraint(equalToConstant: width).isActive = true
        }

        if let height = height {
            heightAnchor.constraint(equalToConstant: height).isActive = true
        }
    }

    func center(inView view: UIView, yConstant: CGFloat? = 0) {
        translatesAutoresizingMaskIntoConstraints = false
        centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: yConstant!).isActive = true
    }

    func centerX(inView view: UIView, topAnchor: NSLayoutYAxisAnchor? = nil, paddingTop: CGFloat? = 0) {
        translatesAutoresizingMaskIntoConstraints = false
        centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

        if let topAnchor = topAnchor {
            self.topAnchor.constraint(equalTo: topAnchor, constant: paddingTop!).isActive = true
        }
    }

    func centerY(inView view: UIView, leftAnchor: NSLayoutXAxisAnchor? = nil, paddingLeft: CGFloat? = nil, constant: CGFloat? = 0) {
        translatesAutoresizingMaskIntoConstraints = false

        centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: constant!).isActive = true

        if let leftAnchor = leftAnchor, let padding = paddingLeft {
            self.leftAnchor.constraint(equalTo: leftAnchor, constant: padding).isActive = true
        }
    }

    func setDimensions(width: CGFloat, height: CGFloat) {
        translatesAutoresizingMaskIntoConstraints = false
        widthAnchor.constraint(equalToConstant: width).isActive = true
        heightAnchor.constraint(equalToConstant: height).isActive = true
    }

    func addConstraintsToFillView(_ view: UIView) {
        translatesAutoresizingMaskIntoConstraints = false
        anchor(top: view.topAnchor, left: view.leftAnchor,
               bottom: view.bottomAnchor, right: view.rightAnchor)
    }

}

Body:
The UICollectionReusableView is set up fine I believe and I think an automatic inset is applied to the UICollectionView because of the safe area.

Try one of the two options below in your viewDidLoad and it might work

// Option 1
// Get the inset applied at the top and negate the applied inset
if let top
    = UIApplication.shared.windows.first?.safeAreaInsets.top
{
    collectionView.contentInset.top = -top
}

// Option 2
// Request the collection view to ignore the default behavior
// to add an inset for safe area
collectionView.contentInsetAdjustmentBehavior = .never


问:
When i click the button , It taking another function than the actual clicked function
when i click adult button , href  should take me to link-1 and when i click adult and children button it should take me to link-2 , but which ever button i click it taking me to link-1 only , as im new to development , im unable to figure this out , can any one help me with this please , below i have added my html and script both , one more doubt is , when i give script from app.js windows.open is not working , it working only when i give from same html file , may i know why ?</p>
```<code><div class=" my-3">
                <a target="_blank" class="btn btn-outline-dark btn-h btn-block mx-2 btn-promo">
                  <button data-bs-toggle="modal" data-bs-target="#exampleModal" class="link-text" onclick="adult()">
                    Adult
                  </button>
                </a>
                <a target="_blank" class="btn btn-outline-dark btn-h btn-block mx-2 btn-promo">
                  <button data-bs-toggle="modal" data-bs-target="#exampleModal" class="link-text" onclick="adultChild()">
                  Adult & Child
                  </button>
                </a>
              </div>
</code>```
```<code><div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Redirecting Alert</h5>
            <button type="button" onclick="reload()" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            Now you are redirecting to our partner site. <br><br>

          </div>
        </div>
      </div>
    </div>
</code>```
```<code><!-- Adult button Script -->
  <script>
    setTimeout (function adult() {
      var win = window.open();
      win.location = "www.link-1.com", "_blank";
      win.opener = null;
      win.blur();
      window.focus();
    },7000,false)
  </script>

  <!-- Adult&children button Script -->
  <script>
    setTimeout (function adultChild() {
      var win = window.open();
      win.location = "www.link-2.com", "_blank";
      win.opener = null;
      win.blur();
      window.focus();
    },7000)
  </script>
</code>```

答:
```<code><div class=" my-3">
                <a target="_blank" class="btn btn-outline-dark btn-h btn-block mx-2 btn-promo">
                  <button data-bs-toggle="modal" data-bs-target="#exampleModal" class="link-text" onclick="adult()">
                    Adult
                  </button>
                </a>
                <a target="_blank" class="btn btn-outline-dark btn-h btn-block mx-2 btn-promo">
                  <button data-bs-toggle="modal" data-bs-target="#exampleModal" class="link-text" onclick="adultChild()">
                  Adult & Child
                  </button>
                </a>
              </div>

<script>
    function newadult(){
      var win = window.open();
      win.location = "www.link-1.com","_blank";
      win.opener = null;
      win.blur();
      window.focus();
    }

    function adult(){
      setTimeout(newadult,700)
    }

    function newadultChild(){
      var win = window.open();
      win.location = "www.link-2.com", "_blank";
      win.opener = null;
      win.blur();
      window.focus();
    }

    function adultChild(){
       setTimeout(newadultChild,700)
    }

  </script>
</code>```

Body:
when i click adult button , href  should take me to link-1 and when i click adult and children button it should take me to link-2 , but which ever button i click it taking me to link-1 only , as im new to development , im unable to figure this out , can any one help me with this please , below i have added my html and script both , one more doubt is , when i give script from app.js windows.open is not working , it working only when i give from same html file , may i know why ?

                  <button data-bs-toggle="modal" data-bs-target="#exampleModal" class="link-text" onclick="adult()">
                    Adult
                  </button>

                  <button data-bs-toggle="modal" data-bs-target="#exampleModal" class="link-text" onclick="adultChild()">
                  Adult & Child
                  </button>

Redirecting Alert

            <button type="button" onclick="reload()" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

            Now you are redirecting to our partner site.


问:
Error using Rangy - methods are not working in Angular5
Angular 4 and modules: Rangy
I followed the instructions above to import rangy. I want to use TextRange's function expand() in Rangy's documentation. However, I get the error Property 'expand' does not exist on type 'RangySelection'.

My code:

```<code>    import * as rangy from 'rangy'

    showSelectedText(){
      var selTxt = rangy.getSelection()*.expand()*;
      console.log('selTxt: '+selTxt);
}
</code>```

On console.log(rangy), I get:

console.log(rangy.getSelection()) gives as output

答:
As it is mentioned in this thread:
https://github.com/timdown/rangy/issues/136

The issue is fixed in new version.
yet if you still have issue try using it this way:

```<code>let expandWord = rangy.getSelection();
expandWord.expand("word", {
   trim: true
});
</code>```

Plus:
To avoid error message in angular2+. add its types as below.
try installing the types for Rangy:

npm install --save @types/rangy

Afterwards edit the index.d.ts file and add expand function to the types. in RangySelection Interface.

```<code>interface RangySelection extends Selection {
    nativeSelection: Selection;
    isBackwards(): boolean;
    refresh(checkForChanges?: boolean): any;
    toHtml(): string;
    getAllRanges(): RangyRange[];
    getRangeAt(idx: number): RangyRange;
    getNativeTextRange(): any;
    setSingleRange(range: RangyRange): any;
    setRanges(ranges: RangyRange[]): any;
    getBookmark(containerNode: Node): any;
    moveToBookmark(bookmark: Object): any;
    saveRanges(): Object;
    restoreRanges(saved: Object): any;
    saveCharacterRanges(containerNode: Node, opts?: any): Object;
    restoreCharacterRanges(containerNode: Node, characterRanges: Object, opts?: any): any;
    detach(): any;
    inspect(): string;
    move(units: string, count: number, opts?: any): number;
    //This One
    expand(session, unit?, expandOptions?);
}
</code>```

Body:
Angular 4 and modules: Rangy
I followed the instructions above to import rangy. I want to use TextRange's function expand() in Rangy's documentation. However, I get the error Property 'expand' does not exist on type 'RangySelection'.

My code:

    import * as rangy from 'rangy'

    showSelectedText(){
      var selTxt = rangy.getSelection()*.expand()*;
      console.log('selTxt: '+selTxt);
}

On console.log(rangy), I get:

console.log(rangy.getSelection()) gives as output

Body:
As it is mentioned in this thread:
https://github.com/timdown/rangy/issues/136

The issue is fixed in new version.
yet if you still have issue try using it this way:

let expandWord = rangy.getSelection();
expandWord.expand("word", {
   trim: true
});

Plus:
To avoid error message in angular2+. add its types as below.
try installing the types for Rangy:

npm install --save @types/rangy

Afterwards edit the index.d.ts file and add expand function to the types. in RangySelection Interface.

interface RangySelection extends Selection {
    nativeSelection: Selection;
    isBackwards(): boolean;
    refresh(checkForChanges?: boolean): any;
    toHtml(): string;
    getAllRanges(): RangyRange[];
    getRangeAt(idx: number): RangyRange;
    getNativeTextRange(): any;
    setSingleRange(range: RangyRange): any;
    setRanges(ranges: RangyRange[]): any;
    getBookmark(containerNode: Node): any;
    moveToBookmark(bookmark: Object): any;
    saveRanges(): Object;
    restoreRanges(saved: Object): any;
    saveCharacterRanges(containerNode: Node, opts?: any): Object;
    restoreCharacterRanges(containerNode: Node, characterRanges: Object, opts?: any): any;
    detach(): any;
    inspect(): string;
    move(units: string, count: number, opts?: any): number;
    //This One
    expand(session, unit?, expandOptions?);
}


问:
Generating C++/CLI pointer type via System.CodeDom
I generate C++/CLI code via System.CodeDom of .NET.

Recently, I had to create a C++/CLI method with a pointer, like int foo(char *data) , which turned out tricky.

System.CodeDom.CodeParameterDeclarationExpression(type, name) creates parameters  with handles(^) only, not poiters(*) and I can't find a way to do it.

How could it be done? Any clue is appreciated.

答:
Finally, I decide to use programmatically remove asterisk from the type, create CodeTypeReference for the type without asterisk and create variable with name, starting from the asterisk.

Another way is to create "ForceTypePassThrough" key for UserData dictionary of the type as follows:

```<code>CodeTypeReference tmpTypeRef = new CodeTypeReference("char *");
tmpTypeRef.UserData["ForceTypePassThrough"] = true;

CodeVariableDeclarationStatement tmpVarDecl = new CodeVariableDeclarationStatement(tmpTypeRef, "tmpData");
</code>```

This ways work.

ContentLicense: CC BY-SA 2.5

Body:
Finally, I decide to use programmatically remove asterisk from the type, create CodeTypeReference for the type without asterisk and create variable with name, starting from the asterisk.

Another way is to create "ForceTypePassThrough" key for UserData dictionary of the type as follows:

CodeTypeReference tmpTypeRef = new CodeTypeReference("char *");
tmpTypeRef.UserData["ForceTypePassThrough"] = true;

CodeVariableDeclarationStatement tmpVarDecl = new CodeVariableDeclarationStatement(tmpTypeRef, "tmpData");

This ways work.