问:
How to Save the Form Data With the user_id field to the Database with the JWT token in React?
I'm using Django, Django-Rest-Api, React, and Axios.

I trying to make the youtube clone web-app. So I made a create form with Title, Description, Video, and Image fields. And I need to add the user_id field.

It supposes to take the JWT token, and use it as an user_id in the user field.

JWT token of the glebapetenok@gmail.com user

This file is about video creation form.

// ...
// frontend/src/components/admin/create.js
import React, { useState } from 'react';
import axiosInstance from '../../axios';
import { useHistory } from 'react-router-dom';

export default function Create() {
    const history = useHistory();
    const initialFormData = Object.freeze({
        title: '',
        description: '',
    });

    const [videoData, updateFormData] = useState(initialFormData);
    const [videoimage, setVideoImage] = useState(null);
    const [videovideo, setVideoVideo] = useState(null);

    const handleChange = (e) => {
        if ([e.target.name] == 'image') {
            setVideoImage({
                image: e.target.files,
            });
            console.log(e.target.files);
        }
        if ([e.target.name] == 'video') {
            setVideoVideo({
                video: e.target.files,
            });
            console.log(e.target.files);
        }
        if ([e.target.name] == 'title') {
            updateFormData({
                ...videoData,
                [e.target.name]: e.target.value.trim(),
            });
        } else {
            updateFormData({
                ...videoData,
                [e.target.name]: e.target.value.trim(),
            });
        }
    };

    const handleSubmit = (e) => {
        const config = { headers: { 'Content-Type': 'multipart/form-data' } };
        const URL = 'http://127.0.0.1:8000/api/admin/create/';
        let formData = new FormData();
        formData.append('title', videoData.title);

        // default user_id seted to 1
        formData.append('user', 1);

        formData.append('description', videoData.description);
        formData.append('image', videoimage.image[0]);
        formData.append('video', videovideo.video[0]);
        axios
            .post(URL, formData, config)
            .then((res) => {
                console.log(res.data);
            })
            .catch((err) => console.log(err));
    };
```
<p>Here is the Api file with JWT settings in the frontend folder</p>
<pre class="lang-js prettyprint-override"><code>// frontend/src/axios.js
import axios from 'axios';

const baseURL = 'http://127.0.0.1:8000/api/';

const axiosInstance = axios.create({
    baseURL: baseURL,
    timeout: 5000,
    headers: {
        Authorization: localStorage.getItem('access_token')
            ? 'JWT ' + localStorage.getItem('access_token')
            : null,
        'Content-Type': 'application/json',
        accept: 'application/json',
    },
});

axiosInstance.interceptors.response.use(
    (response) => {
        return response;
    },
    async function (error) {
        const originalRequest = error.config;

        if (typeof error.response === 'undefined') {
            alert(
                'A server/network error occurred. ' +
                    'Looks like CORS might be the problem. ' +
                    'Sorry about this - we will get it fixed shortly.'
            );
            return Promise.reject(error);
        }

        if (
            error.response.status === 401 &&
            originalRequest.url === baseURL + 'token/refresh/'
        ) {
            window.location.href = '/login/';
            return Promise.reject(error);
        }

        if (
            error.response.data.code === 'token_not_valid' &&
            error.response.status === 401 &&
            error.response.statusText === 'Unauthorized'
        ) {
            const refreshToken = localStorage.getItem('refresh_token');

            if (refreshToken) {
                const tokenParts = JSON.parse(atob(refreshToken.split('.')[1]));

                // exp date in token is expressed in seconds, while now() returns milliseconds:
                const now = Math.ceil(Date.now() / 1000);
                console.log(tokenParts.exp);

                if (tokenParts.exp > now) {
                    return axiosInstance
                        .post('/token/refresh/', {
                            refresh: refreshToken,
                        })
                        .then((response) => {
                            localStorage.setItem('access_token', response.data.access);
                            localStorage.setItem('refresh_token', response.data.refresh);

                            axiosInstance.defaults.headers['Authorization'] =
                                'JWT ' + response.data.access;
                            originalRequest.headers['Authorization'] =
                                'JWT ' + response.data.access;

                            return axiosInstance(originalRequest);
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                } else {
                    console.log('Refresh token is expired', tokenParts.exp, now);
                    window.location.href = '/login/';
                }
            } else {
                console.log('Refresh token not available.');
                window.location.href = '/login/';
            }
        }

        // specific error handling done elsewhere
        return Promise.reject(error);
    }

);

export default axiosInstance;
</code>```

Body:
I'm using Django, Django-Rest-Api, React, and Axios.

I trying to make the youtube clone web-app. So I made a create form with Title, Description, Video, and Image fields. And I need to add the user_id field.

It supposes to take the JWT token, and use it as an user_id in the user field.

JWT token of the glebapetenok@gmail.com user

This file is about video creation form.

// ...
// frontend/src/components/admin/create.js
import React, { useState } from 'react';
import axiosInstance from '../../axios';
import { useHistory } from 'react-router-dom';

export default function Create() {
    const history = useHistory();
    const initialFormData = Object.freeze({
        title: '',
        description: '',
    });

    const [videoData, updateFormData] = useState(initialFormData);
    const [videoimage, setVideoImage] = useState(null);
    const [videovideo, setVideoVideo] = useState(null);

    const handleChange = (e) => {
        if ([e.target.name] == 'image') {
            setVideoImage({
                image: e.target.files,
            });
            console.log(e.target.files);
        }
        if ([e.target.name] == 'video') {
            setVideoVideo({
                video: e.target.files,
            });
            console.log(e.target.files);
        }
        if ([e.target.name] == 'title') {
            updateFormData({
                ...videoData,
                [e.target.name]: e.target.value.trim(),
            });
        } else {
            updateFormData({
                ...videoData,
                [e.target.name]: e.target.value.trim(),
            });
        }
    };

    const handleSubmit = (e) => {
        const config = { headers: { 'Content-Type': 'multipart/form-data' } };
        const URL = 'http://127.0.0.1:8000/api/admin/create/';
        let formData = new FormData();
        formData.append('title', videoData.title);

        // default user_id seted to 1
        formData.append('user', 1);

        formData.append('description', videoData.description);
        formData.append('image', videoimage.image[0]);
        formData.append('video', videovideo.video[0]);
        axios
            .post(URL, formData, config)
            .then((res) => {
                console.log(res.data);
            })
            .catch((err) => console.log(err));
    };

Here is the Api file with JWT settings in the frontend folder

// frontend/src/axios.js
import axios from 'axios';

const baseURL = 'http://127.0.0.1:8000/api/';

const axiosInstance = axios.create({
    baseURL: baseURL,
    timeout: 5000,
    headers: {
        Authorization: localStorage.getItem('access_token')
            ? 'JWT ' + localStorage.getItem('access_token')
            : null,
        'Content-Type': 'application/json',
        accept: 'application/json',
    },
});

axiosInstance.interceptors.response.use(
    (response) => {
        return response;
    },
    async function (error) {
        const originalRequest = error.config;

        if (typeof error.response === 'undefined') {
            alert(
                'A server/network error occurred. ' +
                    'Looks like CORS might be the problem. ' +
                    'Sorry about this - we will get it fixed shortly.'
            );
            return Promise.reject(error);
        }

        if (
            error.response.status === 401 &&
            originalRequest.url === baseURL + 'token/refresh/'
        ) {
            window.location.href = '/login/';
            return Promise.reject(error);
        }

        if (
            error.response.data.code === 'token_not_valid' &&
            error.response.status === 401 &&
            error.response.statusText === 'Unauthorized'
        ) {
            const refreshToken = localStorage.getItem('refresh_token');

            if (refreshToken) {
                const tokenParts = JSON.parse(atob(refreshToken.split('.')[1]));

                // exp date in token is expressed in seconds, while now() returns milliseconds:
                const now = Math.ceil(Date.now() / 1000);
                console.log(tokenParts.exp);

                if (tokenParts.exp > now) {
                    return axiosInstance
                        .post('/token/refresh/', {
                            refresh: refreshToken,
                        })
                        .then((response) => {
                            localStorage.setItem('access_token', response.data.access);
                            localStorage.setItem('refresh_token', response.data.refresh);

                            axiosInstance.defaults.headers['Authorization'] =
                                'JWT ' + response.data.access;
                            originalRequest.headers['Authorization'] =
                                'JWT ' + response.data.access;

                            return axiosInstance(originalRequest);
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                } else {
                    console.log('Refresh token is expired', tokenParts.exp, now);
                    window.location.href = '/login/';
                }
            } else {
                console.log('Refresh token not available.');
                window.location.href = '/login/';
            }
        }

        // specific error handling done elsewhere
        return Promise.reject(error);
    }

);

export default axiosInstance;


来源: stackexchange

问:
after upgrade angular versio10 to 13 Property 'msSaveOrOpenBlob' does not exist on type 'Navigator'
after upgrade angular versio10 to 13 , Its throwing error like this while running the application. Property 'msSaveOrOpenBlob' does not exist on type 'Navigator'.

I have upgrade the version 10 to 13 one by one but when its come to 13 throwing error , also the typescript version get upgraded and its now 4.6.4

ContentLicense: CC BY-SA 4.0


问:
How to output many to many in Java Spring boot JPA?
I have 2 entities Board and Tag. They have a many to many relationship joined by the table board_tag_table. When I add the tags to the board, it saves the correct pair id to the join table. However when I try to output the Board using Thymeleaf my tags show up as blank.

```<code>@Table(name="board_table")
public class Board {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String title;

    @ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinTable(name = "board_tag_table",
    joinColumns = {
            //primary key of Board
            @JoinColumn(name = "id", referencedColumnName = "id")
    },
    inverseJoinColumns = {
            //primary key of Tag
            @JoinColumn(name = "tag_id", referencedColumnName = "tag_id")
    })
    private Set<Tag> tags = new HashSet<>();

}
</code>```
```<code>@Table(name="tag_table")
public class Tag {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer tag_id;

    private String tagname;

    @JsonIgnore
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "tags")
    private Set<Board> boards = new HashSet<>();
}
</code>```
```<code><tr th:each="board : ${list}">
  <td th:text="${board.id}"></td>
  <td>
    <a  th:text="${board.title}" th:href="@{/board/view(id=${board.id})}"></a>
  </td>
  <td th:text="${board.tags}"> </td>
</code>```

I tried creating a seperate repository and entity for the join table but keep getting an error.

Body:
I have 2 entities Board and Tag. They have a many to many relationship joined by the table board_tag_table. When I add the tags to the board, it saves the correct pair id to the join table. However when I try to output the Board using Thymeleaf my tags show up as blank.

@Table(name="board_table")
public class Board {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String title;

    @ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinTable(name = "board_tag_table",
    joinColumns = {
            //primary key of Board
            @JoinColumn(name = "id", referencedColumnName = "id")
    },
    inverseJoinColumns = {
            //primary key of Tag
            @JoinColumn(name = "tag_id", referencedColumnName = "tag_id")
    })
    private Set<Tag> tags = new HashSet<>();

}

@Table(name="tag_table")
public class Tag {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer tag_id;

    private String tagname;

    @JsonIgnore
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "tags")
    private Set<Board> boards = new HashSet<>();
}

I tried creating a seperate repository and entity for the join table but keep getting an error.


问:
how to render from json file to UI?
```<code>The thing i want
</code>```
```<code><div className='cards'>
          {
           homes.map((home, index) => (
            <div className='card' key={index} onClick={() => togglePop(home)}>
              <div className='card__image'>

                <img src={home.image} alt="Home" />
              </div>
              <div className='card__info'>
                <h4>{home.attributes[0].value} ETH</h4>
                <p>
                  <strong>{home.attributes[2].value}</strong> bds |
                  <strong>{home.attributes[3].value}</strong> ba |
                  <strong>{home.attributes[4].value}</strong> sqft
                </p>
                <p>{home.address}</p>
              </div>
            </div>
           ))
          }
        </div>

      </div>

[enter image description here](https://i.stack.imgur.com/Lpffe.jpg)

</code>```

My website is currently

```<code>
[enter image description here](https://i.stack.imgur.com/BXq24.png)

</code>```

This is the source I got from youtube : https://github.com/dappuniversity/millow

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

I have no experience to do react js :((

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

Title: how to render from json file to UI?

Body:
The thing i want

          {
           homes.map((home, index) => (

 togglePop(home)}>

{home.attributes[0].value} ETH

                  {home.attributes[2].value} bds |
                  {home.attributes[3].value} ba |
                  {home.attributes[4].value} sqft

{home.address}

           ))
          }

[enter image description here](https://i.stack.imgur.com/Lpffe.jpg)

My website is currently

[enter image description here](https://i.stack.imgur.com/BXq24.png)

This is the source I got from youtube : https://github.com/dappuniversity/millow

I have no experience to do react js :((


问:
Junit test : Properties value are not resolved in Deserializer class
I'm writing some junit tests for my rest webservice. When I run my test, I got my response from the webservice. So I use objectMapper to map the json to my POJO class. However it fails on this line :

```<code>    return objectMapper.readValue(json, clazz);
</code>```

Error : com.fasterxml.jackson.databind.JsonMappingException: zoneId (through reference chain: com.customer.CustomerResponse["customerDetails"]->com.customer.CustomerDetails["licenseDate"])

This is because I'm using this annotation in my POJO class :                    @JsonDeserialize(using = CustomDateDeserializer.class) and in the Deserializer, I have a variable timezone , where the value is taken from properties file. It seems that the object Mapper is not able to resolve this properties in my Deserializer class :

@Value("${current.timezone}")
private String timezone;

Can you please help how to resolve this issue ? Thanks

```<code>@Transactional
@Rollback
class CustomerServiceIntegrationTest {

@Autowired
private DbUnitUtils dbUnitUtils;

protected MockMvc mvc;

@BeforeEach
void setup() throws Exception {
    mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@BeforeEach
void setupData() throws Exception {
    dbUnitUtils.initialiseDataSet(new File("src/test/resources/dbunit/test-dataset.xml"),
    DatabaseOperation.CLEAN_INSERT);
}

  @Test
void listCustomer_WhenIdExists_Then_ReturnCustomerInfo() throws Exception {

    /*
     * setup test-data
     */

    Long idCustomer= 15L;
    String uri = "/customer/" + 15L;

    /*
     * invoke endpoint being tested
     */
    MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON_VALUE))
            .andReturn();

    /*
     * Verification
     */

    int status = mvcResult.getResponse().getStatus();
    assertEquals(200, status);

    CustomerResponse customerResponse =
    mapFromJson(mvcResult.getResponse().getContentAsString(), CustomerResponse.class);
    assertEquals(idCustomer, customerResponse.getId());

}

protected <T> T mapFromJson(String json, Class<T> clazz)
        throws JsonParseException, JsonMappingException, IOException {

    ObjectMapper objectMapper = new ObjectMapper();
    SimpleModule module =
            new SimpleModule("CustomDateDeserializer", new Version(1, 0, 0, null, null, null));
    module.addDeserializer(ZonedDateTime.class, new CustomDateDeserializer());
    objectMapper.registerModule(module);

    return objectMapper.readValue(json, clazz);
}
}

public class CustomerResponse{

        String name;

        String address;

        String phoneNo;

        CustomerDetails customerDetails;

        //getter and setter
     }

     public class CustomerDetails {

            @JsonDeserialize(using = CustomDateDeserializer.class)
            @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = Utils.FORMAT_DATE)
            private ZonedDateTime licenseDate;
            //getter and setters

      }

     public class CustomDateDeserializer extends StdDeserializer<ZonedDateTime> {

            @Serial
            private static final long serialVersionUID = 1L;

            @Value("${current.timezone}")
            private String timezone;

            public CustomDateDeserializer () {
                   super((Class<?>) null);

            }

            protected CustomDateDeserializer (Class<?> vc) {
                    super(vc);
            }

            @Override
           public ZonedDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws
           IOException   {
                  String stringValue = p.getCodec().readValue(p, String.class);

                  if (StringUtils.isBlank(stringValue)) {
                     return null;
                  }

                  LocalDate localDate = LocalDate.parse(stringValue);
                  return localDate.atStartOfDay().atZone(ZoneId.of(timezone));
               }

            }

        }
</code>```

Body:
I'm writing some junit tests for my rest webservice. When I run my test, I got my response from the webservice. So I use objectMapper to map the json to my POJO class. However it fails on this line :

    return objectMapper.readValue(json, clazz);

Error : com.fasterxml.jackson.databind.JsonMappingException: zoneId (through reference chain: com.customer.CustomerResponse["customerDetails"]->com.customer.CustomerDetails["licenseDate"])

This is because I'm using this annotation in my POJO class :                    @JsonDeserialize(using = CustomDateDeserializer.class) and in the Deserializer, I have a variable timezone , where the value is taken from properties file. It seems that the object Mapper is not able to resolve this properties in my Deserializer class :

@Value("${current.timezone}")
private String timezone;

Can you please help how to resolve this issue ? Thanks

@Transactional
@Rollback
class CustomerServiceIntegrationTest {

@Autowired
private DbUnitUtils dbUnitUtils;

protected MockMvc mvc;

@BeforeEach
void setup() throws Exception {
    mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@BeforeEach
void setupData() throws Exception {
    dbUnitUtils.initialiseDataSet(new File("src/test/resources/dbunit/test-dataset.xml"),
    DatabaseOperation.CLEAN_INSERT);
}

  @Test
void listCustomer_WhenIdExists_Then_ReturnCustomerInfo() throws Exception {

    /*
     * setup test-data
     */

    Long idCustomer= 15L;
    String uri = "/customer/" + 15L;

    /*
     * invoke endpoint being tested
     */
    MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON_VALUE))
            .andReturn();

    /*
     * Verification
     */

    int status = mvcResult.getResponse().getStatus();
    assertEquals(200, status);

    CustomerResponse customerResponse =
    mapFromJson(mvcResult.getResponse().getContentAsString(), CustomerResponse.class);
    assertEquals(idCustomer, customerResponse.getId());

}

protected <T> T mapFromJson(String json, Class<T> clazz)
        throws JsonParseException, JsonMappingException, IOException {

    ObjectMapper objectMapper = new ObjectMapper();
    SimpleModule module =
            new SimpleModule("CustomDateDeserializer", new Version(1, 0, 0, null, null, null));
    module.addDeserializer(ZonedDateTime.class, new CustomDateDeserializer());
    objectMapper.registerModule(module);

    return objectMapper.readValue(json, clazz);
}
}

public class CustomerResponse{

        String name;

        String address;

        String phoneNo;

        CustomerDetails customerDetails;

        //getter and setter
     }

     public class CustomerDetails {

            @JsonDeserialize(using = CustomDateDeserializer.class)
            @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = Utils.FORMAT_DATE)
            private ZonedDateTime licenseDate;
            //getter and setters

      }

     public class CustomDateDeserializer extends StdDeserializer<ZonedDateTime> {

            @Serial
            private static final long serialVersionUID = 1L;

            @Value("${current.timezone}")
            private String timezone;

            public CustomDateDeserializer () {
                   super((Class<?>) null);

            }

            protected CustomDateDeserializer (Class<?> vc) {
                    super(vc);
            }

            @Override
           public ZonedDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws
           IOException   {
                  String stringValue = p.getCodec().readValue(p, String.class);

                  if (StringUtils.isBlank(stringValue)) {
                     return null;
                  }

                  LocalDate localDate = LocalDate.parse(stringValue);
                  return localDate.atStartOfDay().atZone(ZoneId.of(timezone));
               }

            }

        }


问:
Flutter - How to close OS related permission dialog without user interaction?
How to close OS related permission dialog without user interaction ?

USE CASE Example -  if camera permission dialog is prompted in Android / IOS while requesting camera permission and user did not allowed permission in specific time then it should close the dialog.

I'm expecting to close the dialog after specific time if user did not allow / deny the permission. but don't want dialog to be visible unless user closes manually.


问:
Error installing package Orange to convert pickle-file
I would like to install Orange in Pycharm (On Windows 10).  I get this error when I run pip install Orange

(venv) PS C:\Users\xxx\PycharmProjects\ConvertPickleToCode> pip install Orange --pre
Collecting Orange
Using cached Orange-2.7.8.tar.gz (15.0 MB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error

× python setup.py egg_info did not run successfully.

│ exit code: 1

╰─> [7 lines of output]

Traceback (most recent call last):

File "", line 2, in

File "", line 34, in

File "C:\Users\xxx\AppData\Local\Temp\pip-install-9fslw8vb\orange_19ffe98e627c4d8f80cb888affb41473\setup.py", line 261
except OSError, ex:

^

SyntaxError: invalid syntax
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.


问:
RESTCOMM Mobicent Creating a Sip Message issue
I am migrating from Websphere Application Server (WAS) to Mobicent on Tomcat (MSS). In WAS Iused to create SIP message like-

```<code>sipMsg = sipFactory.createRequest(appSession, "INVITE", fromAddr,
            toAddr);
</code>```

If the fromAddr and toAddr contained parameters it stayed after creation of the SIP message in WAS.
After migrating to MSS, its dropping the parameters in from Address.

Has anyone faced this issue before?
Thanks
Shayak

This is the from address before creation of SIP message
(Mobicents-SIP-Servlets-UDPMessageChannelThread-0) Creating new SipServletRequest for SipApplicationSession[f13b687e;xxxx] METHOD[INVITE] FROM_A["'xxxxxxx'" sip:xxxxxx@xxxxxxxx:5060;user=phone;otg=xxxx;tag=487426600;isup-oli=xxx] TO_A[sip:xxxxx@xxxxxx]

After the creation it is
From: "'xxxxxxx'" sip:xxxxxx@xxxxxx:5060;user=phone;tag=80035311_5bb2b653_0c8e0cb5_f13b687e^M

Body:
I am migrating from Websphere Application Server (WAS) to Mobicent on Tomcat (MSS). In WAS Iused to create SIP message like-

sipMsg = sipFactory.createRequest(appSession, "INVITE", fromAddr,
            toAddr);

If the fromAddr and toAddr contained parameters it stayed after creation of the SIP message in WAS.
After migrating to MSS, its dropping the parameters in from Address.

Has anyone faced this issue before?
Thanks
Shayak

This is the from address before creation of SIP message
(Mobicents-SIP-Servlets-UDPMessageChannelThread-0) Creating new SipServletRequest for SipApplicationSession[f13b687e;xxxx] METHOD[INVITE] FROM_A["'xxxxxxx'" sip:xxxxxx@xxxxxxxx:5060;user=phone;otg=xxxx;tag=487426600;isup-oli=xxx] TO_A[sip:xxxxx@xxxxxx]

After the creation it is
From: "'xxxxxxx'" sip:xxxxxx@xxxxxx:5060;user=phone;tag=80035311_5bb2b653_0c8e0cb5_f13b687e^M


问:
How to create custom validation based on xml in .net 6
I am trying to perform validation using custom class attributes. I have to keep my model validation rules inside XML files. Custom Class attribute specifies the path to the XML file and custom attributes will contain the logic to read XML files and get the validation rules for that class. When I will call Model.Isvalidate() that time Validation will get executed. I already have this working in .Net 4.5 MVC application. The same thing I am trying in .Net 6 its not working.</p>
```<code>public class CustomDynamicModelValidatorProvider : DataAnnotationsModelValidatorProvider,IModelValidatorProvider
{
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)
    {
        string resourceKeyPath = string.Empty;
        IList<Attribute> newAttributes = new List<Attribute>(attributes);
        CustomDynamicValidatorsAttribute resourceMapperAttr = attributes.FirstOrDefault(a => a is CustomDynamicValidatorsAttribute) as CustomDynamicValidatorsAttribute;

        if (resourceMapperAttr == null)
        {
            System.Reflection.MemberInfo classInfo = metadata.ContainerType;
            if (classInfo != null)
            {
                var resourceMapperRootAttr = classInfo.GetCustomAttributes(typeof(ResourceMappingRootAttribute), false).FirstOrDefault() as ResourceMappingRootAttribute;
                if (resourceMapperRootAttr != null)
                {
                    resourceKeyPath = resourceMapperRootAttr.Path + "." + metadata.PropertyName;
                }
            }
        }
        else
        {
            resourceKeyPath = resourceMapperAttr.ResourceKeyPath;
        }

        if (!string.IsNullOrEmpty(resourceKeyPath))
        {
            string[] validators = ResourceManager.GetValidators(resourceKeyPath).Replace(" ", "").Split(',');
            var maxLength = ResourceManager.GetMaxLength(resourceKeyPath);
            if (!string.IsNullOrEmpty(maxLength))
            {
                var required = new MaxLengthAttribute(maxLength.ToInteger());
                required.ErrorMessage = string.Format(CustomAttributeHelper.GetResourceText("Shared.Messages.MaximumLengthExceeded"), maxLength);
                newAttributes.Add(required);
            }
            for (int i = 0; i < validators.Length; i++)
            {
                if (string. Equals(validators[i], "required", StringComparison.OrdinalIgnoreCase))
                {
                    var required = new CustomRequiredAttribute();
                    newAttributes.Add(required);
                }
                else if (validators[i].StartsWith("email", StringComparison.OrdinalIgnoreCase))
                {
                    var email = new CustomEmailAttribute();
                    newAttributes.Add(email);
                }

            }
        }

        return base.GetValidators(metadata,validatorProviders);
    }

    public static IDictionary<string, object> GetValidatorAttributes(string validators)
    {
        IDictionary<string, object> attributes = new Dictionary<string, object>();

        string[] validatorList = !string.IsNullOrEmpty(validators) ? validators.Replace(" ", "").Split(',') : new string[] { };
        foreach (var item in validatorList)
        {
            if (!attributes.Keys.Contains("data-val"))
            {
                attributes.Add("data-val", "true");
            }
            if (string.Equals(item, "required", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-required", CustomAttributeHelper.GetResourceText("Shared.Messages.Mandatory"));
            }
            else if (item.StartsWith("email", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-email", CustomAttributeHelper.GetResourceText("Shared.Messages.vEmailField"));
            }
            else if (item.StartsWith("phone", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-phone", CustomAttributeHelper.GetResourceText("Shared.Messages.vPhoneField"));
            }
            else if (item.StartsWith("zipcode", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-zipcode", CustomAttributeHelper.GetResourceText("Shared.Messages.vZipCodeField"));
            }
            else if (item.StartsWith("mark", StringComparison.OrdinalIgnoreCase))
            {
                string min = string.Empty;
                string max = string.Empty;
                string rangeValidatorMessage = string.Empty;
                if (item.Contains("-"))
                {
                    var rangeArray = item.Split('-');
                    if (rangeArray.Length > 2)
                    {
                        min = rangeArray[1];
                        max = rangeArray[2];
                        rangeValidatorMessage = CustomAttributeHelper.GetResourceText("Shared.Messages.NumberRange");
                    }
                    else
                    {
                        max = rangeArray[1];
                        rangeValidatorMessage = CustomAttributeHelper.GetResourceText("Shared.Messages.vNumericLimited");
                    }
                }
                else
                {
                    max = "10000";
                }
                if (!string.IsNullOrWhiteSpace(min))
                {
                    attributes.Add("data-val-range-min", min);
                }
                attributes.Add("data-val-range-max", max);
                attributes.Add("data-val-range", rangeValidatorMessage);
            }
            else if (item.StartsWith("number", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-number", CustomAttributeHelper.GetResourceText("Shared.Messages.NumberRange"));
            }
            else if (item.StartsWith("number", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-decimal", string.Format(CustomAttributeHelper.GetResourceText("Shared.Messages.DecimalRange"), CustomAttributeHelper.GetResourceText("Shared.Limits.Decimal")));
            }
            else if (item.StartsWith("file-", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-filetype", item.Split('-')[1]);
            }
        }
        return attributes;
    }

    public void CreateValidators(ModelValidatorProviderContext context)
    {

    }

}
</code>```

Body:
I am trying to perform validation using custom class attributes. I have to keep my model validation rules inside XML files. Custom Class attribute specifies the path to the XML file and custom attributes will contain the logic to read XML files and get the validation rules for that class. When I will call Model.Isvalidate() that time Validation will get executed. I already have this working in .Net 4.5 MVC application. The same thing I am trying in .Net 6 its not working.

public class CustomDynamicModelValidatorProvider : DataAnnotationsModelValidatorProvider,IModelValidatorProvider
{
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)
    {
        string resourceKeyPath = string.Empty;
        IList<Attribute> newAttributes = new List<Attribute>(attributes);
        CustomDynamicValidatorsAttribute resourceMapperAttr = attributes.FirstOrDefault(a => a is CustomDynamicValidatorsAttribute) as CustomDynamicValidatorsAttribute;

        if (resourceMapperAttr == null)
        {
            System.Reflection.MemberInfo classInfo = metadata.ContainerType;
            if (classInfo != null)
            {
                var resourceMapperRootAttr = classInfo.GetCustomAttributes(typeof(ResourceMappingRootAttribute), false).FirstOrDefault() as ResourceMappingRootAttribute;
                if (resourceMapperRootAttr != null)
                {
                    resourceKeyPath = resourceMapperRootAttr.Path + "." + metadata.PropertyName;
                }
            }
        }
        else
        {
            resourceKeyPath = resourceMapperAttr.ResourceKeyPath;
        }

        if (!string.IsNullOrEmpty(resourceKeyPath))
        {
            string[] validators = ResourceManager.GetValidators(resourceKeyPath).Replace(" ", "").Split(',');
            var maxLength = ResourceManager.GetMaxLength(resourceKeyPath);
            if (!string.IsNullOrEmpty(maxLength))
            {
                var required = new MaxLengthAttribute(maxLength.ToInteger());
                required.ErrorMessage = string.Format(CustomAttributeHelper.GetResourceText("Shared.Messages.MaximumLengthExceeded"), maxLength);
                newAttributes.Add(required);
            }
            for (int i = 0; i < validators.Length; i++)
            {
                if (string. Equals(validators[i], "required", StringComparison.OrdinalIgnoreCase))
                {
                    var required = new CustomRequiredAttribute();
                    newAttributes.Add(required);
                }
                else if (validators[i].StartsWith("email", StringComparison.OrdinalIgnoreCase))
                {
                    var email = new CustomEmailAttribute();
                    newAttributes.Add(email);
                }

            }
        }

        return base.GetValidators(metadata,validatorProviders);
    }

    public static IDictionary<string, object> GetValidatorAttributes(string validators)
    {
        IDictionary<string, object> attributes = new Dictionary<string, object>();

        string[] validatorList = !string.IsNullOrEmpty(validators) ? validators.Replace(" ", "").Split(',') : new string[] { };
        foreach (var item in validatorList)
        {
            if (!attributes.Keys.Contains("data-val"))
            {
                attributes.Add("data-val", "true");
            }
            if (string.Equals(item, "required", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-required", CustomAttributeHelper.GetResourceText("Shared.Messages.Mandatory"));
            }
            else if (item.StartsWith("email", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-email", CustomAttributeHelper.GetResourceText("Shared.Messages.vEmailField"));
            }
            else if (item.StartsWith("phone", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-phone", CustomAttributeHelper.GetResourceText("Shared.Messages.vPhoneField"));
            }
            else if (item.StartsWith("zipcode", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-zipcode", CustomAttributeHelper.GetResourceText("Shared.Messages.vZipCodeField"));
            }
            else if (item.StartsWith("mark", StringComparison.OrdinalIgnoreCase))
            {
                string min = string.Empty;
                string max = string.Empty;
                string rangeValidatorMessage = string.Empty;
                if (item.Contains("-"))
                {
                    var rangeArray = item.Split('-');
                    if (rangeArray.Length > 2)
                    {
                        min = rangeArray[1];
                        max = rangeArray[2];
                        rangeValidatorMessage = CustomAttributeHelper.GetResourceText("Shared.Messages.NumberRange");
                    }
                    else
                    {
                        max = rangeArray[1];
                        rangeValidatorMessage = CustomAttributeHelper.GetResourceText("Shared.Messages.vNumericLimited");
                    }
                }
                else
                {
                    max = "10000";
                }
                if (!string.IsNullOrWhiteSpace(min))
                {
                    attributes.Add("data-val-range-min", min);
                }
                attributes.Add("data-val-range-max", max);
                attributes.Add("data-val-range", rangeValidatorMessage);
            }
            else if (item.StartsWith("number", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-number", CustomAttributeHelper.GetResourceText("Shared.Messages.NumberRange"));
            }
            else if (item.StartsWith("number", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-decimal", string.Format(CustomAttributeHelper.GetResourceText("Shared.Messages.DecimalRange"), CustomAttributeHelper.GetResourceText("Shared.Limits.Decimal")));
            }
            else if (item.StartsWith("file-", StringComparison.OrdinalIgnoreCase))
            {
                attributes.Add("data-val-filetype", item.Split('-')[1]);
            }
        }
        return attributes;
    }

    public void CreateValidators(ModelValidatorProviderContext context)
    {

    }

}


问:
How to implement client authentication in netcoreserver SSL chat example
I'm trying to implement client authentication using the netcoreserver library and I have no clue of where to start. Specifically I would like to add client authentication to the example code provided with the library, i.e. SslChatServer and SslChatClient. Also I would like to know when the authentication has failed but it is unclear where to check this. Any help would be appreciated.

I have tried to supply the client certificate in the server code but this crashs the program. I don't know what to try.


问:
continuous error with jenkins using pipeline

header 1
header 2

cell 1enter image description here
cell 2enter image description here

cell 3enter image description here
cell 4enter image description here

I am new to jenkins and im creating a project using pipelin when i put the  script in jekinsfile its giving me error. Also attaching the script from jenkins fileenter image description here


问:
Selenium Chrome DevTools command to new window
I have a problem in order to execute Page.addScriptToEvaluateOnNewDocument
in the context of a new window when called via window.open from js

i do driver.SwitchTo().Window(window)
when the Page.WindowOpen event fires
and then I use the code from the selenium documentation

```<code>var domains = GetDomains();
domains.Page.Enable(new OpenQA.Selenium.DevTools.V106.Page.EnableCommandSettings());
domains.Page.AddScriptToEvaluateOnNewDocument(new AddScriptToEvaluateOnNewDocumentCommandSettings()
{
    Source = script
});
</code>```
```<code>private static DevToolsSessionDomains GetDomains()
{
    IDevTools devTools = driver as IDevTools;
    DevToolsSession session = devTools.GetDevToolsSession();
    var domains = session.GetVersionSpecificDomains<DevToolsSessionDomains>();
    return domains;
}
</code>```

but TargetId in session obj is still same.

the expected behavior should be like this. js Opens a new window and selenium sends an AddScriptToEvaluateOnNewDocumentCommandSettings event to it so that the target script is executed every time the page is loaded.

Body:
I have a problem in order to execute Page.addScriptToEvaluateOnNewDocument
in the context of a new window when called via window.open from js

i do driver.SwitchTo().Window(window)
when the Page.WindowOpen event fires
and then I use the code from the selenium documentation

var domains = GetDomains();
domains.Page.Enable(new OpenQA.Selenium.DevTools.V106.Page.EnableCommandSettings());
domains.Page.AddScriptToEvaluateOnNewDocument(new AddScriptToEvaluateOnNewDocumentCommandSettings()
{
    Source = script
});

private static DevToolsSessionDomains GetDomains()
{
    IDevTools devTools = driver as IDevTools;
    DevToolsSession session = devTools.GetDevToolsSession();
    var domains = session.GetVersionSpecificDomains<DevToolsSessionDomains>();
    return domains;
}

but TargetId in session obj is still same.

the expected behavior should be like this. js Opens a new window and selenium sends an AddScriptToEvaluateOnNewDocumentCommandSettings event to it so that the target script is executed every time the page is loaded.


问:
three js LoadObject pivot
enter image description here

I want to move pivot at glb model.

How move pivot like picture?

And if change scale, how change scale on right?

Title: three js LoadObject pivot


问:
Tensorflow-metal/Tensorflow-macos freezing on specific epoch based on batch size
I have created this fairly basic Densely connected model in TensorFlow in python on an M1 Mac ARM architecture.

```<code>model = tf.keras.Sequential()
model.add(tf.keras.Input(shape=(len(x_train[0]),)))
model.add(tf.keras.layers.Dense(1261, activation="sigmoid"))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Dense(1261, activation="sigmoid"))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Dense(624, activation="sigmoid"))
model.add(tf.keras.layers.Dense(1))

model.compile(loss="mean_squared_error",
              optimizer=tf.keras.optimizers.Adam(learning_rate=0.001))

reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='loss', factor=0.1,
                                                 patience=20, min_lr=0.001)
model.fit(x_train, y_train, epochs=1600, batch_size=30, callbacks=[reduce_lr])
</code>```

I am running this in a miniconda environment and what seems to be happening is the model will fit fine for some number of epochs, and then randomly on one epoch that is proportional to batch size (say 867 for a batch size of 100), training will suddenly slow down massively. Everything is still running, but ETA goes from 2s to 7h to several days soon enough. I know the mini-batch is still being trained because I see the number tick up every now and then.

I am fairly certain this is an issue with TensorFlow-metal because it started happening as soon as I switched to it to be able to utilize M1 metal.

I have tried changing batch sizes, epochs, callbacks, and learning rates, and the only thing that seems to have any effect is change batch size which proportionally changes which epoch the slow down will occur oc. i.e earlier if batch size is smaller and later if it is larger.

This issue is really frustrating since it seems to be so random, I'll be very appreciative of any assistance.

Body:
I have created this fairly basic Densely connected model in TensorFlow in python on an M1 Mac ARM architecture.

model = tf.keras.Sequential()
model.add(tf.keras.Input(shape=(len(x_train[0]),)))
model.add(tf.keras.layers.Dense(1261, activation="sigmoid"))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Dense(1261, activation="sigmoid"))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Dense(624, activation="sigmoid"))
model.add(tf.keras.layers.Dense(1))

model.compile(loss="mean_squared_error",
              optimizer=tf.keras.optimizers.Adam(learning_rate=0.001))

reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='loss', factor=0.1,
                                                 patience=20, min_lr=0.001)
model.fit(x_train, y_train, epochs=1600, batch_size=30, callbacks=[reduce_lr])

I am running this in a miniconda environment and what seems to be happening is the model will fit fine for some number of epochs, and then randomly on one epoch that is proportional to batch size (say 867 for a batch size of 100), training will suddenly slow down massively. Everything is still running, but ETA goes from 2s to 7h to several days soon enough. I know the mini-batch is still being trained because I see the number tick up every now and then.

I am fairly certain this is an issue with TensorFlow-metal because it started happening as soon as I switched to it to be able to utilize M1 metal.

I have tried changing batch sizes, epochs, callbacks, and learning rates, and the only thing that seems to have any effect is change batch size which proportionally changes which epoch the slow down will occur oc. i.e earlier if batch size is smaller and later if it is larger.

This issue is really frustrating since it seems to be so random, I'll be very appreciative of any assistance.


问:
Concurrent modification during iteration: Instance(length:3) of '_GrowableList'
I am new in flutter and i want to do pagination. I am using one package which name is pull to refresh. All work are doing well but when I reach last data of list then current page is increment with +1 and api call of page=2. in my code its open new page, i want to append with current listview. When i write code for append its throw error "Concurrent modification during iteration: Instance(length:3) of '_GrowableList'."(my english is not good but I hope you are understood).
Following are my code.

```<code> int currentPage = 1;
 bool isRefersh = false;

Future<UserPost> getUserPost() async {

    var url =
        "https://myApiLink/getUserPost.php?page=$currentPage";
    var response = await http.get(Uri.parse(url));
    var jsondata = jsonDecode(response.body.toString());
    var _apiData = UserPost.fromJson(jsondata);

    if (response.statusCode == 200) {

      if(isRefersh == true){
        setState((){
          isRefersh = false;
        });
        refreshController.refreshCompleted();
        return UserPost.fromJson(jsondata);
      }
      else{
        print(_apiData.hasNextPage.toString());
        if(_apiData.hasNextPage == 0){
          refreshController.loadNoData();
        }else{
          refreshController.loadComplete();
        }
        return UserPost.fromJson(jsondata);
      }

    } else {
      return UserPost.fromJson(jsondata);
    }
  }
</code>```

My list view code:

```<code> FutureBuilder<UserPost>(
                              future: getUserPost(),
                              builder: (context, snapshot) {
                                if (snapshot.hasData) {
                                  return SmartRefresher(
                                    controller: refreshController,
                                    enablePullUp: true,

                                    child: ListView.builder(
                                      //close keyboard while scroll
                                        keyboardDismissBehavior:
                                        ScrollViewKeyboardDismissBehavior.onDrag,
                                        //itemCount: isFilter? ComparisonText.length : snapshot.data!.data!.length,
                                        itemCount: snapshot.data!.data!.length,
                                        itemBuilder: (context, i) {

                                          var postList = snapshot.data!.data![i];
                                          String tempSearch =
                                          postList.azakhanaName.toString();
)}
</code>```

onRefersh for refreshing and onLoading for pagination.

```<code>onRefresh: () async{
                                  await Future.delayed(Duration(milliseconds: 1000));
                                  setState(() {
                                    isRefersh = true;
                                    currentPage = 1;
                                  });
                                },

                                onLoading: () async {
                                  if(snapshot.data!.hasNextPage == 0){
                                    refreshController.loadNoData();
                                  }else{
                                    setState(() {
                                      currentPage++;
                                      snapshot.data!.data!.addAll(snapshot.data!.data!);
                                    });
                                    await Future.delayed(Duration(milliseconds: 1000));
                                    refreshController.loadComplete();
                                  }

                                },
</code>```

I am trying to append listview with new data like this and and error also throw in this code:

```<code>snapshot.data!.data!.addAll(snapshot.data!.data!);
</code>```

Body:
I am new in flutter and i want to do pagination. I am using one package which name is pull to refresh. All work are doing well but when I reach last data of list then current page is increment with +1 and api call of page=2. in my code its open new page, i want to append with current listview. When i write code for append its throw error "Concurrent modification during iteration: Instance(length:3) of '_GrowableList'."(my english is not good but I hope you are understood).
Following are my code.

 int currentPage = 1;
 bool isRefersh = false;

Future<UserPost> getUserPost() async {

    var url =
        "https://myApiLink/getUserPost.php?page=$currentPage";
    var response = await http.get(Uri.parse(url));
    var jsondata = jsonDecode(response.body.toString());
    var _apiData = UserPost.fromJson(jsondata);

    if (response.statusCode == 200) {

      if(isRefersh == true){
        setState((){
          isRefersh = false;
        });
        refreshController.refreshCompleted();
        return UserPost.fromJson(jsondata);
      }
      else{
        print(_apiData.hasNextPage.toString());
        if(_apiData.hasNextPage == 0){
          refreshController.loadNoData();
        }else{
          refreshController.loadComplete();
        }
        return UserPost.fromJson(jsondata);
      }

    } else {
      return UserPost.fromJson(jsondata);
    }
  }

My list view code:

 FutureBuilder<UserPost>(
                              future: getUserPost(),
                              builder: (context, snapshot) {
                                if (snapshot.hasData) {
                                  return SmartRefresher(
                                    controller: refreshController,
                                    enablePullUp: true,

                                    child: ListView.builder(
                                      //close keyboard while scroll
                                        keyboardDismissBehavior:
                                        ScrollViewKeyboardDismissBehavior.onDrag,
                                        //itemCount: isFilter? ComparisonText.length : snapshot.data!.data!.length,
                                        itemCount: snapshot.data!.data!.length,
                                        itemBuilder: (context, i) {

                                          var postList = snapshot.data!.data![i];
                                          String tempSearch =
                                          postList.azakhanaName.toString();
)}

onRefersh for refreshing and onLoading for pagination.

onRefresh: () async{
                                  await Future.delayed(Duration(milliseconds: 1000));
                                  setState(() {
                                    isRefersh = true;
                                    currentPage = 1;
                                  });
                                },

                                onLoading: () async {
                                  if(snapshot.data!.hasNextPage == 0){
                                    refreshController.loadNoData();
                                  }else{
                                    setState(() {
                                      currentPage++;
                                      snapshot.data!.data!.addAll(snapshot.data!.data!);
                                    });
                                    await Future.delayed(Duration(milliseconds: 1000));
                                    refreshController.loadComplete();
                                  }

                                },

I am trying to append listview with new data like this and and error also throw in this code:

snapshot.data!.data!.addAll(snapshot.data!.data!);


问:
Calculator Button will delete single digits but won't allow for more numbers to be added
The delete button will function properly, as far as delete single digits in a set of numbers, but if the numbers are still on the display screen - after then hitting delete with a couple numbers still on the screen - it won't allow me to add new numbers to the current screen.

let operator = '';
let previousValue = '';
let currentValue = '';

//let deleteBtn = document.getElementById('delete')

document.addEventListener("DOMContentLoaded", function() {
  let clear = document.querySelector('.clear');
  let equal = document.querySelector(".equal");
  let backspace = document.querySelector('.delete');

  //let deletes = document.querySelector('.delete');
  //let deletebtn = del[0]

  let numbers = document.querySelectorAll(".number");
  let operators = document.querySelectorAll(".operator");

  let previousScreen = document.querySelector('.previous');
  let currentScreen = document.querySelector('.current');

  numbers.forEach((number) => number.addEventListener("click", function(e) {
    handleNumber(e.target.textContent)
    currentScreen.textContent = currentValue;
  }))

  operators.forEach((op) => op.addEventListener("click", function(e) {

    handleOperator(e.target.textContent)
    previousScreen.textContent = previousValue + "" + operator;
    currentScreen.textContent = currentValue;
  }))

  clear.addEventListener("click", function() {
    previousValue = '';
    currentValue = '';
    operator = '';
    previousScreen.textContent = currentValue;
    currentScreen.textContent = currentValue;
  })

  equal.addEventListener("click", function() {
    answer();
    previousScreen.textContent = '';
    currentScreen.textContent = previousValue;
  })

  backspace.addEventListener("click", function() {
    let temp
    if (currentValue === 0) {
      currentValue = 0;
      temp = currentValue;
    }

    //temp = currentValue.toString().slice(0,-1)
    else {
      temp = currentValue.toString().slice(0, -1)
    }

    if (temp === '' || temp === '') {
      temp = '';
      currentValue = temp;
      upDateDisplay();
    } else {
      currentValue = parseFloat(temp)
      upDateDisplay();
    }

    function upDateDisplay() {
      currentScreen.textContent = currentValue;
      previousScreen.textContent = previousValue;
    }
  })
})

function handleNumber(num) {
  if (currentValue.length <= 10) {
    currentValue += num;
  }
}

function handleOperator(op) {
  operator = op;
  previousValue = currentValue;
  currentValue = "";
}

//function back(backspace){
// currentScreen('backspace', -1);
//}

function answer() {

  previousValue = Number(previousValue);
  currentValue = Number(currentValue);

  if (operator === "+") {
    previousValue += currentValue;
  } else if (operator === "^") {
    previousValue **= currentValue;
  } else if (operator === "-") {
    previousValue -= currentValue;
  } else if (operator === "x") {
    previousValue *= currentValue;
  } else {
    previousValue /= currentValue;
  }

  previousValue = round(previousValue);
  previousValue = previousValue.toString();
  currentValue = previousValue.toString();
}

function round(num) {
  return Math.round(num * 1000) / 1000;
}```

I did mess around with some of the javascript code shown but it only lead to other errors without fixing my current problem.

Body:
The delete button will function properly, as far as delete single digits in a set of numbers, but if the numbers are still on the display screen - after then hitting delete with a couple numbers still on the screen - it won't allow me to add new numbers to the current screen.

let operator = '';
let previousValue = '';
let currentValue = '';

//let deleteBtn = document.getElementById('delete')

document.addEventListener("DOMContentLoaded", function() {
  let clear = document.querySelector('.clear');
  let equal = document.querySelector(".equal");
  let backspace = document.querySelector('.delete');

  //let deletes = document.querySelector('.delete');
  //let deletebtn = del[0]

  let numbers = document.querySelectorAll(".number");
  let operators = document.querySelectorAll(".operator");

  let previousScreen = document.querySelector('.previous');
  let currentScreen = document.querySelector('.current');

  numbers.forEach((number) => number.addEventListener("click", function(e) {
    handleNumber(e.target.textContent)
    currentScreen.textContent = currentValue;
  }))

  operators.forEach((op) => op.addEventListener("click", function(e) {

    handleOperator(e.target.textContent)
    previousScreen.textContent = previousValue + "" + operator;
    currentScreen.textContent = currentValue;
  }))

  clear.addEventListener("click", function() {
    previousValue = '';
    currentValue = '';
    operator = '';
    previousScreen.textContent = currentValue;
    currentScreen.textContent = currentValue;
  })

  equal.addEventListener("click", function() {
    answer();
    previousScreen.textContent = '';
    currentScreen.textContent = previousValue;
  })

  backspace.addEventListener("click", function() {
    let temp
    if (currentValue === 0) {
      currentValue = 0;
      temp = currentValue;
    }

    //temp = currentValue.toString().slice(0,-1)
    else {
      temp = currentValue.toString().slice(0, -1)
    }

    if (temp === '' || temp === '') {
      temp = '';
      currentValue = temp;
      upDateDisplay();
    } else {
      currentValue = parseFloat(temp)
      upDateDisplay();
    }

    function upDateDisplay() {
      currentScreen.textContent = currentValue;
      previousScreen.textContent = previousValue;
    }
  })
})

function handleNumber(num) {
  if (currentValue.length <= 10) {
    currentValue += num;
  }
}

function handleOperator(op) {
  operator = op;
  previousValue = currentValue;
  currentValue = "";
}

//function back(backspace){
// currentScreen('backspace', -1);
//}

function answer() {

  previousValue = Number(previousValue);
  currentValue = Number(currentValue);

  if (operator === "+") {
    previousValue += currentValue;
  } else if (operator === "^") {
    previousValue **= currentValue;
  } else if (operator === "-") {
    previousValue -= currentValue;
  } else if (operator === "x") {
    previousValue *= currentValue;
  } else {
    previousValue /= currentValue;
  }

  previousValue = round(previousValue);
  previousValue = previousValue.toString();
  currentValue = previousValue.toString();
}

function round(num) {
  return Math.round(num * 1000) / 1000;
}

I did mess around with some of the javascript code shown but it only lead to other errors without fixing my current problem.


问:
Failed to load module "canberra-gtk-module" Error when running javafx program in netbeans on Ubuntu
I am running a minimal "getting started" program with Javafx in Netbeans on Ubuntu.

My application start method is:

```<code>public class App extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("scene.fxml"));

        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());

        stage.setTitle("JavaFX and Gradle");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}
</code>```

The errors I get are

```<code>Gtk-Message: 05:42:26.590: Failed to load module "canberra-gtk-module"
Gtk-Message: 05:42:26.590: Failed to load module "canberra-gtk-module"
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3316)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3280)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3249)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3222)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3199)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3192)
    at Experimenting.App.start(App.java:17)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:474)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:447)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:446)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(GtkApplication.java:277)
    ... 1 more
Exception running application Experimenting.App

FAILURE: Build failed with an exception.

</code>```

I have tried installing all the GTK Canberra stuff on Ubuntu. No joy.

I think this is something to do with JavaFX trying to run the app in my native style with native fonts etc. but can't find the right files. I may be wrong.

Can anybody help?

Edit - As per the comment, I changed the

```<code>  getClass().getResource("scene.fxml")
</code>```

to

```<code>  getClass().getClassLoader().getResource("scene.fxml")
</code>```

and now I get the errors:

```<code>Gtk-Message: 06:39:30.226: Failed to load module "canberra-gtk-module"
Gtk-Message: 06:39:30.226: Failed to load module "canberra-gtk-module"
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.NullPointerException
    at Experimenting.App.start(App.java:20)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:474)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:447)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:446)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(GtkApplication.java:277)
    ... 1 more
Exception running application Experimenting.App
</code>```

Body:
I am running a minimal "getting started" program with Javafx in Netbeans on Ubuntu.

My application start method is:

public class App extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("scene.fxml"));

        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());

        stage.setTitle("JavaFX and Gradle");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

The errors I get are

Gtk-Message: 05:42:26.590: Failed to load module "canberra-gtk-module"
Gtk-Message: 05:42:26.590: Failed to load module "canberra-gtk-module"
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3316)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3280)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3249)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3222)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3199)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3192)
    at Experimenting.App.start(App.java:17)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:474)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:447)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:446)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(GtkApplication.java:277)
    ... 1 more
Exception running application Experimenting.App

FAILURE: Build failed with an exception.

I have tried installing all the GTK Canberra stuff on Ubuntu. No joy.

I think this is something to do with JavaFX trying to run the app in my native style with native fonts etc. but can't find the right files. I may be wrong.

Can anybody help?

Edit - As per the comment, I changed the

  getClass().getResource("scene.fxml")

to

  getClass().getClassLoader().getResource("scene.fxml")

and now I get the errors:

Gtk-Message: 06:39:30.226: Failed to load module "canberra-gtk-module"
Gtk-Message: 06:39:30.226: Failed to load module "canberra-gtk-module"
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.NullPointerException
    at Experimenting.App.start(App.java:20)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:474)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:447)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:446)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(GtkApplication.java:277)
    ... 1 more
Exception running application Experimenting.App


问:
Generate PDF from specific CSS class WKHTMLTOPDF
Is it possible to generate PDF from specific CSS class html with WKHTMLTOPDF?

I need to capture just specific class not for all page
Example :

```<code><div class="chartup">
   ...
</div>
</code>```

Body:
Is it possible to generate PDF from specific CSS class html with WKHTMLTOPDF?

I need to capture just specific class not for all page
Example :

   ...


问:
Log4j not printing debug logs in case of an error
I have a method foo which is called inside a loop over a list of objects.

```<code>class Bar{

    private static final Logger logger = LoggerFactory.getLogger(Bar.class);

    void foo(A obj){

        //bunch of debug logs
        logger.debug("A");
        logger.debug("B");

        //..and so on

        //processing functionality
    }
}
</code>```

Now, whenever the object is processed successfully, the debug logs are printed in the log file. But if an object throws an error while processing, the debug logs are not getting printed.

I am using log4j2 and my log4j.xml file is below:

```<code><Configuration monitorInterval="60" status="WARN">

<Loggers>
    <Logger name="com.abc" level="INFO"/>
</Loggers>

<Loggers>
  <Root level="INFO">
  <AppenderRef ref="console"/>
  <AppenderRef ref="asyncFileLogger"/>
  </Root>
</Loggers>

</Configuration>
</code>```

What could be the issue behind this?

Body:
I have a method foo which is called inside a loop over a list of objects.

class Bar{

    private static final Logger logger = LoggerFactory.getLogger(Bar.class);

    void foo(A obj){

        //bunch of debug logs
        logger.debug("A");
        logger.debug("B");

        //..and so on

        //processing functionality
    }
}

Now, whenever the object is processed successfully, the debug logs are printed in the log file. But if an object throws an error while processing, the debug logs are not getting printed.

I am using log4j2 and my log4j.xml file is below:

<Configuration monitorInterval="60" status="WARN">

<Loggers>
    <Logger name="com.abc" level="INFO"/>
</Loggers>

<Loggers>
  <Root level="INFO">
  <AppenderRef ref="console"/>
  <AppenderRef ref="asyncFileLogger"/>
  </Root>
</Loggers>

</Configuration>

What could be the issue behind this?


问:
Can the default priority be changed in J1939 from SAE?
As per SAE document for J1939 the default priority is specified but can the default priority be changed.
Will it have any impact if the default priority is changed?</p>


问:
How to sort for most negative values and most positive values across columns?
I am trying to create a new column in my dataframe based on the maximum values across 3 columns. However, depending on the values within each row, I want it to sort for either the most negative value or the most positive value. If the average for an individual row across the 3 columns is greater than 0, I want it to report the most positive value. If it is less than 0, I want it to report back the most negative value.

Here is an example of the dataframe

```<code> A      B      C
-0.30  -0.45  -0.25
 0.25   0.43   0.21
-0.10   0.10   0.25
-0.30  -0.10   0.05
</code>```

And here is the desired output

```<code> A      B      C      D
-0.30  -0.45  -0.25  -0.45
 0.25   0.43   0.21   0.43
-0.10   0.10   0.25   0.25
-0.30  -0.10   0.05  -0.30
</code>```

I had first tried playing around with something like

```<code>data %>%
  mutate(D = pmax(abs(A), abs(B), abs(C)))
</code>```

But that just returns a column with the greatest of the absolute values where everything is positive.

Thanks in advance for your help, and apologies if the formatting of the question is off, I don't use this site a lot. Happy to clarify anything as well.

Body:
I am trying to create a new column in my dataframe based on the maximum values across 3 columns. However, depending on the values within each row, I want it to sort for either the most negative value or the most positive value. If the average for an individual row across the 3 columns is greater than 0, I want it to report the most positive value. If it is less than 0, I want it to report back the most negative value.

Here is an example of the dataframe

 A      B      C
-0.30  -0.45  -0.25
 0.25   0.43   0.21
-0.10   0.10   0.25
-0.30  -0.10   0.05

And here is the desired output

 A      B      C      D
-0.30  -0.45  -0.25  -0.45
 0.25   0.43   0.21   0.43
-0.10   0.10   0.25   0.25
-0.30  -0.10   0.05  -0.30

I had first tried playing around with something like

data %>%
  mutate(D = pmax(abs(A), abs(B), abs(C)))

But that just returns a column with the greatest of the absolute values where everything is positive.

Thanks in advance for your help, and apologies if the formatting of the question is off, I don't use this site a lot. Happy to clarify anything as well.


问:
How can I edit this apriori algorithm code in market basket analysis using rhs and lhs?
I'm trying Market Bakset Analysis using 'apriori' algorithm.

The 'Catalog' data set consists of 8 columns and 200 rows :

```<code>Automotive Computers Personal.Electronics Garden Clothing Health Jewelry Housewares
0               1       0          1        1       0        0      0         1
0               0       0          1        0       1        0      0         1
0               1       1          0        0       0        1      0         0
1               0       0          0        0       1        0      0         0
0               0       0          1        1       0        0      1         0
</code>```

First, I tried apriori algorithm withtout any rhs, lhs limitation and here's the result :

```<code>
Catalogrules <- apriori(Catalog, parameter= list(support =
0.1, confidence = 0.3, minlen = 2))

inspect(sort(Catalogrules, by = "lift")[1:5])
    lhs                          rhs          support confidence coverage     lift count

\[1\] {Automotive=0,
Computers=0,
Personal.Electronics=0,
Clothing=0}              =\> {Garden=1}     0.110  0.9565217    0.115 2.943144    22
\[2\] {Personal.Electronics=0,
Jewelry=1}               =\> {Clothing=1}   0.125  0.7142857    0.175 2.857143    25
\[3\] {Clothing=1,
Health=0}                =\> {Jewelry=1}    0.120  0.8888889    0.135 2.821869    24
\[4\] {Automotive=0,
Personal.Electronics=0,
Clothing=0}              =\> {Garden=1}     0.110  0.9166667    0.120 2.820513    22
\[5\] {Computers=0,
Personal.Electronics=0,
Jewelry=1}               =\> {Clothing=1}   0.105  0.6774194    0.155 2.709677    21

</code>```

I wanted to see rules with "=1" because '0' cannot show any meaningful relationships.
ex) {Jewelry=1, Computers=1} -> {Clothing=1}

So, I tried to make new code using rhs and lhs.

```<code>Catalogrules <- apriori(Catalog, parameter= list(support =
                                                   0.1, confidence = 0.3, minlen = 2), appearance=list(rhs = c("Automotive=1", "Computers=1", "Personal.Electronics=1", "Garden=1", "Clothing=1", "Health=1", "Jewelry=1", "Housewares=1"), lhs = c("Automotive=1", "Computers=1", "Personal.Electronics=1", "Garden=1", "Clothing=1", "Health=1", "Jewelry=1", "Housewares=1"), default="rhs"))
</code>```

But this is the error message:

```<code>Error in asMethod(object) :
  The following items cannot be specified in multiple appearance locations: Automotive=1, Computers=1, Personal.Electronics=1, Garden=1, Clothing=1, Health=1, Jewelry=1, Housewares=1
</code>```

I want to print top 5 rules using apriori algorithm.

```<code>
ex) inspect(sort(Catalogrules, by = "lift")[1:5])
    1. {Automotive=1} -> {Garden=1}
    2. {Personal.Electronics=1} -> {Computers=1}
    3. {Jewelry=1} -> {Clothing=1}
    4. {Garden=1} -> (Automotives=1}
    5. {Clothing=1} -> {Jewelry=1}
</code>```

I need your help.

Body:
I'm trying Market Bakset Analysis using 'apriori' algorithm.

The 'Catalog' data set consists of 8 columns and 200 rows :

Automotive Computers Personal.Electronics Garden Clothing Health Jewelry Housewares
0               1       0          1        1       0        0      0         1
0               0       0          1        0       1        0      0         1
0               1       1          0        0       0        1      0         0
1               0       0          0        0       1        0      0         0
0               0       0          1        1       0        0      1         0

First, I tried apriori algorithm withtout any rhs, lhs limitation and here's the result :

Catalogrules <- apriori(Catalog, parameter= list(support =
0.1, confidence = 0.3, minlen = 2))

inspect(sort(Catalogrules, by = "lift")[1:5])
    lhs                          rhs          support confidence coverage     lift count

\[1\] {Automotive=0,
Computers=0,
Personal.Electronics=0,
Clothing=0}              =\> {Garden=1}     0.110  0.9565217    0.115 2.943144    22
\[2\] {Personal.Electronics=0,
Jewelry=1}               =\> {Clothing=1}   0.125  0.7142857    0.175 2.857143    25
\[3\] {Clothing=1,
Health=0}                =\> {Jewelry=1}    0.120  0.8888889    0.135 2.821869    24
\[4\] {Automotive=0,
Personal.Electronics=0,
Clothing=0}              =\> {Garden=1}     0.110  0.9166667    0.120 2.820513    22
\[5\] {Computers=0,
Personal.Electronics=0,
Jewelry=1}               =\> {Clothing=1}   0.105  0.6774194    0.155 2.709677    21

I wanted to see rules with "=1" because '0' cannot show any meaningful relationships.
ex) {Jewelry=1, Computers=1} -> {Clothing=1}

So, I tried to make new code using rhs and lhs.

Catalogrules <- apriori(Catalog, parameter= list(support =
                                                   0.1, confidence = 0.3, minlen = 2), appearance=list(rhs = c("Automotive=1", "Computers=1", "Personal.Electronics=1", "Garden=1", "Clothing=1", "Health=1", "Jewelry=1", "Housewares=1"), lhs = c("Automotive=1", "Computers=1", "Personal.Electronics=1", "Garden=1", "Clothing=1", "Health=1", "Jewelry=1", "Housewares=1"), default="rhs"))

But this is the error message:

Error in asMethod(object) :
  The following items cannot be specified in multiple appearance locations: Automotive=1, Computers=1, Personal.Electronics=1, Garden=1, Clothing=1, Health=1, Jewelry=1, Housewares=1

I want to print top 5 rules using apriori algorithm.

ex) inspect(sort(Catalogrules, by = "lift")[1:5])
    1. {Automotive=1} -> {Garden=1}
    2. {Personal.Electronics=1} -> {Computers=1}
    3. {Jewelry=1} -> {Clothing=1}
    4. {Garden=1} -> (Automotives=1}
    5. {Clothing=1} -> {Jewelry=1}

I need your help.


问:
GraphQL Polling mechanism using python Flask
I am building a Python flask Rest API Application using graphql and trying to implement long polling and short polling mechanism using Graphql. Are there way to implement long polling and short polling for graphql query. Any documentation or any suggestion would be helpful to implement my component</p>


问:
EF Core joining tables
I have just started with EF and am stuck with relationships. I have two tables (Point and Prop) and I want to get the result table (Result) joining these tables.

```<code>class Point {
  public int Id { get; set;}
  public int Type { get; set;}
}

class Prop {
  public int Id { get; set;}
  public int PointId { get; set;}
  public int Foo { get; set;}
  public int Bar { get; set;}
}

class Result {
  public int PointId { get; set;}
  public int PontType { get; set;}
  public int Foo { get; set;}
  public int Bar { get; set;}
}

</code>```

The problem is that there might be zero, one or many Props for each point and I want to have some logic here.

if there are no Prop with PointId for Point, just skip this Point

if there is only one Prop for Point, just combine these

if there are many Props for Point and there is Prop.Foo == Point.Type, take this one otherwise take any pair Prop-Point

So, I understand how to solve this with series queries - select Ponts, select Props, foreach etc.
I'm wondering if it might be done with a single query (I believe yes, but have no idea how). I played with GroupJoin and GroupBy, but it seems that EF core is not good with that. Any ideas are welcome.

Title: EF Core joining tables

Body:
I have just started with EF and am stuck with relationships. I have two tables (Point and Prop) and I want to get the result table (Result) joining these tables.

class Point {
  public int Id { get; set;}
  public int Type { get; set;}
}

class Prop {
  public int Id { get; set;}
  public int PointId { get; set;}
  public int Foo { get; set;}
  public int Bar { get; set;}
}

class Result {
  public int PointId { get; set;}
  public int PontType { get; set;}
  public int Foo { get; set;}
  public int Bar { get; set;}
}

The problem is that there might be zero, one or many Props for each point and I want to have some logic here.

if there are no Prop with PointId for Point, just skip this Point

if there is only one Prop for Point, just combine these

if there are many Props for Point and there is Prop.Foo == Point.Type, take this one otherwise take any pair Prop-Point

So, I understand how to solve this with series queries - select Ponts, select Props, foreach etc.
I'm wondering if it might be done with a single query (I believe yes, but have no idea how). I played with GroupJoin and GroupBy, but it seems that EF core is not good with that. Any ideas are welcome.


问:
Wrong site size in Vue
Hi I'm currently learning Vue but I've noticed that for some reason all my sites have the wrong size, as if the default mode was center and small, I haven't touched any setting that I'm aware of, see pics for examples, notice the huge viewport compared to the info that is shown:

This one is almost right, apparently got the heighht right but the width wrong, I have no idea why

This one is at the center for some reason

This one is the worst, look at how tiny it is, like what the hell

I've tried tinkering a bit with CSS margins, height, width, etc., but nothing really works, it only gets worse

I'll provide a code example of the second case, the simplest one:

```<code> <script setup>
import { ref, computed } from 'vue';
const name = 'Vue Dinámico';
const counter = ref(0);
const colorRed = "color: red";
const colorGreen = "color: green";
const increment = () => {
  counter.value++;
};
const decrement = () => {
  counter.value--;
};
const reset = () => {
  counter.value = 0;
};

const classCounter = computed(() => {
  if(counter.value === 0){
    return 'zero';
  }
  if(counter.value > 0) {
    return 'positive';
  }
  if(counter.value < 0){
    return 'negative';
  }
});
const arrayNum = ref([]);
const addNum = () => {
  arrayNum.value.push(counter.value);
};

const bloquearBtnAdd = computed(() => {
  const numSearch = arrayNum.value.find(num => num === counter.value);
  console.log(numSearch);
  //if(numSearch === 0) return true;
  //return numSearch ? true : false;
  return numSearch || numSearch === 0;
})
</script>

<template>
  <div class="container text-center mt-3">
    <h1>Hola {{ name.toUpperCase() }}</h1>
  <h2 :class="classCounter">{{ counter }}</h2>
  <div class="btn-group">
    <button @click="increment" class="btn btn-success">Aumentar</button>
  <button @click="decrement" class="btn btn-danger">Disminuir</button>
  <button @click="reset" class="btn btn-sceondary">Reset</button>
  <button @click="addNum" :disabled="bloquearBtnAdd" class="btn btn-primary">Agregar</button>
  </div>

  <ul class="list-group mt-4">
    <li
    class="list-group-item"
    v-for="(num, index) in arrayNum"
    :key="index">
      {{num}}
    </li>
  </ul>
  </div>

</template>

<style>
h1 {
  color: red;

}
.positive {
  color: green;
}
.negative {
  color: red;
}
.zero {
  color: peru;
}
</style>
</code>```

Title: Wrong site size in Vue

Body:
Hi I'm currently learning Vue but I've noticed that for some reason all my sites have the wrong size, as if the default mode was center and small, I haven't touched any setting that I'm aware of, see pics for examples, notice the huge viewport compared to the info that is shown:

This one is almost right, apparently got the heighht right but the width wrong, I have no idea why

This one is at the center for some reason

This one is the worst, look at how tiny it is, like what the hell

I've tried tinkering a bit with CSS margins, height, width, etc., but nothing really works, it only gets worse

I'll provide a code example of the second case, the simplest one:

<template>

Hola {{ name.toUpperCase() }}

{{ counter }}

    <button @click="increment" class="btn btn-success">Aumentar</button>
  <button @click="decrement" class="btn btn-danger">Disminuir</button>
  <button @click="reset" class="btn btn-sceondary">Reset</button>
  <button @click="addNum" :disabled="bloquearBtnAdd" class="btn btn-primary">Agregar</button>

      {{num}}

</template>


问:
pointing my ingress domain something.com to kubernetes ingress domain web.example.com using cname is not working
I have a domain name web.example.com in kubernetes ingress . When I point another domain something.com to web.example.com the ingress is not allowing this domain . The page is not opening . I need several domains to kubernetes ingress domain . These domains belongs to different customers . So what ever domain point to my domain web.example.com it should work . The other domains are pointed to ingress domain using the cname of the customer domain .Please help

I tried to point my domain something.com to my kubernetes ingress domain using cname .but it is not working .


问:
Laravel nested-set: Integrity constraint violation error when deleting a node
I use the lazychaser's laravel-nestedset package and I'm having a problem when I try to delete a node with descendants.

```<code>namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Post\Category;

class Post extends Model
{
    use HasFactory;

    ...

    /**
     * The categories that belong to the post.
     */
    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

    ...

}

namespace App\Models\Post;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Post;
use Kalnoy\Nestedset\NodeTrait;

class Category extends Model
{
    use HasFactory, NodeTrait;

    protected $table = 'post_categories';

    ...

    /**
     * The posts that belong to the category.
     */
    public function posts()
    {
        return $this->belongsToMany(Post::class);
    }

    public function delete()
    {
        $this->posts()->detach();
        parent::delete();
    }

    ...

}
</code>```

When I delete a node that hasn't any descendant everything is ok.

```<code>$category->delete();
</code>```

Now when I try to delete a node that has one or more descendants I get this error:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
update a parent row: a foreign key constraint fails
(myproject.category_post, CONSTRAINT
category_post_category_id_foreign FOREIGN KEY (category_id)
REFERENCES post_categories (id)) delete from post_categories
where post_categories._lft between 4 and 8

It looks like the Category delete() method is not called when the nested-set trait deletes the descendants.

How can I fix this issue, should I delete the descendant nodes manually ?

Body:
I use the lazychaser's laravel-nestedset package and I'm having a problem when I try to delete a node with descendants.

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Post\Category;

class Post extends Model
{
    use HasFactory;

    ...

    /**
     * The categories that belong to the post.
     */
    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

    ...

}

namespace App\Models\Post;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Post;
use Kalnoy\Nestedset\NodeTrait;

class Category extends Model
{
    use HasFactory, NodeTrait;

    protected $table = 'post_categories';

    ...

    /**
     * The posts that belong to the category.
     */
    public function posts()
    {
        return $this->belongsToMany(Post::class);
    }

    public function delete()
    {
        $this->posts()->detach();
        parent::delete();
    }

    ...

}

When I delete a node that hasn't any descendant everything is ok.

$category->delete();

Now when I try to delete a node that has one or more descendants I get this error:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
update a parent row: a foreign key constraint fails
(myproject.category_post, CONSTRAINT
category_post_category_id_foreign FOREIGN KEY (category_id)
REFERENCES post_categories (id)) delete from post_categories
where post_categories._lft between 4 and 8

It looks like the Category delete() method is not called when the nested-set trait deletes the descendants.

How can I fix this issue, should I delete the descendant nodes manually ?


问:
How to set the Content-Type differently for each key value when requesting POST with multipart/form-data in Golang
When requesting POST with multipart/form-data using Golang, is there a way to send the request by setting the content-type differently for each key? For example, one key will send a file, and one key will send data in json format in application/json type. It was possible with postman, but I couldn't find a way to do it with Golang. If you know, please share it with me. Thank you. :)

Below is the cURL of the successful request value in postman.

```<code>curl --location --request POST '{API_URL}' \
--header 'Cookie: JSESSIONID={}' \
--form 'images=@"{dsfsdfs.png}"' \
--form 'request="{ \"id\": \"yoon\", \"memberName\": \"yoon\"}";type=application/json'
</code>```

And when I tried several times in Golang, I got an error requesting the content type 'application/octet-stream'.

Body:
When requesting POST with multipart/form-data using Golang, is there a way to send the request by setting the content-type differently for each key? For example, one key will send a file, and one key will send data in json format in application/json type. It was possible with postman, but I couldn't find a way to do it with Golang. If you know, please share it with me. Thank you. :)

Below is the cURL of the successful request value in postman.

curl --location --request POST '{API_URL}' \
--header 'Cookie: JSESSIONID={}' \
--form 'images=@"{dsfsdfs.png}"' \
--form 'request="{ \"id\": \"yoon\", \"memberName\": \"yoon\"}";type=application/json'

And when I tried several times in Golang, I got an error requesting the content type 'application/octet-stream'.