问:
how to use setInterval with redux-thunk?
I'm using redux-thunk to manage async functions, and I want to use setInterval within an action creator, this is my code:

```<code>export const startLobbyPolling = () => dispatch => {
  const pollTimer = setInterval(() => {
    dispatch(fetchLobby);
  }, POLL_TIME);
  dispatch({ type: START_LOBBY_POLLING, payload: pollTimer });
};
</code>```

fetchLobby is another action creator that simply fetch a request and store its data.
but surprisingly it's not working as it only shows START_LOBBY_POLLING action in redux debugger tool and nothing happens afterward. I would appreciate it to know how to use setInterval with redux.

答:
Seems like i should had called the function not just pass it as an argument to dispatch
    dispatch(fetchLobby); -->
 dispatch(fetchLobby()); and it works now

Body:
I'm using redux-thunk to manage async functions, and I want to use setInterval within an action creator, this is my code:

export const startLobbyPolling = () => dispatch => {
  const pollTimer = setInterval(() => {
    dispatch(fetchLobby);
  }, POLL_TIME);
  dispatch({ type: START_LOBBY_POLLING, payload: pollTimer });
};

fetchLobby is another action creator that simply fetch a request and store its data.
but surprisingly it's not working as it only shows START_LOBBY_POLLING action in redux debugger tool and nothing happens afterward. I would appreciate it to know how to use setInterval with redux.


来源: stackexchange

问:
(FLASK) I can't figure out why my html file doesn't update/render
I already tried clearing my browser cache and history, but that did not seem to help. The old html file I used (Jinja) doesn't seem to update.

Basically, I rendered a file before this and jinja seems to be rendering that old file (not sample or index) instead of either sample or index .html.

I'm a beginner at Flask, so if this is a simple fix I apologize I don't know much...

Here is my code:

sample.py

```<code>from flask import Flask, render_template, redirect, url_for

app = Flask(" APP ")

@app.route("/home")
def home():
    return render_template("sample.html")

if __name__ == "__main__":
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.run(debug = True)
</code>```

index.html (inherits from sample.html)

```<code>{% extends "sample.html" %}
{% block title %}Home Page {% endblock %}
{% block content %}
<h1> Welcome to the Index Page!</h1>
{% endblock %}
</code>```

sample.html

```<code><!doctype html>
<html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
       <span class="navbar-toggler-icon"></span>
   </button>
         <div class="collapse navbar-collapse" id="navbarNav">
             <ul class="navbar-nav">
           <li class="nav-item active">
                     <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
    </li>
    <li class="nav-item">
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
    </li>
      </ul>
        </div>
    </nav>
    {% block content %}
    {% endblock %}
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
</code>```

答:
I just figured it out. I ran the file in another text editor and never ended the process (even though I closed that window). Just restarted my PC and problem solved.

Silly mistake, but I guess beginners learn? :D

ContentLicense: CC BY-SA 4.0

Body:
I already tried clearing my browser cache and history, but that did not seem to help. The old html file I used (Jinja) doesn't seem to update.

Basically, I rendered a file before this and jinja seems to be rendering that old file (not sample or index) instead of either sample or index .html.

I'm a beginner at Flask, so if this is a simple fix I apologize I don't know much...

Here is my code:

sample.py

from flask import Flask, render_template, redirect, url_for

app = Flask(" APP ")

@app.route("/home")
def home():
    return render_template("sample.html")

if __name__ == "__main__":
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.run(debug = True)

index.html (inherits from sample.html)

{% extends "sample.html" %}
{% block title %}Home Page {% endblock %}
{% block content %}

 Welcome to the Index Page!

{% endblock %}

sample.html

<!doctype html>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}{% endblock %}</title>

        Navbar
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

   </button>

                     Home (current)

        Features

        Pricing

        Disabled

    {% block content %}
    {% endblock %}


答:
You can use arithmetics and aggregation for this:

```<code>select
    cast(timestamp as int) / 60 * 60 timestamp_minute,
    avg(tel1) avg_tel1,
    avg(tel2) avg_tel2
from plik3
group by cast(timestamp as int) / 60 * 60
</code>```

Expression cast(timestamp as int) / 60 * 60 rounds the unix timestamp to the minute.

If you want to display the (rounded) timestamp as a datetime instead, you can use datetime() on top of this:

```<code>select
    datetime(cast(timestamp as int) / 60 * 60, 'unixepoch') date_minute,
    avg(tel1) avg_tel1,
    avg(tel2) avg_tel2
from plik3
group by datetime(cast(timestamp as int) / 60 * 60, 'unixepoch')
</code>```

Title: Counting the average for many rows

Body:
Each line is a second (timestamp increases by a second)
I want to calculate the average values for tel1 and tel2 for every minute.
Can you help?

CREATE TABLE "plik3" (
    "timestamp" REAL,
    "tel1"  REAL,
    "tel2"  REAL
);

1577833200.0    0.0         0.0
1577833201.0    0.0         0.0
1577833202.0    0.4000317   0.0
1577833203.0    0.80006206  0.80006146
1577833204.0    0.0         0.40002593
1577833205.0    0.400032    0.0
1577833206.0    0.800055    0.400024
1577833207.0    0.0         1.2000787
1577833208.0    0.40002337  0.8000576
1577833209.0    0.0         0.40002495
1577833210.0    0.0         0.0
1577833211.0    0.4000275   0.0
1577833212.0    0.400032    0.40003648
1577833213.0    0.0         1.2000787
1577833214.0    0.0         0.40003487
1577833215.0    0.8000595   0.0
1577833216.0    0.40002593  0.40003297

the base is large. 13,046,098 lines

Body:
You can use arithmetics and aggregation for this:

select
    cast(timestamp as int) / 60 * 60 timestamp_minute,
    avg(tel1) avg_tel1,
    avg(tel2) avg_tel2
from plik3
group by cast(timestamp as int) / 60 * 60

Expression cast(timestamp as int) / 60 * 60 rounds the unix timestamp to the minute.

If you want to display the (rounded) timestamp as a datetime instead, you can use datetime() on top of this:

select
    datetime(cast(timestamp as int) / 60 * 60, 'unixepoch') date_minute,
    avg(tel1) avg_tel1,
    avg(tel2) avg_tel2
from plik3
group by datetime(cast(timestamp as int) / 60 * 60, 'unixepoch')


问:
How do I get a Access Token for my Microsoft Personal Account - Microsoft Graph API
I am working on a project, that sorts my emails in to folders in Python. I having a @outlook.com email and I am going to be using Microsoft Graph API. First I have just been using cURL to try out the different endpoints.

I have had a few problems, I am trying to get my personal access token, so I can use the endpoint /me/messages I have tried many different ways to authenticate using the documentation, but none of them seem to work. I don't have any active directory, I just want to use my own personal account, which I have selected when creating the project. Since my project is going to be running on the backend, I will be using the Application permissions instead of Delegated permission (please tell me if it is possible to use application permissions with my idea)

It would be helpful, if people could send me the cURL commands, to get my access token and maybe a example request to get my emails. Then I can translate this into Python code. If I receive any errors while executing your commands I will just comment on your answer.

Thanks in advance.

答:
Based on the following documents I do not believe it is possible to use application permissions for a non-interactive (daemon) solution with a Microsoft Account.  Only delegated permissions are supported since you as a user will not be able to grant admin consent on your Microsoft Account.

"Daemon applications can be used only with Azure AD organizations. It doesn't make sense to try to use daemon applications to manipulate Microsoft personal accounts. The admin consent will never be granted."

Scenario: Daemon application that calls web APIs

Account type support in authentication flows


问:
oracle apex giving me an error when using INSERT INTO to add data to tables
I have an assignment due in a few days but cannot remember coming across this error before, im sure its something tiny that ive skimmed over but could someone take a look?

error is :

ORA-00984: column not allowed here ORA-06512: at
"SYS.WWV_DBMS_SQL_APEX_190100", line 590 ORA-06512: at
"SYS.DBMS_SYS_SQL", line 1658 ORA-06512: at
"SYS.WWV_DBMS_SQL_APEX_190100", line 576 ORA-06512: at
"APEX_190100.WWV_FLOW_DYNAMIC_EXEC", line 2033

ive tried rewriting single lines but it will not take any code that i put into it. The code i have written is in asterisks (bottom 14 lines) it works fine without these lines so i cannot figure out why. Im a newbie to this kind of stuff (first year uni) so any help would be appreciated!

```<code>CREATE TABLE vet(
vetno           NUMBER(6) PRIMARY KEY,
vetname     VARCHAR2(16) NOT NULL,
vetaddressln1   VARCHAR2(20)NOT NULL,
vetaddressln2   VARCHAR2(20),
vetpostcode     VARCHAR2(8)NOT NULL);

DROP TABLE client cascade constraints;
CREATE TABLE client(
clientno        NUMBER(6)PRIMARY KEY,
surname     VARCHAR2(15)NOT NULL,
firstnames      VARCHAR2(15)NOT NULL,
clientaddressln1    VARCHAR2(20)NOT NULL,
clientaddressln2    VARCHAR2(20),
clientpostcode      VARCHAR2(8)NOT NULL);

DROP TABLE animal cascade constraints;
CREATE TABLE animal(
animalno        NUMBER(6) PRIMARY KEY,
name            VARCHAR2(15)NOT NULL ,
sex         VARCHAR2(6),
dateofbirth     DATE,
species     VARCHAR2(30)NOT NULL ,
clientno        NUMBER(6) REFERENCES client(clientno));

DROP TABLE consultation cascade constraints;
CREATE TABLE consultation(
consultationno  NUMBER(6),
consultationdate DATE NOT NULL,
animalno NUMBER(6) REFERENCES animal(animalno),
vetno NUMBER(6) REFERENCES vet(vetno),
Outcomenote VARCHAR2(25) NOT NULL );

INSERT INTO vet VALUES (001,'James Herriot','Skeldale, High St', 'Yarm', 'YM3 6WP');
INSERT INTO vet VALUES (002,'Siegfried Farnon','61 Farnby Mount', 'Yarm', 'YM3 6WD');
INSERT INTO vet VALUES (003,'Danielle Chang','North St', 'Leeds', 'LS6 3NG');
INSERT INTO vet VALUES (004,'Emma Milne','87 Arncliffe Road', 'Harrogate', 'HG5 5HY');
INSERT INTO vet VALUES (005,'Harry Cooper','15, Coniston Avenue', 'Leeds', 'LS11 4PE');

INSERT INTO client VALUES (0034,'Wong','Judy','Flat 5, Victoria Av', 'Leeds', 'LS5 9PL');
INSERT INTO client VALUES (0035,'Spencer','Tom','4, Broad Lane', 'Harrogate', 'HG4 9DL');
INSERT INTO client VALUES (0036,'Hamza','Farhan','35A, Waterloo Cres', 'Harrogate', 'HG3 3FD');
INSERT INTO client VALUES (0037,'Cummins','Dominic','184, Queenswood Rd', 'Bradford', 'BR3 2GD');
INSERT INTO client VALUES (0038,'Stuart','Moira','77, Westgate', 'Leeds', 'LS1 4KL');

** INSERT INTO animal VALUES (00100,'Elsie','M', 01-FEB-13, 'PERSIAN CAT', '0034');
INSERT INTO animal VALUES (00101,'Thurston','M', 15-MAY-11, 'MAINE COON CAT', '0034');
INSERT INTO animal VALUES (00102,'Jeff','F', 11-SEP-19, 'NORWEIGAN FOREST CAT', '0035');
INSERT INTO animal VALUES (00103,'Monkey','M', 16-SEP-99, 'BOMBAY CAT', '0036');
INSERT INTO animal VALUES (00104,'Terry','M', 11-MAY-14, 'RED-FOOTED TORTOISE', '0037');
INSERT INTO animal VALUES (00105,'Emilia','F', 29-OCT-19, 'RED-KNEE TARANTULA', '0038');

INSERT INTO consultation VALUES (001001,14-jan-20,'00101','001','Given antibiotics');
INSERT INTO consultation VALUES (001002,11-JUL-20,'00101','002','Given respiratory tablets');
INSERT INTO consultation VALUES (001003,08-JUN-20,'00102','003','Given antibiotics');
INSERT INTO consultation VALUES (001004,11-AUG-20,'00103','005','Saline Drip');
INSERT INTO consultation VALUES (001005,11-SEP-20,'00104','001','Laid 3 eggs');
INSERT INTO consultation VALUES (001006,17-NOV-20,'00102','004','Given antibiotics');
INSERT INTO consultation VALUES (001007,11-DEC-20,'00105','004','Moult Assistance');
INSERT INTO consultation VALUES (001008,04-OCT-20,'00101','005','Given antibiotics');** ```
```

答:
It is about invalid dates. The way you tried to do it is wrong - not just because it didn't work, but because you wanted to insert them as strings (only if they were enclosed into single quotes). You should insert dates.

One option is to use date literal which is always in format date 'yyyy-mm-dd':

```<code>SQL> INSERT INTO animal VALUES (00100,'Elsie','M', date '2013-02-01', 'PERSIAN CAT', '0034');

1 row created.

SQL>
</code>```

Another is to use TO_DATE function with appropriate format mask:

```<code>SQL> INSERT INTO animal VALUES (00101,'Thurston','M', to_date('15-MAY-11', 'dd-mon-yy', 'nls_date_language = english'), 'MAINE COON CAT', '0034');

1 row created.

SQL>
</code>```

The same goes for the consultation table.

Body:
I have an assignment due in a few days but cannot remember coming across this error before, im sure its something tiny that ive skimmed over but could someone take a look?

error is :

ORA-00984: column not allowed here ORA-06512: at
"SYS.WWV_DBMS_SQL_APEX_190100", line 590 ORA-06512: at
"SYS.DBMS_SYS_SQL", line 1658 ORA-06512: at
"SYS.WWV_DBMS_SQL_APEX_190100", line 576 ORA-06512: at
"APEX_190100.WWV_FLOW_DYNAMIC_EXEC", line 2033

ive tried rewriting single lines but it will not take any code that i put into it. The code i have written is in asterisks (bottom 14 lines) it works fine without these lines so i cannot figure out why. Im a newbie to this kind of stuff (first year uni) so any help would be appreciated!

CREATE TABLE vet(
vetno           NUMBER(6) PRIMARY KEY,
vetname     VARCHAR2(16) NOT NULL,
vetaddressln1   VARCHAR2(20)NOT NULL,
vetaddressln2   VARCHAR2(20),
vetpostcode     VARCHAR2(8)NOT NULL);

DROP TABLE client cascade constraints;
CREATE TABLE client(
clientno        NUMBER(6)PRIMARY KEY,
surname     VARCHAR2(15)NOT NULL,
firstnames      VARCHAR2(15)NOT NULL,
clientaddressln1    VARCHAR2(20)NOT NULL,
clientaddressln2    VARCHAR2(20),
clientpostcode      VARCHAR2(8)NOT NULL);

DROP TABLE animal cascade constraints;
CREATE TABLE animal(
animalno        NUMBER(6) PRIMARY KEY,
name            VARCHAR2(15)NOT NULL ,
sex         VARCHAR2(6),
dateofbirth     DATE,
species     VARCHAR2(30)NOT NULL ,
clientno        NUMBER(6) REFERENCES client(clientno));

DROP TABLE consultation cascade constraints;
CREATE TABLE consultation(
consultationno  NUMBER(6),
consultationdate DATE NOT NULL,
animalno NUMBER(6) REFERENCES animal(animalno),
vetno NUMBER(6) REFERENCES vet(vetno),
Outcomenote VARCHAR2(25) NOT NULL );

INSERT INTO vet VALUES (001,'James Herriot','Skeldale, High St', 'Yarm', 'YM3 6WP');
INSERT INTO vet VALUES (002,'Siegfried Farnon','61 Farnby Mount', 'Yarm', 'YM3 6WD');
INSERT INTO vet VALUES (003,'Danielle Chang','North St', 'Leeds', 'LS6 3NG');
INSERT INTO vet VALUES (004,'Emma Milne','87 Arncliffe Road', 'Harrogate', 'HG5 5HY');
INSERT INTO vet VALUES (005,'Harry Cooper','15, Coniston Avenue', 'Leeds', 'LS11 4PE');

INSERT INTO client VALUES (0034,'Wong','Judy','Flat 5, Victoria Av', 'Leeds', 'LS5 9PL');
INSERT INTO client VALUES (0035,'Spencer','Tom','4, Broad Lane', 'Harrogate', 'HG4 9DL');
INSERT INTO client VALUES (0036,'Hamza','Farhan','35A, Waterloo Cres', 'Harrogate', 'HG3 3FD');
INSERT INTO client VALUES (0037,'Cummins','Dominic','184, Queenswood Rd', 'Bradford', 'BR3 2GD');
INSERT INTO client VALUES (0038,'Stuart','Moira','77, Westgate', 'Leeds', 'LS1 4KL');

** INSERT INTO animal VALUES (00100,'Elsie','M', 01-FEB-13, 'PERSIAN CAT', '0034');
INSERT INTO animal VALUES (00101,'Thurston','M', 15-MAY-11, 'MAINE COON CAT', '0034');
INSERT INTO animal VALUES (00102,'Jeff','F', 11-SEP-19, 'NORWEIGAN FOREST CAT', '0035');
INSERT INTO animal VALUES (00103,'Monkey','M', 16-SEP-99, 'BOMBAY CAT', '0036');
INSERT INTO animal VALUES (00104,'Terry','M', 11-MAY-14, 'RED-FOOTED TORTOISE', '0037');
INSERT INTO animal VALUES (00105,'Emilia','F', 29-OCT-19, 'RED-KNEE TARANTULA', '0038');

INSERT INTO consultation VALUES (001001,14-jan-20,'00101','001','Given antibiotics');
INSERT INTO consultation VALUES (001002,11-JUL-20,'00101','002','Given respiratory tablets');
INSERT INTO consultation VALUES (001003,08-JUN-20,'00102','003','Given antibiotics');
INSERT INTO consultation VALUES (001004,11-AUG-20,'00103','005','Saline Drip');
INSERT INTO consultation VALUES (001005,11-SEP-20,'00104','001','Laid 3 eggs');
INSERT INTO consultation VALUES (001006,17-NOV-20,'00102','004','Given antibiotics');
INSERT INTO consultation VALUES (001007,11-DEC-20,'00105','004','Moult Assistance');
INSERT INTO consultation VALUES (001008,04-OCT-20,'00101','005','Given antibiotics');** ```

Body:
It is about invalid dates. The way you tried to do it is wrong - not just because it didn't work, but because you wanted to insert them as strings (only if they were enclosed into single quotes). You should insert dates.

One option is to use date literal which is always in format date 'yyyy-mm-dd':

SQL> INSERT INTO animal VALUES (00100,'Elsie','M', date '2013-02-01', 'PERSIAN CAT', '0034');

1 row created.

SQL>

Another is to use TO_DATE function with appropriate format mask:

SQL> INSERT INTO animal VALUES (00101,'Thurston','M', to_date('15-MAY-11', 'dd-mon-yy', 'nls_date_language = english'), 'MAINE COON CAT', '0034');

1 row created.

SQL>

The same goes for the consultation table.


问:
Can receive but cant send data to firebase, Code problem?
While i'm trying to send those values into the Firebase i'm getting this error: "Invalid document reference. Document references must have an even number of segments, but printers has 1"
ill post pictures of the code below maybe someone can shed some light on this thanks a lot!

Typescript:

import { Component, OnInit } from '@angular/core';
import { PrintersService } from '../printers.service';

@Component({
  selector: 'app-addprinter',
  templateUrl: './addprinter.component.html',
  styleUrls: ['./addprinter.component.css']
})
export class AddprinterComponent implements OnInit {

  constructor(private printersService: PrintersService) { }

  ngOnInit() {

  }

  AddPrinter(form) {

    this.printersService.AddPrinter(
      form.value.hostName,
      form.value.ip,
       form.value.location,
        form.value.manufacturer,
         form.value.model,
          form.value.specificLocation).then(
    data => console.log(data))
    .catch(err => console.log(err));
    console.log(form);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>Service:

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';

@Injectable({
  providedIn: 'root'
})
export class PrintersService {

  constructor(private fs: AngularFirestore) { }

  getAllPrinters() {
    return this.fs.collection('Printers').valueChanges();
  }

  AddPrinter(HostName, Ip, Location, Manufacturer, Model, SpecificLocation) {
    return this.fs.doc('Printers/').set({
      HostName,
      Ip,
      Location,
      Manufacturer,
      Model,
      SpecificLocation

    });

  }
}</code>```

HTML:

Add Printer

<form #f="ngForm" (ngSubmit)="AddPrinter(f)">

<input ngModel name="hostName" #hostname="ngModel" type="text" class="formControl" required placeholder="Enter HostName here">

The HostName is requied

<input ngModel name="ip" #ip="ngModel" type="text" class="formControl" required placeholder="Enter Ip here">

The Ip is requied

<input ngModel name="location" #location="ngModel" type="text" class="formControl" required placeholder="Enter Loctaion here">

The Location is requied

<input ngModel name="manufacturer" #manufacturer="ngModel" type="text" class="formControl" required placeholder="Enter Manufacturer here">

The Manufacturer is requied

<input ngModel name="Model" #model="ngModel" type="text" class="formControl" required required placeholder="Enter Model here">

The Model is requied

<input ngModel name="specificLocation" #specificLocation="ngModel" type="text" class="formControl" required placeholder="Enter Specific Location here">

The Specific Location is requied

<button class="btn btn-primary" [disabled]="f.invalid">Send</button>

</form>```

答:
The error is complaining about this line:

```<code>this.fs.doc('Printers/').set({ ... })
</code>```

If you want to create a document with set(), you must provide the full path including the collection where it lives, for example "Printers/printer_id".

If you are trying to add a new document with a random ID, use add() instead of set().

```<code>this.fs.collection('Printers').add({ ... })
</code>```

Body:
While i'm trying to send those values into the Firebase i'm getting this error: "Invalid document reference. Document references must have an even number of segments, but printers has 1"
ill post pictures of the code below maybe someone can shed some light on this thanks a lot!

Typescript:

import { Component, OnInit } from '@angular/core';
import { PrintersService } from '../printers.service';

@Component({
  selector: 'app-addprinter',
  templateUrl: './addprinter.component.html',
  styleUrls: ['./addprinter.component.css']
})
export class AddprinterComponent implements OnInit {

  constructor(private printersService: PrintersService) { }

  ngOnInit() {

  }

  AddPrinter(form) {

    this.printersService.AddPrinter(
      form.value.hostName,
      form.value.ip,
       form.value.location,
        form.value.manufacturer,
         form.value.model,
          form.value.specificLocation).then(
    data => console.log(data))
    .catch(err => console.log(err));
    console.log(form);
  }
}

Service:

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';

@Injectable({
  providedIn: 'root'
})
export class PrintersService {

  constructor(private fs: AngularFirestore) { }

  getAllPrinters() {
    return this.fs.collection('Printers').valueChanges();
  }

  AddPrinter(HostName, Ip, Location, Manufacturer, Model, SpecificLocation) {
    return this.fs.doc('Printers/').set({
      HostName,
      Ip,
      Location,
      Manufacturer,
      Model,
      SpecificLocation

    });

  }
}

HTML:

Add Printer

<form #f="ngForm" (ngSubmit)="AddPrinter(f)">

<input ngModel name="hostName" #hostname="ngModel" type="text" class="formControl" required placeholder="Enter HostName here">

The HostName is requied

<input ngModel name="ip" #ip="ngModel" type="text" class="formControl" required placeholder="Enter Ip here">

The Ip is requied

<input ngModel name="location" #location="ngModel" type="text" class="formControl" required placeholder="Enter Loctaion here">

The Location is requied

<input ngModel name="manufacturer" #manufacturer="ngModel" type="text" class="formControl" required placeholder="Enter Manufacturer here">

The Manufacturer is requied

<input ngModel name="Model" #model="ngModel" type="text" class="formControl" required required placeholder="Enter Model here">

The Model is requied

<input ngModel name="specificLocation" #specificLocation="ngModel" type="text" class="formControl" required placeholder="Enter Specific Location here">

The Specific Location is requied

<button class="btn btn-primary" [disabled]="f.invalid">Send</button>

</form>

Body:
The error is complaining about this line:

this.fs.doc('Printers/').set({ ... })

If you want to create a document with set(), you must provide the full path including the collection where it lives, for example "Printers/printer_id".

If you are trying to add a new document with a random ID, use add() instead of set().

this.fs.collection('Printers').add({ ... })


问:
Wrting python script that uses youtube-dl to extract just only the download link?
I'm new to python and I'm writing a python script to use youtube-dl to extract only download link, exactly like link given by the console (youtube-dl --get-url url).
I don't want to download the media, I just need the download-link from my script.</p>

答:
from youtube_dl import YoutubeDL

ydl = YoutubeDL()
url = 'https://youtu.be/x0RXU3n1GM0'
r = ydl.extract_info(url, download=False)
# if any link will do
urls = [format['url'] for format in r['formats']]

# if you want links with video and audio
urls = [f['url'] for f in r['formats'] if f['acodec'] != 'none' and f['vcodec'] != 'none']
```

ContentLicense: CC BY-SA 3.0


问:
Seed data import failed on jboss-javaee6-webapp
I am trying to get a basic Seam 3 webapplication to work and use the jboss-javaee6-webapp to achieve this goal. Using the manual at http://seamframework.org/Documentation/CDIQuickstartForMavenUsers.

However, I am running into some problems which I haven't been able to solve for days. I have basically no experience in JavaEE so the solution is probably really easy.

What I've done? I've simply generated a new maven project based on the supplied archetype and didn't change anything about it. I've installed Eclipse Helios including JBoss Tools and downloaded JBoss 6.0.0 and got Eclipse to deploy the application to the server succesfully.

While deploying, an exception occurs in the example code. To be specific the following exceptions occurs:

```<code>09:29:20,712 WARN  [seam3-example] Seed data import failed.: java.lang.NullPointerException
        at org.jboss.weld.integration.persistence.JBossJpaServices.resolvePersistenceContext(JBossJpaServices.java:59) [:6.0.0.Final]
    at org.jboss.weld.util.Beans.injectEEFields(Beans.java:781) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1$1.proceed(ManagedBean.java:181) [:6.0.0.Final]
    at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:54) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1.work(ManagedBean.java:176) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$FixInjectionPoint.run(ManagedBean.java:142) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.inject(ManagedBean.java:170) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:339) [:6.0.0.Final]
    at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:67) [:6.0.0.Final]
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:669) [:6.0.0.Final]
    at org.jboss.weld.bean.AbstractReceiverBean.getReceiver(AbstractReceiverBean.java:84) [:6.0.0.Final]
    at org.jboss.weld.bean.ProducerField$1.produce(ProducerField.java:134) [:6.0.0.Final]
    at org.jboss.weld.bean.AbstractProducerBean.create(AbstractProducerBean.java:361) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField.createUnderlying(EEResourceProducerField.java:170) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField.access$000(EEResourceProducerField.java:54) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField$EEResourceCallable.call(EEResourceProducerField.java:80) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.CallableMethodHandler.invoke(CallableMethodHandler.java:50) [:6.0.0.Final]
    at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:62) [:6.0.0.Final]
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:125) [:6.0.0.Final]
    at org.jboss.weldx.persistence.org$jboss$weld$bean-jboss$classloader:id="vfs:$$$Users$sander$Workspaces$eclipse$web-dev-32$$metadata$$plugins$org$jboss$ide$eclipse$as$core$JBoss_6$0_Runtime_Server1306911969901$deploy$seam3-example$war"-ProducerField-nl$jdi$examples$data$MemberRepositoryProducer$em_$$_WeldProxy.persist(org$jboss$weld$bean-jboss$classloader:id="vfs:$$$Users$sander$Workspaces$eclipse$web-dev-32$$metadata$$plugins$org$jboss$ide$eclipse$as$core$JBoss_6$0_Runtime_Server1306911969901$deploy$seam3-example$war"-ProducerField-nl$jdi$examples$data$MemberRepositoryProducer$em_$$_WeldProxy.java)
    at nl.jdi.examples.data.SeedDataImporter.importData(SeedDataImporter.java:51) [:]
...
</code>```

I've searched for a solution for this exact exception but I could barely find anything about it. This probably means that I've overlooked something very simple. So I've analysed the exception and found the following:

The exception message is from the example code (SeedDataImporter.java:61)

The exception itself (NullPointer) is thrown somewhere in the weld code

The problem seems to be purely persistence related (it can't find the PersistenceContext?)

Since the problem is persistence related, I've tried to change the persistence.xml however this didn't pay out. I think the problem is within the JDNI/Persistence.xml/Server config domain, however I can't be sure.

Can anybody point me in the right direction?

persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="primary">
    <jta-data-source>jdbc/__default</jta-data-source>
    <properties>
        <!-- Properties for Hibernate (default provider for JBoss AS) -->
        <property name="hibernate.hbm2ddl.auto" value="create-drop" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="false" />
        <!-- Properties for EclipseLink (default provider for GlassFish) -->
        <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
        <property name="eclipselink.logging.level" value="FINE" />
    </properties>
</persistence-unit>
</code>```

Edit:

When I try to deploy the unchanged application to GlassFish 3.1 within Eclipse I get the following error:

```<code>cannot Deploy seam3-example
Deployment Error for module: seam3-example: Error occurred during deployment: Exception while loading the app : javax.ejb.CreateException: Initialization failed for Singleton SeedDataImporter. Please see server.log for more details.

Cannot create tables for application seam3-example. The expected DDL file seam3-example_primary_createDDL.jdbc is not available.

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused.
</code>```

答:
At least on the command line I can start the example doing this:

Download and install the latest jboss 6 to

mvn archetype:generate -DarchetypeArtifactId=jboss-javaee6-webapp -DarchetypeGroupId=org.jboss.weld.archetypes -DarchetypeVersion=1.0.1.CR1 -DarchetypeRepository=central -DgroupId=com.example -DartifactId=jee-example -Dversion=0.0.1-SNAPSHOT

cd jee-example

mvn clean package jboss:hard-deploy -Djboss.home=<jboss-6.0.0.Final>

start the jboss with <jboss-6.0.0.Final>/bin/run.sh (run.bat on Windws)

open http://localhost:8080/jee-example/

For more details have a look at the readme.html that is created by the archtype in the same folder as the pom.xml

To work in eclipse you should install

eclipse for Java EE Developers

m2eclipse from this update site

m2eclipse wtp extension from the m2eclipse-extra update site documentation

I did not try the eclipse part for the archetype...

Body:
I am trying to get a basic Seam 3 webapplication to work and use the jboss-javaee6-webapp to achieve this goal. Using the manual at http://seamframework.org/Documentation/CDIQuickstartForMavenUsers.

However, I am running into some problems which I haven't been able to solve for days. I have basically no experience in JavaEE so the solution is probably really easy.

What I've done? I've simply generated a new maven project based on the supplied archetype and didn't change anything about it. I've installed Eclipse Helios including JBoss Tools and downloaded JBoss 6.0.0 and got Eclipse to deploy the application to the server succesfully.

While deploying, an exception occurs in the example code. To be specific the following exceptions occurs:

09:29:20,712 WARN  [seam3-example] Seed data import failed.: java.lang.NullPointerException
        at org.jboss.weld.integration.persistence.JBossJpaServices.resolvePersistenceContext(JBossJpaServices.java:59) [:6.0.0.Final]
    at org.jboss.weld.util.Beans.injectEEFields(Beans.java:781) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1$1.proceed(ManagedBean.java:181) [:6.0.0.Final]
    at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:54) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1.work(ManagedBean.java:176) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$FixInjectionPoint.run(ManagedBean.java:142) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.inject(ManagedBean.java:170) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:339) [:6.0.0.Final]
    at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:67) [:6.0.0.Final]
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:669) [:6.0.0.Final]
    at org.jboss.weld.bean.AbstractReceiverBean.getReceiver(AbstractReceiverBean.java:84) [:6.0.0.Final]
    at org.jboss.weld.bean.ProducerField$1.produce(ProducerField.java:134) [:6.0.0.Final]
    at org.jboss.weld.bean.AbstractProducerBean.create(AbstractProducerBean.java:361) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField.createUnderlying(EEResourceProducerField.java:170) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField.access$000(EEResourceProducerField.java:54) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField$EEResourceCallable.call(EEResourceProducerField.java:80) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.CallableMethodHandler.invoke(CallableMethodHandler.java:50) [:6.0.0.Final]
    at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:62) [:6.0.0.Final]
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:125) [:6.0.0.Final]
    at org.jboss.weldx.persistence.org$jboss$weld$bean-jboss$classloader:id="vfs:$$$Users$sander$Workspaces$eclipse$web-dev-32$$metadata$$plugins$org$jboss$ide$eclipse$as$core$JBoss_6$0_Runtime_Server1306911969901$deploy$seam3-example$war"-ProducerField-nl$jdi$examples$data$MemberRepositoryProducer$em_$$_WeldProxy.persist(org$jboss$weld$bean-jboss$classloader:id="vfs:$$$Users$sander$Workspaces$eclipse$web-dev-32$$metadata$$plugins$org$jboss$ide$eclipse$as$core$JBoss_6$0_Runtime_Server1306911969901$deploy$seam3-example$war"-ProducerField-nl$jdi$examples$data$MemberRepositoryProducer$em_$$_WeldProxy.java)
    at nl.jdi.examples.data.SeedDataImporter.importData(SeedDataImporter.java:51) [:]
...

I've searched for a solution for this exact exception but I could barely find anything about it. This probably means that I've overlooked something very simple. So I've analysed the exception and found the following:

The exception message is from the example code (SeedDataImporter.java:61)

The exception itself (NullPointer) is thrown somewhere in the weld code

The problem seems to be purely persistence related (it can't find the PersistenceContext?)

Since the problem is persistence related, I've tried to change the persistence.xml however this didn't pay out. I think the problem is within the JDNI/Persistence.xml/Server config domain, however I can't be sure.

Can anybody point me in the right direction?

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="primary">
    <jta-data-source>jdbc/__default</jta-data-source>
    <properties>

        <property name="hibernate.hbm2ddl.auto" value="create-drop" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="false" />

        <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
        <property name="eclipselink.logging.level" value="FINE" />
    </properties>
</persistence-unit>

Edit:

When I try to deploy the unchanged application to GlassFish 3.1 within Eclipse I get the following error:

cannot Deploy seam3-example
Deployment Error for module: seam3-example: Error occurred during deployment: Exception while loading the app : javax.ejb.CreateException: Initialization failed for Singleton SeedDataImporter. Please see server.log for more details.

Cannot create tables for application seam3-example. The expected DDL file seam3-example_primary_createDDL.jdbc is not available.

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused.


问:
How to write Inner Query Programatically to fetch latest record based on condition
My use case is to find latest records( by date) based on some filter criteria from a SQL table.I had constructed the SQL query and ran it through the SQL IDE and it is working fine. I am using MS Sql Serve as my database.

But when i am trying to convert this query programatically using Spring-Data JPA/Criteria, i am not getting how to achieve that.

Here is my query to find latest record based on src_cc, src_nbr and isvariableWeight: -

```<code>    SELECT *
    FROM
    dcfin_test Tab1
    INNER JOIN (
        SELECT
            ibd_doc_nbr,
            ibd_doc_line_nbr,
            MAX(create_ts) AS max_Ts
        FROM
            dcfin_test
        WHERE
            src_cc = 'US'
            AND src_nbr = 6938
            AND isvariableWeight = 'Y'
        GROUP BY
            ibd_doc_nbr,
            ibd_doc_line_nbr) Tab2 ON Tab1.ibd_doc_nbr = Tab2.ibd_doc_nbr
    AND Tab1.ibd_doc_line_nbr = Tab2.ibd_doc_line_nbr
    AND Tab1.create_ts = Tab2.max_Ts;
</code>```

Here src_cc, src_nbr and isVaribaleWeight will be passed during runtime programatically. Above is shown for example purpose.

Here is my Entity Model looks like (other unwanted column has been removed) :-

```<code>import java.math.BigDecimal;
import java.time.Instant;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Entity
@Table(name = "dcfin_test")
@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WeightedAlertEntity {

@Id
@Column(name = "weightedAlertId")
private String weightedAlertId;

@Column(name = "src_cc")
private String sourceCC;

@Column(name = "src_nbr")
private int sourceNbr;

@Column(name = "isVaribaleWeight")
private String isVaribaleWeight;

@Column(name = "ibd_doc_nbr")
private String inboundDocNbr;

@Column(name = "ibd_doc_line_nbr")
private String inboundDocNbrLineNbr;

@Column(name = "item_nbr")
private String itemNbr;

@Column(name = "wac_percent_change")
private BigDecimal percentWacChange;

@Column(name = "waw_percent_change")
private BigDecimal percentWawChange;

@Column(name = "created_by")
private String createdBy;

@Column(name = "create_ts")
private Instant createTs;
</code>```

}

I tried doing it using native Query in spring Data JPA and it looks like as follows :-

```<code>@Repository
public interface WeightedAlertEntityDao
extends JpaRepository<WeightedAlertEntity, String> {

@Query(value = "SELECT * FROM dcfin_weighted_alert_data Tab1 "
        + "INNER JOIN ("
        + "SELECT ibd_doc_nbr,ibd_doc_line_nbr,MAX(create_ts) AS max_Ts FROM dcfin_weighted_alert_data"
        + " WHERE src_cc = ?1 AND src_nbr = ?2 AND weight_format_type = ?3 "
        + "GROUP BY ibd_doc_nbr, ibd_doc_line_nbr) Tab2 "
        + "ON Tab1.ibd_doc_nbr = Tab2.ibd_doc_nbr "
        + "AND Tab1.ibd_doc_line_nbr = Tab2.ibd_doc_line_nbr "
        + "AND Tab1.create_ts = Tab2.max_Ts", nativeQuery = true)
public List<WeightedAlertEntity> getAlertEntityBasedOnFilterCondition(
    String sourceCC, Integer srcNbr, String weightFormatType);
</code>```

}

And when i called above method from my service layer as below :-

```<code>List<WeightedAlertEntity> alertEntityBasedOnFilterCondition = weightedAlertDao.getAlertEntityBasedOnFilterCondition(
        header.getFacilityCountryCode(),Integer.parseInt(header.getFacilityNum()),
        weightFormatType);
</code>```

Update on my Question :-

I have checked it thoroughly and found out that there was a mistake which leads to invalid column name as i used Tab2.create_ts in place of Tab2.max_Ts. Now i am able to get the results.

I need pagination support too as part of this query i.e. if user enters pageNum = 1 and pagesize = 10, i should be able to return 10 results if records are more.
and when user enters pageNum = 2, pageSize = 10, i should return next 10 records.

Can someone look into it and guide me how to achieve this using Spring Data Jpa / Criteria ?

答:
What you're looking for is the solution to "Top N Items Per Group". Use this phrase in your favorite search engine and several methods of solving the problem will appear. The ones I'd opt for are

Window Functions

CROSS APPLY join with subquery.

Body:
My use case is to find latest records( by date) based on some filter criteria from a SQL table.I had constructed the SQL query and ran it through the SQL IDE and it is working fine. I am using MS Sql Serve as my database.

But when i am trying to convert this query programatically using Spring-Data JPA/Criteria, i am not getting how to achieve that.

Here is my query to find latest record based on src_cc, src_nbr and isvariableWeight: -

    SELECT *
    FROM
    dcfin_test Tab1
    INNER JOIN (
        SELECT
            ibd_doc_nbr,
            ibd_doc_line_nbr,
            MAX(create_ts) AS max_Ts
        FROM
            dcfin_test
        WHERE
            src_cc = 'US'
            AND src_nbr = 6938
            AND isvariableWeight = 'Y'
        GROUP BY
            ibd_doc_nbr,
            ibd_doc_line_nbr) Tab2 ON Tab1.ibd_doc_nbr = Tab2.ibd_doc_nbr
    AND Tab1.ibd_doc_line_nbr = Tab2.ibd_doc_line_nbr
    AND Tab1.create_ts = Tab2.max_Ts;

Here src_cc, src_nbr and isVaribaleWeight will be passed during runtime programatically. Above is shown for example purpose.

Here is my Entity Model looks like (other unwanted column has been removed) :-

import java.math.BigDecimal;
import java.time.Instant;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Entity
@Table(name = "dcfin_test")
@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WeightedAlertEntity {

@Id
@Column(name = "weightedAlertId")
private String weightedAlertId;

@Column(name = "src_cc")
private String sourceCC;

@Column(name = "src_nbr")
private int sourceNbr;

@Column(name = "isVaribaleWeight")
private String isVaribaleWeight;

@Column(name = "ibd_doc_nbr")
private String inboundDocNbr;

@Column(name = "ibd_doc_line_nbr")
private String inboundDocNbrLineNbr;

@Column(name = "item_nbr")
private String itemNbr;

@Column(name = "wac_percent_change")
private BigDecimal percentWacChange;

@Column(name = "waw_percent_change")
private BigDecimal percentWawChange;

@Column(name = "created_by")
private String createdBy;

@Column(name = "create_ts")
private Instant createTs;

}

I tried doing it using native Query in spring Data JPA and it looks like as follows :-

@Repository
public interface WeightedAlertEntityDao
extends JpaRepository<WeightedAlertEntity, String> {

@Query(value = "SELECT * FROM dcfin_weighted_alert_data Tab1 "
        + "INNER JOIN ("
        + "SELECT ibd_doc_nbr,ibd_doc_line_nbr,MAX(create_ts) AS max_Ts FROM dcfin_weighted_alert_data"
        + " WHERE src_cc = ?1 AND src_nbr = ?2 AND weight_format_type = ?3 "
        + "GROUP BY ibd_doc_nbr, ibd_doc_line_nbr) Tab2 "
        + "ON Tab1.ibd_doc_nbr = Tab2.ibd_doc_nbr "
        + "AND Tab1.ibd_doc_line_nbr = Tab2.ibd_doc_line_nbr "
        + "AND Tab1.create_ts = Tab2.max_Ts", nativeQuery = true)
public List<WeightedAlertEntity> getAlertEntityBasedOnFilterCondition(
    String sourceCC, Integer srcNbr, String weightFormatType);

}

And when i called above method from my service layer as below :-

List<WeightedAlertEntity> alertEntityBasedOnFilterCondition = weightedAlertDao.getAlertEntityBasedOnFilterCondition(
        header.getFacilityCountryCode(),Integer.parseInt(header.getFacilityNum()),
        weightFormatType);

Update on my Question :-

I have checked it thoroughly and found out that there was a mistake which leads to invalid column name as i used Tab2.create_ts in place of Tab2.max_Ts. Now i am able to get the results.

I need pagination support too as part of this query i.e. if user enters pageNum = 1 and pagesize = 10, i should be able to return 10 results if records are more.
and when user enters pageNum = 2, pageSize = 10, i should return next 10 records.

Can someone look into it and guide me how to achieve this using Spring Data Jpa / Criteria ?


问:
Allow "customer" user role to upload files in front-end with acf_form
I've created a front-end form with acf_form() ( advanced custom field front-end form ) in woocommerce "view order" page which allows customers to upload some files for us , the form works fine for administrators but when you log-in with a customer account and you choose your file it says "you don't have permission to attach files" , after some researches i edited "customer" by adding below code to functions.php :

```<code>/**
 * Allow customers to upload files
 *
 * @package Wordpress
 * @subpackage Rightec Theme
 * @author Dornaweb.com
 */
if ( current_user_can('customer') ) {
    add_action('init', 'allow_customer_uploads', 20);
    add_action('admin_init', 'allow_customer_uploads', 20);
}
function allow_customer_uploads() {
    $customer = get_role('customer');
    $customer->add_cap('upload_files');
    $customer->add_cap('unfiltered_upload');
}
</code>```

i as well tried "user role editor" plugin , but it doesn't work too

help me please!

答:
Solution was easy. Give the user those capabilities: </p>

```<code>$author->add_cap('manage_options');
</code>```

Body:
I've created a front-end form with acf_form() ( advanced custom field front-end form ) in woocommerce "view order" page which allows customers to upload some files for us , the form works fine for administrators but when you log-in with a customer account and you choose your file it says "you don't have permission to attach files" , after some researches i edited "customer" by adding below code to functions.php :

/**
 * Allow customers to upload files
 *
 * @package Wordpress
 * @subpackage Rightec Theme
 * @author Dornaweb.com
 */
if ( current_user_can('customer') ) {
    add_action('init', 'allow_customer_uploads', 20);
    add_action('admin_init', 'allow_customer_uploads', 20);
}
function allow_customer_uploads() {
    $customer = get_role('customer');
    $customer->add_cap('upload_files');
    $customer->add_cap('unfiltered_upload');
}

i as well tried "user role editor" plugin , but it doesn't work too

help me please!

Body:
Solution was easy. Give the user those capabilities:

$author->add_cap('manage_options');


问:
AES-GCM 256 decryption fails even with correct data
I have a given encrypted message (decrypted, it is "encrypted secret message") and I'm trying to retrieve this original string from the AES-GCM 256 encrypted one. I use the aes-gcm crate to do this:

use aes_gcm::Aes256Gcm;
use aead::{Aead, NewAead, generic_array::GenericArray};

fn main() {
    let key_bytes = hex::decode("ce265dbc38bb25ef29fade77a4b88fe07b6063215f6526a4623cf810a3d611c9").unwrap();
    let nonce_bytes = hex::decode("ce77357fe7b2401400408f44").unwrap();
    let ciphertext_bytes = hex::decode("fd77fae68fa27ea00afbe474f4fcd47248a19b3cbf2a6d7e").unwrap();

    let key = GenericArray::clone_from_slice(key_bytes.as_slice());
    let nonce = GenericArray::from_slice(nonce_bytes.as_slice());

    let cipher = Aes256Gcm::new(key);
    let plaintext = cipher.decrypt(nonce, ciphertext_bytes.as_slice()).unwrap(); // panic on a decryption failure

    println!("{:?}", plaintext);
}
```

<p>This is the <code>dependencies</code> section of my Cargo.toml:</p>

```[dependencies]
aes-gcm = "0.5.0"
aead = "0.2.0"
hex = "0.4.2"
```

<p>The problem is that the program always panics at the <code>unwrap</code> call on line 13, even though the encrypted message, the key and the nonce are good: </p>

<pre class="lang-none prettyprint-override"><code>thread 'main' panicked at 'called Result::unwrap() on an Err value: Error', src\main.rs:13:21
</code>```

It looks like it's an error from the encrypted message being invalid, from the encrypted message, the key or the nonce being invalid, but it's not. I wrote a Python program that does exactly the same thing and it works; the output is indeed encrypted secret message!

from Crypto.Cipher import AES

key = bytes.fromhex("ce265dbc38bb25ef29fade77a4b88fe07b6063215f6526a4623cf810a3d611c9")

nonce = bytes.fromhex("ce77357fe7b2401400408f44")
cipher_text = bytes.fromhex("fd77fae68fa27ea00afbe474f4fcd47248a19b3cbf2a6d7e")

cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
plaintext = cipher.decrypt(cipher_text)

print(plaintext.decode("utf-8"))
```

I want to be able to decrypt these kind of encrypted messages in Rust, not in Python. I don't know why I get an error at all. Did I miss something?

答:
From encrypt, emphasis mine:

The default implementation assumes a postfix tag (ala AES-GCM, AES-GCM-SIV, ChaCha20Poly1305). Aead implementations which do not use a postfix tag will need to override this to correctly assemble the ciphertext message.

Since you say you have the tag:

I have the associated tag for this encrypted message as well

You can follow the same pattern:

```<code>use aead::{generic_array::GenericArray, Aead, NewAead};
use aes_gcm::Aes256Gcm;

fn main() {
    let key_hex = "ce265dbc38bb25ef29fade77a4b88fe07b6063215f6526a4623cf810a3d611c9";
    let nonce_hex = "ce77357fe7b2401400408f44";
    let ciphertext_hex = "fd77fae68fa27ea00afbe474f4fcd47248a19b3cbf2a6d7e";

    // Append the tag data to the encrypted data
    let tag_hex = "2ef2a9d27909df90bcb45606067148a6";
    let ciphertext_and_tag_hex = format!("{}{}", ciphertext_hex, tag_hex);
    let ciphertext_bytes = hex::decode(ciphertext_and_tag_hex).unwrap();

    let key_bytes = hex::decode(key_hex).unwrap();
    let nonce_bytes = hex::decode(nonce_hex).unwrap();

    let key = GenericArray::clone_from_slice(&key_bytes);
    let nonce = GenericArray::from_slice(&nonce_bytes);

    let cipher = Aes256Gcm::new(key);

    let plaintext = cipher.decrypt(nonce, &*ciphertext_bytes).unwrap();
    println!("{}", String::from_utf8_lossy(&plaintext));
}
</code>```

You can also investigate the decrypt_in_place_detached method, which is more complicated but allows specifying the tag separately.

Body:
I have a given encrypted message (decrypted, it is "encrypted secret message") and I'm trying to retrieve this original string from the AES-GCM 256 encrypted one. I use the aes-gcm crate to do this:

use aes_gcm::Aes256Gcm;
use aead::{Aead, NewAead, generic_array::GenericArray};

fn main() {
    let key_bytes = hex::decode("ce265dbc38bb25ef29fade77a4b88fe07b6063215f6526a4623cf810a3d611c9").unwrap();
    let nonce_bytes = hex::decode("ce77357fe7b2401400408f44").unwrap();
    let ciphertext_bytes = hex::decode("fd77fae68fa27ea00afbe474f4fcd47248a19b3cbf2a6d7e").unwrap();

    let key = GenericArray::clone_from_slice(key_bytes.as_slice());
    let nonce = GenericArray::from_slice(nonce_bytes.as_slice());

    let cipher = Aes256Gcm::new(key);
    let plaintext = cipher.decrypt(nonce, ciphertext_bytes.as_slice()).unwrap(); // panic on a decryption failure

    println!("{:?}", plaintext);
}

This is the dependencies section of my Cargo.toml:

[dependencies]
aes-gcm = "0.5.0"
aead = "0.2.0"
hex = "0.4.2"

The problem is that the program always panics at the unwrap call on line 13, even though the encrypted message, the key and the nonce are good:

thread 'main' panicked at 'called Result::unwrap() on an Err value: Error', src\main.rs:13:21

It looks like it's an error from the encrypted message being invalid, from the encrypted message, the key or the nonce being invalid, but it's not. I wrote a Python program that does exactly the same thing and it works; the output is indeed encrypted secret message!

from Crypto.Cipher import AES

key = bytes.fromhex("ce265dbc38bb25ef29fade77a4b88fe07b6063215f6526a4623cf810a3d611c9")

nonce = bytes.fromhex("ce77357fe7b2401400408f44")
cipher_text = bytes.fromhex("fd77fae68fa27ea00afbe474f4fcd47248a19b3cbf2a6d7e")

cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
plaintext = cipher.decrypt(cipher_text)

print(plaintext.decode("utf-8"))

I want to be able to decrypt these kind of encrypted messages in Rust, not in Python. I don't know why I get an error at all. Did I miss something?

Body:
From encrypt, emphasis mine:

The default implementation assumes a postfix tag (ala AES-GCM, AES-GCM-SIV, ChaCha20Poly1305). Aead implementations which do not use a postfix tag will need to override this to correctly assemble the ciphertext message.

Since you say you have the tag:

I have the associated tag for this encrypted message as well

You can follow the same pattern:

use aead::{generic_array::GenericArray, Aead, NewAead};
use aes_gcm::Aes256Gcm;

fn main() {
    let key_hex = "ce265dbc38bb25ef29fade77a4b88fe07b6063215f6526a4623cf810a3d611c9";
    let nonce_hex = "ce77357fe7b2401400408f44";
    let ciphertext_hex = "fd77fae68fa27ea00afbe474f4fcd47248a19b3cbf2a6d7e";

    // Append the tag data to the encrypted data
    let tag_hex = "2ef2a9d27909df90bcb45606067148a6";
    let ciphertext_and_tag_hex = format!("{}{}", ciphertext_hex, tag_hex);
    let ciphertext_bytes = hex::decode(ciphertext_and_tag_hex).unwrap();

    let key_bytes = hex::decode(key_hex).unwrap();
    let nonce_bytes = hex::decode(nonce_hex).unwrap();

    let key = GenericArray::clone_from_slice(&key_bytes);
    let nonce = GenericArray::from_slice(&nonce_bytes);

    let cipher = Aes256Gcm::new(key);

    let plaintext = cipher.decrypt(nonce, &*ciphertext_bytes).unwrap();
    println!("{}", String::from_utf8_lossy(&plaintext));
}

You can also investigate the decrypt_in_place_detached method, which is more complicated but allows specifying the tag separately.


问:
I want to create a new column with the value that a string has matched on from a list
```<code>To_Find_lst = ["Q1","Q2","Q3","Q4","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]
</code>```

DF:

```<code>   A                 B
Q1_MONDAY            55
Q3_LA                87
WEDNESDAY_FRIDAY     67
</code>```

I want to create a new column that will identify values from the list in col A and create a column C with the values it identified.

```<code>   A                 B         C
Q1_MONDAY            55.     Q1, MONDAY
Q3_LA                87.     Q3
WEDNESDAY_FRIDAY     67.     WEDNESDAY, FRIDAY
</code>```

答:
try str.extractall

```<code>lst = '|'.join(To_Find_lst )
#'Q1|Q2|Q3|Q4|MONDAY|TUESDAY|WEDNESDAY|THURSDAY|FRIDAY|SATURDAY|SUNDAY'

df['C'] = df['A'].str.extractall(f'({lst})').groupby(level=0).agg(','.join)

print(df)

                  A   B                 C
0         Q1_MONDAY  55         Q1,MONDAY
1             Q3_LA  87                Q3
2  WEDNESDAY_FRIDAY  67  WEDNESDAY,FRIDAY
</code>```

Body:
To_Find_lst = ["Q1","Q2","Q3","Q4","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]

DF:

   A                 B
Q1_MONDAY            55
Q3_LA                87
WEDNESDAY_FRIDAY     67

I want to create a new column that will identify values from the list in col A and create a column C with the values it identified.

   A                 B         C
Q1_MONDAY            55.     Q1, MONDAY
Q3_LA                87.     Q3
WEDNESDAY_FRIDAY     67.     WEDNESDAY, FRIDAY

Body:
try str.extractall

lst = '|'.join(To_Find_lst )
#'Q1|Q2|Q3|Q4|MONDAY|TUESDAY|WEDNESDAY|THURSDAY|FRIDAY|SATURDAY|SUNDAY'

df['C'] = df['A'].str.extractall(f'({lst})').groupby(level=0).agg(','.join)

print(df)

                  A   B                 C
0         Q1_MONDAY  55         Q1,MONDAY
1             Q3_LA  87                Q3
2  WEDNESDAY_FRIDAY  67  WEDNESDAY,FRIDAY


问:
Cannot delete or update a parent row: a foreign key constraint fails when deleting entity with reference
I want to delete an instance of "UserRegistration" which has a reference to an instance of "Authority". When deleting the instance of "UserRegistration" via the repository I get following Error:
"Cannot delete or update a parent row: a foreign key constraint fails (seprojekt.authorities, CONSTRAINT authorities_ibfk_1 FOREIGN KEY (userid) REFERENCES users (id))"
Is there a possibility of deleting the referenced Entity when the Instance of "UserRegistration" ist deleted? I tried this with Cascadetype and orphanRemoval in "UserRegistration" but nothing happened.

The Method which tries to delete the Entity:

```<code>@DeleteMapping
public boolean deleteUser(@RequestParam String username) {
    Optional<UserRegistration> optUserRegistration = uRepo.findByUsername(username);
    if(optUserRegistration.isPresent()) {
        System.out.println("!!! Authority is: '" + optUserRegistration.get().getAuthority().getAuthority());
        uRepo.delete(optUserRegistration.get());
        return true;
    }
    return false;
}
</code>```

The UserRegistrationclass looks like this:

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

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
@Entity
@Table(name = "users")
public class UserRegistration {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
@JsonIgnore
private String password;
@JsonIgnore
private boolean enabled;
private Integer profilePicture;
private String email;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "id")
private Authority authority;
@JsonManagedReference
@ManyToMany
@JoinTable(name = "userhasfavorite", joinColumns = @JoinColumn(name = "userid"), inverseJoinColumns = @JoinColumn(name = "channelid"))
private List<Channel> favorites;

public UserRegistration() {
}

public UserRegistration(String email, String username, String password, boolean enabled, int profilePicture) {
    this.email = email;
    this.username = username;
    this.password = password;
    this.enabled = enabled;
    this.profilePicture = profilePicture;
}

public int getId() {
    return id;
}

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

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public boolean getEnabled() {
    return enabled;
}

public void setEnabled(boolean enabled) {
    this.enabled = enabled;
}

public Integer getProfilePicture() {
    return profilePicture;
}

public void setProfilePicture(Integer profilePicture) {
    this.profilePicture = profilePicture;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public Authority getAuthority() {
    return authority;
}

public void setAuthority(Authority authority) {
    this.authority = authority;
}

public List<Channel> getFavorites() {
    return favorites;
}

public void setFavorites(List<Channel> favorites) {
    this.favorites = favorites;
}
}
</code>```

The Authorityclass looks like this:

```<code>import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "authorities")
public class Authority {

    @Id
    @Column(name = "userid")
    private int userID;
    private String username;
    private String authority;
    @OneToOne(mappedBy = "authority")
    private UserRegistration user;

    public Authority() {
    }

    public Authority(int userID, String username, String authority) {
        this.userID = userID;
        this.username = username;
        this.authority = authority;
    }

    public int getUserID() {
        return userID;
    }

    public void setUserID(int userID) {
        this.userID = userID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAuthority() {
        return authority;
    }

    public void setAuthority(String authority) {
        this.authority = authority;
    }

    public UserRegistration getUser() {
        return user;
    }

    public void setUser(UserRegistration user) {
        this.user = user;
    }
}
</code>```

Thanks a lot for reading this. Please ask me for more details if required.

答:
In order for cascading to work; you need to reverse the entity relation definition. The cascading only works for parent entity to child entity. What I mean is the following. Please define authority in UserRegistration as:

```<code>@OneToOne(mappedBy="user", cascade = CascadeType.ALL)
private Authority authority;
</code>```

and the userRegistration in Authority as:

```<code>@OneToOne
@MapsId
private UserRegistration user;
</code>```

I believe this should work. Take a look at the following for more information. Hope that helps.

Body:
I want to delete an instance of "UserRegistration" which has a reference to an instance of "Authority". When deleting the instance of "UserRegistration" via the repository I get following Error:
"Cannot delete or update a parent row: a foreign key constraint fails (seprojekt.authorities, CONSTRAINT authorities_ibfk_1 FOREIGN KEY (userid) REFERENCES users (id))"
Is there a possibility of deleting the referenced Entity when the Instance of "UserRegistration" ist deleted? I tried this with Cascadetype and orphanRemoval in "UserRegistration" but nothing happened.

The Method which tries to delete the Entity:

@DeleteMapping
public boolean deleteUser(@RequestParam String username) {
    Optional<UserRegistration> optUserRegistration = uRepo.findByUsername(username);
    if(optUserRegistration.isPresent()) {
        System.out.println("!!! Authority is: '" + optUserRegistration.get().getAuthority().getAuthority());
        uRepo.delete(optUserRegistration.get());
        return true;
    }
    return false;
}

The UserRegistrationclass looks like this:

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
@Entity
@Table(name = "users")
public class UserRegistration {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
@JsonIgnore
private String password;
@JsonIgnore
private boolean enabled;
private Integer profilePicture;
private String email;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "id")
private Authority authority;
@JsonManagedReference
@ManyToMany
@JoinTable(name = "userhasfavorite", joinColumns = @JoinColumn(name = "userid"), inverseJoinColumns = @JoinColumn(name = "channelid"))
private List<Channel> favorites;

public UserRegistration() {
}

public UserRegistration(String email, String username, String password, boolean enabled, int profilePicture) {
    this.email = email;
    this.username = username;
    this.password = password;
    this.enabled = enabled;
    this.profilePicture = profilePicture;
}

public int getId() {
    return id;
}

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

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public boolean getEnabled() {
    return enabled;
}

public void setEnabled(boolean enabled) {
    this.enabled = enabled;
}

public Integer getProfilePicture() {
    return profilePicture;
}

public void setProfilePicture(Integer profilePicture) {
    this.profilePicture = profilePicture;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public Authority getAuthority() {
    return authority;
}

public void setAuthority(Authority authority) {
    this.authority = authority;
}

public List<Channel> getFavorites() {
    return favorites;
}

public void setFavorites(List<Channel> favorites) {
    this.favorites = favorites;
}
}

The Authorityclass looks like this:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "authorities")
public class Authority {

    @Id
    @Column(name = "userid")
    private int userID;
    private String username;
    private String authority;
    @OneToOne(mappedBy = "authority")
    private UserRegistration user;

    public Authority() {
    }

    public Authority(int userID, String username, String authority) {
        this.userID = userID;
        this.username = username;
        this.authority = authority;
    }

    public int getUserID() {
        return userID;
    }

    public void setUserID(int userID) {
        this.userID = userID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAuthority() {
        return authority;
    }

    public void setAuthority(String authority) {
        this.authority = authority;
    }

    public UserRegistration getUser() {
        return user;
    }

    public void setUser(UserRegistration user) {
        this.user = user;
    }
}

Thanks a lot for reading this. Please ask me for more details if required.

Body:
In order for cascading to work; you need to reverse the entity relation definition. The cascading only works for parent entity to child entity. What I mean is the following. Please define authority in UserRegistration as:

@OneToOne(mappedBy="user", cascade = CascadeType.ALL)
private Authority authority;

and the userRegistration in Authority as:

@OneToOne
@MapsId
private UserRegistration user;

I believe this should work. Take a look at the following for more information. Hope that helps.


问:
wordpress page redirect from iframe to paypal page
I have a Wordpress page with iframe integrated which contains booking calendar script as per below.

```<code><div class="booking-calendar">
                    <iframe id="frame1" name="frame1" src="http://www.xxxxxx.co.uk/booking/frontend/" width="100%" height="450px" frameborder="0" scrolling="auto"></iframe>

                    </div>
</code>```

Demo for the script in this iframe can be found here: http://www.phpjabbers.com/hotels-booking-system/
What I want to do is once the user clicks on Book now button is to redirect them to Paypal page. At the moment is set up so that they have to click on 'Pay now' button to get to this Paypal page where they make a payment. The code for this Pay now button is as follows:

```<code><?php
    if ($deposit > 0) {
        if ($_REQUEST['payment_type'] == 'paypal') {
            ?>
            <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
                <input type="hidden" name="cmd" value="_xclick">
                <input type="hidden" name="business" value="<?php echo $SETTINGS_DB["paypal_address"]; ?>">
                <input type="hidden" name="item_name" value="Booking confirmation - <?php echo $BookingID; ?>">
                <input type="hidden" name="item_number" value="">
                <input type="hidden" name="amount" value="<?php echo number_format($deposit, 2, '.', ''); ?>">
                <input type="hidden" name="no_shipping" value="1">
                <input type="hidden" name="no_note" value="1">
                <input type="hidden" name="currency_code" value="<?php echo $Currencies[$SETTINGS_DB["currency"]]; ?>">
                <input type="hidden" name="lc" value="US">
                <input type="hidden" name="bn" value="PP-BuyNowBF">
                <input type="hidden" name="return" value="<?php echo $SETTINGS_DB["thankyou_page"]; ?>">
                <input name="submit" type='submit' value='PAY NOW' >
            </form>
            <?php
                header ("https://www.paypal.com/cgi-bin/webscr");
                exit;
            ?>
</code>```

I was wondering how could I make a redirect so that the user goes automatically to Paypal page without clicking on Pay now? If somebody can put me in the right direction that would be great. I understand that hidden values have to be carried over to Paypal page, I just don't know how to make it so they get carried over. Any ideas? Any tips would be really appreciated.

答:
I have been trying to sort it out myself so what I did so far: As I want the redirect to PayPal happen once the user clicks on Book button, I copied hidden fields which are part of Pay now form to the part with Book button --> part of the last bit of code:

```<code>($deposit > 0) {

        <input type="hidden" name="cmd" value="_xclick">
                <input type="hidden" name="business" value="<?php echo $SETTINGS_DB["paypal_address"]; ?>">
                <input type="hidden" name="item_name" value="Booking confirmation - <?php echo $BookingID; ?>">
                <input type="hidden" name="item_number" value="">
                <input type="hidden" name="amount" value="<?php echo number_format($deposit, 2, '.', ''); ?>">
                <input type="hidden" name="no_shipping" value="1">
                <input type="hidden" name="no_note" value="1">
                <input type="hidden" name="currency_code" value="<?php echo $Currencies[$SETTINGS_DB["currency"]]; ?>">
                <input type="hidden" name="lc" value="US">
                <input type="hidden" name="bn" value="PP-BuyNowBF">
                <input type="hidden" name="return" value="<?php echo $SETTINGS_DB["thankyou_page"]; ?>">
    <?php   }
?>
        <div style="float:left"><input type="submit" value="Book"></div>
        <div style="clear:both"></div>

</form>
</code>```

Once the user clicks on Book button, the code will check if it's been submitted with this:

```<code>elseif ($_REQUEST["ac"]=='save_booking') {
</code>```

and then the Booking details (name, tel, email,..) will be inserted into the database like this:

```<code>$sql = "INSERT INTO ".$TABLES["bookings"]." SET
                  `from` = '".Date2MySQL(SaveToDB($_REQUEST["from"]))."',
                  `to` = '".Date2MySQL(SaveToDB($_REQUEST["to"]))."',
                  `name` = '".SaveToDB($_REQUEST["name"])."',
                  `email` = '".SaveToDB($_REQUEST["email"])."',
                  `phone` = '".SaveToDB($_REQUEST["phone"])."',
                  `notes` = '".SaveToDB($_REQUEST["notes"])."',
                  `people` = '".SaveToDB($_REQUEST["people"])."',
                  `payment_type` = '".SaveToDB($_REQUEST["payment_type"])."',
                  `dt` = now()";
            $sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql.mysql_error());
            $BookingID = mysql_insert_id();

            $total_price = 0;
            $sql = "SELECT * FROM ".$TABLES["rooms"]." ORDER BY id DESC";
            $sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
            while ($row = mysql_fetch_assoc($sql_result)) {
                if ($_REQUEST["room_".$row["id"]]>0) {
                    $sql = "INSERT INTO ".$TABLES["bookings_rooms"]." SET
                          `booking_id` = '".$BookingID."',
                          `room_id` = '".$row["id"]."',
                          `quantity` = '".SaveToDB($_REQUEST["room_".$row["id"]])."'";
                    $sql_resultT = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql.mysql_error());
                    $total_price = $total_price + $_REQUEST["room_price_".$row["id"]]*$_REQUEST["room_".$row["id"]];
                };
            };

            $sql = "UPDATE ".$TABLES["bookings"]." SET
                  `price` = '".$total_price."'
                  WHERE id = '".$BookingID."'";
            $sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql.mysql_error());

            $deposit = $SETTINGS_DB["payment_deposit"];

            $sql = "SELECT * FROM ".$TABLES["bookings"]." WHERE id='".$BookingID."'";
            $sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
            $booking = mysql_fetch_assoc($sql_result);

            $sql = "SELECT * FROM `".$TABLES["bookings_rooms"]."` INNER JOIN ".$TABLES["rooms"]." ON ".$TABLES["rooms"].".id = ".$TABLES["bookings_rooms"].".room_id WHERE `".$TABLES["bookings_rooms"]."`.booking_id='".$BookingID."'";
            $sql_resultP = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
            while ($rooms = mysql_fetch_assoc($sql_resultP)) {
                 $roomsemail .= $rooms["quantity"]." x ".$rooms["room_type"].", ";
            };

            $message = ReadFromDB($SETTINGS_DB["email_message"]);
            $search_tokens=array("{name}","{email}","{phone}","{from_date}","{to_date}","{price}","{rooms}");
            $replace_tokens=array(ReadFromDB($booking["name"]),ReadFromDB($booking["email"]),ReadFromDB($booking["phone"]),MySQL2Date(ReadFromDB($booking["from"])),MySQL2Date(ReadFromDB($booking["to"])),formatCurrencyExport($booking["price"]),$roomsemail);
            $message=str_replace($search_tokens,$replace_tokens,$message);

            $mailheader    = "From: ".$SETTINGS_DB["admin_email"]."\r\n";
            $mailheader   .= "Reply-To: ".$SETTINGS_DB["admin_email"]."\r\n";
            $mailheader   .= "Content-type: text/plain; charset=UTF-8\r\n";

            mail($booking["email"], $SETTINGS_DB["email_subject"], $message, $mailheader);
            if ($SETTINGS_DB["admin_email"]) {
                mail($SETTINGS_DB["admin_email"], $SETTINGS_DB["email_subject"], $message, $mailheader);

            }
</code>```

After the data has been inserted into the database I want the user to go automatically to PayPal payment page, so I inserted this code after the above code:

```<code>header ("https://www.paypal.com/cgi-bin/webscr");
                exit;
?>
</code>```

Now when I click on Book button nothing happens, well the form disappears, so I just have some instruction text on the page, but we are not redirected to the PayPal page. Could somebody please point me to the right direction?

Body:
I have a Wordpress page with iframe integrated which contains booking calendar script as per below.

Demo for the script in this iframe can be found here: http://www.phpjabbers.com/hotels-booking-system/
What I want to do is once the user clicks on Book now button is to redirect them to Paypal page. At the moment is set up so that they have to click on 'Pay now' button to get to this Paypal page where they make a payment. The code for this Pay now button is as follows:

<?php
    if ($deposit > 0) {
        if ($_REQUEST['payment_type'] == 'paypal') {
            ?>
            <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
                <input type="hidden" name="cmd" value="_xclick">
                <input type="hidden" name="business" value="<?php echo $SETTINGS_DB["paypal_address"]; ?>">
                <input type="hidden" name="item_name" value="Booking confirmation - <?php echo $BookingID; ?>">
                <input type="hidden" name="item_number" value="">
                <input type="hidden" name="amount" value="<?php echo number_format($deposit, 2, '.', ''); ?>">
                <input type="hidden" name="no_shipping" value="1">
                <input type="hidden" name="no_note" value="1">
                <input type="hidden" name="currency_code" value="<?php echo $Currencies[$SETTINGS_DB["currency"]]; ?>">
                <input type="hidden" name="lc" value="US">
                <input type="hidden" name="bn" value="PP-BuyNowBF">
                <input type="hidden" name="return" value="<?php echo $SETTINGS_DB["thankyou_page"]; ?>">
                <input name="submit" type='submit' value='PAY NOW' >
            </form>
            <?php
                header ("https://www.paypal.com/cgi-bin/webscr");
                exit;
            ?>

I was wondering how could I make a redirect so that the user goes automatically to Paypal page without clicking on Pay now? If somebody can put me in the right direction that would be great. I understand that hidden values have to be carried over to Paypal page, I just don't know how to make it so they get carried over. Any ideas? Any tips would be really appreciated.

Body:
I have been trying to sort it out myself so what I did so far: As I want the redirect to PayPal happen once the user clicks on Book button, I copied hidden fields which are part of Pay now form to the part with Book button --> part of the last bit of code:

($deposit > 0) {

        <input type="hidden" name="cmd" value="_xclick">
                <input type="hidden" name="business" value="<?php echo $SETTINGS_DB["paypal_address"]; ?>">
                <input type="hidden" name="item_name" value="Booking confirmation - <?php echo $BookingID; ?>">
                <input type="hidden" name="item_number" value="">
                <input type="hidden" name="amount" value="<?php echo number_format($deposit, 2, '.', ''); ?>">
                <input type="hidden" name="no_shipping" value="1">
                <input type="hidden" name="no_note" value="1">
                <input type="hidden" name="currency_code" value="<?php echo $Currencies[$SETTINGS_DB["currency"]]; ?>">
                <input type="hidden" name="lc" value="US">
                <input type="hidden" name="bn" value="PP-BuyNowBF">
                <input type="hidden" name="return" value="<?php echo $SETTINGS_DB["thankyou_page"]; ?>">
    <?php   }
?>
        <div style="float:left"><input type="submit" value="Book"></div>
        <div style="clear:both"></div>

</form>

Once the user clicks on Book button, the code will check if it's been submitted with this:

elseif ($_REQUEST["ac"]=='save_booking') {

and then the Booking details (name, tel, email,..) will be inserted into the database like this:

$sql = "INSERT INTO ".$TABLES["bookings"]." SET
                  `from` = '".Date2MySQL(SaveToDB($_REQUEST["from"]))."',
                  `to` = '".Date2MySQL(SaveToDB($_REQUEST["to"]))."',
                  `name` = '".SaveToDB($_REQUEST["name"])."',
                  `email` = '".SaveToDB($_REQUEST["email"])."',
                  `phone` = '".SaveToDB($_REQUEST["phone"])."',
                  `notes` = '".SaveToDB($_REQUEST["notes"])."',
                  `people` = '".SaveToDB($_REQUEST["people"])."',
                  `payment_type` = '".SaveToDB($_REQUEST["payment_type"])."',
                  `dt` = now()";
            $sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql.mysql_error());
            $BookingID = mysql_insert_id();

            $total_price = 0;
            $sql = "SELECT * FROM ".$TABLES["rooms"]." ORDER BY id DESC";
            $sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
            while ($row = mysql_fetch_assoc($sql_result)) {
                if ($_REQUEST["room_".$row["id"]]>0) {
                    $sql = "INSERT INTO ".$TABLES["bookings_rooms"]." SET
                          `booking_id` = '".$BookingID."',
                          `room_id` = '".$row["id"]."',
                          `quantity` = '".SaveToDB($_REQUEST["room_".$row["id"]])."'";
                    $sql_resultT = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql.mysql_error());
                    $total_price = $total_price + $_REQUEST["room_price_".$row["id"]]*$_REQUEST["room_".$row["id"]];
                };
            };

            $sql = "UPDATE ".$TABLES["bookings"]." SET
                  `price` = '".$total_price."'
                  WHERE id = '".$BookingID."'";
            $sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql.mysql_error());

            $deposit = $SETTINGS_DB["payment_deposit"];

            $sql = "SELECT * FROM ".$TABLES["bookings"]." WHERE id='".$BookingID."'";
            $sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
            $booking = mysql_fetch_assoc($sql_result);

            $sql = "SELECT * FROM `".$TABLES["bookings_rooms"]."` INNER JOIN ".$TABLES["rooms"]." ON ".$TABLES["rooms"].".id = ".$TABLES["bookings_rooms"].".room_id WHERE `".$TABLES["bookings_rooms"]."`.booking_id='".$BookingID."'";
            $sql_resultP = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
            while ($rooms = mysql_fetch_assoc($sql_resultP)) {
                 $roomsemail .= $rooms["quantity"]." x ".$rooms["room_type"].", ";
            };

            $message = ReadFromDB($SETTINGS_DB["email_message"]);
            $search_tokens=array("{name}","{email}","{phone}","{from_date}","{to_date}","{price}","{rooms}");
            $replace_tokens=array(ReadFromDB($booking["name"]),ReadFromDB($booking["email"]),ReadFromDB($booking["phone"]),MySQL2Date(ReadFromDB($booking["from"])),MySQL2Date(ReadFromDB($booking["to"])),formatCurrencyExport($booking["price"]),$roomsemail);
            $message=str_replace($search_tokens,$replace_tokens,$message);

            $mailheader    = "From: ".$SETTINGS_DB["admin_email"]."\r\n";
            $mailheader   .= "Reply-To: ".$SETTINGS_DB["admin_email"]."\r\n";
            $mailheader   .= "Content-type: text/plain; charset=UTF-8\r\n";

            mail($booking["email"], $SETTINGS_DB["email_subject"], $message, $mailheader);
            if ($SETTINGS_DB["admin_email"]) {
                mail($SETTINGS_DB["admin_email"], $SETTINGS_DB["email_subject"], $message, $mailheader);

            }

After the data has been inserted into the database I want the user to go automatically to PayPal payment page, so I inserted this code after the above code:

header ("https://www.paypal.com/cgi-bin/webscr");
                exit;
?>

Now when I click on Book button nothing happens, well the form disappears, so I just have some instruction text on the page, but we are not redirected to the PayPal page. Could somebody please point me to the right direction?


问:
p64() from pwntools not working correctly
I want to send input to a process which includes unprintable characters like "\x90". I when I try to send it like this: p.sendline(p64(0x414190)), my programm which prints it back, returns AA\x90. It took the "\x90" as a string, not as a byte. Can someone help me how to send raw bytes?

My program (vulnerable to format string, I dont need to be told):

```<code>#include <stdio.h>

int main() {
  char name[512];
  char passwd[512];

  printf("Enter your name: ");
  fgets(name, sizeof(name), stdin);
  printf(name);

  printf("Enter your password: ");
  fgets(passwd, sizeof(passwd), stdin);
  printf(passwd);

  exit(1);
}
</code>```

答:
Using p64() does send the input as raw bytes. You can check it by adding pwntools' DEBUG flag while running your script. The debug output then prints everything that is sent and received. E.g.:

```<code>python2 solve.py DEBUG
[+] Starting local process './script': pid 23732
[DEBUG] Received 0x11 bytes:
    'Enter your name: '
[DEBUG] Sent 0x9 bytes:
    00000000  90 41 41 00  00 00 00 00  0a                        │·AA·│····│·│
    00000009
[*] Switching to interactive mode
[DEBUG] Received 0x18 bytes:
    00000000  90 41 41 45  6e 74 65 72  20 79 6f 75  72 20 70 61  │·AAE│nter│ you│r pa│
    00000010  73 73 77 6f  72 64 3a 20                            │sswo│rd: │
    00000018
\x90AAEnter your password: $
</code>```

In the example above, you see that the bytes 90 41 41 00  00 00 00 00  0a are sent to the program, and not the string \x90.

Body:
I want to send input to a process which includes unprintable characters like "\x90". I when I try to send it like this: p.sendline(p64(0x414190)), my programm which prints it back, returns AA\x90. It took the "\x90" as a string, not as a byte. Can someone help me how to send raw bytes?

My program (vulnerable to format string, I dont need to be told):

#include <stdio.h>

int main() {
  char name[512];
  char passwd[512];

  printf("Enter your name: ");
  fgets(name, sizeof(name), stdin);
  printf(name);

  printf("Enter your password: ");
  fgets(passwd, sizeof(passwd), stdin);
  printf(passwd);

  exit(1);
}

Body:
Using p64() does send the input as raw bytes. You can check it by adding pwntools' DEBUG flag while running your script. The debug output then prints everything that is sent and received. E.g.:

python2 solve.py DEBUG
[+] Starting local process './script': pid 23732
[DEBUG] Received 0x11 bytes:
    'Enter your name: '
[DEBUG] Sent 0x9 bytes:
    00000000  90 41 41 00  00 00 00 00  0a                        │·AA·│····│·│
    00000009
[*] Switching to interactive mode
[DEBUG] Received 0x18 bytes:
    00000000  90 41 41 45  6e 74 65 72  20 79 6f 75  72 20 70 61  │·AAE│nter│ you│r pa│
    00000010  73 73 77 6f  72 64 3a 20                            │sswo│rd: │
    00000018
\x90AAEnter your password: $

In the example above, you see that the bytes 90 41 41 00  00 00 00 00  0a are sent to the program, and not the string \x90.


问:
Accesing more Window Extra Bytes than LongPointer
Im trying to figure out of how to correctly work with the Extra Bytes that you can let windows allocate for your windows and window classes.

If i'm reading the docs correctly, you can tell windows to allocate a specified amount of memory for your window or window class.
But there is only two methods i could find to access and modify said data, SetWindowLongPtr and GetWindowLongPtr.

Problem is, with those methods you can only set a LongPtr full of data, so 64 / 32 bits depending on your system.

Can somebody explain this to me, is there a method i am missing or is this as it should be?

答:
(Get|Set)WindowLong() accesses a value at the specified nIndex as a whole LONG.

(Get|Set)WindowLongPtr() accesses a value at the specified nIndex as a whole LONG_PTR.

So yes, this does mean that (Get|Set)WindowLongPtr() will access a different number of bytes depending on whether you are compiling your project for 32bit or 64bit.  As such, if you want to read/write a smaller number of bytes, you will have to read/write a whole LONG/_PTR and do some bit shifting as needed.

Even though you can specify an arbitrary byte count for the WNDCLASS/EX::cbWndExtra field, in reality it needs to be large enough to hold at least sizeof(LONG/_PTR) number of bytes at the last byte offset you intend to specify in the nIndex parameter.

This is stated in the GetWindowLong()/SetWindowLong() and GetWindowLongPtr()/SetWindowLongPtr documentations:

nIndex

Type: int

The zero-based offset to the value to be retrieved. Valid values are in the range zero through the number of bytes of extra window memory, minus four; for example, if you specified 12 or more bytes of extra memory, a value of 8 would be an index to the third 32-bit integer.

nIndex

Type: int

The zero-based offset to the value to be retrieved. Valid values are in the range zero through the number of bytes of extra window memory, minus the size of a LONG_PTR.