问:
Highcharts. Django won't load. Highcharts with Django
There is a wonderful library of js - Highcharts. I'm trying to link it to Django, and everything actually works, but not when I'm trying to insert a variable with content into data. Here's the code.

This function returns what I substitute in data in Highcharts.

```<code>def get_series(context):
    data_ser = []

for i in context:
    if i in ['One', "Two", "Three", "Four", "Five"]:
        data_ser.append({
            'name': i,
            'y': context[i],
            'z': 22.2
        })

data_ser = json.dumps(data_ser)

return data_ser
</code>```

And this is the jquery code itself:

```<code><script>
    $(document).ready(function () {

        var data_ser = '{{ data_ser|safe }}'
        console.log(data_ser)

        Highcharts.chart('container', {
            chart: {
                type: 'variablepie'
            },
            title: {
                text: 'Stats'
            },
            series: [{
                minPointSize: 10,
                innerSize: '20%',
                zMin: 0,
                name: 'countries',
                data: data_ser
            }]
        });
    })
</script>
</code>```

In series in data, I try to substitute data_ser, but the graph is not output. Although, if you write it manually, then everything will work.

Similar code works:

```<code><script>
    $(document).ready(function () {

        var data_ser = '{{ data_ser|safe }}'
        console.log(data_ser)

        Highcharts.chart('container', {
            chart: {
                type: 'variablepie'
            },
            title: {
                text: 'Stats'
            },
            series: [{
                minPointSize: 10,
                innerSize: '20%',
                zMin: 0,
                name: 'countries',
                data: [
                    {
                        "name": "One",
                        "y": 50.0,
                        "z": 22.2
                    }]
            }]
        });
    })
</script>
</code>```

I really hope for help. Or give at least alternative js libraries with graphs where this will work.

Body:
There is a wonderful library of js - Highcharts. I'm trying to link it to Django, and everything actually works, but not when I'm trying to insert a variable with content into data. Here's the code.

This function returns what I substitute in data in Highcharts.

def get_series(context):
    data_ser = []

for i in context:
    if i in ['One', "Two", "Three", "Four", "Five"]:
        data_ser.append({
            'name': i,
            'y': context[i],
            'z': 22.2
        })

data_ser = json.dumps(data_ser)

return data_ser

And this is the jquery code itself:

In series in data, I try to substitute data_ser, but the graph is not output. Although, if you write it manually, then everything will work.

Similar code works:

I really hope for help. Or give at least alternative js libraries with graphs where this will work.


来源: stackexchange

问:
How to generate different invoice series for different vendors in MySQL and Spring JPA alongwith Vendor Code and Year Prefixed
My scenario is I have different vendors who will be generating invoices. The series must be maintained for all in incremental order as follows

VEN1-2223-0001
VEN1-2223-0002
VEN2-2223-0001
VEN1-2223-0003
VEN2-2223-0002

where "VEN1" is a vendor code, 2223 is as per financial year and 0001 is series. I am able to prefix VEN1 using custom generator as follows

```<code>@Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "test_seq")
    @GenericGenerator(name = "test_seq", strategy = "VendorDealerCodePrefixedSequenceIdGenerator",
            parameters = {
                    @org.hibernate.annotations.Parameter(name = VendorCodePrefixedSequenceIdGenerator.INCREMENT_PARAM, value = "50"),
                    @org.hibernate.annotations.Parameter(name = VendorCodePrefixedSequenceIdGenerator.CODE_NUMBER_SEPARATOR_PARAMETER, value = "_"),
                    @org.hibernate.annotations.Parameter(name = VendorCodePrefixedSequenceIdGenerator.NUMBER_FORMAT_PARAMETER, value = "%05d") })
    private String testId;
</code>```

and

```<code>public class VendorCodePrefixedSequenceIdGenerator extends SequenceStyleGenerator {

    public static final String CODE_NUMBER_SEPARATOR_PARAMETER = "codeNumberSeparator";
    public static final String CODE_NUMBER_SEPARATOR_DEFAULT = "-";

    public static final String NUMBER_FORMAT_PARAMETER = "numberFormat";
    public static final String NUMBER_FORMAT_DEFAULT = "%05d";

    private String numberFormat;

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        return String.format("%s-", ((Test) object).getDealer().getDealerCode()) + String.format(numberFormat,
                super.generate(session, object));
    }

    @Override
    public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
        super.configure(LongType.INSTANCE, params, serviceRegistry);
        numberFormat = ConfigurationHelper.getString(NUMBER_FORMAT_PARAMETER,
                params, NUMBER_FORMAT_DEFAULT);
    }
}
</code>```

the year part is not there but that can be done on similar basis. Now I'm struggling for

how to reset series every financial year.

how to maintain different series for different vendors.

ContentLicense: CC BY-SA 4.0

Body:
My scenario is I have different vendors who will be generating invoices. The series must be maintained for all in incremental order as follows

VEN1-2223-0001
VEN1-2223-0002
VEN2-2223-0001
VEN1-2223-0003
VEN2-2223-0002

where "VEN1" is a vendor code, 2223 is as per financial year and 0001 is series. I am able to prefix VEN1 using custom generator as follows

@Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "test_seq")
    @GenericGenerator(name = "test_seq", strategy = "VendorDealerCodePrefixedSequenceIdGenerator",
            parameters = {
                    @org.hibernate.annotations.Parameter(name = VendorCodePrefixedSequenceIdGenerator.INCREMENT_PARAM, value = "50"),
                    @org.hibernate.annotations.Parameter(name = VendorCodePrefixedSequenceIdGenerator.CODE_NUMBER_SEPARATOR_PARAMETER, value = "_"),
                    @org.hibernate.annotations.Parameter(name = VendorCodePrefixedSequenceIdGenerator.NUMBER_FORMAT_PARAMETER, value = "%05d") })
    private String testId;

and

public class VendorCodePrefixedSequenceIdGenerator extends SequenceStyleGenerator {

    public static final String CODE_NUMBER_SEPARATOR_PARAMETER = "codeNumberSeparator";
    public static final String CODE_NUMBER_SEPARATOR_DEFAULT = "-";

    public static final String NUMBER_FORMAT_PARAMETER = "numberFormat";
    public static final String NUMBER_FORMAT_DEFAULT = "%05d";

    private String numberFormat;

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        return String.format("%s-", ((Test) object).getDealer().getDealerCode()) + String.format(numberFormat,
                super.generate(session, object));
    }

    @Override
    public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
        super.configure(LongType.INSTANCE, params, serviceRegistry);
        numberFormat = ConfigurationHelper.getString(NUMBER_FORMAT_PARAMETER,
                params, NUMBER_FORMAT_DEFAULT);
    }
}

the year part is not there but that can be done on similar basis. Now I'm struggling for

how to reset series every financial year.

how to maintain different series for different vendors.


问:
Merging Paginator and export html to xlsx and large amount of data
I'm trying to create a way to export the HTML table to xlsx, but I have a large amount of data in the queries. So I need to use pagination with Paginator so the browser doesn't load the data all at once and end up causing TimeOut. But when applying the Paginator and exporting, it only exports what is on the current page. Any suggestions to improve this code, such as creating a loop so that it can export all pages?

View function:

```<code>def export_project_data(request, pk):
    if str(request.user) != 'AnonymousUser':  # só vai ter acesso se for diferente de AnonymousUser
        individuals_list = Individual.objects.filter(Project=pk)
        traps = Sample_unit_trap.objects.filter(Project=pk)

        page = request.GET.get('page', 1)

        paginator = Paginator(individuals_list, 1000)
        try:
            individuals = paginator.page(page)
        except PageNotAnInteger:
            individuals = paginator.page(1)
        except EmptyPage:
            individuals = paginator.page(paginator.num_pages)

        path_info = request.META['PATH_INFO']

        context = {
            'individuals': individuals,
            'pk': pk,
            'traps': traps,
            'header': 'export_project_data',
            'path_info': path_info
        }

        return render(request, 'inv/index.html', context)
</code>```

HTML paginator code:

```<code><div class="table-div">
{% if individuals.has_other_pages %}
  <ul class="pagination pagination-sm">
    {% if individuals.has_previous %}
      <li><a href="?page={{ individuals.previous_page_number }}">«</a></li>
    {% else %}
      <li class="disabled"><span>«</span></li>
    {% endif %}
    {% for i in individuals.paginator.page_range %}
      {% if individuals.number == i %}
        <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
      {% else %}
        <li><a href="?page={{ i }}">{{ i }}</a></li>
      {% endif %}
    {% endfor %}
    {% if individuals.has_next %}
      <li><a href="?page={{ individuals.next_page_number }}">»</a></li>
    {% else %}
      <li class="disabled"><span>»</span></li>
    {% endif %}
  </ul>
{% endif %}
</div>
{% endif %}
</code>```

Javascript html to xlsx code:

```<code><script>
  function html_table_to_excel(type)
    {
        var data = document.getElementById('data');

        var file = XLSX.utils.table_to_book(data, {sheet: "Dados_Ecológicos"});

        XLSX.write(file, { bookType: type, bookSST: true, type: 'base64' });

        XLSX.writeFile(file, 'file.' + type);
    }

    const export_button = document.getElementById('export_button');

    export_button.addEventListener('click', () =>  {
        html_table_to_excel('xlsx');
    });
</script>
</code>```

Body:
I'm trying to create a way to export the HTML table to xlsx, but I have a large amount of data in the queries. So I need to use pagination with Paginator so the browser doesn't load the data all at once and end up causing TimeOut. But when applying the Paginator and exporting, it only exports what is on the current page. Any suggestions to improve this code, such as creating a loop so that it can export all pages?

View function:

def export_project_data(request, pk):
    if str(request.user) != 'AnonymousUser':  # só vai ter acesso se for diferente de AnonymousUser
        individuals_list = Individual.objects.filter(Project=pk)
        traps = Sample_unit_trap.objects.filter(Project=pk)

        page = request.GET.get('page', 1)

        paginator = Paginator(individuals_list, 1000)
        try:
            individuals = paginator.page(page)
        except PageNotAnInteger:
            individuals = paginator.page(1)
        except EmptyPage:
            individuals = paginator.page(paginator.num_pages)

        path_info = request.META['PATH_INFO']

        context = {
            'individuals': individuals,
            'pk': pk,
            'traps': traps,
            'header': 'export_project_data',
            'path_info': path_info
        }

        return render(request, 'inv/index.html', context)

HTML paginator code:

{% if individuals.has_other_pages %}

    {% if individuals.has_previous %}

«

    {% else %}

«

    {% endif %}
    {% for i in individuals.paginator.page_range %}
      {% if individuals.number == i %}

{{ i }} (current)

      {% else %}

{{ i }}

      {% endif %}
    {% endfor %}
    {% if individuals.has_next %}

»

    {% else %}

»

    {% endif %}

{% endif %}

{% endif %}

Javascript html to xlsx code:


问:
How to disable Camunda http and soap connectors
The docmentation only tells me how to add more connectors, but I cannot find anywhere to tell me how to stop those connectors from being loaded. Removing the camunda-connector libs from the classpath just causes the ProcessEngineConfiguration to throw ClassNotFoundException.

We use Camunda 7.17.0 as an embedded workflow engine that doesn't need to be accessed through REST or SOAP, so I want to close those avenues of attack.


问:
Dynamically adding new subclasses to a main class with owlready in python
I'm trying to add a subclass to a main class, Using owlready2 on an ontology I created on Protege, when I try to run the program i see no error.

But when I go to look at the ontology with Protege, I don't see any changes

To simplify things I have an Ontology like this:

```<code> - owl:Thing
     - TypeOfWine
        - White_wine
        - Red_wine
            - red_wine1
            - red_wine2
</code>```

I am trying to add a new subclass called "white_wine1" to a class called "White_wine":

parent_class = "White_wine"

child_class_name = "white_wine1

with onto:
        new_generated_class = types.new_class(
            child_class_name, tuple(list(onto[parent_class].subclasses())))

        print("New class added: {}".format(new_generated_class))

        onto.save(
            file="C:/wines2.owl", format="rdfxml")

```

at this point I expect to have correctly added the subclass to the class, and going to Protege I should see the new subclass.
Unfortunately, I don't see the new subclass.

what am i doing wrong? i didn't understand how ontologies work or is there some error in the code i wrote

Body:
I'm trying to add a subclass to a main class, Using owlready2 on an ontology I created on Protege, when I try to run the program i see no error.

But when I go to look at the ontology with Protege, I don't see any changes

To simplify things I have an Ontology like this:

 - owl:Thing
     - TypeOfWine
        - White_wine
        - Red_wine
            - red_wine1
            - red_wine2

I am trying to add a new subclass called "white_wine1" to a class called "White_wine":

parent_class = "White_wine"

child_class_name = "white_wine1

with onto:
        new_generated_class = types.new_class(
            child_class_name, tuple(list(onto[parent_class].subclasses())))

        print("New class added: {}".format(new_generated_class))

        onto.save(
            file="C:/wines2.owl", format="rdfxml")

at this point I expect to have correctly added the subclass to the class, and going to Protege I should see the new subclass.
Unfortunately, I don't see the new subclass.

what am i doing wrong? i didn't understand how ontologies work or is there some error in the code i wrote


问:
Interrupt operation if client connection is already closed or client has received SocketTimeoutException
I have created an API at my backend server side code, suppose a request comes from browser and it got timeout because identityService took more than expected time. Since, client has already received SocketTimeoutException so there is no benefit to call hrService and accountService because client/browser is not going to get the response as TCP connection is already closed.

Is there a way or line of code I can write between identityService and hrService API call (and other places too) where if Client connection is already closed, my code should also stop executing next line of code.
In above example, the thread should break before hrService and accountService API call since connection is already closed.

```<code>////Controller class
@RestController
@RequestMapping(path = "/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping(path = "/detail/{employeeId}")
    public ResponseEntity<EmployeeDetailResponse> employeeDetail(@PathVariable("employeeId") Long employeeId)  {
        return new ResponseEntity(employeeService.getEmployeeDetail(employeeId), HttpStatus.OK);
    }
}

//// Service class
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private HRService hrService;

    @Autowired
    private AccountService accountService;

    @Transactional
    public EmployeeDetailResponse getEmployeeDetail(Long employeeId) {
        Employee employee = employeeRepository.findById(employeeId);

        //Call API-1 identityService to get Address and phone details
        IdentityDetail identityDetail = identityService.getIdentity(employeeId);

        //Call  API-2 hrService to get employement Details
        EmplyementDetail employementDetail = hrService.getEmployementDetail(employeeId);

        //Call API-3 accountService to get Salary details
        AccountDetail accountDetail = accountService.getAccountDetail(employeeId);

        return mergeResponses(employee,identityDetail,employementDetail,accountDetail)
    }
}
</code>```

Appriciate your help.

Body:
I have created an API at my backend server side code, suppose a request comes from browser and it got timeout because identityService took more than expected time. Since, client has already received SocketTimeoutException so there is no benefit to call hrService and accountService because client/browser is not going to get the response as TCP connection is already closed.

Is there a way or line of code I can write between identityService and hrService API call (and other places too) where if Client connection is already closed, my code should also stop executing next line of code.
In above example, the thread should break before hrService and accountService API call since connection is already closed.

////Controller class
@RestController
@RequestMapping(path = "/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping(path = "/detail/{employeeId}")
    public ResponseEntity<EmployeeDetailResponse> employeeDetail(@PathVariable("employeeId") Long employeeId)  {
        return new ResponseEntity(employeeService.getEmployeeDetail(employeeId), HttpStatus.OK);
    }
}

//// Service class
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private HRService hrService;

    @Autowired
    private AccountService accountService;

    @Transactional
    public EmployeeDetailResponse getEmployeeDetail(Long employeeId) {
        Employee employee = employeeRepository.findById(employeeId);

        //Call API-1 identityService to get Address and phone details
        IdentityDetail identityDetail = identityService.getIdentity(employeeId);

        //Call  API-2 hrService to get employement Details
        EmplyementDetail employementDetail = hrService.getEmployementDetail(employeeId);

        //Call API-3 accountService to get Salary details
        AccountDetail accountDetail = accountService.getAccountDetail(employeeId);

        return mergeResponses(employee,identityDetail,employementDetail,accountDetail)
    }
}

Appriciate your help.


问:
How do i get a shinyshortcut of a new App?
I have developed an R Shiny App during the last April 2022 and used the shinyshortcut library in order to create shortcut for my app. Then I just deleted that file of the App and its shinyshortcut. Now in this month I developed a new app with new code (totally different from the previous) and I included the code for shortcut creation but when I launch the new shinyshortcut I get that old App from the last year. I tried to clean everything but in vain.

```<code>Library(shinyshortcut)
shinyShortcut()
</code>```

Body:
I have developed an R Shiny App during the last April 2022 and used the shinyshortcut library in order to create shortcut for my app. Then I just deleted that file of the App and its shinyshortcut. Now in this month I developed a new app with new code (totally different from the previous) and I included the code for shortcut creation but when I launch the new shinyshortcut I get that old App from the last year. I tried to clean everything but in vain.

Library(shinyshortcut)
shinyShortcut()


问:
fork() Server in C doesnt respond to client
I wrote a login server with fork in C using txt file as a database. I found a problem when im trying to use my client more than one time, that sometimes its bugs, and doesnt print anything in the console.

Here is the server code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <arpa/inet.h>
FILE* fp;

int main() {
  int server_socket;
  socklen_t addr_size;
  struct sockaddr_in server_address;
  struct sockaddr_in client_address;
  char buffor[1024], info[21], pass[21], decision[10];
  pid_t childpid;
  fp = fopen("baza.txt", "a+");
  server_socket = socket(AF_INET, SOCK_STREAM,0);
  if(server_socket < 0){
    printf("Błąd tworzenia socketu.\n");
    exit(EXIT_FAILURE);
  }
  printf("Utworzono socket\n");
  memset(&server_address,'\0',sizeof(server_socket));
  server_address.sin_family = AF_INET;
  server_address.sin_port = htons(9002);
  server_address.sin_addr.s_addr = inet_addr("127.0.0.1");

  if ((bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address)))<0){
    printf("Błąd przy przybijaniu gniazda");
    exit(EXIT_FAILURE);
  }
  listen(server_socket, 20);
  while(1){
    rewind(fp);
    int client_socket = accept(server_socket, (struct sockaddr*)&client_address, &addr_size);
    printf("Połączenie od IP: %s i portu: %d\n",inet_ntoa(client_address.sin_addr),ntohs(client_address.sin_port));
    if ((childpid = fork()) == 0){
      bzero(&decision,sizeof(decision));
      bzero(&buffor,sizeof(buffor));
      bzero(&pass,sizeof(pass));
      recv(client_socket,&decision,sizeof(decision),0);
      FILE *local_fp = fdopen(fileno(fp),"a+");
      int foundlog = 0;
      int foundrej = 0;
      char line[100];
      if(strcmp(decision,"log")==0){
        rewind(local_fp);
        recv(client_socket,&buffor,sizeof(buffor),0);
        strcat(buffor,"login");
        while(fscanf(local_fp,"%100s",info)==1){
          if(strcmp(info, buffor)==0){
            send(client_socket,"Znaleziono login",strlen("znaleziono login"),0);
            foundlog = 1;
          }
        }

        if (foundlog==0){
          send(client_socket,"Nie ma takiego loginu", strlen("Nie ma takiego loginu"),0);
          exit(EXIT_FAILURE);
        }
        rewind(local_fp);
        if (foundlog==1){
          recv(client_socket,&pass,sizeof(pass),0);
          strcat(buffor,"\t");
          strcat(buffor,pass);
          while(fgets(line,100,local_fp)!=NULL){
            if(strstr(line,buffor)!=NULL){
              send(client_socket,"Zalogowano",strlen("Zalogowano"),0);
              foundlog=2;
            }
          }
        }

        if (foundlog==1){
          send(client_socket,"Hasło nie pasuje do nazwy użytkownika",strlen("Hasło nie pasuje do nazwy użytkownika"),0);
          exit(EXIT_FAILURE);
        }
      }
      if(strcmp(decision,"rej")==0){
        recv(client_socket,&buffor,sizeof(buffor),0);
        strcat(buffor,"login");
        while(fscanf(local_fp,"%100s",info)==1){
          if(strcmp(info, buffor)==0){
            send(client_socket,"Taki login już istnieje",strlen("Taki login już istnieje"),0);
            exit(EXIT_FAILURE);
          }
        }
        send(client_socket,"Podany login jest wolny",strlen("Podany login jest wolny"),0);
        recv(client_socket,&pass,sizeof(pass),0);
        strcat(buffor,"\t");
        strcat(buffor,pass);
        rewind(local_fp);
        fprintf(local_fp,"%s\n",buffor);
        send(client_socket,"Zarejestrowano nowego użytkownika",strlen("Zarejestrowano nowego użytkownika"),0);
      }
      fclose(local_fp);
      close(client_socket);

    }
    close(client_socket);
  }
  fclose(fp);
  return 0;
}
</code>```

And client

```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <arpa/inet.h>

int main(){

  int client_socket;
  char login[20], info[20], ans[1024], pass[20];
  client_socket = socket(AF_INET, SOCK_STREAM, 0);

  struct sockaddr_in server_address;
  server_address.sin_family = AF_INET;
  server_address.sin_port = htons(9002);
  server_address.sin_addr.s_addr = INADDR_ANY;
  system("clear");

  int status = connect(client_socket, (struct sockaddr *) &server_address, sizeof(server_address));
  if (status == -1){
    printf("Nie udało się połączyć do serwera\n");
    exit(EXIT_FAILURE);
  }
  bzero(&login,sizeof(login));
  bzero(&ans,sizeof(ans));
  bzero(&info,sizeof(info));
  printf("--------Witaj na serwerze--------\n");
  printf("Wybierz operację\n");
  printf("1. Rejestracja\n");
  printf("2. Logowanie\n");
  scanf("%s",info);
  if((strcmp(info, "logowanie")) == 0 || (strcmp(info,"2")) == 0){
      send(client_socket,"log",strlen("log"),0);
      system("clear");
      printf("Wybrano zalogowanie\n");
      printf("Login: ");
      scanf("%s",login);
      if((send(client_socket,&login,sizeof(login),0))<0){
        printf("Błąd przy wysyłaniu\n");
      }
      if((recv(client_socket,&ans,sizeof(ans),0))<0){
        printf("Błąd przy odbieraniu\n");
      }
      printf("%s\n",ans);
      bzero(&ans,sizeof(ans));
      printf("Podaj hasło: ");
      scanf("%s",pass);
      send(client_socket,&pass,sizeof(pass),0);
      recv(client_socket,&ans,sizeof(ans),0);
      printf("Odpowiedź z serwera: %s\n",ans);
  }
  if((strcmp(info, "rejestracja")) == 0 || (strcmp(info,"1")) == 0){
      send(client_socket,"rej",strlen("rej"),0);
      system("clear");
      printf("Wybrano tworzenie nowego użytkownika\n");
      printf("Podaj swój login:");
      scanf("%s",login);
      if((send(client_socket,&login,sizeof(login),0))<0){
        printf("Błąd przy wysyłaniu\n");
      }
      if((recv(client_socket,&ans,sizeof(ans),0))<0){
        printf("Błąd przy odbieraniu\n");
      }
      printf("%s\n",ans);
      printf("Podaj swoje hasło:");
      scanf("%s",pass);
      send(client_socket,&pass,sizeof(pass),0);
      recv(client_socket,&ans,sizeof(ans),0);
      printf("Odpowiedź z serwera: %s\n",ans);
  }
  return 0;
}
</code>```

And output of the terminal

the database looks like this

```<code>macieklogin 123
kubalogin   123
kacperlogin 1234
</code>```

I have tried rewriting the client and server but it didnt help at all

Body:
I wrote a login server with fork in C using txt file as a database. I found a problem when im trying to use my client more than one time, that sometimes its bugs, and doesnt print anything in the console.

Here is the server code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <arpa/inet.h>
FILE* fp;

int main() {
  int server_socket;
  socklen_t addr_size;
  struct sockaddr_in server_address;
  struct sockaddr_in client_address;
  char buffor[1024], info[21], pass[21], decision[10];
  pid_t childpid;
  fp = fopen("baza.txt", "a+");
  server_socket = socket(AF_INET, SOCK_STREAM,0);
  if(server_socket < 0){
    printf("Błąd tworzenia socketu.\n");
    exit(EXIT_FAILURE);
  }
  printf("Utworzono socket\n");
  memset(&server_address,'\0',sizeof(server_socket));
  server_address.sin_family = AF_INET;
  server_address.sin_port = htons(9002);
  server_address.sin_addr.s_addr = inet_addr("127.0.0.1");

  if ((bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address)))<0){
    printf("Błąd przy przybijaniu gniazda");
    exit(EXIT_FAILURE);
  }
  listen(server_socket, 20);
  while(1){
    rewind(fp);
    int client_socket = accept(server_socket, (struct sockaddr*)&client_address, &addr_size);
    printf("Połączenie od IP: %s i portu: %d\n",inet_ntoa(client_address.sin_addr),ntohs(client_address.sin_port));
    if ((childpid = fork()) == 0){
      bzero(&decision,sizeof(decision));
      bzero(&buffor,sizeof(buffor));
      bzero(&pass,sizeof(pass));
      recv(client_socket,&decision,sizeof(decision),0);
      FILE *local_fp = fdopen(fileno(fp),"a+");
      int foundlog = 0;
      int foundrej = 0;
      char line[100];
      if(strcmp(decision,"log")==0){
        rewind(local_fp);
        recv(client_socket,&buffor,sizeof(buffor),0);
        strcat(buffor,"login");
        while(fscanf(local_fp,"%100s",info)==1){
          if(strcmp(info, buffor)==0){
            send(client_socket,"Znaleziono login",strlen("znaleziono login"),0);
            foundlog = 1;
          }
        }

        if (foundlog==0){
          send(client_socket,"Nie ma takiego loginu", strlen("Nie ma takiego loginu"),0);
          exit(EXIT_FAILURE);
        }
        rewind(local_fp);
        if (foundlog==1){
          recv(client_socket,&pass,sizeof(pass),0);
          strcat(buffor,"\t");
          strcat(buffor,pass);
          while(fgets(line,100,local_fp)!=NULL){
            if(strstr(line,buffor)!=NULL){
              send(client_socket,"Zalogowano",strlen("Zalogowano"),0);
              foundlog=2;
            }
          }
        }

        if (foundlog==1){
          send(client_socket,"Hasło nie pasuje do nazwy użytkownika",strlen("Hasło nie pasuje do nazwy użytkownika"),0);
          exit(EXIT_FAILURE);
        }
      }
      if(strcmp(decision,"rej")==0){
        recv(client_socket,&buffor,sizeof(buffor),0);
        strcat(buffor,"login");
        while(fscanf(local_fp,"%100s",info)==1){
          if(strcmp(info, buffor)==0){
            send(client_socket,"Taki login już istnieje",strlen("Taki login już istnieje"),0);
            exit(EXIT_FAILURE);
          }
        }
        send(client_socket,"Podany login jest wolny",strlen("Podany login jest wolny"),0);
        recv(client_socket,&pass,sizeof(pass),0);
        strcat(buffor,"\t");
        strcat(buffor,pass);
        rewind(local_fp);
        fprintf(local_fp,"%s\n",buffor);
        send(client_socket,"Zarejestrowano nowego użytkownika",strlen("Zarejestrowano nowego użytkownika"),0);
      }
      fclose(local_fp);
      close(client_socket);

    }
    close(client_socket);
  }
  fclose(fp);
  return 0;
}

And client

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <arpa/inet.h>

int main(){

  int client_socket;
  char login[20], info[20], ans[1024], pass[20];
  client_socket = socket(AF_INET, SOCK_STREAM, 0);

  struct sockaddr_in server_address;
  server_address.sin_family = AF_INET;
  server_address.sin_port = htons(9002);
  server_address.sin_addr.s_addr = INADDR_ANY;
  system("clear");

  int status = connect(client_socket, (struct sockaddr *) &server_address, sizeof(server_address));
  if (status == -1){
    printf("Nie udało się połączyć do serwera\n");
    exit(EXIT_FAILURE);
  }
  bzero(&login,sizeof(login));
  bzero(&ans,sizeof(ans));
  bzero(&info,sizeof(info));
  printf("--------Witaj na serwerze--------\n");
  printf("Wybierz operację\n");
  printf("1. Rejestracja\n");
  printf("2. Logowanie\n");
  scanf("%s",info);
  if((strcmp(info, "logowanie")) == 0 || (strcmp(info,"2")) == 0){
      send(client_socket,"log",strlen("log"),0);
      system("clear");
      printf("Wybrano zalogowanie\n");
      printf("Login: ");
      scanf("%s",login);
      if((send(client_socket,&login,sizeof(login),0))<0){
        printf("Błąd przy wysyłaniu\n");
      }
      if((recv(client_socket,&ans,sizeof(ans),0))<0){
        printf("Błąd przy odbieraniu\n");
      }
      printf("%s\n",ans);
      bzero(&ans,sizeof(ans));
      printf("Podaj hasło: ");
      scanf("%s",pass);
      send(client_socket,&pass,sizeof(pass),0);
      recv(client_socket,&ans,sizeof(ans),0);
      printf("Odpowiedź z serwera: %s\n",ans);
  }
  if((strcmp(info, "rejestracja")) == 0 || (strcmp(info,"1")) == 0){
      send(client_socket,"rej",strlen("rej"),0);
      system("clear");
      printf("Wybrano tworzenie nowego użytkownika\n");
      printf("Podaj swój login:");
      scanf("%s",login);
      if((send(client_socket,&login,sizeof(login),0))<0){
        printf("Błąd przy wysyłaniu\n");
      }
      if((recv(client_socket,&ans,sizeof(ans),0))<0){
        printf("Błąd przy odbieraniu\n");
      }
      printf("%s\n",ans);
      printf("Podaj swoje hasło:");
      scanf("%s",pass);
      send(client_socket,&pass,sizeof(pass),0);
      recv(client_socket,&ans,sizeof(ans),0);
      printf("Odpowiedź z serwera: %s\n",ans);
  }
  return 0;
}

And output of the terminal

the database looks like this

macieklogin 123
kubalogin   123
kacperlogin 1234

I have tried rewriting the client and server but it didnt help at all


问:
Read previously exported object with a non primitive class associated
I have exported an ArrayList of instances of class defined by myself, and I need to read in another project. I don't intend to use the methods of that class in particular, only to use its atributes.

I could transform those atribuites into ArrayList of primitive objects, that I could read afterwards without the need of having that class implemented again in that project, but I'm specifically asked not to do so. Is there a way to get only the atributes of such class?


问:
How do I stop the attribute "position: fixed" at a certain point?
How do I stop the attribute "position: fixed" at a certain point so the button in my case, isn't kind of following the user when scrolling anymore. Because I have this footer at the bottom of my page and the "book now" button overlaps the footer and I don't want that. How do I "stop" the button just above the footer?

const slideshowImages = document.querySelectorAll('#slideshow img');
let currentIndex = 0;

function showNextImage() {
  console.log(slideshowImages[currentIndex]);
  slideshowImages[currentIndex].style.display = 'none';
  currentIndex = (currentIndex + 1) % slideshowImages.length;
  slideshowImages[currentIndex].style.display = 'block';
}
console.log(slideshowImages);
setInterval(showNextImage, 5000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  overflow: scroll;
}

h1 {
  text-align: center;
  font-size: 3.5em;
}

h2 {
  text-align: center;
  font-size: 2em;
  padding-top: 2%;
}

p {
  margin: 20px 0;
  line-height: 1.5;
}

ul {
  list-style: none;
  margin: 20px 0;
  padding: 0;
}

header {
  overflow: hidden;
  position: relative;
}

li {
  margin: 10px 0;
}

.content {
  position: relative;
  padding: 20px 1px;
  padding-left: 2.5%;
}

img {
  width: 90vw;
  margin-left: auto;
  margin-right: auto;
  display: block;
  vertical-align: top;
}

#slideshow {
  position: absolute;
  top: 55%;
  left: 12%;
  width: 300px;
  height: 300 px;
}

#slideshow img {
  width: 170%;
  height: 170%;
  object-fit: cover;
}

#menu {
  position: fixed;
  width: 100%;
  background-color: #333;
  color: #fff;
  z-index: 2;
  padding: 0;
}

.menu-button {
  font-family: Arial;
}

#menu ul {
  display: flex;
  margin: 0;
  padding: 0;
}

#menu li {
  flex: 1;
  text-align: center;
}

#menu a {
  display: block;
  color: #fff;
  text-decoration: none;
  padding: 20px;
}

#menu a:hover {
  background-color: #444;
}

.Infotext {
  position: absolute;
  top: 57%;
  left: 40%;
  font-size: 1.5em;
}

.InfotextÜ {
  position: absolute;
  top: 53.5%;
  left: 40%;
  font-family: Arno Pro Caption;
  font-size: 2.0em;
}

.button-24 {
  position: fixed;
  top: 90%;
  left: 45.3%;
  background: #FF4742;
  border: 1px solid #FF4742;
  border-radius: 6px;
  box-shadow: rgba(0, 0, 0, 0.1) 1px 2px 4px;
  box-sizing: border-box;
  color: #FFFFFF;
  cursor: pointer;
  display: inline-block;
  font-family: nunito, roboto, proxima-nova, "proxima nova", sans-serif;
  font-size: 16px;
  font-weight: 800;
  line-height: 16px;
  min-height: 40px;
  outline: 0;
  padding: 12px 43px;
  text-align: center;
  text-rendering: geometricprecision;
  text-transform: none;
  user-select: none;
  -webkit-user-select: none;
  touch-action: manipulation;
  vertical-align: middle;
}

.button-24:hover,
.button-24:active {
  background-color: initial;
  background-position: 0 0;
  color: #FF4742;
}

.button-24:active {
  opacity: .5;
}

footer {
  background-color: #333;
  color: #fff;
  padding: 20px;
  text-align: center;
}</code>```

Home

Bildgalerie

Kontakt

In der Nähe

Paradiso Piccolo

Das Paradiso Piccolo ist eine Ferienwohnung am See.

Das Apartment

Das Apartment ist für bis zu 6 Personen geignet.
 Im Apartment gibt es außerdem:

TV

Stereo-Anlage

WLAN (auf Wunsch)

Bücher

Brettspiele

Decken- und tragbare Ventilatoren

Infrarotheizung (gegen Aufpreis)

Kühlschrank

Mikrowelle

Geschirr und Besteck

Grundausstattung zum Kochen (Töpfe, Pfannen, Öl, Salz, Pfeffer)

Gefrierschrank

Herd (Gas und Elektro)

Bügeleisen

Geschirrspülmaschine

Waschmaschine

Wasserkocher

Nespresso-Maschine

Toaster

Grill

Holzkohle

Grillbesteck

Föhn

Shampoo, Duschgel, Seife, etc

Gartenmöbel (Liege, etc)

Kostenlose Parkplätze

  Bettwäsche und Handtücher sind selbst mitzunehmen!

Standort

Via Cristoforo Colombo, 4, 37010 Brenzone VR, Italien

    <button class="button-24" role="button">Book Now!</button>

Paradiso Piccolo

123 Main Street

Anytown, USA

  <button onclick="location.href='C:/Users/Charlie/Desktop/Impressum.html'">Impressum</button>
  <button onclick="location.href='C:/Users/Charlie/Desktop/Datenschutz.html'">Datenschutz</button>
```

Body:
How do I stop the attribute "position: fixed" at a certain point so the button in my case, isn't kind of following the user when scrolling anymore. Because I have this footer at the bottom of my page and the "book now" button overlaps the footer and I don't want that. How do I "stop" the button just above the footer?

const slideshowImages = document.querySelectorAll('#slideshow img');
let currentIndex = 0;

function showNextImage() {
  console.log(slideshowImages[currentIndex]);
  slideshowImages[currentIndex].style.display = 'none';
  currentIndex = (currentIndex + 1) % slideshowImages.length;
  slideshowImages[currentIndex].style.display = 'block';
}
console.log(slideshowImages);
setInterval(showNextImage, 5000);

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  overflow: scroll;
}

h1 {
  text-align: center;
  font-size: 3.5em;
}

h2 {
  text-align: center;
  font-size: 2em;
  padding-top: 2%;
}

p {
  margin: 20px 0;
  line-height: 1.5;
}

ul {
  list-style: none;
  margin: 20px 0;
  padding: 0;
}

header {
  overflow: hidden;
  position: relative;
}

li {
  margin: 10px 0;
}

.content {
  position: relative;
  padding: 20px 1px;
  padding-left: 2.5%;
}

img {
  width: 90vw;
  margin-left: auto;
  margin-right: auto;
  display: block;
  vertical-align: top;
}

#slideshow {
  position: absolute;
  top: 55%;
  left: 12%;
  width: 300px;
  height: 300 px;
}

#slideshow img {
  width: 170%;
  height: 170%;
  object-fit: cover;
}

#menu {
  position: fixed;
  width: 100%;
  background-color: #333;
  color: #fff;
  z-index: 2;
  padding: 0;
}

.menu-button {
  font-family: Arial;
}

#menu ul {
  display: flex;
  margin: 0;
  padding: 0;
}

#menu li {
  flex: 1;
  text-align: center;
}

#menu a {
  display: block;
  color: #fff;
  text-decoration: none;
  padding: 20px;
}

#menu a:hover {
  background-color: #444;
}

.Infotext {
  position: absolute;
  top: 57%;
  left: 40%;
  font-size: 1.5em;
}

.InfotextÜ {
  position: absolute;
  top: 53.5%;
  left: 40%;
  font-family: Arno Pro Caption;
  font-size: 2.0em;
}

.button-24 {
  position: fixed;
  top: 90%;
  left: 45.3%;
  background: #FF4742;
  border: 1px solid #FF4742;
  border-radius: 6px;
  box-shadow: rgba(0, 0, 0, 0.1) 1px 2px 4px;
  box-sizing: border-box;
  color: #FFFFFF;
  cursor: pointer;
  display: inline-block;
  font-family: nunito, roboto, proxima-nova, "proxima nova", sans-serif;
  font-size: 16px;
  font-weight: 800;
  line-height: 16px;
  min-height: 40px;
  outline: 0;
  padding: 12px 43px;
  text-align: center;
  text-rendering: geometricprecision;
  text-transform: none;
  user-select: none;
  -webkit-user-select: none;
  touch-action: manipulation;
  vertical-align: middle;
}

.button-24:hover,
.button-24:active {
  background-color: initial;
  background-position: 0 0;
  color: #FF4742;
}

.button-24:active {
  opacity: .5;
}

footer {
  background-color: #333;
  color: #fff;
  padding: 20px;
  text-align: center;
}

Home

Bildgalerie

Kontakt

In der Nähe

Paradiso Piccolo

Das Paradiso Piccolo ist eine Ferienwohnung am See.

Das Apartment

Das Apartment ist für bis zu 6 Personen geignet.
 Im Apartment gibt es außerdem:

TV

Stereo-Anlage

WLAN (auf Wunsch)

Bücher

Brettspiele

Decken- und tragbare Ventilatoren

Infrarotheizung (gegen Aufpreis)

Kühlschrank

Mikrowelle

Geschirr und Besteck

Grundausstattung zum Kochen (Töpfe, Pfannen, Öl, Salz, Pfeffer)

Gefrierschrank

Herd (Gas und Elektro)

Bügeleisen

Geschirrspülmaschine

Waschmaschine

Wasserkocher

Nespresso-Maschine

Toaster

Grill

Holzkohle

Grillbesteck

Föhn

Shampoo, Duschgel, Seife, etc

Gartenmöbel (Liege, etc)

Kostenlose Parkplätze

  Bettwäsche und Handtücher sind selbst mitzunehmen!

Standort

Via Cristoforo Colombo, 4, 37010 Brenzone VR, Italien

    <button class="button-24" role="button">Book Now!</button>

Paradiso Piccolo

123 Main Street

Anytown, USA

  <button onclick="location.href='C:/Users/Charlie/Desktop/Impressum.html'">Impressum</button>
  <button onclick="location.href='C:/Users/Charlie/Desktop/Datenschutz.html'">Datenschutz</button>


问:
Integrate CSS with yagmail python
I am trying to automate a report and send it by mail daily. I would like to have images / graphs embedded in my mail.

My program currently generates graphs and saves them on my Destok so I can then join them to my mail with yagmail. I pass a list of HTML lines as strings in a "body" variable to generate the mail. I then extend my HTML body to scale it for every studied subject automatically.

Issue : the graphs do not show on mobile. I think a good option would be to add something in my HTML mail body like CSS : img {max-height : 100 %;} but can't figure how to do it with my current method.

I tried to use a mail service provider (mailjet) but could not customize my mail as I wished (ex: loop through text and images).

Hope someone can help.

My mail code :

```<code>
#receivers as a list
receivers = ["abcdef@gmail.com",
    "ghijkl@gmail.com"
    ]

#date
now=datetime.now()  #record current moment
date_mail=str(now.strftime('%d%m%Y'))+ " (ddmmYYYY)"    #format as daymonthyear + add some text + all as text => will be in mail header

#Identification
yagmail.register("my_sender_mail@gmail.com", "password_me")    #register to yagmail / gmail adress + application password
yag = yagmail.SMTP("my_sender_mail@gmail.com")                      #define mail

#mail body
body = ["<p>Hello,</p>",  #will be merged for every analysis / is a list !
"<p>Please find below your daily ......</p>",
"<p>Our method combines different strategies to ..... </p>",
"<p>If we are not confident enough accross multiple methods ....</p>",
"<p>If a method yields poor result it will not be displayed on the graphs.</p>",
"<br>",    #input a line
"<p>If the graphs do not show properly please allow your mailbox to ""download"" images for this sender.</p>",
"<p>Please do not hesitate to contact us to ....</p>",
"<br>",
"<p><b>"+str(tickers[0])+" </b></p>",                                 # first ticker in the body
"<p>Daily signal: "+ mail_decision[0] +" </p>",                       # first decision for the ticker
"<p>Graph :</p>",
"""<img src="C://Users//tangu//OneDrive//Bureau//image_"""+str(0)+"""_complete.png" width="700" height="450">""",   #embed main graph for the whole period, set width (issue!) and height
"""<img src="C://Users//tangu//OneDrive//Bureau//image_"""+str(0)+"""_reduced.png" width="700" height="450">"""     #embed the reduced graph for a short term view, set width (issue!) and height
]

for i in range(1,len(tickers)):                         #extend the body for every strategy
    body_to_app=["<p><b>"+str(tickers[i])+" </b></p>",  #ticker in the body
    "<p>Daily signal: "+ mail_decision[i] +" </p>",     #decision for the ticker
    "<p>Graph :</p>",
    """<img src="C://Users//tangu//OneDrive//Bureau//image_"""+str(i)+"""_complete.png" width="700" height="450">""",   #embed main graph for the whole period, set width (issue!) and height
    """<img src="C://Users//tangu//OneDrive//Bureau//image_"""+str(i)+"""_reduced.png" width="700" height="450">""",    #embed the reduced graph for a short term view, set width (issue!) and height
    ]
    body.extend(body_to_app)                            #extend (/"merge") the list

#add best regards
body.extend(["<p>Best Regards,<p>"])

#loop through recievers
for receiver in receivers:                                  #for element in recievers
    #send the mail
    yag.send(
        to=receiver,
        subject="Subject at date :  _ "+str(date_mail),
        contents=body
    )

</code>```

Title: Integrate CSS with yagmail python

Body:
I am trying to automate a report and send it by mail daily. I would like to have images / graphs embedded in my mail.

My program currently generates graphs and saves them on my Destok so I can then join them to my mail with yagmail. I pass a list of HTML lines as strings in a "body" variable to generate the mail. I then extend my HTML body to scale it for every studied subject automatically.

Issue : the graphs do not show on mobile. I think a good option would be to add something in my HTML mail body like CSS : img {max-height : 100 %;} but can't figure how to do it with my current method.

I tried to use a mail service provider (mailjet) but could not customize my mail as I wished (ex: loop through text and images).

Hope someone can help.

My mail code :

#receivers as a list
receivers = ["abcdef@gmail.com",
    "ghijkl@gmail.com"
    ]

#date
now=datetime.now()  #record current moment
date_mail=str(now.strftime('%d%m%Y'))+ " (ddmmYYYY)"    #format as daymonthyear + add some text + all as text => will be in mail header

#Identification
yagmail.register("my_sender_mail@gmail.com", "password_me")    #register to yagmail / gmail adress + application password
yag = yagmail.SMTP("my_sender_mail@gmail.com")                      #define mail

#mail body
body = ["
Hello,
",  #will be merged for every analysis / is a list !
"
Please find below your daily ......
",
"
Our method combines different strategies to .....
",
"
If we are not confident enough accross multiple methods ....
",
"
If a method yields poor result it will not be displayed on the graphs.
",
"
",    #input a line
"
If the graphs do not show properly please allow your mailbox to ""download"" images for this sender.
",
"
Please do not hesitate to contact us to ....
",
"
",
"
"+str(tickers[0])+"
",                                 # first ticker in the body
"
Daily signal: "+ mail_decision[0] +"
",                       # first decision for the ticker
"
Graph :
",
"""""",   #embed main graph for the whole period, set width (issue!) and height
""""""     #embed the reduced graph for a short term view, set width (issue!) and height
]

for i in range(1,len(tickers)):                         #extend the body for every strategy
    body_to_app=["
"+str(tickers[i])+"
",  #ticker in the body
    "
Daily signal: "+ mail_decision[i] +"
",     #decision for the ticker
    "
Graph :
",
    """""",   #embed main graph for the whole period, set width (issue!) and height
    """""",    #embed the reduced graph for a short term view, set width (issue!) and height
    ]
    body.extend(body_to_app)                            #extend (/"merge") the list

#add best regards
body.extend(["
Best Regards,
"])

#loop through recievers
for receiver in receivers:                                  #for element in recievers
    #send the mail
    yag.send(
        to=receiver,
        subject="Subject at date :  _ "+str(date_mail),
        contents=body
    )


问:
Gitlab CI/CD pipeline: how to run git diff between my current branch and main branch in the CI/CD pipeline?
I wanna run in a pipeline step from gitlab ci/cd a command for getting all the files changed in the current branch comparing to main branch.
Unfortunately I couldn't find the proper reference for main branch.

I tried in many ways, instead of "HEAD origin" I tried a couple of versions like "HEAD..origin", "HEAD..main", "HEAD..origin/main", "..origin" etc.

Does anyone knows if it's possible to run git diff between my current branch and main branch directly in the ci pipeline from the remote repo?


问:
Is it possible to interact with components from other activities?
Playing around with Chrome Custom Tabs made me realize that I cannot interact with my MainActivity``ViewModel when using the Chrome Tabs. More specifically unable to use the ViewModel methods in the Chrome Tab

This is a problem as I am running a News Application, and upon opening the Chrome Tab the user may choose to save this article, the problem is I have no idea how to do it with Intents

Here is the code to launch a custom chrome tab

```<code>val intent = Intent(requireContext(),MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            requireContext(),
            100,
            intent,
            PendingIntent.FLAG_MUTABLE
        )

        builder.addMenuItem("test", pendingIntent);

        button.setOnClickListener {
            val url = "https://www.google.com"
            //val url = "https://www.wikipedia.org"
            val customTabsIntent: CustomTabsIntent = builder.build()
            customTabsIntent.launchUrl(requireActivity(), Uri.parse(url))
        }
</code>```

I need to implement this line of code to save the article
article?.let { viewModel.saveArticle(it) }

Here is how the menu looks like Chrome tab Reference, I need to implement the line of code above into the testing list item.

I have read through the docs regarding intents, I can't seem to find anything related to this issue

Body:
Playing around with Chrome Custom Tabs made me realize that I cannot interact with my MainActivity``ViewModel when using the Chrome Tabs. More specifically unable to use the ViewModel methods in the Chrome Tab

This is a problem as I am running a News Application, and upon opening the Chrome Tab the user may choose to save this article, the problem is I have no idea how to do it with Intents

Here is the code to launch a custom chrome tab

val intent = Intent(requireContext(),MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            requireContext(),
            100,
            intent,
            PendingIntent.FLAG_MUTABLE
        )

        builder.addMenuItem("test", pendingIntent);

        button.setOnClickListener {
            val url = "https://www.google.com"
            //val url = "https://www.wikipedia.org"
            val customTabsIntent: CustomTabsIntent = builder.build()
            customTabsIntent.launchUrl(requireActivity(), Uri.parse(url))
        }

I need to implement this line of code to save the article
article?.let { viewModel.saveArticle(it) }

Here is how the menu looks like Chrome tab Reference, I need to implement the line of code above into the testing list item.

I have read through the docs regarding intents, I can't seem to find anything related to this issue


问:
Error accessing field [private java.lang.Long engine.Quiz.id] by reflection for persistent property [engine.Quiz#id] : 47;
I've two entities (User and Quiz) that I want to build a relationship between so I made another entity (UserQuiz) to store their primary keys. Here's the code for UserQuiz:

```<code>public class UserQuiz {
    @Id
    @Column(name = "id", nullable = false)
    private Long id;

    @ManyToOne(targetEntity = User.class, cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private Long user_id;

    @ManyToOne(targetEntity = Quiz.class, cascade = CascadeType.ALL)
    @JoinColumn(name = "quiz_id")
    private Long quiz_id;
}
</code>```

I then create an instance of the UserQuiz and pass it to a UserQuizSerivce method which abstracts the CrudeRepository save method.

```<code>@PostMapping("/quizzes")
public Quiz postQuiz(@Valid @RequestBody Quiz quiz, Authentication details){
    UserDetailsImpl currentUser = (UserDetailsImpl) details.getPrincipal();
    UserQuiz userQuiz = UserQuiz.builder().user_id(currentUser.getId()).quiz_id(quiz.getId()).build();
    userQuizService.saveUserQuiz(userQuiz);
    return quizService.saveQuiz(quiz);
}
</code>```

The issue here is the CrudRepository save methods throws an IllegalArgumentException even though a print statement clearly shows the userQuiz object is not null before it gets passed into the method. And also the error from the title is thrown by postman talking about Quiz.id which i don't understand why that field is even been accessed. Very confusing

Because of the error from postman, I tried turning the the id (primary keys) fields of User and Quiz entities into public fields. Tried using the setAccessible(true) methods on these fields too but all to no avail.

Body:
I've two entities (User and Quiz) that I want to build a relationship between so I made another entity (UserQuiz) to store their primary keys. Here's the code for UserQuiz:

public class UserQuiz {
    @Id
    @Column(name = "id", nullable = false)
    private Long id;

    @ManyToOne(targetEntity = User.class, cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private Long user_id;

    @ManyToOne(targetEntity = Quiz.class, cascade = CascadeType.ALL)
    @JoinColumn(name = "quiz_id")
    private Long quiz_id;
}

I then create an instance of the UserQuiz and pass it to a UserQuizSerivce method which abstracts the CrudeRepository save method.

@PostMapping("/quizzes")
public Quiz postQuiz(@Valid @RequestBody Quiz quiz, Authentication details){
    UserDetailsImpl currentUser = (UserDetailsImpl) details.getPrincipal();
    UserQuiz userQuiz = UserQuiz.builder().user_id(currentUser.getId()).quiz_id(quiz.getId()).build();
    userQuizService.saveUserQuiz(userQuiz);
    return quizService.saveQuiz(quiz);
}

The issue here is the CrudRepository save methods throws an IllegalArgumentException even though a print statement clearly shows the userQuiz object is not null before it gets passed into the method. And also the error from the title is thrown by postman talking about Quiz.id which i don't understand why that field is even been accessed. Very confusing

Because of the error from postman, I tried turning the the id (primary keys) fields of User and Quiz entities into public fields. Tried using the setAccessible(true) methods on these fields too but all to no avail.


问:
From Expecting value: line 1 column 1 (char 0) to Response content not in json format in python
```<code>res = self.session.post(url=self.url, data=json.dumps(data), headers=self.h, verify=False)
try:
    js = res.json()
    token = js['token']
    self.cookie['reese84'] = token
    print(fg + ' (success)')
    return token
except ValueError:
    print("Response content is not valid JSON")
</code>```

I am getting this :

[*] Fetching Token Response content is not valid JSON

Would be appreciated if someone help me out

I am expecting the Jason response but not receiving

Body:
res = self.session.post(url=self.url, data=json.dumps(data), headers=self.h, verify=False)
try:
    js = res.json()
    token = js['token']
    self.cookie['reese84'] = token
    print(fg + ' (success)')
    return token
except ValueError:
    print("Response content is not valid JSON")

I am getting this :

[*] Fetching Token Response content is not valid JSON

Would be appreciated if someone help me out

I am expecting the Jason response but not receiving


问:
IIS-10 worker processes crashing
We recently upgraded our server O/S from Win2012 to Win2019. While on 2012, in IIS, we had configured a Virtual Directory called PDFReader. The physical path was a filestream directory which contains a series of PDFs, which is essentially just a UNC share.

The directory was being called by an SSRS report & its sole purpose was to call the PDF from filestream and render it in SSRS.

We used a simple virtual directory when we were on Windows 2012 which worked fine. But we noticed that the app pool kept crashing on 2019. So that led to me convert it to an application because that way, I could assign an individual app pool to it & manage the rapid fail protection settings as a band-aid for now until we could identify the underlying issue. That has been getting us by.

I tried a few things such as changing the application pool identity to LocalSystem, then a privileged domain user w/SQL Filestream access. I also tried changing the .NET CLR Version to "No Managed Code" and the pipeline from Integrated to Classic. The latter seemed to slow the failures slightly, but nevertheless the problem persists.

Here's the stacktrace which we consistently see every few minutes as users frequently pull up PDFs.

Faulting application name: w3wp.exe, version: 10.0.17763.1, time stamp: 0xa7ccada2
Faulting module name: nativerd.dll, version: 10.0.17763.1, time stamp: 0x84a81d7a
Exception code: 0xc0000005
Fault offset: 0x0000a8f0
Faulting process id: 0x25cc
Faulting application start time: 0x01d921151b65f242
Faulting application path: C:\Windows\SysWOW64\inetsrv\w3wp.exe
Faulting module path: C:\Windows\System32\inetsrv\nativerd.dll
Report Id: 88535cc3-8716-40f7-bfab-1f53f9c77b92
Faulting package full name:
Faulting package-relative application ID:

Fault bucket 1192683016347496699, type 1
Event Name: APPCRASH
Response: Not available
Cab Id: 0

Problem signature:
P1: w3wp.exe
P2: 10.0.17763.1
P3: a7ccada2
P4: nativerd.dll
P5: 10.0.17763.1
P6: 84a81d7a
P7: c0000005
P8: 0000a8f0
P9:
P10:

There are a number of PDFs that are called which one might consider large, over 20MB with a handful of them over 100mb.

As for the user experience, since I implemented the rapid fail protection, the user doesn't run into the 503 errors anymore, requiring me to start the stopped app pool. Occasionally, when the worker process dies & hands off to the next one spawned, it's a minor delay.

Any help or insight would be appreciated.

Thanks,
Mike

Converted virtual directory to application.

Created/assigned individual app pool to application.

Changed rapid fail protection settings to allow for 25 failures in 10 minutes instead of the 5/5 out of the box.

Changed application pool identity to LocalSystem... Problem persisted. So I changed to a privileged domain user/local admin with proper SQL filestream rights, same behavior.

Ensured nativerd.dll was present in system directory, no discernible permissions issues.

Looked into MaxWebConfigFileSizeInKB registry key associated with nativerd.dll per a Microsoft KB article, but I don't see that key present in the registry.

Ran DebugDiag analysis with this summary result:

In w3wp__PDFReader__PID__160__Date__06_15_2022__Time_08_39_35AM__249__Second_Chance_Exception_C0000005.dmp the assembly instruction at nativerd!INDEXED_ARRAY_LIST::FindEntry+18 in c:\Windows\System32\inetsrv\nativerd.dll from Microsoft Corporation has caused an access violation exception (0xC0000005) when trying to read from memory location 0x00000038 on thread 6

Title: IIS-10 worker processes crashing


问:
index.html working well, localhost:5000/ not showing background
index.html working well, localhost:5000/ not showing background, help!

i set the correct path to style.css and it works opened using index. But i do using server localhost:5000/ and it doesn't show any background. not sure what im doing wrong.

when i try to inspect from browser it say ERROR 404, style.css NOT FOUND
i just want to show the background animated like it seems in codepen.

```<code>Here is my code app.py:

# -------------------- Importaciones -------------------- #

from flask import Flask, render_template, request, redirect
from flask import send_from_directory

# -------------------- App -------------------- #

app = Flask(__name__) # Creo la app.

# -------------------- ROUTES -------------------- #

@app.route('/') # Página principal, qué se llama index.
def start(): # Creo una función que me retorne con un return hacia la página.
    return render_template('website/index.html')

@app.route('/register') # Página de registro.
def register():
    return render_template('website/register.html')

@app.route('/loged') # Página para logearse.
def loged():
    return render_template('website/loged.html')

@app.route('/us') # Página de nosotros.
def us():
    return render_template('website/us.html')

if __name__ == '__main__': # Inicializamos nuestra app con el .run.
    app.run(debug = True)

-------------------------------

index.html code:

<!-- Importaciones y demás -->
<!DOCTYPE html>
<html lang="es">

<head>
    <title>Título</title>
    <link rel="stylesheet" href="css/style.css" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
</head>

<!-- Comienza el código -->

<body>
    <header>
        <div class="main">

        <!-- Menú cabecera -->

        <nav class="navbar navbar-expand navbar-light bg-light">
            <div class="nav navbar-nav">
                <a class="nav-item nav-link" href="/register" aria-current="page">Registrarse</a>
                <a class="nav-item nav-link" href="/loged">Iniciar sesión</a>
                <a class="nav-item nav-link" href="#">FREE</a>
                <a class="nav-item nav-link" href="/us">Nosotros</a>
            </div>
        </nav>

            <!-- Boton de Iniciar sesión -->

            <!--<button  class="pulse" onclick="window.location.href='http://Tibia.com';" >
                <b>Iniciar sesion</b>
            </button>-->

            <!-- Animación fondo -->

            <div class="d1"></div>
            <div class="d2"></div>
            <div class="d3"></div>
            <div class="d4"></div>
        </div>
    </header>
</body>

</html>

style.css code:

*{
  margin: 0;
  padding: 0;
  background-color: #ffffff;
}
  .main {
    height: 100vh;
    width: 100vw;
    position: relative;
  }
  .d1 {
    position: absolute;
    background-image: url(../image/Leesinbackground.png);
    background-size: 1920px 1080px;

    height: 30vh;
    width: 15vw;

    background-position: 0 50%;

    box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.8);
    top: 50%;
    transform: translateY(-50%);
    z-index: 2;
    animation: dd1 10s 1, dd12 10s 1;
    animation-delay: 4s, 14s;
  }
  .d2 {
    position: absolute;
    background-image: url(https://images4.alphacoders.com/817/817016.png);
    background-size: 1920px 1080px;

    height: 50vh;
    width: 25vw;

    background-position: -10vw 50%;
    left: 10vw;

    box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.8);

    top: 50%;
    transform: translateY(-50%);
    z-index: 1;
    animation: dd2 10s 2;
    animation-delay: 4s;
  }
  .d3 {
    position: absolute;
    background-image: url(https://images4.alphacoders.com/817/817016.png);
    background-size: 1920px 1080px;
    overflow: hidden;

    height: 100vh;
    width: 40vw;
    left: 25vw;
    box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.8);
    background-position: -35vw 50%;

    top: 50%;
    transform: translateY(-50%);
    z-index: 3;
    animation: dd3 10s 2;
    animation-delay: 4s;
  }
  .d4 {
    position: absolute;
    overflow: hidden;
    background-image: url(https://images4.alphacoders.com/817/817016.png);
    background-size: 1920px 1080px;

    height: 80vh;
    width: 25vw;
    left: 60vw;
    background-position: -70vw 50%;

    top: 50%;
    transform: translateY(-50%);
    z-index: 1;
    animation: dd4 10s 2;
    animation-delay: 4s;
  }

  @keyframes dd1 {
    0% {
    }
    50% {
      width: 95vw;
    }
  }
  @keyframes dd12 {
    0% {
    }
    50% {
      background-position: Calc(0vw - 40px) 50%;
    }
  }
  @keyframes dd2 {
    0% {
    }
    50% {
      background-position: Calc(-10vw - 40px) 50%;
    }
  }
  @keyframes dd3 {
    0% {
    }
    50% {
      background-position: Calc(-35vw - 40px) 50%;
    }
  }
  @keyframes dd4 {
    0% {
    }
    50% {
      background-position: Calc(-70vw - 40px) 50%;
    }
  }

/*------------------------- Boton -------------------------*/

.pulse:hover,
.pulse:focus {
  -webkit-animation: pulse 1s;
          animation: pulse 1s;
  box-shadow: 0 0 0 2em transparent;

}

@-webkit-keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 var(--hover);
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 var(--hover);
  }
}

.pulse {
  --color: #4f0909;
  --hover: #1b06a7;
}

button {
  color: var(--color);
  transition: 0.25s;
}
button:hover, button:focus {
  border-color: var(--hover);
  color: rgb(18, 0, 108);
}

body {
  font: 300 1em "Fira Sans", sans-serif;
}

button {
  background: none;
  border: 2px solid;
  font: inherit;
  line-height: 1;
  margin: 0.5em;
  padding: 1em 2em;
}

h1 {
  font-weight: 400;
}

code {
  color: #e4cb58;
  font: inherit;
}

/*------------------------- OTROS -------------------------*/

</code>```

Body:
index.html working well, localhost:5000/ not showing background, help!

i set the correct path to style.css and it works opened using index. But i do using server localhost:5000/ and it doesn't show any background. not sure what im doing wrong.

when i try to inspect from browser it say ERROR 404, style.css NOT FOUND
i just want to show the background animated like it seems in codepen.

Here is my code app.py:

# -------------------- Importaciones -------------------- #

from flask import Flask, render_template, request, redirect
from flask import send_from_directory

# -------------------- App -------------------- #

app = Flask(__name__) # Creo la app.

# -------------------- ROUTES -------------------- #

@app.route('/') # Página principal, qué se llama index.
def start(): # Creo una función que me retorne con un return hacia la página.
    return render_template('website/index.html')

@app.route('/register') # Página de registro.
def register():
    return render_template('website/register.html')

@app.route('/loged') # Página para logearse.
def loged():
    return render_template('website/loged.html')

@app.route('/us') # Página de nosotros.
def us():
    return render_template('website/us.html')

if __name__ == '__main__': # Inicializamos nuestra app con el .run.
    app.run(debug = True)

-------------------------------

index.html code:

<!DOCTYPE html>

    <title>Título</title>
    <link rel="stylesheet" href="css/style.css" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">

                Registrarse
                Iniciar sesión
                FREE
                Nosotros

style.css code:

*{
  margin: 0;
  padding: 0;
  background-color: #ffffff;
}
  .main {
    height: 100vh;
    width: 100vw;
    position: relative;
  }
  .d1 {
    position: absolute;
    background-image: url(../image/Leesinbackground.png);
    background-size: 1920px 1080px;

    height: 30vh;
    width: 15vw;

    background-position: 0 50%;

    box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.8);
    top: 50%;
    transform: translateY(-50%);
    z-index: 2;
    animation: dd1 10s 1, dd12 10s 1;
    animation-delay: 4s, 14s;
  }
  .d2 {
    position: absolute;
    background-image: url(https://images4.alphacoders.com/817/817016.png);
    background-size: 1920px 1080px;

    height: 50vh;
    width: 25vw;

    background-position: -10vw 50%;
    left: 10vw;

    box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.8);

    top: 50%;
    transform: translateY(-50%);
    z-index: 1;
    animation: dd2 10s 2;
    animation-delay: 4s;
  }
  .d3 {
    position: absolute;
    background-image: url(https://images4.alphacoders.com/817/817016.png);
    background-size: 1920px 1080px;
    overflow: hidden;

    height: 100vh;
    width: 40vw;
    left: 25vw;
    box-shadow: 0px 0px 25px rgba(0, 0, 0, 0.8);
    background-position: -35vw 50%;

    top: 50%;
    transform: translateY(-50%);
    z-index: 3;
    animation: dd3 10s 2;
    animation-delay: 4s;
  }
  .d4 {
    position: absolute;
    overflow: hidden;
    background-image: url(https://images4.alphacoders.com/817/817016.png);
    background-size: 1920px 1080px;

    height: 80vh;
    width: 25vw;
    left: 60vw;
    background-position: -70vw 50%;

    top: 50%;
    transform: translateY(-50%);
    z-index: 1;
    animation: dd4 10s 2;
    animation-delay: 4s;
  }

  @keyframes dd1 {
    0% {
    }
    50% {
      width: 95vw;
    }
  }
  @keyframes dd12 {
    0% {
    }
    50% {
      background-position: Calc(0vw - 40px) 50%;
    }
  }
  @keyframes dd2 {
    0% {
    }
    50% {
      background-position: Calc(-10vw - 40px) 50%;
    }
  }
  @keyframes dd3 {
    0% {
    }
    50% {
      background-position: Calc(-35vw - 40px) 50%;
    }
  }
  @keyframes dd4 {
    0% {
    }
    50% {
      background-position: Calc(-70vw - 40px) 50%;
    }
  }

/*------------------------- Boton -------------------------*/

.pulse:hover,
.pulse:focus {
  -webkit-animation: pulse 1s;
          animation: pulse 1s;
  box-shadow: 0 0 0 2em transparent;

}

@-webkit-keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 var(--hover);
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 var(--hover);
  }
}

.pulse {
  --color: #4f0909;
  --hover: #1b06a7;
}

button {
  color: var(--color);
  transition: 0.25s;
}
button:hover, button:focus {
  border-color: var(--hover);
  color: rgb(18, 0, 108);
}

body {
  font: 300 1em "Fira Sans", sans-serif;
}

button {
  background: none;
  border: 2px solid;
  font: inherit;
  line-height: 1;
  margin: 0.5em;
  padding: 1em 2em;
}

h1 {
  font-weight: 400;
}

code {
  color: #e4cb58;
  font: inherit;
}

/*------------------------- OTROS -------------------------*/


问:
Mapping through icons from json data fetched from database doesn't seem to be displaying icon
I have a terms and conditions table in the database, so far I have successfully mapped the conditions but for some reason the icons aren't showing

```<code>        <Layout>
            <div className='container bg-white mx-auto border rounded p-4 lg:w-1/2'>
            {data.map((term) => {
              const {condition, icon} = term;

            return (

              <div key={term.id}  className='p-2 flex flex-row text-md'>
              <div className='w-4 h-4'>
                {console.log(icon)}
                <FontAwesomeIcon icon={icon}  />
              </div>
              <h3 className='mx-2'>{condition}</h3>
              </div>

              );

            })}
            </div>
        </Layout>
</code>```

And also if you're wondering if the icon variable is valid here is a picture of the console log

Console log of data

You see when I manually type faUser the  shows, but now its not showing anything at all..

I tried to map icons from database expecting them to show, but ended up with white spaces instead.

Body:
I have a terms and conditions table in the database, so far I have successfully mapped the conditions but for some reason the icons aren't showing

        <Layout>

            {data.map((term) => {
              const {condition, icon} = term;

            return (

                {console.log(icon)}
                <FontAwesomeIcon icon={icon}  />

{condition}

              );

            })}

        </Layout>

And also if you're wondering if the icon variable is valid here is a picture of the console log

Console log of data

You see when I manually type faUser the  shows, but now its not showing anything at all..

I tried to map icons from database expecting them to show, but ended up with white spaces instead.


问:
net6 minimal web API override settings for test
Program.cs

```<code>WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
string foo = builder.Configuration.GetValue<string>("foo"); // Is null. Shoudn't be.

public partial class Program{}
</code>```

Test project

```<code>    public class MyWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration((context, configBuilder) =>
            {
                configBuilder.AddInMemoryCollection(
                    (new Dictionary<string, string?>
                    {
                        ["foo"] = "bar"
                    }).AsEnumerable());
            });
        }
    }

    public class Test
    {
        private readonly HttpClient _client;

        public Test(MyWebApplicationFactory<Program> factory)
        {
            _client = factory.WithWebHostBuilder().CreateClient();

</code>```

But the new settings are never added -- when I debug the test foo is always null.
I don't see how the settings can added, either, because Program creates a new builder that never goes anywhere near the WebApplicationFactory.

I think this might be something to do with my Program needing to read settings in order to configure services, but the settings not being updated by the test system until after the services have been configured?

Can it be made to work?

Body:
Program.cs

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
string foo = builder.Configuration.GetValue<string>("foo"); // Is null. Shoudn't be.

public partial class Program{}

Test project

    public class MyWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration((context, configBuilder) =>
            {
                configBuilder.AddInMemoryCollection(
                    (new Dictionary<string, string?>
                    {
                        ["foo"] = "bar"
                    }).AsEnumerable());
            });
        }
    }

    public class Test
    {
        private readonly HttpClient _client;

        public Test(MyWebApplicationFactory<Program> factory)
        {
            _client = factory.WithWebHostBuilder().CreateClient();

But the new settings are never added -- when I debug the test foo is always null.
I don't see how the settings can added, either, because Program creates a new builder that never goes anywhere near the WebApplicationFactory.

I think this might be something to do with my Program needing to read settings in order to configure services, but the settings not being updated by the test system until after the services have been configured?

Can it be made to work?


问:
User didn't receive any notification? (Deepstream.io)
When sending notifications in DeepstreamIO, if a user is offline and later reconnects, he will not see the notification. In addition to that records is empty. Can you please suggest any solution?

I try to send notifications to many users, I found that if I send for example 3 notifs the user received the last one, but if he is offline and the reconnect, he can't notify.


问:
Pinescript ma step
How to write high timeframe ma in step correctly in version 5

versoin 2 be like ：
`test =  security(tickerid, res, close )

plot(test , color = white)`

versoin 5 be like ：
`test =  request.security(syminfo.tickerid, res, close )

plot(test , color = color.orange )`

The result comes out

The orange line is not the correct step shape . Thats wiered. :(

I wish to know what exactly happenned in Ver 5

Title: Pinescript ma step


问:
I am trying to dynamically allocate memory for a matrix in assembly using mmap but it does not work
I am having trouble with the syscall mmap to dynamically allocate memory for a matrix,%eax should return at the end of the call the memory address but it returns a big negative value and the program has segmentation fault. And I know that I can use malloc to do this but I have to use mmap. This is the code for the mmap call:

```<code>main:
pushl $n#number of columns/lines
pushl $formatS
call scanf
popl %ebx
popl %ebx

movl n,%eax
movl $0,%edx
mull n
movl $8,x
mull x
movl %eax, len

mmap:
#syscall mmap
movl $192,%eax#code for mmap
movl $0,%ebx
movl len,%ecx
movl $3 ,%edx#PROT_WRITE+READ
movl $0x22 ,%esi#flags,MAP_ANONYMOUS+PRIVATE
movl $-1, %edi#file d
movl $0, %ebp#offset, porneste de la 0
int $0x80

mov %eax,%esi#matrix address
</code>```

I tried to put $1 for the file in %edi but eax returns -9 which from what I read it is a problem with the file and I saw someone say that with -1 it works. I don't get that error anymore but eax is a big negative number.

Body:
I am having trouble with the syscall mmap to dynamically allocate memory for a matrix,%eax should return at the end of the call the memory address but it returns a big negative value and the program has segmentation fault. And I know that I can use malloc to do this but I have to use mmap. This is the code for the mmap call:

main:
pushl $n#number of columns/lines
pushl $formatS
call scanf
popl %ebx
popl %ebx

movl n,%eax
movl $0,%edx
mull n
movl $8,x
mull x
movl %eax, len

mmap:
#syscall mmap
movl $192,%eax#code for mmap
movl $0,%ebx
movl len,%ecx
movl $3 ,%edx#PROT_WRITE+READ
movl $0x22 ,%esi#flags,MAP_ANONYMOUS+PRIVATE
movl $-1, %edi#file d
movl $0, %ebp#offset, porneste de la 0
int $0x80

mov %eax,%esi#matrix address

I tried to put $1 for the file in %edi but eax returns -9 which from what I read it is a problem with the file and I saw someone say that with -1 it works. I don't get that error anymore but eax is a big negative number.


问:
Terraform helm_release upgrade
I have some terraform code that deploys the helm chart, currently I am running some Apache Airflow 2.0.1 and wanted to perform some upgrade with helm release

Old code

```<code>resource "helm_release" "airflow" {
  name          = "airflow"
  repository    = "https://charts.bitnami.com/bitnami"
  chart         = "airflow"
  reuse_values  = "true"
  version       = "8.2.0"
  recreate_pods = var.airflow_helm_recreate_pods

  values = [
    file(var.helm_file)
  ]

  # ... some set variables here

</code>```

New code

```<code>resource "helm_release" "airflow" {
  name          = "airflow"
  repository    = "https://charts.bitnami.com/bitnami"
  chart         = "airflow"
  reuse_values  = "true"
  version       = "13.0.0"
  recreate_pods = var.airflow_helm_recreate_pods

  values = [
    file(var.helm_file)
  ]

  # ... some set variables here

</code>```

This should target 2.3.3 application. I'am getting some strange error about fernet key

```<code>│ Error: execution error at (airflow/templates/config/secret.yaml:21:25):
│ PASSWORDS ERROR: The secret "airflow" does not contain the key "airflow-fernet-key"
│
│
│   with helm_release.airflow,
│   on airflow.tf line 145, in resource "helm_release" "airflow":
│  145: resource "helm_release" "airflow" {
</code>```

Based on this documentation, there is some key like airflow-fernet-key
https://artifacthub.io/packages/helm/bitnami/airflow/13.0.0?modal=template&template=config/secret.yaml

I already tried to delete & re-install providers as well as to make some upgrades but did not work.

Title: Terraform helm_release upgrade

Body:
I have some terraform code that deploys the helm chart, currently I am running some Apache Airflow 2.0.1 and wanted to perform some upgrade with helm release

Old code

resource "helm_release" "airflow" {
  name          = "airflow"
  repository    = "https://charts.bitnami.com/bitnami"
  chart         = "airflow"
  reuse_values  = "true"
  version       = "8.2.0"
  recreate_pods = var.airflow_helm_recreate_pods

  values = [
    file(var.helm_file)
  ]

  # ... some set variables here

New code

resource "helm_release" "airflow" {
  name          = "airflow"
  repository    = "https://charts.bitnami.com/bitnami"
  chart         = "airflow"
  reuse_values  = "true"
  version       = "13.0.0"
  recreate_pods = var.airflow_helm_recreate_pods

  values = [
    file(var.helm_file)
  ]

  # ... some set variables here

This should target 2.3.3 application. I'am getting some strange error about fernet key

│ Error: execution error at (airflow/templates/config/secret.yaml:21:25):
│ PASSWORDS ERROR: The secret "airflow" does not contain the key "airflow-fernet-key"
│
│
│   with helm_release.airflow,
│   on airflow.tf line 145, in resource "helm_release" "airflow":
│  145: resource "helm_release" "airflow" {

Based on this documentation, there is some key like airflow-fernet-key
https://artifacthub.io/packages/helm/bitnami/airflow/13.0.0?modal=template&template=config/secret.yaml

I already tried to delete & re-install providers as well as to make some upgrades but did not work.


问:
How do I delay the execution of a function within tkinter button command
I am trying to simulate a computer player "clicking" a button after a human user clicks a button In a grid of buttons. If I use the .after method the 'state' of the button change is delayed but it executes my check_state() method which doesn't detect the change. When I try time.sleep() method it prolongs the human click but still immediately invokes the 'auto' click regardless of where I put it in my code. I want a delay between the human click and 'auto' click.

I have tried widget.after(1000) which gives the desired delay of 'auto' click, but doesn't allow my the change to be seen by my check_state() function. I have tried time.sleep() which delays the execution of the human button click but the 'auto' click is still immediately invokes regardless of which order I place the sleep() function in relation to the call to auto_click(). I know there are better practices for this code implementation like using class based structure which I plan on using once my logic and functionality issues are resolved. My code is as follows:

import tkinter as tk

import random

def app():

```<code>def auto_click():

    grid_state = get_grid_state()

    possible_clicks = []

    for i in range(0, len(grid_state)):

        if grid_state[i] == " ":

            possible_clicks.append(i)

#debug.config(text=possible_moves)

    click = random.choice(possible_clicks)

    buttons[click].after(1000, lambda: buttons[click].config(text = "auto", state=tk.DISABLED))

    #time.sleep(1)

    check_grid_state()

    check_grid_full()

    debug.config(text="test")

def onclick(*arg):

    global is_full

    buttons[arg[0]].config(text = "clicked", state=tk.DISABLED)

    check_grid_state()

    check_grid_full()

    if not is_full:

        auto_click()

def check_grid_full():

    global is_full

    result=[]

    for i in range(len(buttons)):

        result.append(buttons[i].cget('state'))

        r = [*set(result)]

    if r == ['disabled']:

        is_full = True

        grid_status.config(text=is_full)

    else:

        is_full = False

</code>```

Retrieve the current state of the grid

```<code>def get_grid_state():

   grid_state =[]

   for i in range(len(buttons)):

       grid_state.append(buttons[i].cget('text'))

   return grid_state
</code>```

Check grid state

```<code>def check_grid_state():

    grid_states.config(text=get_grid_state())
</code>```

Global Variables

```<code>is_full = False

buttons = []

c=0

</code>```

Window

```<code>root = tk.Tk()

root.title("Title")
</code>```

Heading

```<code>label = tk.Label(root, text="grid state", font = ("Ariel black",22, "bold"))

label.pack()
</code>```

Grid Frame

```<code>frame = tk.Frame(root)

frame.pack()

for row in range(3):

    for column in range(3):

        buttons.append(tk.Button(frame, text=f" ", font=("arial", "22"), state=tk.ACTIVE,  height=2, width=2, command=lambda c=c: onclick(c)))

        buttons[c].grid(row=row, column=column)

        c += 1
</code>```

Status bar

```<code>grid_states = tk.Label(root, text=f"")

grid_states.pack()

grid_status = tk.Label(root, text=f"")

grid_status.pack()
</code>```

#btn_is = tk.Label(root, text=f"")

#btn_is.pack()

Debugging output label

```<code>debug = tk.Label(root, text="debug")

debug.pack()
</code>```

Event loop

```<code>root.mainloop()
</code>```

if name == "main":

```<code>app()
</code>```

Body:
I am trying to simulate a computer player "clicking" a button after a human user clicks a button In a grid of buttons. If I use the .after method the 'state' of the button change is delayed but it executes my check_state() method which doesn't detect the change. When I try time.sleep() method it prolongs the human click but still immediately invokes the 'auto' click regardless of where I put it in my code. I want a delay between the human click and 'auto' click.

I have tried widget.after(1000) which gives the desired delay of 'auto' click, but doesn't allow my the change to be seen by my check_state() function. I have tried time.sleep() which delays the execution of the human button click but the 'auto' click is still immediately invokes regardless of which order I place the sleep() function in relation to the call to auto_click(). I know there are better practices for this code implementation like using class based structure which I plan on using once my logic and functionality issues are resolved. My code is as follows:

import tkinter as tk

import random

def app():

def auto_click():

    grid_state = get_grid_state()

    possible_clicks = []

    for i in range(0, len(grid_state)):

        if grid_state[i] == " ":

            possible_clicks.append(i)

#debug.config(text=possible_moves)

    click = random.choice(possible_clicks)

    buttons[click].after(1000, lambda: buttons[click].config(text = "auto", state=tk.DISABLED))

    #time.sleep(1)

    check_grid_state()

    check_grid_full()

    debug.config(text="test")

def onclick(*arg):

    global is_full

    buttons[arg[0]].config(text = "clicked", state=tk.DISABLED)

    check_grid_state()

    check_grid_full()

    if not is_full:

        auto_click()

def check_grid_full():

    global is_full

    result=[]

    for i in range(len(buttons)):

        result.append(buttons[i].cget('state'))

        r = [*set(result)]

    if r == ['disabled']:

        is_full = True

        grid_status.config(text=is_full)

    else:

        is_full = False

Retrieve the current state of the grid

def get_grid_state():

   grid_state =[]

   for i in range(len(buttons)):

       grid_state.append(buttons[i].cget('text'))

   return grid_state

Check grid state

def check_grid_state():

    grid_states.config(text=get_grid_state())

Global Variables

is_full = False

buttons = []

c=0

Window

root = tk.Tk()

root.title("Title")

Heading

label = tk.Label(root, text="grid state", font = ("Ariel black",22, "bold"))

label.pack()

Grid Frame

frame = tk.Frame(root)

frame.pack()

for row in range(3):

    for column in range(3):

        buttons.append(tk.Button(frame, text=f" ", font=("arial", "22"), state=tk.ACTIVE,  height=2, width=2, command=lambda c=c: onclick(c)))

        buttons[c].grid(row=row, column=column)

        c += 1

Status bar

grid_states = tk.Label(root, text=f"")

grid_states.pack()

grid_status = tk.Label(root, text=f"")

grid_status.pack()

#btn_is = tk.Label(root, text=f"")

#btn_is.pack()

Debugging output label

debug = tk.Label(root, text="debug")

debug.pack()

Event loop

root.mainloop()

if name == "main":

app()


问:
How To Solve 504 Bad Gateway Timeout Error From Aws Api Gateway?

I am getting 504 Bad Gateway Timeout error in responce but data gets inserted sucessfully to the databse.

Code executes perfectly locally with response time within 1.15s but whenever deployed to lambda it start giving this Timeout Error.

Node js Endpoint Route is as Follows

```<code>route.post("/Register", async (req, res) => {
  try {
    const user = new userschema({
      Name: req.body.Name,
      Email: req.body.Email,
      UserName: req.body.UserName,
      PhotoUrl: req.body.PhotoUrl,
    });
    await user.save();
    return res.status.send("Created");
  } catch (error) {
    return res.status(500).send("Something Went Wrong");
  }
});
</code>```

I have Deployed Nodejs backend to aws lambda which is running in a VPC and using mongodb atlas it follow this architecture

I am new to aws so i followed This Youtube Video.

Data gets inserted to mongodb atlas Database sucessfully. So the Vpc Peering conncetion beetween lambda function and Mongodb Atlas must be all right.

Cloudwatch Logs is as Follows

I tried everything i could but still facing this issue.

Body:
I am getting 504 Bad Gateway Timeout error in responce but data gets inserted sucessfully to the databse.

Code executes perfectly locally with response time within 1.15s but whenever deployed to lambda it start giving this Timeout Error.

Node js Endpoint Route is as Follows

route.post("/Register", async (req, res) => {
  try {
    const user = new userschema({
      Name: req.body.Name,
      Email: req.body.Email,
      UserName: req.body.UserName,
      PhotoUrl: req.body.PhotoUrl,
    });
    await user.save();
    return res.status.send("Created");
  } catch (error) {
    return res.status(500).send("Something Went Wrong");
  }
});

I have Deployed Nodejs backend to aws lambda which is running in a VPC and using mongodb atlas it follow this architecture

I am new to aws so i followed This Youtube Video.

Data gets inserted to mongodb atlas Database sucessfully. So the Vpc Peering conncetion beetween lambda function and Mongodb Atlas must be all right.

Cloudwatch Logs is as Follows

I tried everything i could but still facing this issue.


问:
Is checking ifstream::read() return value necessary?
The following example code from https://en.cppreference.com/w/cpp/io/basic_istream/read uses the if-check for the returned value of ifstream::read. Is that necessary? Why?

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdint>

int main()
{
    // read() is often used for binary I/O
    std::string bin = {'\x12', '\x12', '\x12', '\x12'};
    std::istringstream raw(bin);
    std::uint32_t n;
    if(raw.read(reinterpret_cast<char*>(&n), sizeof n))
        std::cout << std::hex << std::showbase << n << '\n';

    // prepare file for next snippet
    std::ofstream("test.txt", std::ios::binary) << "abcd1\nabcd2\nabcd3";

    // read entire file into string
    if(std::ifstream is{"test.txt", std::ios::binary | std::ios::ate}) {
        auto size = is.tellg();
        std::string str(size, '\0'); // construct string to stream size
        is.seekg(0);
        if(is.read(&str[0], size)) // <- is this necessary and why?
            std::cout << str << '\n';
    }
}
```


问:
Vaadin: Grid Cell Colour, Slow To React
I have Vaadin Spring Boot Application that has a grid that uses a class name generator to style a columns cells. When setItems() is called on this grid the values in the cells are updated almost immediately but the cell colour doesn't change for some time after.

My class uses a Poll to call an update method every 10 seconds which calls setItems() on the grid. See below for a basic example of the set up I am using. In the example below when the update method is called, the overall score value will be updated in an acceptable amount of time, but the colour of the cell is taking too long.

Any advice to speed this up would be great, I'm not that keen on the poll so if anyone thinks that may be the problem I would love to hear your thoughts.

```<code>@Route("simple-layout")
@CssImport(value = "./styles/grid-styles.css")
public class SimpleLayout extends VerticalLayout {

    private Grid<Student> grid;
    private StudentService service;

    public SimpleLayout(StudentService service) {

        ... ommitted other code fragments

        grid.addColumn(Student::getOverallScore).setClassNameGenerator(this::getCellStyle());
        add(grid);

        UI ui = UI.getCurrent();
        ui.setPollInterval(10000);
        PollListenerRegistration pollListenerRegistration = ui.addPollListener(pollEvent -> updateGrid());
    }

    private String getCellStyle(Student student) {

        if(student.getOverallScore() > 50) {
            return "green-cell-colour";
        } else {
            return "red-cell-colour";
        }
    }

    private void updateGrid() {

        grid.setItems(service.findAll());
    }
}

@Entity
public class Student implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    private int overallScore;

    public Student() {}

    ...getters and setters omitted
}

@Service
public class StudentService {

    private StudentRepo repo;

    public StudentService(StudentRepo repo) {

        this.repo = repo;
    }

    public List<Student> findAll() {

        return repo.findAll();
    }
}

public interface StudentRepo extends JpaRepository<Student, Long> {

    List<Student> findAll();
}
</code>```

Title: Vaadin: Grid Cell Colour, Slow To React

Body:
I have Vaadin Spring Boot Application that has a grid that uses a class name generator to style a columns cells. When setItems() is called on this grid the values in the cells are updated almost immediately but the cell colour doesn't change for some time after.

My class uses a Poll to call an update method every 10 seconds which calls setItems() on the grid. See below for a basic example of the set up I am using. In the example below when the update method is called, the overall score value will be updated in an acceptable amount of time, but the colour of the cell is taking too long.

Any advice to speed this up would be great, I'm not that keen on the poll so if anyone thinks that may be the problem I would love to hear your thoughts.

@Route("simple-layout")
@CssImport(value = "./styles/grid-styles.css")
public class SimpleLayout extends VerticalLayout {

    private Grid<Student> grid;
    private StudentService service;

    public SimpleLayout(StudentService service) {

        ... ommitted other code fragments

        grid.addColumn(Student::getOverallScore).setClassNameGenerator(this::getCellStyle());
        add(grid);

        UI ui = UI.getCurrent();
        ui.setPollInterval(10000);
        PollListenerRegistration pollListenerRegistration = ui.addPollListener(pollEvent -> updateGrid());
    }

    private String getCellStyle(Student student) {

        if(student.getOverallScore() > 50) {
            return "green-cell-colour";
        } else {
            return "red-cell-colour";
        }
    }

    private void updateGrid() {

        grid.setItems(service.findAll());
    }
}

@Entity
public class Student implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    private int overallScore;

    public Student() {}

    ...getters and setters omitted
}

@Service
public class StudentService {

    private StudentRepo repo;

    public StudentService(StudentRepo repo) {

        this.repo = repo;
    }

    public List<Student> findAll() {

        return repo.findAll();
    }
}

public interface StudentRepo extends JpaRepository<Student, Long> {

    List<Student> findAll();
}