问:
JavaScript - Math.random() - parameter
What changes adding the parameter in Math.random()?

For example:

```<code>Math.random() == Math.random(1234)
</code>```

答: Nothing.  There is no seed for Math.random in Javascript.  Anything inside the function call will just be dropped.

Title: JavaScript - Math.random() - parameter

Body:
What changes adding the parameter in Math.random()?

For example:

Math.random() == Math.random(1234)


来源: stackexchange

问:
RxJS, understanding defer
I searched for the usage of defer in RxJS but still I don't understand why and when to use it.

As I understand neither Observable methods is fired before someone subscribes to it.

If that's the case then why do we need to wrap an Observable method with defer?

An example

I'm still wondering why it wrapped Observable with defer? Does it make any difference?

var source = Rx.Observable.defer(function () {
  return Rx.Observable.return(42);
});

var subscription = source.subscribe(
  function (x) { console.log('Next: ' + x); },
  function (err) { console.log('Error: ' + err); },
  function () { console.log('Completed'); } );
```

答:
Let's say you want to create an observable which when subscribed to, it performs an ajax request.

If you try the code below, the ajax request will be performed immediately,
and after 5 seconds the response object will be printed, which is not what you want.

```<code>const obs = from(fetch('http://jsonplaceholder.typicode.com/todos/1'));
setTimeout(()=>obs.subscribe((resp)=>console.log(resp)), 5000)
</code>```

One solution is to manually create an Observable like below.

In this case the ajax response will be performed after 5 seconds (when subscribe() is called):

```<code>let obs = new Observable(observer => {
    from(fetch('http://jsonplaceholder.typicode.com/todos/1')).subscribe(observer)
});
setTimeout(()=>obs.subscribe((resp)=>console.log(resp)), 5000)
</code>```

defer achieves the above in a more straightforward way, and also without the need to use from() to convert promise to observable:

```<code>const obs = defer(()=>fetch('http://jsonplaceholder.typicode.com/todos/1'))
setTimeout(()=>obs.subscribe((resp)=>console.log(resp)), 5000)
</code>```

ContentLicense: CC BY-SA 4.0

Title: RxJS, understanding defer

Body:
Let's say you want to create an observable which when subscribed to, it performs an ajax request.

If you try the code below, the ajax request will be performed immediately,
and after 5 seconds the response object will be printed, which is not what you want.

const obs = from(fetch('http://jsonplaceholder.typicode.com/todos/1'));
setTimeout(()=>obs.subscribe((resp)=>console.log(resp)), 5000)

One solution is to manually create an Observable like below.

In this case the ajax response will be performed after 5 seconds (when subscribe() is called):

let obs = new Observable(observer => {
    from(fetch('http://jsonplaceholder.typicode.com/todos/1')).subscribe(observer)
});
setTimeout(()=>obs.subscribe((resp)=>console.log(resp)), 5000)

defer achieves the above in a more straightforward way, and also without the need to use from() to convert promise to observable:

const obs = defer(()=>fetch('http://jsonplaceholder.typicode.com/todos/1'))
setTimeout(()=>obs.subscribe((resp)=>console.log(resp)), 5000)


问:
TypeError: Cannot read property 'name' of undefined error in a controlled-component
I'm trying to get a date as user input through a controlled component but always running into this error "TypeError: Cannot read property 'name' of undefined". This is the piece of code that's causing the error. I'm using the react-datepicker module to get the Date input as when I try to use the HTML input type="date" i'm unable to disable previousdates.

```<code>import React, {Fragment,useState,useEffect} from 'react';
import {Link,withRouter} from 'react-router-dom';
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {addTask} from '../../actions/task';
import { addDays } from 'date-fns';

const TaskForm = ({addTask}) => {
    const [formData,setFormData] = useState({
        description:'',
        due_at:'',
        toBeReminded:''
    })

    const onSubmit = e => {
        e.preventDefault();
        addTask(formData);
    }

    const onChange = e=>setFormData({...formData, [e.target.name]:e.target.value})
    const {description,due_at} = formData;
    return (
        <Fragment>
            <h1 className="large text-primary">
                New Task
            </h1>
            <form className="form my-1" onSubmit={e=>onSubmit(e)}>
                <div className="form-group">
                    <label htmlFor="descr">Description:</label><br/>
                    <input type="text" id="descr" placeholder="Task Description" name="description" value={description} onChange={e=> onChange(e)}/>
                </div>
                <div className="form-group">
                    <label htmlFor="due_date">Due Date for Task:</label><br></br>
                    <DatePicker id="due_date" minDate={addDays(new Date(), 1)} id="due_date" name="due_at" value={due_at} onChange={e=> onChange(e)} />
                </div>
                <div className="form-group">
                    <label htmlFor="reminder">Set Reminder:</label><br></br>
                    <input type="radio" id="yes" name="toBeReminded"  value="true" onClick={e=> onChange(e)}/>
                    <label htmlFor="yes">Yes</label><br/>
                    <input type="radio" id="no" name="toBeReminded" value="false" onClick={e=> onChange(e)}/>
                    <label htmlFor="no">No</label><br></br>
                </div>
                <input type="submit" className="btn btn-dark my-1" value="Submit" />
                <Link className="btn btn-light my-1" to="/tasks">Go Back</Link>
            </form>
        </Fragment>
    )
}

TaskForm.propTypes = {
    addTask:PropTypes.func.isRequired
}

export default connect(null,{addTask})(TaskForm);
</code>```

答:
Looking at the docs for react-datepicker, it doesn't look like its onChange receives an event, but the date.

You should use a separate handler for the date change handler since they expect different signatures.

```<code>const onChange = e => setFormData({...formData, [e.target.name]:e.target.value})
const onDateChange = date => setFormData({...formData, due_at: date})
</code>```

There's a lot of other solutions that would work if you really want to stick to one change handler, but I recommend just creating two like above.

But.. you could do something like this (I don't really recommend this):

const onChange = e => {
  if (typeof e === 'object') {
    setFormData({...formData, [e.target.name]:e.target.value})
  } else {
    setFormData({...formData, due_at: e})
  }
}
```

<p>Or since you're declaring new inline functions already (its unnecessary by the way, just do <code>onChange={onChange}</code> unless you use the following approach) you could do this:</p>

<pre class="lang-js prettyprint-override"><code>const onChange = (name, value) => setFormData({...formData, [e.target.name]:e.target.value})

// Regular inputs
onChange={e => onChange('input name', e.target.value)}

// Date input
onChange={date => onChange('input name', date)}
</code>```

The bottom line is: you have to pay attention to what onChange is expected to receive. It will differ depending on the input type or the library implementation.

Body:
I'm trying to get a date as user input through a controlled component but always running into this error "TypeError: Cannot read property 'name' of undefined". This is the piece of code that's causing the error. I'm using the react-datepicker module to get the Date input as when I try to use the HTML input type="date" i'm unable to disable previousdates.

import React, {Fragment,useState,useEffect} from 'react';
import {Link,withRouter} from 'react-router-dom';
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {addTask} from '../../actions/task';
import { addDays } from 'date-fns';

const TaskForm = ({addTask}) => {
    const [formData,setFormData] = useState({
        description:'',
        due_at:'',
        toBeReminded:''
    })

    const onSubmit = e => {
        e.preventDefault();
        addTask(formData);
    }

    const onChange = e=>setFormData({...formData, [e.target.name]:e.target.value})
    const {description,due_at} = formData;
    return (
        <Fragment>

                New Task

            <form className="form my-1" onSubmit={e=>onSubmit(e)}>

                    Description:

                    <input type="text" id="descr" placeholder="Task Description" name="description" value={description} onChange={e=> onChange(e)}/>

                    Due Date for Task:

                    <DatePicker id="due_date" minDate={addDays(new Date(), 1)} id="due_date" name="due_at" value={due_at} onChange={e=> onChange(e)} />

                    Set Reminder:

                    <input type="radio" id="yes" name="toBeReminded"  value="true" onClick={e=> onChange(e)}/>
                    Yes

                    <input type="radio" id="no" name="toBeReminded" value="false" onClick={e=> onChange(e)}/>
                    No

                <input type="submit" className="btn btn-dark my-1" value="Submit" />
                <Link className="btn btn-light my-1" to="/tasks">Go Back</Link>
            </form>
        </Fragment>
    )
}

TaskForm.propTypes = {
    addTask:PropTypes.func.isRequired
}

export default connect(null,{addTask})(TaskForm);

Body:
Looking at the docs for react-datepicker, it doesn't look like its onChange receives an event, but the date.

You should use a separate handler for the date change handler since they expect different signatures.

const onChange = e => setFormData({...formData, [e.target.name]:e.target.value})
const onDateChange = date => setFormData({...formData, due_at: date})

There's a lot of other solutions that would work if you really want to stick to one change handler, but I recommend just creating two like above.

But.. you could do something like this (I don't really recommend this):

const onChange = e => {
  if (typeof e === 'object') {
    setFormData({...formData, [e.target.name]:e.target.value})
  } else {
    setFormData({...formData, due_at: e})
  }
}

Or since you're declaring new inline functions already (its unnecessary by the way, just do onChange={onChange} unless you use the following approach) you could do this:

const onChange = (name, value) => setFormData({...formData, [e.target.name]:e.target.value})

// Regular inputs
onChange={e => onChange('input name', e.target.value)}

// Date input
onChange={date => onChange('input name', date)}

The bottom line is: you have to pay attention to what onChange is expected to receive. It will differ depending on the input type or the library implementation.


问:
Scraping an ASPX session site with python requests, and a few redirects
I'm trying to scrape a site for an appliance that I own.  The appliance uploads its data to this site, and the site itself does not an offer an API, or any other programmatic way for me to access this data.

A successful looks like this (per browser inspection tool):

GET /Site/Login.

POST /Site/Login

302 to /Site/Index

302 to /Customer/Account

302 to /Customer/Account/email%40domain.tld

Here's the code that I have thus far:

```<code>#!/usr/bin/python3

import requests
import json

payload = {
    "Email" : email,
    "Password" : password,
    "Remember" : 'false'
}
headers = {
  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  'Accept-Encoding': 'gzip, deflate, br',
  'Accept-Language' : 'en-US,en;q=0.5',
  'Content-Type': 'application/x-www-form-urlencoded',
  'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0',
}

s = requests.Session()

s.get('https://www.wifi.ecowater.com/Site/Login')

# Add the RequestVerificationToken to the payloay.
RVT = requests.utils.dict_from_cookiejar(s.cookies)
payload['__RequestVerificationToken'] = RVT['__RequestVerificationToken']

r = s.post('https://www.wifi.ecowater.com/Site/Login', params=payload, headers=headers)

print(r.text)
</code>```

This code gets me an error page, almost like requests is not following all of the redirects.

Here are the curl commands for the 5 steps from above, per Firefox's browser inspection tool.

EDIT:  Tried posting the 5 curl commands, but stackoverflow flags this as a spam when I do so, and does not let me post.

答:
I almost had it in my original question, but after looking at the website a bit closer, I found a hidden form input with a second __RequestVerificationToken.

Essentially, I don't need to manually manage the __RequestVerificationToken cookie at all - requests.Session does that - but I do need to add the hidden __RequestVerificationToken to the form data payload.

We end up with two different tokens, both named __RequestVerificationToken.  One is sent from the server and is a cookie, the other is form data, which you need to manually find.

Here is my working code:

```<code>#!/usr/bin/python3

import requests
import re

# Regex to match the hidden input on the initial log in page
request_validation_re = re.compile(r'<input name="__RequestVerificationToken" type="hidden" value="(.*?)" />')

# The serial number of your ecowater device
dsn = { "dsn": "serial" }

# The initial form data
payload = {
    "Email" : "emailaddress",
    "Password" : "password",
    "Remember" : 'false'
}

# The headers needed for the JSON request
headers = {
    'Accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language' : 'en-US,en;q=0.5',
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0'
}

with requests.Session() as s:
    # Initial GET request
    g = s.get('https://www.wifi.ecowater.com/Site/Login')

    # Grab the token from the hidden input
    tokens = request_validation_re.findall(g.text)
    # Add the token to the form data payload
    payload['__RequestVerificationToken'] = tokens[0]

    # Log in to the site
    login = s.post('https://www.wifi.ecowater.com/Site/Login', data=payload)
    # Add the correct Referer header
    headers['Referer'] = login.url + '/' + dsn['dsn']

    # Query the JSON endpoint for the data that we actually want
    data = s.post('https://www.wifi.ecowater.com/Dashboard/UpdateFrequentData', data=dsn, headers=headers)
    print(data.json())
</code>```

Body:
I'm trying to scrape a site for an appliance that I own.  The appliance uploads its data to this site, and the site itself does not an offer an API, or any other programmatic way for me to access this data.

A successful looks like this (per browser inspection tool):

GET /Site/Login.

POST /Site/Login

302 to /Site/Index

302 to /Customer/Account

302 to /Customer/Account/email%40domain.tld

Here's the code that I have thus far:

#!/usr/bin/python3

import requests
import json

payload = {
    "Email" : email,
    "Password" : password,
    "Remember" : 'false'
}
headers = {
  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  'Accept-Encoding': 'gzip, deflate, br',
  'Accept-Language' : 'en-US,en;q=0.5',
  'Content-Type': 'application/x-www-form-urlencoded',
  'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0',
}

s = requests.Session()

s.get('https://www.wifi.ecowater.com/Site/Login')

# Add the RequestVerificationToken to the payloay.
RVT = requests.utils.dict_from_cookiejar(s.cookies)
payload['__RequestVerificationToken'] = RVT['__RequestVerificationToken']

r = s.post('https://www.wifi.ecowater.com/Site/Login', params=payload, headers=headers)

print(r.text)

This code gets me an error page, almost like requests is not following all of the redirects.

Here are the curl commands for the 5 steps from above, per Firefox's browser inspection tool.

EDIT:  Tried posting the 5 curl commands, but stackoverflow flags this as a spam when I do so, and does not let me post.

Body:
I almost had it in my original question, but after looking at the website a bit closer, I found a hidden form input with a second __RequestVerificationToken.

Essentially, I don't need to manually manage the __RequestVerificationToken cookie at all - requests.Session does that - but I do need to add the hidden __RequestVerificationToken to the form data payload.

We end up with two different tokens, both named __RequestVerificationToken.  One is sent from the server and is a cookie, the other is form data, which you need to manually find.

Here is my working code:

#!/usr/bin/python3

import requests
import re

# Regex to match the hidden input on the initial log in page
request_validation_re = re.compile(r'<input name="__RequestVerificationToken" type="hidden" value="(.*?)" />')

# The serial number of your ecowater device
dsn = { "dsn": "serial" }

# The initial form data
payload = {
    "Email" : "emailaddress",
    "Password" : "password",
    "Remember" : 'false'
}

# The headers needed for the JSON request
headers = {
    'Accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language' : 'en-US,en;q=0.5',
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0'
}

with requests.Session() as s:
    # Initial GET request
    g = s.get('https://www.wifi.ecowater.com/Site/Login')

    # Grab the token from the hidden input
    tokens = request_validation_re.findall(g.text)
    # Add the token to the form data payload
    payload['__RequestVerificationToken'] = tokens[0]

    # Log in to the site
    login = s.post('https://www.wifi.ecowater.com/Site/Login', data=payload)
    # Add the correct Referer header
    headers['Referer'] = login.url + '/' + dsn['dsn']

    # Query the JSON endpoint for the data that we actually want
    data = s.post('https://www.wifi.ecowater.com/Dashboard/UpdateFrequentData', data=dsn, headers=headers)
    print(data.json())


问:
Starting a web request when an nfc sticker is detected
Is there an app which calls a definable URL when a NFC sticker is detected? I want to put different stickers on my desk and when I place my phone on one of the stickers a specific URL should be call:

If StickerA is detectd call https://www.myserver.com/?val=a

If StickerB is detectd call https://www.myserver.com/?val=b

If StickerC is detectd call https://www.myserver.com/?val=c

etc.

Is this possible with android without activating the phone and is there a an existing app for that task?

答:
The Android OS itself has the ability to detect NFC and launch a web browser to open a URL on the NFC stickers/Tags (as long has the phone has NFC hardware and it is turned on)

The Sticker/Tag has to have the correctly formatted NDEF data written to it.

You can use https://play.google.com/store/apps/details?id=com.wakdev.wdnfc or other apps to write the correct data to the stickers/tags to store the URL correctly.

You can write your own App to do this as well but it does not require a "rooted device". But it does require then device to have the hardware and for it to be turned on.


问:
Using fetch method from componentDidMount again in different method
I have a method called fetchMovies that I use to get data from an API as soon as the component mounts. What I'm trying to accomplish is to have a Load More movies button that calls the function again if clicked to get more movies, 20 movies at a time. However, I get an error saying that the method is undefined when it's used inside the LoadMoreMovies method. What could be a good way to get around this?</p>

```<code>componentDidMount(){
        const fetchMovies = async endpoint => {

            const isLoadMore = endpoint.search('page');
            try{
                const result = await (await fetch(endpoint)).json();
                this.setState(prev => ({
                    ...prev,
                    movies: isLoadMore !== -1 ? [...prev.movies, ...result.results] : [...result.results],
                    heroImage: prev.heroImage || result.results[0],
                    currentPage: result.page,
                    totalPages: result.total_pages
                }));
            } catch(error){
                alert(error);
            }
        }
        console.log('...fetching');
        fetchMovies(POPULAR_BASE_URL);
        console.log('done fetching...');
    }

    loadMoreMovies = () => {
        const searchEndpoint = `${SEARCH_BASE_URL}${this.state.searchTerm}&page=${this.state.currentPage + 1}`;
        const popularEndpoint = `${POPULAR_BASE_URL}&page=${this.state.currentPage + 1}`;

        const endpoint = this.state.searchTerm ? searchEndpoint : popularEndpoint;

        fetchMovies(endpoint);
    }

    render(){
        const {heroImage, movies, searchTerm, currentPage, totalPages, loading} = this.state;
        console.log('rendered');
        return(
            <React.Fragment>
                {currentPage < totalPages && !loading && (
                    <LoadMoreBtn text="Load More" callback={this.loadMoreMovies}/>
                )}
            <React.Fragment/>
</code>```

答:
You defined your 'fetchMovies' function inside the 'componentDidMount', so outside from that scope the function would be surely undefined.
you need to define the fetchMovies inside the component but outside the componentDidMount for it to work</p>

Body:
I have a method called fetchMovies that I use to get data from an API as soon as the component mounts. What I'm trying to accomplish is to have a Load More movies button that calls the function again if clicked to get more movies, 20 movies at a time. However, I get an error saying that the method is undefined when it's used inside the LoadMoreMovies method. What could be a good way to get around this?

componentDidMount(){
        const fetchMovies = async endpoint => {

            const isLoadMore = endpoint.search('page');
            try{
                const result = await (await fetch(endpoint)).json();
                this.setState(prev => ({
                    ...prev,
                    movies: isLoadMore !== -1 ? [...prev.movies, ...result.results] : [...result.results],
                    heroImage: prev.heroImage || result.results[0],
                    currentPage: result.page,
                    totalPages: result.total_pages
                }));
            } catch(error){
                alert(error);
            }
        }
        console.log('...fetching');
        fetchMovies(POPULAR_BASE_URL);
        console.log('done fetching...');
    }

    loadMoreMovies = () => {
        const searchEndpoint = `${SEARCH_BASE_URL}${this.state.searchTerm}&page=${this.state.currentPage + 1}`;
        const popularEndpoint = `${POPULAR_BASE_URL}&page=${this.state.currentPage + 1}`;

        const endpoint = this.state.searchTerm ? searchEndpoint : popularEndpoint;

        fetchMovies(endpoint);
    }

    render(){
        const {heroImage, movies, searchTerm, currentPage, totalPages, loading} = this.state;
        console.log('rendered');
        return(
            <React.Fragment>
                {currentPage < totalPages && !loading && (
                    <LoadMoreBtn text="Load More" callback={this.loadMoreMovies}/>
                )}
            <React.Fragment/>


问:
Pandas DataFrame find closest index in previous rows where condition is met
I have the following df1 dataframe:

```<code>    t       A
0   23:00   2
1   23:01   1
2   23:02   2
3   23:03   2
4   23:04   6
5   23:05   5
6   23:06   4
7   23:07   9
8   23:08   7
9   23:09   10
10  23:10   8
</code>```

For each t (increments simplified here, not uniformly distributed in real life), I would like to find, if any, the most recent time tr within the previous 5 min where A(t)- A(tr) >= 4. I want to get:

```<code>    t       A    tr
0   23:00   2
1   23:01   1
2   23:02   2
3   23:03   2
4   23:04   6    23:03
5   23:05   5    23:01
6   23:06   4
7   23:07   9    23:06
8   23:08   7
9   23:09   10   23:06
10  23:10   8    23:06
</code>```

Currently, I can use shift(-1) to compare each row to the previous row like cond = df1['A'] >= df1['A'].shift(-1) + 4.

How can I look further in time?

Body:
I have the following df1 dataframe:

    t       A
0   23:00   2
1   23:01   1
2   23:02   2
3   23:03   2
4   23:04   6
5   23:05   5
6   23:06   4
7   23:07   9
8   23:08   7
9   23:09   10
10  23:10   8

For each t (increments simplified here, not uniformly distributed in real life), I would like to find, if any, the most recent time tr within the previous 5 min where A(t)- A(tr) >= 4. I want to get:

    t       A    tr
0   23:00   2
1   23:01   1
2   23:02   2
3   23:03   2
4   23:04   6    23:03
5   23:05   5    23:01
6   23:06   4
7   23:07   9    23:06
8   23:08   7
9   23:09   10   23:06
10  23:10   8    23:06

Currently, I can use shift(-1) to compare each row to the previous row like cond = df1['A'] >= df1['A'].shift(-1) + 4.

How can I look further in time?

Body:
I added a datetime index and used rolling(), which now includes time-window functionalities beyond simple index-window.

import pandas as pd
import numpy as np
import datetime

df1 = pd.DataFrame({'t' : [
        datetime.datetime(2020, 5, 17, 23, 0, 0),
        datetime.datetime(2020, 5, 17, 23, 0, 1),
        datetime.datetime(2020, 5, 17, 23, 0, 2),
        datetime.datetime(2020, 5, 17, 23, 0, 3),
        datetime.datetime(2020, 5, 17, 23, 0, 4),
        datetime.datetime(2020, 5, 17, 23, 0, 5),
        datetime.datetime(2020, 5, 17, 23, 0, 6),
        datetime.datetime(2020, 5, 17, 23, 0, 7),
        datetime.datetime(2020, 5, 17, 23, 0, 8),
        datetime.datetime(2020, 5, 17, 23, 0, 9),
        datetime.datetime(2020, 5, 17, 23, 0, 10)
        ], 'A' : [2,1,2,2,6,5,4,9,7,10,8]}, columns=['t', 'A'])
df1.index = df1['t']
df2 = df1
cond = df1['A'] >= df1.rolling('5s')['A'].apply(lambda x: x[0] + 4)
result = df1[cond]

Gives

t                         A
2020-05-17 23:00:04       6
2020-05-17 23:00:05       5
2020-05-17 23:00:07       9
2020-05-17 23:00:09      10
2020-05-17 23:00:10       8


问:
Apache Nifi custom processor and custom controller service packaging structure
I saw this example for Apache NiFi (https://medium.com/hashmapinc/creating-custom-processors-and-controllers-in-apache-nifi-e14148740ea) but still can't get my head around on how to implement packaging structure for custom processors and controller service.

My goal is to create a custom controller service to be used my multiple custom processors. How should my maven structure look like?

Should I create a nar for controller service?

Should I include controller service dependency in all my custom processors?

Should I be copying both the CS nar and CP nars to NiFi /lib directory?

Example:
Controller Service - CS1
Custom Processor 1 - CP1
Custom Processor 2 - CP2

I want CS1 to be used in both CP1 and CP2. If possible please share maven structure for this scenario and how it works. Thanks in Advance.

答:
The most flexible setup would be the one shown here:

https://github.com/bbende/nifi-dependency-example


问:
Appsync GraphQL api Authorization with oidc
I am using OIDC protocol for authentication in Appsync. For authorization/role management I am using a custom server which I am calling from an Appsync function. The problem here is, if I do the authorization part, all of the the resolvers should be turned into PIPELINE. In my opinion that's a bad design. I was wondering if there is any alternative way to implement this. Thanks in advance.

答:
AppSync supports OpenID Connect as an authorization mechanism, you don't need to validate the JWT token yourself in a function. Is there a use case for which you need to do that?

Also, what you described by using pipeline resolvers where the first function validates the authorization information is the current recommended way for doing this.


问:
Adding interface to get request
I am trying to add an interface to my code but am stuck with where and how to put it. Please see my code below.

Service.ts

```<code>getData() {
  return this.httpClient.get(Constants.API_ENDPOINT + 'data.json');
}
</code>```

Component.ts

```<code>ngOnInit() {
  this.apiService.getData().subscribe((res) => {
    console.log(res);
  });
}
</code>```

Interface.ts

```<code>export interface Items {
  name: string;
  description: string;
  url: string;
}
</code>```

How would I change the service.ts to use the interface?

答:
You can declare return type of Items type in your service:-

```<code>  getData(): Observable<Items>{
     return this.httpClient.get<Items>(Constants.API_ENDPOINT + 'data.json');
  }
</code>```

And in your component you can do this:-

```<code>  ngOnInit() {
  this.apiService.getData().subscribe((res: Items) => {
    console.log(res);
  });
}
</code>```

For more info see the documentation

Title: Adding interface to get request

Body:
I am trying to add an interface to my code but am stuck with where and how to put it. Please see my code below.

Service.ts

getData() {
  return this.httpClient.get(Constants.API_ENDPOINT + 'data.json');
}

Component.ts

ngOnInit() {
  this.apiService.getData().subscribe((res) => {
    console.log(res);
  });
}

Interface.ts

export interface Items {
  name: string;
  description: string;
  url: string;
}

How would I change the service.ts to use the interface?

Body:
You can declare return type of Items type in your service:-

  getData(): Observable<Items>{
     return this.httpClient.get<Items>(Constants.API_ENDPOINT + 'data.json');
  }

And in your component you can do this:-

  ngOnInit() {
  this.apiService.getData().subscribe((res: Items) => {
    console.log(res);
  });
}

For more info see the documentation


问:
How to make your own scrollable Column like this?
I'm new in flutter and I'm doing an app from dribble, do not know how to do this kinda scrolling
https://cdn.dribbble.com/users/1837506/videos/32005/influenza_small.mp4

Please, can u show me how to make or share some links :)

答:
Try using a PageView with vertical axis.

Take a look at this video


问:
Should I return an array or a collection from a function?
What's the preferred container type when returning multiple objects of the same type from a function?

Is it against good practice to return a simple array (like MyType[]), or should you wrap it in some generic container (like ICollection<MyType>)?

Thanks!

答:
Use generics.  It's easier to interoperate with other collections classes and the type system is more able to help you with potential errors.

The old style of returning an array was a crutch before generics.

OwnerDisplayName: Pwninstein

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jason Cohen


问:
url rewrite question
i want to rewrite the url from the parameter name to directory name:

```<code>mydomaindotcom/index.php?op=fceebook_aa =>
mydomaindotcom/fceebook_aa/
</code>```

here is my testing code(not working of course):

```<code>Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\\$ index.php?op=$1
</code>```

anyone can help? thanks

答:
```<code>RewriteEngine on
RewriteRule ^(.*)\/$ index.php?op=$1
</code>```

ContentLicense: CC BY-SA 3.0

Title: url rewrite question

Body:
i want to rewrite the url from the parameter name to directory name:

mydomaindotcom/index.php?op=fceebook_aa =>
mydomaindotcom/fceebook_aa/

here is my testing code(not working of course):

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\\$ index.php?op=$1

anyone can help? thanks


问:
how to create SSLEngine for connecting to any https website specifically google cloud run?
Since all the certs from websites are signed by Root CA's and such, and I am writing a client, not a server, how would I create an SSLEngine that can connect to them all?  or do I have to download certs and such to connect?  (I am hoping that jdk has all the same info as the browsers regarding certs and such so doing this should be easy although I am having trouble with my google skills in finding it since most links are servers).

EDIT: For more clarity, I have client code like so that works with a self-signed cert.  Currently, I downloaded the cert from the website I wanted through chrome clicking on the lock.  I then imported that into my keystore but it's still not working...

```<code>private SSLEngine createEngine() {
    try {

        InputStream in = this.getClass().getResourceAsStream("/prodKeyStore.jks");

        //char[] passphrase = password.toCharArray();
        // First initialize the key and trust material.
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(in, "lP9Ow1uYXZr9zgt6".toCharArray());
        SSLContext sslContext = SSLContext.getInstance("TLS");

        //****************Client side specific*********************
        // TrustManager's decide whether to allow connections.
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ks);
        sslContext.init(null, tmf.getTrustManagers(), null);
        //****************Client side specific*********************

        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(true);
        return engine;
    } catch(Exception e) {
        throw new RuntimeException("Could not create SSLEngine", e);
    }
}
</code>```

Next, I am going to try to figure out how to turn debug on for ssl exchange and see if that helps any.  Currently, I am at a loss as to why this is not working.

OUCH, debug logs point to this

```<code>javax.net.ssl|DEBUG|21|httpclient2|2020-02-18 08:13:05.095 MST|CertificateMessage.java:358|Consuming server Certificate handshake message (
"Certificates": [
  "certificate" : {
   "version"            : "v3",
   "serial number"      : "00 90 76 89 18 E9 33 93 A0",
   "signature algorithm": "SHA256withRSA",
   "issuer"             : "CN=invalid2.invalid, OU="No SNI provided; please fix your client."",
   "not before"         : "2014-12-31 17:00:00.000 MST",
   "not  after"         : "2029-12-31 17:00:00.000 MST",
   "subject"            : "CN=invalid2.invalid, OU="No SNI provided; please fix your client."",
   "subject public key" : "RSA",
   "extensions"         : [
</code>```

so something is screwing things up bigtime but not sure what yet.  This is jdk8.  Not sure how to fix this yet.

thanks,
Dean

答:
It turned out there is one line wrong and it has to be this

```<code>SSLEngine engine = sslContext.createSSLEngine(host, port);
</code>```

and then it all works!

Body:
Since all the certs from websites are signed by Root CA's and such, and I am writing a client, not a server, how would I create an SSLEngine that can connect to them all?  or do I have to download certs and such to connect?  (I am hoping that jdk has all the same info as the browsers regarding certs and such so doing this should be easy although I am having trouble with my google skills in finding it since most links are servers).

EDIT: For more clarity, I have client code like so that works with a self-signed cert.  Currently, I downloaded the cert from the website I wanted through chrome clicking on the lock.  I then imported that into my keystore but it's still not working...

private SSLEngine createEngine() {
    try {

        InputStream in = this.getClass().getResourceAsStream("/prodKeyStore.jks");

        //char[] passphrase = password.toCharArray();
        // First initialize the key and trust material.
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(in, "lP9Ow1uYXZr9zgt6".toCharArray());
        SSLContext sslContext = SSLContext.getInstance("TLS");

        //****************Client side specific*********************
        // TrustManager's decide whether to allow connections.
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ks);
        sslContext.init(null, tmf.getTrustManagers(), null);
        //****************Client side specific*********************

        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(true);
        return engine;
    } catch(Exception e) {
        throw new RuntimeException("Could not create SSLEngine", e);
    }
}

Next, I am going to try to figure out how to turn debug on for ssl exchange and see if that helps any.  Currently, I am at a loss as to why this is not working.

OUCH, debug logs point to this

javax.net.ssl|DEBUG|21|httpclient2|2020-02-18 08:13:05.095 MST|CertificateMessage.java:358|Consuming server Certificate handshake message (
"Certificates": [
  "certificate" : {
   "version"            : "v3",
   "serial number"      : "00 90 76 89 18 E9 33 93 A0",
   "signature algorithm": "SHA256withRSA",
   "issuer"             : "CN=invalid2.invalid, OU="No SNI provided; please fix your client."",
   "not before"         : "2014-12-31 17:00:00.000 MST",
   "not  after"         : "2029-12-31 17:00:00.000 MST",
   "subject"            : "CN=invalid2.invalid, OU="No SNI provided; please fix your client."",
   "subject public key" : "RSA",
   "extensions"         : [

so something is screwing things up bigtime but not sure what yet.  This is jdk8.  Not sure how to fix this yet.

thanks,
Dean

Body:
It turned out there is one line wrong and it has to be this

SSLEngine engine = sslContext.createSSLEngine(host, port);

and then it all works!


问:
Join lookup table on lowest-level/most detailed field value first
I have two tables that I am trying to left join based on a single field in SQL Server 2014, but the problem is that this single field contains a value which relates to one of four "levels" that appear in separate columns in the main table. The SalesOrg field is also part of the key since there can be more than one sales org in both the transactional and lookup tables.

Here's the main transactional table:

```<code>SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty
-----------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20
AB1          Z000        Y000        X000        V001        30
AB1          Z001        Y000        X001        V001        10
AB1          Z001        Y001        X000        V003        45
AB1          Z001        Y001        X000        V004        48
AB1          Z002        Y003        X002        V005        67
</code>```

Here's the lookup table I'm trying to join onto the transactional table:

```<code>SalesOrg     PH              PHLevel      SalesRep
--------------------------------------------------
AB1          <null>          0            Mr. Pink
AB1          Z000            1            Mr. White
AB1          Z001            1            Mr. White
AB1          Z001Y000        2            Mr. Orange
AB1          Z001Y001        2            Mr. Orange
AB1          Z001Y001X000    3            Mr. Blonde
</code>```

So what should happen is that the "lowest" (i.e. highest PHLevel, 3) should be matched first, i.e.:

```<code>SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20
AB1          Z000        Y000        X000        V001        30
AB1          Z001        Y000        X001        V001        10
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67
</code>```

Then we need to match level 2 that hasn't already been matched using level 3:

```<code>SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20
AB1          Z000        Y000        X000        V001        30
AB1          Z001        Y000        X001        V001        10          Mr. Orange
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67
</code>```

Then we need to match level 1 that hasn't already been matched using level 2 or 3:

```<code>SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20          Mr. White
AB1          Z000        Y000        X000        V001        30          Mr. White
AB1          Z001        Y000        X001        V001        10          Mr. Orange
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67
</code>```

Finally, for any remaining items, we need to check level 0, which is the default for "unmatched" entries:

```<code>SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20          Mr. White
AB1          Z000        Y000        X000        V001        30          Mr. White
AB1          Z001        Y000        X001        V001        10          Mr. Orange
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67          Mr. Pink
</code>```

It is no problem if a concatenated field is created in the transactional table to make it easier to match the lookup table.

I am not sure if it would be advantageous to expand the lookup table so that the PH field contains "fully-qualified" values (i.e. so that PH always contains PHLevel1/PHLevel2/PHLevel3/PHLevel4 values, e.g. Z001Y000X001V001) but this could then make the lookup table huge and then possibly slow down the join (since the transactional table can contain perhaps a million rows).

I am not sure how to start with this, since I've seen other examples with hierarchies, but the lookup table is not exactly a hierarchy - are there any elegant solutions in SQL please?

答:
I get a little anxious when I see code like this, but in your situation, it seems to reflect the real requirements, assuming you aren't able to change the underlying structure of your tables:

```<code>select      t.*,
            SalesRep = coalesce(l4.SalesRep, l3.SalesRep, l2.SalesRep, l1.SalesRep, l0.SalesRep)
from        @transactionals t
left join   @lookup l4 on t.SalesOrg = l4.SalesOrg and l4.PH = t.PHLevel1 + t.PHLevel2 + t.PHLevel3 + t.PHLevel4
left join   @lookup l3 on t.SalesOrg = l3.SalesOrg and l3.PH = t.PHLevel1 + t.PHLevel2 + t.PHLevel3
left join   @lookup l2 on t.SalesOrg = l2.SalesOrg and l2.PH = t.PHLevel1 + t.PHLevel2
left join   @lookup l1 on t.SalesOrg = l1.SalesOrg and l1.PH = t.PHLevel1
left join   @lookup l0 on t.SalesOrg = l0.SalesOrg and l0.PH is null
</code>```

After a little more consideration, I think another strategy will work.  As you suspected, you can concatenate the levels in the transactionals table.  Then you can match based on a like statement.  Of course, that will get you too many matches, so you use a windowed function to find the maximum phLevel between matches.  And then query where the phLevel equals the max.

```<code>with

    leadMatches as (

        select      t.*,
                    l.SalesRep,
                    l.PHLevel,
                    maxPhLevel = max(l.phLevel) over (partition by ap.ph)
        from        @transactionals t
        cross apply (select PH = PHLevel1 + PHLevel2 + PHLevel3 + PHLevel4) ap
        join        @lookup l on t.SalesOrg = l.SalesOrg and ap.ph like isnull(l.ph,'') + '%'

    )

    select      m.SalesOrg, m.PHLevel1, m.PHLevel2, m.PHLevel3, m.PHLevel4,
                m.SalesQty, m.SalesRep
    from        leadMatches m
    where       PHLevel = maxPhLevel
</code>```

Body:
I have two tables that I am trying to left join based on a single field in SQL Server 2014, but the problem is that this single field contains a value which relates to one of four "levels" that appear in separate columns in the main table. The SalesOrg field is also part of the key since there can be more than one sales org in both the transactional and lookup tables.

Here's the main transactional table:

SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty
-----------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20
AB1          Z000        Y000        X000        V001        30
AB1          Z001        Y000        X001        V001        10
AB1          Z001        Y001        X000        V003        45
AB1          Z001        Y001        X000        V004        48
AB1          Z002        Y003        X002        V005        67

Here's the lookup table I'm trying to join onto the transactional table:

SalesOrg     PH              PHLevel      SalesRep
--------------------------------------------------
AB1          <null>          0            Mr. Pink
AB1          Z000            1            Mr. White
AB1          Z001            1            Mr. White
AB1          Z001Y000        2            Mr. Orange
AB1          Z001Y001        2            Mr. Orange
AB1          Z001Y001X000    3            Mr. Blonde

So what should happen is that the "lowest" (i.e. highest PHLevel, 3) should be matched first, i.e.:

SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20
AB1          Z000        Y000        X000        V001        30
AB1          Z001        Y000        X001        V001        10
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67

Then we need to match level 2 that hasn't already been matched using level 3:

SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20
AB1          Z000        Y000        X000        V001        30
AB1          Z001        Y000        X001        V001        10          Mr. Orange
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67

Then we need to match level 1 that hasn't already been matched using level 2 or 3:

SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20          Mr. White
AB1          Z000        Y000        X000        V001        30          Mr. White
AB1          Z001        Y000        X001        V001        10          Mr. Orange
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67

Finally, for any remaining items, we need to check level 0, which is the default for "unmatched" entries:

SalesOrg     PHLevel1    PHLevel2    PHLevel3    PHLevel4    SalesQty    SalesRep
---------------------------------------------------------------------------------
AB1          Z000        Y000        X000        V000        20          Mr. White
AB1          Z000        Y000        X000        V001        30          Mr. White
AB1          Z001        Y000        X001        V001        10          Mr. Orange
AB1          Z001        Y001        X000        V003        45          Mr. Blonde
AB1          Z001        Y001        X000        V004        48          Mr. Blonde
AB1          Z002        Y003        X002        V005        67          Mr. Pink

It is no problem if a concatenated field is created in the transactional table to make it easier to match the lookup table.

I am not sure if it would be advantageous to expand the lookup table so that the PH field contains "fully-qualified" values (i.e. so that PH always contains PHLevel1/PHLevel2/PHLevel3/PHLevel4 values, e.g. Z001Y000X001V001) but this could then make the lookup table huge and then possibly slow down the join (since the transactional table can contain perhaps a million rows).

I am not sure how to start with this, since I've seen other examples with hierarchies, but the lookup table is not exactly a hierarchy - are there any elegant solutions in SQL please?

Body:
I get a little anxious when I see code like this, but in your situation, it seems to reflect the real requirements, assuming you aren't able to change the underlying structure of your tables:

select      t.*,
            SalesRep = coalesce(l4.SalesRep, l3.SalesRep, l2.SalesRep, l1.SalesRep, l0.SalesRep)
from        @transactionals t
left join   @lookup l4 on t.SalesOrg = l4.SalesOrg and l4.PH = t.PHLevel1 + t.PHLevel2 + t.PHLevel3 + t.PHLevel4
left join   @lookup l3 on t.SalesOrg = l3.SalesOrg and l3.PH = t.PHLevel1 + t.PHLevel2 + t.PHLevel3
left join   @lookup l2 on t.SalesOrg = l2.SalesOrg and l2.PH = t.PHLevel1 + t.PHLevel2
left join   @lookup l1 on t.SalesOrg = l1.SalesOrg and l1.PH = t.PHLevel1
left join   @lookup l0 on t.SalesOrg = l0.SalesOrg and l0.PH is null

After a little more consideration, I think another strategy will work.  As you suspected, you can concatenate the levels in the transactionals table.  Then you can match based on a like statement.  Of course, that will get you too many matches, so you use a windowed function to find the maximum phLevel between matches.  And then query where the phLevel equals the max.

with

    leadMatches as (

        select      t.*,
                    l.SalesRep,
                    l.PHLevel,
                    maxPhLevel = max(l.phLevel) over (partition by ap.ph)
        from        @transactionals t
        cross apply (select PH = PHLevel1 + PHLevel2 + PHLevel3 + PHLevel4) ap
        join        @lookup l on t.SalesOrg = l.SalesOrg and ap.ph like isnull(l.ph,'') + '%'

    )

    select      m.SalesOrg, m.PHLevel1, m.PHLevel2, m.PHLevel3, m.PHLevel4,
                m.SalesQty, m.SalesRep
    from        leadMatches m
    where       PHLevel = maxPhLevel


问:
Redirect whit SweetAlert2
i have a problem with redirect page after the user click on ok button in sweet alert. i don't understand where i have to insert the code and which code. i would like that when the user press ok, after the success on form, is redirected to... example "google.com".

I tried to use the solutions on the site, but they did not work or I was wrong to insert them
Thanks to all for help

```

答:
I think it must be placed before the success code, something like this:</p>

```<code><script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<script>
    $(function() {
        $(document).ajaxStop($.unblockUI);
        $('form').on('submit', function(e) {
            e.preventDefault();
            var response = grecaptcha.getResponse();
            if(response.length == 0) {
                //reCaptcha not verified
                alert("Verifica di non essere un robot!");
                return false;
            } else {
                //reCaptch verified
                $.blockUI({
                    message: '<p><img src="img/Eclipse-1s-134px.svg" alt="">Ci siamo...non uscire</p>'
                });
                var formData = new FormData(this);

                $.ajax({
                    type: 'post',
                    url: 'mailer.php',
                    data: formData,
                    cache: false,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    mimeType: "multipart/form-data",
                    xhr: function () {
                        //upload Progress
                        var xhr = $.ajaxSettings.xhr();
                        if (xhr.upload) {
                            xhr.upload.addEventListener('progress', function (event) {
                                var percent = 0;
                                var position = event.loaded || event.position;
                                var total = event.total;
                                if (event.lengthComputable) {
                                    percent = Math.ceil(position / total * 100);
                                }
                                //update progressbar
                                $('.progress-bar').animate({
                                    width: percent + '%'
                                }, {
                                    duration: 100
                                });
                            }, true);
                        }
                        return xhr;
                    },
                    success: function (response) {
                        if (response.success) {
                                Swal.fire(
                                   'Perfetto!',
                                   'Il tuo locale è registrato!',
                                   'success'
                                 );
                            $('form').trigger("reset");
                            $('.progress-bar').animate({
                                width: '10%'
                            }, {
                                duration: 1000
                            });

                            window.location.href = 'www.yourpage.com';

                        } else {
                            alert(response.message);
                        }
                    },
                    error: function (response) {
                                        Swal.fire({
                         icon: 'error',
                         title: 'Oops...',
                         text: 'Qualcosa è andato storto!',
                         footer: '<a href>Riprovaci!</a>'
                        });
                    }
                });
            }
        });
    });
</script>
</code>```

Title: Redirect whit SweetAlert2

Body:
I think it must be placed before the success code, something like this:

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<script>
    $(function() {
        $(document).ajaxStop($.unblockUI);
        $('form').on('submit', function(e) {
            e.preventDefault();
            var response = grecaptcha.getResponse();
            if(response.length == 0) {
                //reCaptcha not verified
                alert("Verifica di non essere un robot!");
                return false;
            } else {
                //reCaptch verified
                $.blockUI({
                    message: '<p><img src="img/Eclipse-1s-134px.svg" alt="">Ci siamo...non uscire</p>'
                });
                var formData = new FormData(this);

                $.ajax({
                    type: 'post',
                    url: 'mailer.php',
                    data: formData,
                    cache: false,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    mimeType: "multipart/form-data",
                    xhr: function () {
                        //upload Progress
                        var xhr = $.ajaxSettings.xhr();
                        if (xhr.upload) {
                            xhr.upload.addEventListener('progress', function (event) {
                                var percent = 0;
                                var position = event.loaded || event.position;
                                var total = event.total;
                                if (event.lengthComputable) {
                                    percent = Math.ceil(position / total * 100);
                                }
                                //update progressbar
                                $('.progress-bar').animate({
                                    width: percent + '%'
                                }, {
                                    duration: 100
                                });
                            }, true);
                        }
                        return xhr;
                    },
                    success: function (response) {
                        if (response.success) {
                                Swal.fire(
                                   'Perfetto!',
                                   'Il tuo locale è registrato!',
                                   'success'
                                 );
                            $('form').trigger("reset");
                            $('.progress-bar').animate({
                                width: '10%'
                            }, {
                                duration: 1000
                            });

                            window.location.href = 'www.yourpage.com';

                        } else {
                            alert(response.message);
                        }
                    },
                    error: function (response) {
                                        Swal.fire({
                         icon: 'error',
                         title: 'Oops...',
                         text: 'Qualcosa è andato storto!',
                         footer: '<a href>Riprovaci!</a>'
                        });
                    }
                });
            }
        });
    });
</script>


问:
Replace null values in query with a previous value
I'm creating a query through SSMS, working on SQL Server 2012.

Part of my query is to find the supervisor for the associates.  My issue is that for the table containing supervisor names it doesn't make a new daily record.  Because there is no record for that day my query shows up as NULL for supervisor.

How can I fill these NULL values with the last Supervisor they reported to in the table?

Supervisor Table

```<code>MeasureDate    Associate            Supervisor
2019-09-02     Goodman, Michelle    Moody, Robin
2019-09-01     Goodman, Michelle    Moody, Robin
2019-08-20     Goodman, Michelle    Henry, Jack
2019-08-19     Goodman, Michelle    Henry, Jack
</code>```

Current Query Output

```<code>Date        Supervisor     Associate
2019-09-01  Moody, Robin   Goodman, Michelle
2019-08-21  NULL           Goodman, Michelle
2019-08-20  Henry, Jack    Goodman, Michelle
</code>```

Improved Query Output

```<code>Date        Supervisor     Associate
2019-09-01  Moody, Robin   Goodman, Michelle
2019-08-21  Henry, Jack    Goodman, Michelle
2019-08-20  Henry, Jack    Goodman, Michelle
</code>```

Current Query

```<code>SELECT
z.Date,
z.Supervisor,
z.Associate,
CAST('XXX' AS char) AS [Group],
z.Task,
Sum(z.Minutes) as Minutes,
Sum(z.Count) as Cases

FROM
(
SELECT
a.DS_LOAD_DT AS Date,
c.CASE_TASK_TYPE_NM AS Task,
b.AssociateName AS Associate,
d.Supervisor,
(CONVERT(decimal,a.DURATIONSEC)/60) AS Minutes,
COUNT(*) AS Count

FROM DW_RawData_XXXDetail a
LEFT JOIN DW_Dim_AssociateMapping b ON a.XXX_EMP_ID = b.XXX_ID AND a.DS_LOAD_DT = b.ScheduleDate
LEFT JOIN DW_Dim_XXX_Case_Types c ON left(a.MSG_TYPE_CD, patindex('%[0-9][^0-9]%', a.MSG_TYPE_CD)) =
c.CASE_TASK_TYPE_ID
LEFT JOIN OperationScoreCard_Daily_Associates d ON b.AssociateName = d.Associate AND b.ScheduleDate =
d.MeasureDate

WHERE b.MUID = '400'
AND a.DS_LOAD_DT >= '2019-08-01'

GROUP BY
a.DS_LOAD_DT,
c.CASE_TASK_TYPE_NM,
b.AssociateName,
d.Supervisor,
(CONVERT(decimal,a.DURATIONSEC)/60)
) z

GROUP BY
z.Date,
z.Task,
z.Associate,
z.Supervisor
</code>```

答:
```<code>select top 1 '2019-08-01' as Date, Supervisor, Associate
from DW_RawData_XXXDetail --plus any joins you need
where Date <= '2019-08-01'
group by MAX(Date), Supervisor, Associate
</code>```

The group by gives you the most recent date for each Supervisor/Associate combo, so you can just compare that to whatever target date you need. Ideally replace the hardcoded date with a variable.

Body:
I'm creating a query through SSMS, working on SQL Server 2012.

Part of my query is to find the supervisor for the associates.  My issue is that for the table containing supervisor names it doesn't make a new daily record.  Because there is no record for that day my query shows up as NULL for supervisor.

How can I fill these NULL values with the last Supervisor they reported to in the table?

Supervisor Table

MeasureDate    Associate            Supervisor
2019-09-02     Goodman, Michelle    Moody, Robin
2019-09-01     Goodman, Michelle    Moody, Robin
2019-08-20     Goodman, Michelle    Henry, Jack
2019-08-19     Goodman, Michelle    Henry, Jack

Current Query Output

Date        Supervisor     Associate
2019-09-01  Moody, Robin   Goodman, Michelle
2019-08-21  NULL           Goodman, Michelle
2019-08-20  Henry, Jack    Goodman, Michelle

Improved Query Output

Date        Supervisor     Associate
2019-09-01  Moody, Robin   Goodman, Michelle
2019-08-21  Henry, Jack    Goodman, Michelle
2019-08-20  Henry, Jack    Goodman, Michelle

Current Query

SELECT
z.Date,
z.Supervisor,
z.Associate,
CAST('XXX' AS char) AS [Group],
z.Task,
Sum(z.Minutes) as Minutes,
Sum(z.Count) as Cases

FROM
(
SELECT
a.DS_LOAD_DT AS Date,
c.CASE_TASK_TYPE_NM AS Task,
b.AssociateName AS Associate,
d.Supervisor,
(CONVERT(decimal,a.DURATIONSEC)/60) AS Minutes,
COUNT(*) AS Count

FROM DW_RawData_XXXDetail a
LEFT JOIN DW_Dim_AssociateMapping b ON a.XXX_EMP_ID = b.XXX_ID AND a.DS_LOAD_DT = b.ScheduleDate
LEFT JOIN DW_Dim_XXX_Case_Types c ON left(a.MSG_TYPE_CD, patindex('%[0-9][^0-9]%', a.MSG_TYPE_CD)) =
c.CASE_TASK_TYPE_ID
LEFT JOIN OperationScoreCard_Daily_Associates d ON b.AssociateName = d.Associate AND b.ScheduleDate =
d.MeasureDate

WHERE b.MUID = '400'
AND a.DS_LOAD_DT >= '2019-08-01'

GROUP BY
a.DS_LOAD_DT,
c.CASE_TASK_TYPE_NM,
b.AssociateName,
d.Supervisor,
(CONVERT(decimal,a.DURATIONSEC)/60)
) z

GROUP BY
z.Date,
z.Task,
z.Associate,
z.Supervisor

Body:
select top 1 '2019-08-01' as Date, Supervisor, Associate
from DW_RawData_XXXDetail --plus any joins you need
where Date <= '2019-08-01'
group by MAX(Date), Supervisor, Associate

The group by gives you the most recent date for each Supervisor/Associate combo, so you can just compare that to whatever target date you need. Ideally replace the hardcoded date with a variable.


问:
Unable to figure out 504 error in NodeJS running on NGINX Web Server on AWS
When I'm making POST requests to 3rd party APIs like Facebook, Google etc in a sequence, I'm getting 504 error randomly. I'm unable to pinpoint an exact scenario that is causing the error.

Here is how I'm making the POST request:

```<code> var options = { uri: uri,
                 headers: {
                   "Content-Type": "application/json",
                 },
                 strictSSL: true,
                 json: obj
               };

 request.post(options, function(err, response) {

 });
</code>```

Here is my NGINX config file:

```<code>user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
 worker_connections  1024;
}

http {

  client_max_body_size 100M;
  include       /etc/nginx/mime.types;
  default_type  application/octet-stream;

  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

  access_log  /var/log/nginx/access.log  main;

  sendfile        on;

  keepalive_timeout  65;

  include /etc/nginx/conf.d/*.conf;
  include /etc/nginx/sites-enabled/*;

}
</code>```

I'm running my app on 2 EC2 Instances in AWS with a load balancer attached to it.

What could be the issue here?

答:
I believe you're missing a server block inside the http block. And it wouldn't hurt to have location blocks to redirect the client to more finely tuned routes rather than just the root</p>

```<code>server {
  listen 80;
  listen [::]:80;

  root /home/ubuntu/public_html;

  server_name example-one.com www.example-one.com;

  location /application1 {
      proxy_pass http://localhost:8080/sampleApp;
  }

  location /images {
      root /home/ubuntu/data;
  }
}
</code>```

Body:
When I'm making POST requests to 3rd party APIs like Facebook, Google etc in a sequence, I'm getting 504 error randomly. I'm unable to pinpoint an exact scenario that is causing the error.

Here is how I'm making the POST request:

 var options = { uri: uri,
                 headers: {
                   "Content-Type": "application/json",
                 },
                 strictSSL: true,
                 json: obj
               };

 request.post(options, function(err, response) {

 });

Here is my NGINX config file:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
 worker_connections  1024;
}

http {

  client_max_body_size 100M;
  include       /etc/nginx/mime.types;
  default_type  application/octet-stream;

  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

  access_log  /var/log/nginx/access.log  main;

  sendfile        on;

  keepalive_timeout  65;

  include /etc/nginx/conf.d/*.conf;
  include /etc/nginx/sites-enabled/*;

}

I'm running my app on 2 EC2 Instances in AWS with a load balancer attached to it.

What could be the issue here?

Body:
I believe you're missing a server block inside the http block. And it wouldn't hurt to have location blocks to redirect the client to more finely tuned routes rather than just the root

server {
  listen 80;
  listen [::]:80;

  root /home/ubuntu/public_html;

  server_name example-one.com www.example-one.com;

  location /application1 {
      proxy_pass http://localhost:8080/sampleApp;
  }

  location /images {
      root /home/ubuntu/data;
  }
}


问:
No web browser found: could not locate runnable browser. Jupyter-notebook
Jupyter-notebook doesn't open a web browser. It worked just fine before, then after windows 10 prompted for an update it began to open in Microsoft edge. When I tried to change it to the default browser which is chrome now it won't open at all.

I followed how to open Jupyter notebook in chrome on windows to try and change it back to chrome.

When I try and run

```<code>jupyter notebook
</code>```

in cmd all I get is

```<code>[I 21:39:08.015 NotebookApp] JupyterLab extension loaded from C:\Users\roy\Anaconda3\lib\site-packages\jupyterlab
[I 21:39:08.015 NotebookApp] JupyterLab application directory is C:\Users\roy\Anaconda3\share\jupyter\lab
[I 21:39:08.015 NotebookApp] Serving notebooks from local directory: C:\Users\roy
[I 21:39:08.015 NotebookApp] The Jupyter Notebook is running at:
[I 21:39:08.015 NotebookApp] http://localhost:8888/?token=d0a958999d7e59da3f097809882e8f40eb5845e3a07cebe8
[I 21:39:08.031 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[W 21:39:08.109 NotebookApp] No web browser found: could not locate runnable browser.

    To access the notebook, open this file in a browser:
        file:///C:/Users/roy/AppData/Roaming/jupyter/runtime/nbserver-1516-open.html
    Or copy and paste one of these URLs:
        http://localhost:8888/?token=d0a958999d7e59da3f097809882e8f40eb5845e3a07cebe8
</code>```

However when I copy and paste the url in a web browser it just works fine.

答: This solved my similar issue when jupyter is installed under my python 2.7 directory, but is not necessary under the jupyter installed in my python 3.7 directory. Readers with a 3.7 directory may be encountering a different issue.</p>

Body:
Jupyter-notebook doesn't open a web browser. It worked just fine before, then after windows 10 prompted for an update it began to open in Microsoft edge. When I tried to change it to the default browser which is chrome now it won't open at all.

I followed how to open Jupyter notebook in chrome on windows to try and change it back to chrome.

When I try and run

jupyter notebook

in cmd all I get is

[I 21:39:08.015 NotebookApp] JupyterLab extension loaded from C:\Users\roy\Anaconda3\lib\site-packages\jupyterlab
[I 21:39:08.015 NotebookApp] JupyterLab application directory is C:\Users\roy\Anaconda3\share\jupyter\lab
[I 21:39:08.015 NotebookApp] Serving notebooks from local directory: C:\Users\roy
[I 21:39:08.015 NotebookApp] The Jupyter Notebook is running at:
[I 21:39:08.015 NotebookApp] http://localhost:8888/?token=d0a958999d7e59da3f097809882e8f40eb5845e3a07cebe8
[I 21:39:08.031 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[W 21:39:08.109 NotebookApp] No web browser found: could not locate runnable browser.

    To access the notebook, open this file in a browser:
        file:///C:/Users/roy/AppData/Roaming/jupyter/runtime/nbserver-1516-open.html
    Or copy and paste one of these URLs:
        http://localhost:8888/?token=d0a958999d7e59da3f097809882e8f40eb5845e3a07cebe8

However when I copy and paste the url in a web browser it just works fine.


问:
MySQL writing efficient procedures for geometry queries
This is a question regarding efficiency because what I want to write is likely to break my machine.

Brief description. I have two sets of data,

Set1 contains ~2500 entries, each entry has a polygon associated.

Set2 contains ~4000 entries, each entry has a point associated.

I want to find out which polygons from set1 enclose which points from set2. All points and polygons are unique and do not overlap.

I was about to embark on writing a procedure using a nested cursor that will look at a point in set2 scroll through all of set1 and find a polygon that encloses the point.

Then I realized how much data I have, that I will want to run it more than once, and this may take quite a while. Is there a better way?

答:
MySQL for Geometry - Fine.

Does not seem to be a lengthy process.

You may or may not have nested cursor.

You can pretty well create a linked view having each point from set2 along with all poygons enclosing the point.

And that view can be called from your code for selection list, etc (replacing your expected cursor). Once the view is defined, MySQL will be almost ready with the output always.


问:
What is the Ideal way to return data from function without leaking memory?
In IPhone Development ObjC , I wonder what is the right approach for functions to return some values in Dictionaries or Arrays. I mean should they return autorelease objects, but wouldn't it be bad if I am using too many functions to return values, like getUserRecordsFromDB() function will return all the user records, so should they return me autorelease objects? also when I am calling them multiple times, suppose with a span of 4 seconds to get the newely updated data. Can somebody let me an ideal scanario of how to get data from a function called frequently in the flow of program, and not leaking the memory.</p>

答:
You can always pass a mutable object to be filled in.

```<code>-(void) getMoreUsers:(NSMutableArray *)ioArray {
  for ( ... ) {
    NSMutableDictionary *user = [NSMutableDictionary new];
    // fill in user ...
    [ioArray addObject:user];
    [user release]; // explicit release so only reference is owned by ioArray
  }
}
</code>```

This gives you explicit control when you know the lifetime of an object, but makes it easy to write a wrapper when you want to use autorelease.

```<code>-(NSArray *) getUsers {
  NSMutableArray *result = [NSMutableArray array]; // implicit autorelease
  [self getMoreUsers:result];
  return result;
}
</code>```

An example of using this with a known lifetime would be:

```<code>-(void) operateOnUsers {
  NSMutableArray *array = [NSMutableArray new];
  [self getMoreUsers:array];
  // do stuff that will not retain array
  [array release];
}
</code>```

Body:
You can always pass a mutable object to be filled in.

-(void) getMoreUsers:(NSMutableArray *)ioArray {
  for ( ... ) {
    NSMutableDictionary *user = [NSMutableDictionary new];
    // fill in user ...
    [ioArray addObject:user];
    [user release]; // explicit release so only reference is owned by ioArray
  }
}

This gives you explicit control when you know the lifetime of an object, but makes it easy to write a wrapper when you want to use autorelease.

-(NSArray *) getUsers {
  NSMutableArray *result = [NSMutableArray array]; // implicit autorelease
  [self getMoreUsers:result];
  return result;
}

An example of using this with a known lifetime would be:

-(void) operateOnUsers {
  NSMutableArray *array = [NSMutableArray new];
  [self getMoreUsers:array];
  // do stuff that will not retain array
  [array release];
}


问:
How to check if a url is valid (actually loads a page with content) efficiently?
QUESTION:

How to check if a url is valid and actually loads a page ?

With my current code, only the status code is checked, which means that a url like http://fsd.com/ will be considered as valid although it does not load anything.

How can I check that the url actually points to a website that can be loaded ?

CODE:

```<code>$.ajax({
                    url: link,
                    dataType: 'jsonp',
                    statusCode: {
                        200: function() {
                            console.log( "status code 200 returned");
                            validURL = true;
                        },
                        404: function() {
                            console.log( "status code 404 returned");
                            validURL = false;
                        }
                    },
                    error:function(){
                        console.log("Error");
                    }
                });
</code>```

EDIT: By valid, I mean that the page is at last partially loaded (as in at least the html & css are loaded) instead of loading forever or somehow failing without the status code being 404.

EDIT2: http://fsd.com actually returns a 404 now as it should...

EDIT3: Another example: https://dsd.com loads an empty page (status code 200) and http://dsd.com actually loads a page with content (status code 200). On my Node.js backend, the npm package "url-exists" indicates that https://dsd.com is invalid, while my frontend with the code shown in my question indicates it is a valid url. This is what the package code looks like: https://github.com/boblauer/url-exists/blob/master/index.js but I wanted to know what would be the best way according to SO users.

EDIT4:

Sadly, the request provided by Addis is apparently blocked by CORS which blocks the execution of the rest of my code while my original request did not.

```<code>$.ajax({
                    type: "HEAD",
                    url: link,
                    dataType: 'jsonp',
                }).done(function(message,text,response){
                    const size = response.getResponseHeader('Content-Length');
                    const status = response.status;
                    console.log("SIZE: "+size);
                    console.log("STATUS: "+status);
                    if(size > 0 && status == "200") {
                        $("#submitErrorMessage").css("display","none");
                        $('#directoryForm').submit();
                    }
                    else {
                        $("#submitErrorMessage").css("display","block");
                        $("#submitLoading").css("display","none");
                    }
                });
</code>```

EDIT 5:

To be more precise, both requests trigger a warning message in the browser console indicating that the response has been blocked because of CORS but my original code is actually executed in its entirety while the the other request doesn't get to the console.log().

EDIT 6:

```<code>$.ajax({
                    async: true,
                    url: link,
                    dataType: 'jsonp',
                    success: function( data, status, jqxhr ){
                        console.log( "Response data received: ", data );
                        console.log("Response data length: ", data.length);
                        console.log("Response status code: ", status);
                        if (status == "200" && data.length > 0) {
                            $("#submitErrorMessage").css("display","none");
                            $('#directoryForm').submit();
                        }
                        else {
                            $("#submitErrorMessage").css("display","block");
                            $("#submitLoading").css("display","none");
                        }

                    },
                    error:function(jqXHR, textStatus, errorThrown){
                        console.log("Error: ", errorThrown);
                    }
                });
</code>```

Error:

```<code>Error:  Error: jQuery34108117853955031047_1582059896271 was not called
    at Function.error (jquery.js:2)
    at e.converters.script json (jquery.js:2)
    at jquery.js:2
    at l (jquery.js:2)
    at HTMLScriptElement.i (jquery.js:2)
    at HTMLScriptElement.dispatch (jquery.js:2)
    at HTMLScriptElement.v.handle (jquery.js:2)
</code>```

答:
I think the word "valid" is used a bit wrongly here. Looking at the code snippet, I can see that you are using HTTP error codes to decide whether the URL is valid or not. However, based on the description, it is clear that you consider the resource (pointed by the URL) to be valid only if it is a web page. I would like to urge the fact that HTTP can be used to access resources which need not have a web page representation.

I think you need to go a bit deeper and retrieve that info (whether it is a web-page representation) from the HTTP response that you receive and just relying on the status code would be misleading for you. One clear indicator would be looking at the response header for content-type: text/html.

Sample response from accessing www.google.com:

```<code>date: Tue, 18 Feb 2020 17:51:12 GMT
expires: -1
cache-control: private, max-age=0
content-type: text/html; charset=UTF-8
strict-transport-security: max-age=31536000
content-encoding: br
server: gws
content-length: 58083
x-xss-protection: 0
</code>```

Body:
QUESTION:

How to check if a url is valid and actually loads a page ?

With my current code, only the status code is checked, which means that a url like http://fsd.com/ will be considered as valid although it does not load anything.

How can I check that the url actually points to a website that can be loaded ?

CODE:

$.ajax({
                    url: link,
                    dataType: 'jsonp',
                    statusCode: {
                        200: function() {
                            console.log( "status code 200 returned");
                            validURL = true;
                        },
                        404: function() {
                            console.log( "status code 404 returned");
                            validURL = false;
                        }
                    },
                    error:function(){
                        console.log("Error");
                    }
                });

EDIT: By valid, I mean that the page is at last partially loaded (as in at least the html & css are loaded) instead of loading forever or somehow failing without the status code being 404.

EDIT2: http://fsd.com actually returns a 404 now as it should...

EDIT3: Another example: https://dsd.com loads an empty page (status code 200) and http://dsd.com actually loads a page with content (status code 200). On my Node.js backend, the npm package "url-exists" indicates that https://dsd.com is invalid, while my frontend with the code shown in my question indicates it is a valid url. This is what the package code looks like: https://github.com/boblauer/url-exists/blob/master/index.js but I wanted to know what would be the best way according to SO users.

EDIT4:

Sadly, the request provided by Addis is apparently blocked by CORS which blocks the execution of the rest of my code while my original request did not.

$.ajax({
                    type: "HEAD",
                    url: link,
                    dataType: 'jsonp',
                }).done(function(message,text,response){
                    const size = response.getResponseHeader('Content-Length');
                    const status = response.status;
                    console.log("SIZE: "+size);
                    console.log("STATUS: "+status);
                    if(size > 0 && status == "200") {
                        $("#submitErrorMessage").css("display","none");
                        $('#directoryForm').submit();
                    }
                    else {
                        $("#submitErrorMessage").css("display","block");
                        $("#submitLoading").css("display","none");
                    }
                });

EDIT 5:

To be more precise, both requests trigger a warning message in the browser console indicating that the response has been blocked because of CORS but my original code is actually executed in its entirety while the the other request doesn't get to the console.log().

EDIT 6:

$.ajax({
                    async: true,
                    url: link,
                    dataType: 'jsonp',
                    success: function( data, status, jqxhr ){
                        console.log( "Response data received: ", data );
                        console.log("Response data length: ", data.length);
                        console.log("Response status code: ", status);
                        if (status == "200" && data.length > 0) {
                            $("#submitErrorMessage").css("display","none");
                            $('#directoryForm').submit();
                        }
                        else {
                            $("#submitErrorMessage").css("display","block");
                            $("#submitLoading").css("display","none");
                        }

                    },
                    error:function(jqXHR, textStatus, errorThrown){
                        console.log("Error: ", errorThrown);
                    }
                });

Error:

Error:  Error: jQuery34108117853955031047_1582059896271 was not called
    at Function.error (jquery.js:2)
    at e.converters.script json (jquery.js:2)
    at jquery.js:2
    at l (jquery.js:2)
    at HTMLScriptElement.i (jquery.js:2)
    at HTMLScriptElement.dispatch (jquery.js:2)
    at HTMLScriptElement.v.handle (jquery.js:2)

Body:
I think the word "valid" is used a bit wrongly here. Looking at the code snippet, I can see that you are using HTTP error codes to decide whether the URL is valid or not. However, based on the description, it is clear that you consider the resource (pointed by the URL) to be valid only if it is a web page. I would like to urge the fact that HTTP can be used to access resources which need not have a web page representation.

I think you need to go a bit deeper and retrieve that info (whether it is a web-page representation) from the HTTP response that you receive and just relying on the status code would be misleading for you. One clear indicator would be looking at the response header for content-type: text/html.

Sample response from accessing www.google.com:

date: Tue, 18 Feb 2020 17:51:12 GMT
expires: -1
cache-control: private, max-age=0
content-type: text/html; charset=UTF-8
strict-transport-security: max-age=31536000
content-encoding: br
server: gws
content-length: 58083
x-xss-protection: 0


问:
Expose the most direct base class template name
Consider the following code:

```<code>template <class...> struct base {};
template <class... T> struct intermediate: base<void, T...> {};
template <class... T> struct derived: base<T...>, intermediate<T...> {};

using type1 = derived<int>::intermediate::base; // works
using type2 = derived<int>::base; // ambiguous
</code>```

Would there be a way to make it work without ambiguity so that derived<int>::base means the most "direct" base class in the hierarchy (in this example base<int>). Template metaprogramming is welcomed.

答:
If appropriate, you might add alias in derived, so you can use them from outside:

```<code>template <class... Ts> struct derived: base<Ts...>, intermediate<Ts...>
{
    using DirectBase = base<Ts...>;
    using IndirectBase = typename intermediate<Ts...>::base;
};
</code>```

And then

```<code>using type1 = derived<int>::IndirectBase ;
using type2 = derived<int>::DirectBase ;
</code>```

I see no ways to disambiguate.

There was proposal for std::bases std::direct_bases which might help, but rejected.

Body:
Consider the following code:

template <class...> struct base {};
template <class... T> struct intermediate: base<void, T...> {};
template <class... T> struct derived: base<T...>, intermediate<T...> {};

using type1 = derived<int>::intermediate::base; // works
using type2 = derived<int>::base; // ambiguous

Would there be a way to make it work without ambiguity so that derived<int>::base means the most "direct" base class in the hierarchy (in this example base<int>). Template metaprogramming is welcomed.

Body:
If appropriate, you might add alias in derived, so you can use them from outside:

template <class... Ts> struct derived: base<Ts...>, intermediate<Ts...>
{
    using DirectBase = base<Ts...>;
    using IndirectBase = typename intermediate<Ts...>::base;
};

And then

using type1 = derived<int>::IndirectBase ;
using type2 = derived<int>::DirectBase ;

I see no ways to disambiguate.

There was proposal for std::bases std::direct_bases which might help, but rejected.


问:
How to run async function in Airflow?
I am writing a airflow task to read a large csv and save it to postgresql database.
I found this asyncpg package that has a copy function which runs much faster than any other packages. However, it is async, and I don't know how to incorporate it into Airflow.
Here is a sample code:

from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import datetime, timedelta
from pandas import DataFrame
import asyncpg

async def to_sql(dataframe, table_name, schema_name='public', timeout=None, truncate=False):
    connection = await asyncpg.connect(user='postgres', host='host.docker.internal', database='quantaxis', password='123456')
    result = await connection.copy_records_to_table(
        table_name,
        records=dataframe.values.tolist(),
        columns=shared_columns,
        schema_name=schema_name,
        timeout=timeout)
    await connection.close()
    return result

default_args = {
    'owner': 'Airflow',
    'depends_on_past': False,
    'start_date': datetime(2020, 1, 1),
    'retries': 1,
    'retry_delay': timedelta(minutes=1),
}

dag = DAG('pythonexp2123', default_args=default_args, schedule_interval=timedelta(days=1))

async def save_file_to_database(ds):
    df = pd.read_csv("data{0}.csv".format(ds))
    r = await to_sql(df, 'test')
    return r

t1 = PythonOperator(
    task_id='pushing_task',
    provide_context=True,
    python_callable=save_file_to_database,
    dag=dag
    )

t1
```

<p>When I run it, it will return error:</p>

```Can't Pickle Object <Corountine>

```

How could I change the function to make this Dag work? I still want to use asyncpg package because of its speed.

答:
You can try running the async function in an eventloop using asyncio.
If you are uing python 3.7 > you can simply call asyncio.run(async_function())

https://docs.python.org/3/library/asyncio-task.html

```<code>from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import datetime, timedelta
from pandas import DataFrame
import asyncpg
import asyncio

async def to_sql(dataframe, table_name, schema_name='public', timeout=None, truncate=False):
    connection = await asyncpg.connect(user='postgres', host='host.docker.internal', database='quantaxis', password='123456')
    result = await connection.copy_records_to_table(
        table_name,
        records=dataframe.values.tolist(),
        columns=shared_columns,
        schema_name=schema_name,
        timeout=timeout)
    await connection.close()
    return result

default_args = {
    'owner': 'Airflow',
    'depends_on_past': False,
    'start_date': datetime(2020, 1, 1),
    'retries': 1,
    'retry_delay': timedelta(minutes=1),
}

dag = DAG('pythonexp2123', default_args=default_args, schedule_interval=timedelta(days=1))

async def save_file_to_database(ds):
    df = pd.read_csv("data{0}.csv".format(ds))
    r = await to_sql(df, 'test')
    return r

def run_async(ds):
   loop = asyncio.get_event_loop()
   result = loop.run_until_complete(save_file_to_database(ds))
   return result

t1 = PythonOperator(
    task_id='pushing_task',
    provide_context=True,
    python_callable=run_async,
    dag=dag
    )

t1
</code>```

Title: How to run async function in Airflow?

Body:
I am writing a airflow task to read a large csv and save it to postgresql database.
I found this asyncpg package that has a copy function which runs much faster than any other packages. However, it is async, and I don't know how to incorporate it into Airflow.
Here is a sample code:

from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import datetime, timedelta
from pandas import DataFrame
import asyncpg

async def to_sql(dataframe, table_name, schema_name='public', timeout=None, truncate=False):
    connection = await asyncpg.connect(user='postgres', host='host.docker.internal', database='quantaxis', password='123456')
    result = await connection.copy_records_to_table(
        table_name,
        records=dataframe.values.tolist(),
        columns=shared_columns,
        schema_name=schema_name,
        timeout=timeout)
    await connection.close()
    return result

default_args = {
    'owner': 'Airflow',
    'depends_on_past': False,
    'start_date': datetime(2020, 1, 1),
    'retries': 1,
    'retry_delay': timedelta(minutes=1),
}

dag = DAG('pythonexp2123', default_args=default_args, schedule_interval=timedelta(days=1))

async def save_file_to_database(ds):
    df = pd.read_csv("data{0}.csv".format(ds))
    r = await to_sql(df, 'test')
    return r

t1 = PythonOperator(
    task_id='pushing_task',
    provide_context=True,
    python_callable=save_file_to_database,
    dag=dag
    )

t1

When I run it, it will return error:

Can't Pickle Object <Corountine>

How could I change the function to make this Dag work? I still want to use asyncpg package because of its speed.

Body:
You can try running the async function in an eventloop using asyncio.
If you are uing python 3.7 > you can simply call asyncio.run(async_function())

https://docs.python.org/3/library/asyncio-task.html

from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import datetime, timedelta
from pandas import DataFrame
import asyncpg
import asyncio

async def to_sql(dataframe, table_name, schema_name='public', timeout=None, truncate=False):
    connection = await asyncpg.connect(user='postgres', host='host.docker.internal', database='quantaxis', password='123456')
    result = await connection.copy_records_to_table(
        table_name,
        records=dataframe.values.tolist(),
        columns=shared_columns,
        schema_name=schema_name,
        timeout=timeout)
    await connection.close()
    return result

default_args = {
    'owner': 'Airflow',
    'depends_on_past': False,
    'start_date': datetime(2020, 1, 1),
    'retries': 1,
    'retry_delay': timedelta(minutes=1),
}

dag = DAG('pythonexp2123', default_args=default_args, schedule_interval=timedelta(days=1))

async def save_file_to_database(ds):
    df = pd.read_csv("data{0}.csv".format(ds))
    r = await to_sql(df, 'test')
    return r

def run_async(ds):
   loop = asyncio.get_event_loop()
   result = loop.run_until_complete(save_file_to_database(ds))
   return result

t1 = PythonOperator(
    task_id='pushing_task',
    provide_context=True,
    python_callable=run_async,
    dag=dag
    )

t1


问:
Way to differ TypeScript object type from class type
Let's have class definition in typescript:

```<code>class User {
  public id: number;
  public name: string;
  public toString(): string{
    return name + id;
  }
}
</code>```

How to differ class from plain object in TypeScript?

```<code>const user1: User = new User();
const user2: User = {id: 1, name: 'John'};
</code>```

Those both are valid in TypeScript, but user1 is class instance and user2 is object.

I am asking that because I am expiriencing problems with TypeORM package where I am mixing objects and entity instances and it is starting to be very messy and I am not always sure if I have class instance or object.

答:
Answering:

How to differ class from plain object in TypeScript?

You can use instanceof to distinguish the two:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof

For example, user1 instanceof User should be true but not for user2.

Body:
Let's have class definition in typescript:

class User {
  public id: number;
  public name: string;
  public toString(): string{
    return name + id;
  }
}

How to differ class from plain object in TypeScript?

const user1: User = new User();
const user2: User = {id: 1, name: 'John'};

Those both are valid in TypeScript, but user1 is class instance and user2 is object.

I am asking that because I am expiriencing problems with TypeORM package where I am mixing objects and entity instances and it is starting to be very messy and I am not always sure if I have class instance or object.


问:
JavaScript - Math.random() - parameter
What changes adding the parameter in Math.random()?

For example:

```<code>Math.random() == Math.random(1234)
</code>```

答:
Read the specification:

15.8.2.14 random ( )

Returns a number value with positive sign, greater than
or equal to 0 but less than 1, chosen
randomly or pseudo randomly with
approximately uniform distribution
over that range, using an
implementation-dependent algorithm or
strategy. This function takes no
arguments.

Title: JavaScript - Math.random() - parameter

Body:
What changes adding the parameter in Math.random()?

For example:

Math.random() == Math.random(1234)


问:
Best way to implement Azure App ID into C# application
I'm developing an application that makes use of the OneDrive SDK nugget which uses Azure's App ID to authenticate API calls.

I'm not sure what's the best approach to implement that ID as I can't find any information about if it should be securely stored somehow or it can be implemented in a more flexible way (as plain text into a variable e.g).

Right now I'm storing that information in a separated file that has not been uploaded to github repository (as it's an open source project) but would like to know if that's not really necessary as it can be publicly avaible or there's a better way to handle it as I haven't used Azure Portal before.

Thanks in advance for the help.

答:
The application ID / client ID is not really a secret, though I suppose there isn't really any upside to sharing it either :)

If your app uses an application key / client secret, well, that has to be kept a secret.

The application ID is submitted to Azure AD in the sign-in request URL, so it is available to users who sign in to your app and can't really be kept a secret there.

Relevant portion of the OAuth RFC:

The authorization server issues the registered client a client
identifier -- a unique string representing the registration
information provided by the client.  The client identifier is not a
secret; it is exposed to the resource owner and MUST NOT be used
alone for client authentication.  The client identifier is unique to
the authorization server.