问:
How to stop kubectl proxy
I executed below command:

```<code>kubectl proxy --port=8081 &
kubectl proxy --port=8082 &
</code>```

and of course I have 2 accessible endpoints:

```<code>curl http://localhost:8081/api/
curl http://localhost:8082/api/
</code>```

But in the same time two running processes serving the same content.
How to stop one of these processes in "kubectl" manner?
Of course, I can kill the process but it seems to be a less elegant way...

答:
ps -ef | grep "kubectl proxy"
```

<p>will show you the PID of the process</p>

<p>Then you can stop it with </p>

<pre class="lang-sh prettyprint-override"><code>kill -9 <pid>
</code>```

Title: How to stop kubectl proxy

Body:
I executed below command:

kubectl proxy --port=8081 &
kubectl proxy --port=8082 &

and of course I have 2 accessible endpoints:

curl http://localhost:8081/api/
curl http://localhost:8082/api/

But in the same time two running processes serving the same content.
How to stop one of these processes in "kubectl" manner?
Of course, I can kill the process but it seems to be a less elegant way...

Body:
ps -ef | grep "kubectl proxy"

will show you the PID of the process

Then you can stop it with

kill -9 <pid>


来源: stackexchange

问:
My child processes crash silently with no error message even I handle its exceptions
I wrote a program to crawl a website and because of amount of link that I have to crawl I use Python multiprocessing. when my program starts everything is fine and my exceptions log very well but after 2-3 hours 2-3 or all 4 child processes use 0% CPU and cause I didn't use async my last line of the program which is log the "Done!" String does not execute! in the target function of my process pool I wrap all the code with a try/except statement so my process shouldn't be crash and if it crash I have to see some output in nohup.log file (I run this script with nohup myscript.py & in the background!). I dont know what's happening and it's really made me angry.

I searched in the internet and see someone told that use my_pool.close() after the pool statement (cause he said child processes not necessarily close after their tasks) but it didn't work either :(

my code is about 200 lines length so I cant put them all here!
I summarize it for you. if you need detail in some section just tell me

from bs4 import BeautifulSoup
import requests
import urllib.request
import multiprocessing
from orator import DatabaseManager
import os
from datetime import datetime

def login():
    requests_session = requests.session()
    login_page = requests_session.get("https://www.example.com/login")
    payload = {
        "username": "XX",
        "password": "X",
    }
    response = requests_session.post("https://www.example.com/auth/eb-login", data=payload, headers=dict(referer="https://www.example.com/login"))
    if response.status_code == 200:
        return requests_session
    else:
        return False

def media_crawler(url_article_id):
    try:
        url = url_article_id[0] + "/images-videos"
        article_id = url_article_id[1]
        requests_session = url_article_id[2]
        db = DatabaseManager(config)
        page = requests_session.get(url)
        soup = BeautifulSoup(page.text, 'html.parser')
        img_wrapper_list = soup.select("div.example")
        #Check if we are logged in
        if soup.select_one("div.example").text.strip().lower() != "logout":
            #if we not we login again
            current_session = login()
            #if our login failed we log it and stop doing this url task
            if current_session == False:
                log = open("media.log", "a+")
                log.write(datetime.now().strftime('%H:%M:%S') + " We are not logged in and can not log in!: "
                    "\nArticle ID: " + str(article_id)
                    + "\n----------------------------\n"
                )
                log.close()
                print("Error logged!")
                return
            #otherwise we return the new session
            else:
                requests_session = current_session
        #we go in every image wrapper and take all the images
        for img_wrapper in img_wrapper_list:
            if not img_wrapper.has_attr("data-jw"):
                img_source = img_wrapper.select_one("div.image-wrapper.mg > img")["src"]
                image_title = img_wrapper.select_one("div.image-wrapper.mg > img")["alt"]
                file_name_with_extension = img_source.split("/")[-1]
                file_name = file_name_with_extension.split(".")[0]
                file_extension = file_name_with_extension.split(".")[-1]
                try:
                    filename, headers = urllib.request.urlretrieve(img_source, "images/" + str(article_id) + "-" + file_name + "." + file_extension)
                    file_size = int(headers["Content-Length"]) / 1024
                    #Store the file in database
                #if we got any problem in downloading and storing in
                #database we log it and delete the downloaded file(if it downloaded)
                except Exception as e:
                    log = open("media.log", "a+")
                    log.write(datetime.now().strftime('%H:%M:%S') + " Problem in fetching media: \nURL: "
                        + img_source + "\nArticle ID: " + str(article_id) + "\n" + str(e)
                        + "\n----------------------------\n"
                    )
                    log.close()
                    print("Error logged!")
                    try:
                        os.remove("images/" + str(article_id) + "-" + file_name + "." + file_extension)
                    except:
                        pass
        #Update the image article to know which article media we download
        try:
            db.table("articles").where('article_id', article_id).update(image_status=1)
        except Exception as e:
            log = open("media.log", "a+")
            log.write(datetime.now().strftime('%H:%M:%S') + " Problem in updating database record for: "
                + "\nArticle ID: " + str(article_id) + "\n" + str(e)
                + "\n----------------------------\n"
            )
            log.close()
            print("Error logged!")
    #this is the try/except wrapper for my whole function
    except Exception as e:
        log = open("media.log", "a+")
        log.write(datetime.now().strftime('%H:%M:%S') + " Problem in this article media: \nURL: "
            + "\nArticle ID: " + str(article_id) + "\n" + str(e)
            + "\n----------------------------\n"
        )
        log.close()
        print("Error logged!")
    db.disconnect()

db = DatabaseManager()

current_session = login()

if current_session:
    log = open("media.log", "w+")
    log.write("Start!\n")
    log.close()

    articles = db.table("articles").skip(0).take(1000).get()
    url_article_id_tuples_list = []
    for article in articles:
        temp = (article["article_link"], article["article_id"], current_session)
        url_article_id_tuples_list.append(temp)

    myPool = multiprocessing.Pool()
    myPool.
    myPool.map(media_crawler, url_article_id_tuples_list)

    myPool.close()

    log = open("media.log", "a+")
    log.write("\nDone!")
    log.close()

else:
    print("Can not login to the site!")

db.disconnect()
```

<p>after 2-3 hours my processes crash (I think) and their CPU usage reach 0% and my last command not execute </p>

<pre class="lang-py prettyprint-override"><code>log.write("\nDone!")
</code>```

and I dont have anythink I nohup.log and anything special in media.log
I don't know really what happens behind the scene

my log file error is just about the connection and so i hanndle them:(

```<code>Start!
03:20:31 Problem in this article media:
URL:
Article ID: 190830
'alt'
----------------------------
03:50:05 Problem in fetching media:
URL: https://cdn.example.com/30/91430-004-828719A3.jpg
Article ID: 188625
<urlopen error [Errno 104] Connection reset by peer>
----------------------------
06:15:44 Problem in fetching media:
URL: https://cdn.example.com/15/37715-004-AA71C615.jpg
Article ID: 241940
<urlopen error [Errno 104] Connection reset by peer>
----------------------------
06:23:07 Problem in this article media:
URL:
Article ID: 244457
HTTPSConnectionPool(host='www.example.com', port=443): Max retries exceeded with url: /biography/Dore-Schary/images-videos (Caused by SSLError(SSLError("bad handshake: SysCallError(-1, 'Unexpected EOF')")))
----------------------------
06:25:14 Problem in this article media:
URL:
Article ID: 248185
('Connection aborted.', OSError("(104, 'ECONNRESET')"))
----------------------------
06:28:30 Problem in fetching media:
URL: https://cdn.example.com/89/77189-004-9D4A3E0B.jpg
Article ID: 244500
<urlopen error [Errno 104] Connection reset by peer>
----------------------------
06:39:29 Problem in fetching media:
URL: https://cdn.example.com/50/175050-004-8ACF8167.jpg
Article ID: 244763
Remote end closed connection without response
----------------------------
06:39:39 Problem in fetching media:
URL: https://cdn.example.com/34/201734-004-D8779144.jpg
Article ID: 244763
<urlopen error [Errno -2] Name or service not known>
----------------------------
06:39:49 Problem in fetching media:
URL: https://cdn.example.com/60/93460-004-B2993A85.jpg
Article ID: 244763
<urlopen error [Errno -2] Name or service not known>
----------------------------
06:39:59 Problem in fetching media:
URL: https://cdn.example.com/03/174803-004-DE7B5599.jpg
Article ID: 244763
<urlopen error [Errno -2] Name or service not known>
----------------------------
06:40:09 Problem in fetching media:
URL: https://cdn.example.com/81/188981-004-75AB37F3.jpg
Article ID: 244763
<urlopen error [Errno -2] Name or service not known>
----------------------------
06:42:42 Problem in this article media:
URL:
Article ID: 248524
HTTPSConnectionPool(host='www.example.com', port=443): Max retries exceeded with url: /topic/The-Yearling-novel-by-Rawlings/images-videos (Caused by SSLError(SSLError("bad handshake: SysCallError(104, 'ECONNRESET')")))

</code>```

and my crashed processes :
(they are not exactly 0% but no media added over time ...)

xxxxx   26137  0.1  1.6 589696 134320 ?       Sl   May07   1:45 /home/xxxx/anaconda3/envs/xxx/bin/python3.7 MediaCrawler.py
xxxxx   26140  0.3  1.4 379392 120064 ?       SN   May07   4:52 /home/xxxx/anaconda3/envs/xxx/bin/python3.7 MediaCrawler.py
xxxxx   26141  0.5  1.4 380724 121172 ?       S    May07   8:55 /home/xxxx/anaconda3/envs/xxx/bin/python3.7 MediaCrawler.py
xxxxx   26142  0.7  1.5 382860 123112 ?       S    May07  10:37 /home/xxxx/anaconda3/envs/xxx/bin/python3.7 MediaCrawler.py
xxxxx   26143  0.4  1.4 379912 120380 ?       S    May07   6:15 /home/xxxx/anaconda3/envs/xxx/bin/python3.7 MediaCrawler.py
xxxxx   29324  0.0  0.0  21536  1032 pts/1    S+   04:20   0:00 grep --color=auto MediaCrawler.py

```

答:
Tnx for the comments.
I made some experiments and this is what is that I found:

as Sam Mason said the rate of request that goes to the site is high and the way I fix this is to put an 1 sec wait in every request and now the program ends find

ContentLicense: CC BY-SA 4.0

Body:
I wrote a program to crawl a website and because of amount of link that I have to crawl I use Python multiprocessing. when my program starts everything is fine and my exceptions log very well but after 2-3 hours 2-3 or all 4 child processes use 0% CPU and cause I didn't use async my last line of the program which is log the "Done!" String does not execute! in the target function of my process pool I wrap all the code with a try/except statement so my process shouldn't be crash and if it crash I have to see some output in nohup.log file (I run this script with nohup myscript.py & in the background!). I dont know what's happening and it's really made me angry.

I searched in the internet and see someone told that use my_pool.close() after the pool statement (cause he said child processes not necessarily close after their tasks) but it didn't work either :(

my code is about 200 lines length so I cant put them all here!
I summarize it for you. if you need detail in some section just tell me

from bs4 import BeautifulSoup
import requests
import urllib.request
import multiprocessing
from orator import DatabaseManager
import os
from datetime import datetime

def login():
    requests_session = requests.session()
    login_page = requests_session.get("https://www.example.com/login")
    payload = {
        "username": "XX",
        "password": "X",
    }
    response = requests_session.post("https://www.example.com/auth/eb-login", data=payload, headers=dict(referer="https://www.example.com/login"))
    if response.status_code == 200:
        return requests_session
    else:
        return False

def media_crawler(url_article_id):
    try:
        url = url_article_id[0] + "/images-videos"
        article_id = url_article_id[1]
        requests_session = url_article_id[2]
        db = DatabaseManager(config)
        page = requests_session.get(url)
        soup = BeautifulSoup(page.text, 'html.parser')
        img_wrapper_list = soup.select("div.example")
        #Check if we are logged in
        if soup.select_one("div.example").text.strip().lower() != "logout":
            #if we not we login again
            current_session = login()
            #if our login failed we log it and stop doing this url task
            if current_session == False:
                log = open("media.log", "a+")
                log.write(datetime.now().strftime('%H:%M:%S') + " We are not logged in and can not log in!: "
                    "\nArticle ID: " + str(article_id)
                    + "\n----------------------------\n"
                )
                log.close()
                print("Error logged!")
                return
            #otherwise we return the new session
            else:
                requests_session = current_session
        #we go in every image wrapper and take all the images
        for img_wrapper in img_wrapper_list:
            if not img_wrapper.has_attr("data-jw"):
                img_source = img_wrapper.select_one("div.image-wrapper.mg > img")["src"]
                image_title = img_wrapper.select_one("div.image-wrapper.mg > img")["alt"]
                file_name_with_extension = img_source.split("/")[-1]
                file_name = file_name_with_extension.split(".")[0]
                file_extension = file_name_with_extension.split(".")[-1]
                try:
                    filename, headers = urllib.request.urlretrieve(img_source, "images/" + str(article_id) + "-" + file_name + "." + file_extension)
                    file_size = int(headers["Content-Length"]) / 1024
                    #Store the file in database
                #if we got any problem in downloading and storing in
                #database we log it and delete the downloaded file(if it downloaded)
                except Exception as e:
                    log = open("media.log", "a+")
                    log.write(datetime.now().strftime('%H:%M:%S') + " Problem in fetching media: \nURL: "
                        + img_source + "\nArticle ID: " + str(article_id) + "\n" + str(e)
                        + "\n----------------------------\n"
                    )
                    log.close()
                    print("Error logged!")
                    try:
                        os.remove("images/" + str(article_id) + "-" + file_name + "." + file_extension)
                    except:
                        pass
        #Update the image article to know which article media we download
        try:
            db.table("articles").where('article_id', article_id).update(image_status=1)
        except Exception as e:
            log = open("media.log", "a+")
            log.write(datetime.now().strftime('%H:%M:%S') + " Problem in updating database record for: "
                + "\nArticle ID: " + str(article_id) + "\n" + str(e)
                + "\n----------------------------\n"
            )
            log.close()
            print("Error logged!")
    #this is the try/except wrapper for my whole function
    except Exception as e:
        log = open("media.log", "a+")
        log.write(datetime.now().strftime('%H:%M:%S') + " Problem in this article media: \nURL: "
            + "\nArticle ID: " + str(article_id) + "\n" + str(e)
            + "\n----------------------------\n"
        )
        log.close()
        print("Error logged!")
    db.disconnect()

db = DatabaseManager()

current_session = login()

if current_session:
    log = open("media.log", "w+")
    log.write("Start!\n")
    log.close()

    articles = db.table("articles").skip(0).take(1000).get()
    url_article_id_tuples_list = []
    for article in articles:
        temp = (article["article_link"], article["article_id"], current_session)
        url_article_id_tuples_list.append(temp)

    myPool = multiprocessing.Pool()
    myPool.
    myPool.map(media_crawler, url_article_id_tuples_list)

    myPool.close()

    log = open("media.log", "a+")
    log.write("\nDone!")
    log.close()

else:
    print("Can not login to the site!")

db.disconnect()

after 2-3 hours my processes crash (I think) and their CPU usage reach 0% and my last command not execute

log.write("\nDone!")

and I dont have anythink I nohup.log and anything special in media.log
I don't know really what happens behind the scene

my log file error is just about the connection and so i hanndle them:(

Start!
03:20:31 Problem in this article media:
URL:
Article ID: 190830
'alt'
----------------------------
03:50:05 Problem in fetching media:
URL: https://cdn.example.com/30/91430-004-828719A3.jpg
Article ID: 188625
<urlopen error [Errno 104] Connection reset by peer>
----------------------------
06:15:44 Problem in fetching media:
URL: https://cdn.example.com/15/37715-004-AA71C615.jpg
Article ID: 241940
<urlopen error [Errno 104] Connection reset by peer>
----------------------------
06:23:07 Problem in this article media:
URL:
Article ID: 244457
HTTPSConnectionPool(host='www.example.com', port=443): Max retries exceeded with url: /biography/Dore-Schary/images-videos (Caused by SSLError(SSLError("bad handshake: SysCallError(-1, 'Unexpected EOF')")))
----------------------------
06:25:14 Problem in this article media:
URL:
Article ID: 248185
('Connection aborted.', OSError("(104, 'ECONNRESET')"))
----------------------------
06:28:30 Problem in fetching media:
URL: https://cdn.example.com/89/77189-004-9D4A3E0B.jpg
Article ID: 244500
<urlopen error [Errno 104] Connection reset by peer>
----------------------------
06:39:29 Problem in fetching media:
URL: https://cdn.example.com/50/175050-004-8ACF8167.jpg
Article ID: 244763
Remote end closed connection without response
----------------------------
06:39:39 Problem in fetching media:
URL: https://cdn.example.com/34/201734-004-D8779144.jpg
Article ID: 244763
<urlopen error [Errno -2] Name or service not known>
----------------------------
06:39:49 Problem in fetching media:
URL: https://cdn.example.com/60/93460-004-B2993A85.jpg
Article ID: 244763
<urlopen error [Errno -2] Name or service not known>
----------------------------
06:39:59 Problem in fetching media:
URL: https://cdn.example.com/03/174803-004-DE7B5599.jpg
Article ID: 244763
<urlopen error [Errno -2] Name or service not known>
----------------------------
06:40:09 Problem in fetching media:
URL: https://cdn.example.com/81/188981-004-75AB37F3.jpg
Article ID: 244763
<urlopen error [Errno -2] Name or service not known>
----------------------------
06:42:42 Problem in this article media:
URL:
Article ID: 248524
HTTPSConnectionPool(host='www.example.com', port=443): Max retries exceeded with url: /topic/The-Yearling-novel-by-Rawlings/images-videos (Caused by SSLError(SSLError("bad handshake: SysCallError(104, 'ECONNRESET')")))

and my crashed processes :
(they are not exactly 0% but no media added over time ...)

xxxxx   26137  0.1  1.6 589696 134320 ?       Sl   May07   1:45 /home/xxxx/anaconda3/envs/xxx/bin/python3.7 MediaCrawler.py
xxxxx   26140  0.3  1.4 379392 120064 ?       SN   May07   4:52 /home/xxxx/anaconda3/envs/xxx/bin/python3.7 MediaCrawler.py
xxxxx   26141  0.5  1.4 380724 121172 ?       S    May07   8:55 /home/xxxx/anaconda3/envs/xxx/bin/python3.7 MediaCrawler.py
xxxxx   26142  0.7  1.5 382860 123112 ?       S    May07  10:37 /home/xxxx/anaconda3/envs/xxx/bin/python3.7 MediaCrawler.py
xxxxx   26143  0.4  1.4 379912 120380 ?       S    May07   6:15 /home/xxxx/anaconda3/envs/xxx/bin/python3.7 MediaCrawler.py
xxxxx   29324  0.0  0.0  21536  1032 pts/1    S+   04:20   0:00 grep --color=auto MediaCrawler.py


问:
How to get Database Name in a Logon SQL Trigger
How to get Database Name in a Logon Trigger

tried several tsql code

```<code>CREATE TRIGGER tr_stop_excel_users
ON ALL SERVER FOR LOGON
AS
BEGIN
    IF (SELECT DB_NAME() FROM sys.databases) = 'TESTDB' and ORIGINAL_LOGIN() <> N'xx\xxxxxxx' AND APP_NAME() LIKE '%Microsoft Office%'  OR APP_NAME() LIKE '%EXCEL%' OR APP_NAME() LIKE '%ACCESS%
    ROLLBACK;
END
</code>```

above the DB_NAME always yields master

I am trying to get Database Name in a Logon Trigger and its not working in any way I try….below the DB_NAME is always master…what I am trying to do here is to block users who are using excel to query the TESTDB database….

答:
If you are using Db_Name in LOGON trigger, you will get the default database name. So as you get the master, it shows that login's default database is master.

If you need to get other names, you need to change your connection string in application, or provide database name in SSMS Login prompt screen, or any other places where you can provide the database name(Go to Options/Connection Properties/Connect to Database in Login prompt screen in SSMS)

If you do not provide database name, login will connect to its default database, that is set in Security/Login/Default Database

Solution for you

Using Db_Name is not a good option for you, I recommend you to use APP_NAME function instead.

Same problem discussed in StackExchange: https://dba.stackexchange.com/questions/40155/prevent-users-from-using-power-pivot-excel-connections-to-a-database

Body:
How to get Database Name in a Logon Trigger

tried several tsql code

CREATE TRIGGER tr_stop_excel_users
ON ALL SERVER FOR LOGON
AS
BEGIN
    IF (SELECT DB_NAME() FROM sys.databases) = 'TESTDB' and ORIGINAL_LOGIN() <> N'xx\xxxxxxx' AND APP_NAME() LIKE '%Microsoft Office%'  OR APP_NAME() LIKE '%EXCEL%' OR APP_NAME() LIKE '%ACCESS%
    ROLLBACK;
END

above the DB_NAME always yields master

I am trying to get Database Name in a Logon Trigger and its not working in any way I try….below the DB_NAME is always master…what I am trying to do here is to block users who are using excel to query the TESTDB database….


答:
I know it's horrible, not elegant and time consuming, but this query works:

```<code>SELECT deviceId,deviceName,deviceDescription,
  (SELECT time_stamp FROM datalog
    WHERE datalog.DeviceId=devices.deviceId
    ORDER BY time_stamp DESC LIMIT 0,1) time_stamp,
  (SELECT FuelLevel FROM datalog
    WHERE datalog.DeviceId=devices.deviceId
    ORDER BY time_stamp DESC LIMIT 0,1) FuelLevel,
  (SELECT Voltage FROM datalog
    WHERE datalog.DeviceId=devices.deviceId
    ORDER BY time_stamp DESC LIMIT 0,1) Voltage
FROM devices
</code>```

I tried to have a single subquery retrieving multiple columns, but MySql complains because it wants only one column.

ContentLicense: CC BY-SA 3.0

Title: Joining one table to the latest row in another table using MySQL

Body:
I want to join two tables in a special way, first table is devices which has a list of devices.

The second table is datalog which is where abit of data is stored for everytime a device in devices gets polled.

Devices Table:

+----------+------------+----------------------------+---------------------+
| deviceId | deviceName | deviceDescription          | timeCreated         |
+----------+------------+----------------------------+---------------------+
|        1 | System 1   | Main System in Server Room | 2010-01-01 00:00:00 |
|        2 | System 2   | Outdoor System             | 2010-01-01 00:00:00 |
+----------+------------+----------------------------+---------------------+

DataLog Table:

+----+---------------------+----------+-----------+---------+
| id | time_stamp          | DeviceId | FuelLevel | Voltage |
+----+---------------------+----------+-----------+---------+
|  1 | 2010-01-01 00:00:00 |        1 |        60 |     220 |
|  2 | 2010-01-01 00:00:00 |        2 |        20 |     221 |
|  3 | 2010-01-02 00:00:00 |        1 |       100 |     219 |
|  4 | 2010-01-02 00:00:00 |        2 |       100 |     222 |
|  5 | 2010-01-03 00:00:00 |        1 |        80 |     219 |
|  6 | 2010-01-03 00:00:00 |        2 |        99 |     220 |
+----+---------------------+----------+-----------+---------+

Currently I am getting the latest data for each device using a query on the DataLog table with:

 Where DeviceId = 1 ORDER BY timestamp DESC LIMIT 1

What I would like is one query to return a list of all devices, with the columns joined with the latest data for each device like this:

+----------+------------+----------------------------+---------------------+-----------+---------+
| deviceId | deviceName | deviceDescription          | time_stamp          |FuelLevel  | Voltage |
+----------+------------+----------------------------+---------------------+-----------+---------+
|        1 | System 1   | Main System in Server Room | 2010-01-03 00:00:00 |        80 |     219 |
|        2 | System 2   | Outdoor System             | 2010-01-03 00:00:00 |       99  |     220 |
+----------+------------+----------------------------+---------------------+-----------+---------+

Body:
I know it's horrible, not elegant and time consuming, but this query works:

SELECT deviceId,deviceName,deviceDescription,
  (SELECT time_stamp FROM datalog
    WHERE datalog.DeviceId=devices.deviceId
    ORDER BY time_stamp DESC LIMIT 0,1) time_stamp,
  (SELECT FuelLevel FROM datalog
    WHERE datalog.DeviceId=devices.deviceId
    ORDER BY time_stamp DESC LIMIT 0,1) FuelLevel,
  (SELECT Voltage FROM datalog
    WHERE datalog.DeviceId=devices.deviceId
    ORDER BY time_stamp DESC LIMIT 0,1) Voltage
FROM devices

I tried to have a single subquery retrieving multiple columns, but MySql complains because it wants only one column.


问:
Configure Google App Engine yaml file to handle 404 Error
After the deployment of my application on Google App Engine every things works like a charm , I can access all pages but when I refresh I receive a 404 error

Example : when refreching https://my-app...appspot.com/create-ad throw 404 not found

I tried
Angular 6 routes not found on Google App Engine
and
How to configure Google App Engine yaml file to handle 404 Error
but same result

This on my app.yml

```<code>runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /
  static_files: dist/index.html
  upload: dist/index.html
- url: /
  static_dir: dist
- url: /.*
  static_files: dist/index.html
  upload: dist/index.html

skip_files:
- ^.*node_modules(/.*)?
- ^.*json_data(/.*)?
- ^.*e2e(/.*)?
</code>```

and also tried this app.yml config to redirect all url to index.html

```<code>runtime: python27
api_version: 1
threadsafe: false
service: frontend-accept

handlers:
- url: /
  static_files: dist/index.html
  upload: dist/index.html

- url: /
  static_dir: dist

- url: /.*
  script: main.py

skip_files:
- ^.*node_modules(/.*)?
- ^.*json_data(/.*)?
- ^.*e2e(/.*)?
</code>```

this is my main.py

```<code>import webapp2
app = webapp2.WSGIApplication()

class RedirectToHome(webapp2.RequestHandler):
    def get(self, path):
        self.redirect('/dist/index.html')

routes = [
    RedirectRoute('/<path:.*>', RedirectToHome),
]

for r in routes:
    app.router.add(r)
</code>```

But always get 404 when refreshing the page

Any help? Thanks

答:
finally the solution was to configure the app.yml properly</p>

```<code>runtime: python27
api_version: 1
threadsafe: true
skip_files:
- ^(?!dist)  # Skip any files not in the dist folder

handlers:
- url: /((?:runtime|main|polyfills|styles|vendor)\.[a-z0-9]+\.js)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/\1
  upload: dist/browser/.*

- url: /((?:runtime|main|polyfills|styles|vendor)\.[a-z0-9]+\.js\.map)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/\1
  upload: dist/browser/.*

- url: /(styles\.[a-z0-9]+\.css)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/\1
  upload: dist/browser/.*

- url: /((?:assets|docs)/.*|favicon\.ico)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/\1
  upload: dist/browser/.*

- url: /(manifest\.json|ngsw\.json|ngsw-worker\.js|safety-worker\.js|worker-basic\.min\.js|ngsw_worker\.es6\.js\.map)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/\1
  upload: dist/browser/.*

- url: /(.*\.woff)
  mime_type: application/x-font-woff
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/\1
  upload: dist/browser/.*

- url: /.*
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/index.html
  upload: dist/browser/index\.html
  http_headers:
    Strict-Transport-Security: max-age=31536000; includeSubDomains
    X-Frame-Options: DENY
</code>```

Body:
After the deployment of my application on Google App Engine every things works like a charm , I can access all pages but when I refresh I receive a 404 error

Example : when refreching https://my-app...appspot.com/create-ad throw 404 not found

I tried
Angular 6 routes not found on Google App Engine
and
How to configure Google App Engine yaml file to handle 404 Error
but same result

This on my app.yml

runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /
  static_files: dist/index.html
  upload: dist/index.html
- url: /
  static_dir: dist
- url: /.*
  static_files: dist/index.html
  upload: dist/index.html

skip_files:
- ^.*node_modules(/.*)?
- ^.*json_data(/.*)?
- ^.*e2e(/.*)?

and also tried this app.yml config to redirect all url to index.html

runtime: python27
api_version: 1
threadsafe: false
service: frontend-accept

handlers:
- url: /
  static_files: dist/index.html
  upload: dist/index.html

- url: /
  static_dir: dist

- url: /.*
  script: main.py

skip_files:
- ^.*node_modules(/.*)?
- ^.*json_data(/.*)?
- ^.*e2e(/.*)?

this is my main.py

import webapp2
app = webapp2.WSGIApplication()

class RedirectToHome(webapp2.RequestHandler):
    def get(self, path):
        self.redirect('/dist/index.html')

routes = [
    RedirectRoute('/<path:.*>', RedirectToHome),
]

for r in routes:
    app.router.add(r)

But always get 404 when refreshing the page

Any help? Thanks

Body:
finally the solution was to configure the app.yml properly

runtime: python27
api_version: 1
threadsafe: true
skip_files:
- ^(?!dist)  # Skip any files not in the dist folder

handlers:
- url: /((?:runtime|main|polyfills|styles|vendor)\.[a-z0-9]+\.js)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/\1
  upload: dist/browser/.*

- url: /((?:runtime|main|polyfills|styles|vendor)\.[a-z0-9]+\.js\.map)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/\1
  upload: dist/browser/.*

- url: /(styles\.[a-z0-9]+\.css)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/\1
  upload: dist/browser/.*

- url: /((?:assets|docs)/.*|favicon\.ico)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/\1
  upload: dist/browser/.*

- url: /(manifest\.json|ngsw\.json|ngsw-worker\.js|safety-worker\.js|worker-basic\.min\.js|ngsw_worker\.es6\.js\.map)
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/\1
  upload: dist/browser/.*

- url: /(.*\.woff)
  mime_type: application/x-font-woff
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/\1
  upload: dist/browser/.*

- url: /.*
  secure: always
  redirect_http_response_code: 301
  static_files: dist/browser/index.html
  upload: dist/browser/index\.html
  http_headers:
    Strict-Transport-Security: max-age=31536000; includeSubDomains
    X-Frame-Options: DENY


问:
Swift compiler segmentation fault when building
Adding a (convenient) computed height property to UIView in my UIViewExtension.swift file is causing the Swift compiler to segfault... What could possibly be going wrong here?

```<code>0  swift                    0x00000001061e5608 llvm::sys::PrintStackTrace(__sFILE*) + 40
1  swift                    0x00000001061e5af4 SignalHandler(int) + 452
2  libsystem_platform.dylib 0x00007fff894da5aa _sigtramp + 26
3  libsystem_platform.dylib 0xb03939841e997c88 _sigtramp + 2504775416
4  swift                    0x00000001064c8bb9 swift::NominalTypeDecl::getMembers(bool) const + 41
5  swift                    0x00000001055efab9 swift::irgen::ClassMetadataLayout<(anonymous namespace)::FindClassMethodIndex>::addClassMembers(swift::ClassDecl*) + 329
6  swift                    0x00000001055e97b2 swift::irgen::emitVirtualMethodValue(swift::irgen::IRGenFunction&, llvm::Value*, swift::SILType, swift::SILDeclRef, swift::CanTypeWrapper<swift::SILFunctionType>, swift::ResilienceExpansion) + 434
7  swift                    0x00000001056550d3 swift::SILVisitor<(anonymous namespace)::IRGenSILFunction, void>::visit(swift::ValueBase*) + 42611
8  swift                    0x000000010564a266 swift::irgen::IRGenModule::emitSILFunction(swift::SILFunction*) + 8678
9  swift                    0x00000001055cb6f8 swift::irgen::IRGenModule::emitGlobalTopLevel() + 184
10 swift                    0x00000001056376e3 performIRGeneration(swift::IRGenOptions&, swift::Module*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 1859
11 swift                    0x0000000105638033 swift::performIRGeneration(swift::IRGenOptions&, swift::SourceFile&, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, unsigned int) + 51
12 swift                    0x00000001055aa65a frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 4842
13 swift                    0x00000001055a935d main + 1533
14 libdyld.dylib            0x00007fff8a82e5fd start + 1
</code>```

```<code>1.  While emitting IR SIL function @_TFCSo6UIViewg6heightSd for 'anonname=0x7ff422892fd0' at <path redacted>/UIViewExtension.swift:60:5
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254
</code>```

If more information is needed to crack this, just comment. Thanks!

Edit:

Here's a related .xcodeproj that returns this question's compiler error. Download here

答:
I was moving from Xcode 9 to 10.2. And here's a problem place

struct AbstractField<T>: ValidatableField {
    var name: String
    var value: Observable<Validated<T>>
    var setValue: (Validated<T>) -> Void
    var hint: Variable<String?>
    var error: Variable<AviaFieldError?>
    var isHidden: Binder<Bool>
    var isBeingEdited: Observable<Bool>
    var silentMode: Variable<Bool>
}
```

<p>To solve a problem I replaced var to let for setValue closure.</p>

<pre class="lang-swift prettyprint-override"><code>struct AbstractField<T>: ValidatableField {
    var name: String
    var value: Observable<Validated<T>>
    let setValue: (Validated<T>) -> Void
    var hint: Variable<String?>
    var error: Variable<AviaFieldError?>
    var isHidden: Binder<Bool>
    var isBeingEdited: Observable<Bool>
    var silentMode: Variable<Bool>
}
</code>```

Seems it was very hard to parse this construction for the compiler.

Body:
Adding a (convenient) computed height property to UIView in my UIViewExtension.swift file is causing the Swift compiler to segfault... What could possibly be going wrong here?

0  swift                    0x00000001061e5608 llvm::sys::PrintStackTrace(__sFILE*) + 40
1  swift                    0x00000001061e5af4 SignalHandler(int) + 452
2  libsystem_platform.dylib 0x00007fff894da5aa _sigtramp + 26
3  libsystem_platform.dylib 0xb03939841e997c88 _sigtramp + 2504775416
4  swift                    0x00000001064c8bb9 swift::NominalTypeDecl::getMembers(bool) const + 41
5  swift                    0x00000001055efab9 swift::irgen::ClassMetadataLayout<(anonymous namespace)::FindClassMethodIndex>::addClassMembers(swift::ClassDecl*) + 329
6  swift                    0x00000001055e97b2 swift::irgen::emitVirtualMethodValue(swift::irgen::IRGenFunction&, llvm::Value*, swift::SILType, swift::SILDeclRef, swift::CanTypeWrapper<swift::SILFunctionType>, swift::ResilienceExpansion) + 434
7  swift                    0x00000001056550d3 swift::SILVisitor<(anonymous namespace)::IRGenSILFunction, void>::visit(swift::ValueBase*) + 42611
8  swift                    0x000000010564a266 swift::irgen::IRGenModule::emitSILFunction(swift::SILFunction*) + 8678
9  swift                    0x00000001055cb6f8 swift::irgen::IRGenModule::emitGlobalTopLevel() + 184
10 swift                    0x00000001056376e3 performIRGeneration(swift::IRGenOptions&, swift::Module*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 1859
11 swift                    0x0000000105638033 swift::performIRGeneration(swift::IRGenOptions&, swift::SourceFile&, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, unsigned int) + 51
12 swift                    0x00000001055aa65a frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 4842
13 swift                    0x00000001055a935d main + 1533
14 libdyld.dylib            0x00007fff8a82e5fd start + 1

1.  While emitting IR SIL function @_TFCSo6UIViewg6heightSd for 'anonname=0x7ff422892fd0' at <path redacted>/UIViewExtension.swift:60:5
<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254

If more information is needed to crack this, just comment. Thanks!

Edit:

Here's a related .xcodeproj that returns this question's compiler error. Download here

Body:
I was moving from Xcode 9 to 10.2. And here's a problem place

struct AbstractField<T>: ValidatableField {
    var name: String
    var value: Observable<Validated<T>>
    var setValue: (Validated<T>) -> Void
    var hint: Variable<String?>
    var error: Variable<AviaFieldError?>
    var isHidden: Binder<Bool>
    var isBeingEdited: Observable<Bool>
    var silentMode: Variable<Bool>
}

To solve a problem I replaced var to let for setValue closure.

struct AbstractField<T>: ValidatableField {
    var name: String
    var value: Observable<Validated<T>>
    let setValue: (Validated<T>) -> Void
    var hint: Variable<String?>
    var error: Variable<AviaFieldError?>
    var isHidden: Binder<Bool>
    var isBeingEdited: Observable<Bool>
    var silentMode: Variable<Bool>
}

Seems it was very hard to parse this construction for the compiler.


问:
How do I sequentially fill a big range of cells in Google Sheets?
I want to fill an entire column of Google Sheets with numbers from -4000 to 4000, but I can't find an easy way of doing it.

I'm aware of the auto-fill solution of google sheets that allows you to write two sequential numbers and then select them and use the drag-and-drop approach, but for big numbers, this is not a feasible approach.

Is there a way of automating it using some formula or some built-in option?

答:
make sure you have 8001+ rows and then use:

```<code>=ARRAYFORMULA({SORT(ROW(A1:A4000)*-1); 0; ROW(A1:A4000)})
</code>```

or:

```<code>=ARRAYFORMULA(IF(ROW(A1:A8001); {SORT(ROW(A1:A4000)*-1); 0; ROW(A1:A4000)}; ))
</code>```

Body:
make sure you have 8001+ rows and then use:

=ARRAYFORMULA({SORT(ROW(A1:A4000)*-1); 0; ROW(A1:A4000)})

or:

=ARRAYFORMULA(IF(ROW(A1:A8001); {SORT(ROW(A1:A4000)*-1); 0; ROW(A1:A4000)}; ))


问:
dpHibernate: serializerFactory not initialized by Spring -> NullPointerException on service access
I am trying to get dpHibernate 2.0 RC6 running on an Apache Tomcat 7.0.12 with BlazeDS 4.0.0.14931, Spring 3.0.5 and Spring-BlazeDS-Integration 1.5.0.M2

With the following configuration the server starts fine, but as soon as I want to access a service or the RDSDispatchServlet via FlashBuilder4 DCD I am getting a NullPointerException. It seems the serializerFactory is not correctly injected into the dpHibernate HibernateUtil. Did I miss something in the configuration in remoting-config.xml?

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
          version="2.5">

   <display-name>Server</display-name>
   <description>Server Side based on BlazeDS, Spring and Hibernate</description>
   <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
   <listener>
    <listener-class>flex.messaging.HttpFlexSession</listener-class>
   </listener>

   <!-- begin SPRING INTEGRATION -->
   <servlet>
     <servlet-name>springMessageBroker</servlet-name>
     <servlet-class>
       org.springframework.web.servlet.DispatcherServlet
     </servlet-class>
     <!-- <init-param> -->
     <!-- <param-name>contextConfigLocation</param-name> -->
     <!-- <param-value></param-value> Do not use if using ContextLoaderListener (would load app context twice -> Error) -->
     <!-- </init-param> -->
     <init-param>
        <param-name>services.configuration.file</param-name>
        <param-value>/WEB-INF/flex/services-config.xml</param-value>
     </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMessageBroker</servlet-name>
    <url-pattern>/messagebroker/*</url-pattern>
  </servlet-mapping>
  <!-- end SPRING INTEGRATION -->

  <!-- begin rds -->
  <servlet>
    <servlet-name>RDSDispatchServlet</servlet-name>
    <servlet-class>flex.rds.server.servlet.FrontEndServlet</servlet-class>
    <init-param>
        <param-name>useAppserverSecurity</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>messageBrokerId</param-name>
        <param-value>_messageBroker</param-value>
    </init-param>
    <load-on-startup>10</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>RDSDispatchServlet</servlet-name>
    <url-pattern>/CFIDE/main/ide.cfm</url-pattern>
  </servlet-mapping>
  <!-- end rds -->

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
  </welcome-file-list>

  <filter>
    <filter-name>dpHibernateSessionFilter</filter-name>
    <filter-class>org.dphibernate.filters.HibernateSessionServletFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>dpHibernateSessionFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
</code>```

applicationContext.xml (Spring Servlet default configuration file)

```<code><beans  xmlns="http://www.springframework.org/schema/beans"
    xmlns:flex="http://www.springframework.org/schema/flex"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/flex
        http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <import resource="flexContext.xml" />
    <import resource="dataAccessContext.xml" />
    <import resource="dpHibernateContext.xml"/>

    <!-- Enable Spring Transaction Manager with Annotations -->
    <tx:annotation-driven />

    <context:annotation-config />

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations" value="/WEB-INF/server.properties" /></bean>

    <context:component-scan base-package="com.mycompany.myproject.*" />
</beans>
</code>```

flexContext.xml (definitions of services available for flex)

```<code><beans  xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:flex="http://www.springframework.org/schema/flex"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/flex
        http://www.springframework.org/schema/flex/spring-flex-1.0.xsd">

    <flex:message-destination id="chat"/>

    <flex:message-broker services-config-path="/WEB-INF/flex/services-config.xml">
            <flex:remoting-service default-adapter-id="dpHibernateRemotingAdapter" default-channels="my-amf,my-secure-amf" />
            <flex:message-service default-channels="my-streaming-amf,my-polling-amf"/>
    </flex:message-broker>
</beans>
</code>```

fpHibernateContext.xml (configuration of dpHibernate)

```<code><beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:flex="http://www.springframework.org/schema/flex"
      xmlns:security="http://www.springframework.org/schema/security"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xmlns:util="http://www.springframework.org/schema/util"
      xsi:schemaLocation="http://www.springframework.org/schema/aop
                          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                          http://www.springframework.org/schema/beans
                          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                          http://www.springframework.org/schema/context
                          http://www.springframework.org/schema/context/spring-context-3.0.xsd
                          http://www.springframework.org/schema/flex
                          http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
                          http://www.springframework.org/schema/security
                          http://www.springframework.org/schema/security/spring-security-3.0.xsd
                          http://www.springframework.org/schema/tx
                          http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                          http://www.springframework.org/schema/util
                          http://www.springframework.org/schema/util/spring-util-3.0.xsd
                          ">
  <!-- Defines the remoting adapter, which intercepts inbound & outbound messages, and routes them thruogh dpHibernate -->
  <bean id="dpHibernateRemotingAdapter"
    class="org.springframework.flex.core.ManageableComponentFactoryBean">
    <constructor-arg value="org.dphibernate.adapters.RemotingAdapter" />
    <property name="properties">
      <value>
      {"dpHibernate" :
        {
          "serializerFactory" : "org.dphibernate.serialization.SpringContextSerializerFactory"
        }
      }
      </value>
    </property>
  </bean>
  <bean id="dpHibernateMessagingAdapter"
    class="org.springframework.flex.core.ManageableComponentFactoryBean">
    <constructor-arg value="org.dphibernate.adapters.MessagingAdapter" />
  </bean>

  <bean id="dataAccessService" class="org.dphibernate.services.SpringLazyLoadService" autowire="constructor">
    <flex:remoting-destination />
  </bean>

  <!-- Required -->
  <bean id="hibernateSessionFilter" class="org.dphibernate.filters.SpringHibernateSessionServletFilter" />

  <!-- The cache is used to prevent serializing the same object many times during serialization.  Required -->
  <bean id="dpHibernateCache"
    class="org.dphibernate.serialization.DPHibernateCache" scope="prototype" />

  <!-- The main serializer. Converts outbound POJO's to ASObjects with dpHibernate proxies for lazy loading.  Required -->
  <bean id="dpHibernateSerializer"
    class="org.dphibernate.serialization.HibernateSerializer" scope="prototype">
    <property name="pageSize" value="10"/>
  </bean>
  <bean id="dpHibernateDeserializer" class="org.dphibernate.serialization.HibernateDeserializer" scope="prototype" />
  <!--  Handles entity updates (CRUD).  Required if using entity persistence. -->
  <bean id="objectChangeUpdater"
    class="org.dphibernate.persistence.state.AuthenticatedObjectChangeUpdater"
    scope="prototype">
    <property name="preProcessors" ref="dpHibernatePreProcessors" />
    <property name="postProcessors" ref="dpHibernatePostProcessors" />
  </bean>
</beans>
</code>```

remoting-config.xml (imported in services-config.xml)

```<code><service id="remoting-service"
         class="flex.messaging.services.RemotingService"
         messageTypes="flex.messaging.messages.RemotingMessage">

  <adapters>
    <adapter-definition id="hibernate-object" class="org.dphibernate.adapters.RemotingAdapter" default="true">
      <properties>
        <hibernate>
          <sessionFactory>
            <class>org.dphibernate.utils.HibernateUtil</class>
            <getCurrentSessionMethod>getCurrentSession</getCurrentSessionMethod>
          </sessionFactory>
        </hibernate>
      </properties>
    </adapter-definition>
    <adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter"/>
  </adapters>

  <default-channels>
    <channel ref="my-amf"/>
  </default-channels>
</service>
</code>```

NullPointerException (on service access or rds access via FB4 DCD)

startInternal INFO: Starting Servlet
  Engine: Apache Tomcat/7.0.12
  11.04.2011 18:34:19 org.apache.catalina.core.ApplicationContext
  log INFO: Initializing Spring root
  WebApplicationContext 1027 [Thread-2]
  INFO
  org.hibernate.annotations.common.Version
  - Hibernate Commons Annotations 3.2.0.Final 1066 [Thread-2] INFO org.hibernate.cfg.Environment -
  Hibernate 3.6.2.Final 1074 [Thread-2]
  INFO org.hibernate.cfg.Environment -
  hibernate.properties not found 1085
  [Thread-2] INFO
  org.hibernate.cfg.Environment -
  Bytecode provider name : javassist
  1116 [Thread-2] INFO
  org.hibernate.cfg.Environment - using
  JDK 1.4 java.sql.Timestamp handling
  2146 [Thread-2] INFO
  org.hibernate.cfg.Configuration -
  Hibernate Validator not found:
  ignoring 2182 [Thread-2] INFO
  org.hibernate.cfg.search.HibernateSearchEventListenerRegister
  - Unable to find org.hibernate.search.event.FullTextIndexEventListener
  on the classpath. Hibernate Search is
  not enabled. 2194 [Thread-2] INFO
  org.hibernate.connection.ConnectionProviderFactory
  - Initializing connection provider: org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider
  2658 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Database ->
         name : MySQL
      version : 5.0.51a-24+lenny5-log
        major : 5
        minor : 0 2658 [Thread-2] INFO org.hibernate.cfg.SettingsFactory -
  Driver ->
         name : MySQL-AB JDBC Driver
      version : mysql-connector-java-5.1.15 (
  Revision: ${bzr.revision-id} )
        major : 5
        minor : 1 2861 [Thread-2] INFO org.hibernate.dialect.Dialect - Using
  dialect:
  org.hibernate.dialect.MySQLInnoDBDialect
  2981 [Thread-2] INFO
  org.hibernate.transaction.TransactionFactoryFactory
  - Transaction strategy: org.springframework.orm.hibernate3.SpringTransactionFactory
  2991 [Thread-2] INFO
  org.hibernate.transaction.TransactionManagerLookupFactory
  - No TransactionManagerLookup configured (in JTA environment, use of
  read-write or transactional
  second-level cache is not recommended)
  2991 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Automatic flush during
  beforeCompletion(): disabled 2991
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Automatic session close at end of
  transaction: disabled 2991 [Thread-2]
  INFO org.hibernate.cfg.SettingsFactory
  - JDBC batch size: 20 2991 [Thread-2] INFO org.hibernate.cfg.SettingsFactory
  - JDBC batch updates for versioned data: disabled 2998 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Scrollable result sets: enabled 2998
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  JDBC3 getGeneratedKeys(): enabled 2998
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Connection release mode: auto 3003
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Maximum outer join fetch depth: 2 3003
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Default batch fetch size: 1 3003
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Generate SQL with comments: disabled
  3003 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Order SQL updates by primary key:
  disabled 3003 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Order SQL inserts for batching:
  disabled 3003 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Query translator:
  org.hibernate.hql.ast.ASTQueryTranslatorFactory
  3023 [Thread-2] INFO
  org.hibernate.hql.ast.ASTQueryTranslatorFactory
  - Using ASTQueryTranslatorFactory 3023 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Query language substitutions: {} 3023
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  JPA-QL strict compliance: disabled
  3023 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Second-level cache: enabled 3023
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Query cache: disabled 3029 [Thread-2]
  INFO org.hibernate.cfg.SettingsFactory
  - Cache region factory : org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge
  3074 [Thread-2] INFO
  org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge
  - Cache provider: org.hibernate.cache.HashtableCacheProvider
  3084 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Optimize cache for minimal puts:
  disabled 3084 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Structured second-level cache entries:
  disabled 3131 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Echoing all SQL to stdout 3138
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Statistics: disabled 3138 [Thread-2]
  INFO org.hibernate.cfg.SettingsFactory
  - Deleted entity synthetic identifier rollback: disabled 3138 [Thread-2]
  INFO org.hibernate.cfg.SettingsFactory
  - Default entity-mode: pojo 3138 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Named query checking : enabled 3138
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Check Nullability in Core (should be
  disabled when Bean Validation is on):
  enabled 3239 [Thread-2] INFO
  org.hibernate.impl.SessionFactoryImpl
  - building session factory 3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [blob] overrides
  previous :
  org.hibernate.type.BlobType@17f7be7b
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [java.sql.Blob]
  overrides previous :
  org.hibernate.type.BlobType@17f7be7b
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [materialized_clob]
  overrides previous :
  org.hibernate.type.MaterializedClobType@9fa8988
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration
  [wrapper_materialized_blob] overrides
  previous :
  org.hibernate.type.WrappedMaterializedBlobType@1f5b44d6
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [clob] overrides
  previous :
  org.hibernate.type.ClobType@21044daf
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [java.sql.Clob]
  overrides previous :
  org.hibernate.type.ClobType@21044daf
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [characters_clob]
  overrides previous :
  org.hibernate.type.PrimitiveCharacterArrayClobType@21882d18
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration
  [wrapper_characters_clob] overrides
  previous :
  org.hibernate.type.CharacterArrayClobType@734893da
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [materialized_blob]
  overrides previous :
  org.hibernate.type.MaterializedBlobType@21e30857
  3379 [Thread-2] INFO
  org.hibernate.impl.SessionFactoryObjectFactory
  - Not binding factory to JNDI, no JNDI name configured
  11.04.2011 18:34:36 org.apache.catalina.core.ApplicationContext
  log INFO: Initializing Spring
  FrameworkServlet 'springMessageBroker'
  11.04.2011 18:34:36 org.apache.coyote.AbstractProtocolHandler
  start INFO: Starting ProtocolHandler
  ["http-bio-8080"]
  11.04.2011 18:34:36 org.apache.coyote.AbstractProtocolHandler
  start INFO: Starting ProtocolHandler
  ["ajp-bio-8009"]
  11.04.2011 18:34:36 org.apache.catalina.startup.Catalina
  start INFO: Server startup in 21332 ms
  11.04.2011 18:49:02 org.apache.catalina.core.StandardWrapperValve
  invoke SCHWERWIEGEND:
  Servlet.service() for servlet
  [RDSDispatchServlet] in context with
  path [/myJavaServer] threw
  exception
  java.lang.NullPointerException    at
  org.dphibernate.utils.HibernateUtil.getSessionFactory(Unknown
  Source)   at
  org.dphibernate.filters.HibernateSessionServletFilter.getSessionFactory(Unknown
  Source)   at
  org.dphibernate.filters.AbstractHibernateSessionServletFilter.doFilter(Unknown
  Source)   at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
    at
  org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
    at
  org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
    at
  org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
    at
  org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at
  java.lang.Thread.run(Thread.java:662)

org.dphibernate.utils.HibernateUtil (snippet)

```<code>private static ISerializerFactory serializerFactory; // should be injected by Spring

public static SessionFactory getSessionFactory() throws HibernateException
{
    return serializerFactory.getSessionFactory(); // but is null on this call?
}
</code>```

答:
The remotingConfig.xml isn't needed, and appears to be what's causing your problems.

Typically, in a Spring configuration, the HibernateUtil class you've shown there isn't used (the SpringContextSerializerFactory returns the SessionFactory to ensure you're getting the correct one from your Spring session)

However, it looks like your remotingConfig.xml file is overwriting the default settings, forcing it to use the old HibernateUtil approach, which is throwing your NPE.

Body:
I am trying to get dpHibernate 2.0 RC6 running on an Apache Tomcat 7.0.12 with BlazeDS 4.0.0.14931, Spring 3.0.5 and Spring-BlazeDS-Integration 1.5.0.M2

With the following configuration the server starts fine, but as soon as I want to access a service or the RDSDispatchServlet via FlashBuilder4 DCD I am getting a NullPointerException. It seems the serializerFactory is not correctly injected into the dpHibernate HibernateUtil. Did I miss something in the configuration in remoting-config.xml?

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
          version="2.5">

   <display-name>Server</display-name>
   <description>Server Side based on BlazeDS, Spring and Hibernate</description>
   <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
   <listener>
    <listener-class>flex.messaging.HttpFlexSession</listener-class>
   </listener>

   <servlet>
     <servlet-name>springMessageBroker</servlet-name>
     <servlet-class>
       org.springframework.web.servlet.DispatcherServlet
     </servlet-class>

     <init-param>
        <param-name>services.configuration.file</param-name>
        <param-value>/WEB-INF/flex/services-config.xml</param-value>
     </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMessageBroker</servlet-name>
    <url-pattern>/messagebroker/*</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>RDSDispatchServlet</servlet-name>
    <servlet-class>flex.rds.server.servlet.FrontEndServlet</servlet-class>
    <init-param>
        <param-name>useAppserverSecurity</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>messageBrokerId</param-name>
        <param-value>_messageBroker</param-value>
    </init-param>
    <load-on-startup>10</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>RDSDispatchServlet</servlet-name>
    <url-pattern>/CFIDE/main/ide.cfm</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
  </welcome-file-list>

  <filter>
    <filter-name>dpHibernateSessionFilter</filter-name>
    <filter-class>org.dphibernate.filters.HibernateSessionServletFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>dpHibernateSessionFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

applicationContext.xml (Spring Servlet default configuration file)

<beans  xmlns="http://www.springframework.org/schema/beans"
    xmlns:flex="http://www.springframework.org/schema/flex"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/flex
        http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <import resource="flexContext.xml" />
    <import resource="dataAccessContext.xml" />
    <import resource="dpHibernateContext.xml"/>

    <tx:annotation-driven />

    <context:annotation-config />

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations" value="/WEB-INF/server.properties" /></bean>

    <context:component-scan base-package="com.mycompany.myproject.*" />
</beans>

flexContext.xml (definitions of services available for flex)

<beans  xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:flex="http://www.springframework.org/schema/flex"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/flex
        http://www.springframework.org/schema/flex/spring-flex-1.0.xsd">

    <flex:message-destination id="chat"/>

    <flex:message-broker services-config-path="/WEB-INF/flex/services-config.xml">
            <flex:remoting-service default-adapter-id="dpHibernateRemotingAdapter" default-channels="my-amf,my-secure-amf" />
            <flex:message-service default-channels="my-streaming-amf,my-polling-amf"/>
    </flex:message-broker>
</beans>

fpHibernateContext.xml (configuration of dpHibernate)

<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:flex="http://www.springframework.org/schema/flex"
      xmlns:security="http://www.springframework.org/schema/security"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xmlns:util="http://www.springframework.org/schema/util"
      xsi:schemaLocation="http://www.springframework.org/schema/aop
                          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                          http://www.springframework.org/schema/beans
                          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                          http://www.springframework.org/schema/context
                          http://www.springframework.org/schema/context/spring-context-3.0.xsd
                          http://www.springframework.org/schema/flex
                          http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
                          http://www.springframework.org/schema/security
                          http://www.springframework.org/schema/security/spring-security-3.0.xsd
                          http://www.springframework.org/schema/tx
                          http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                          http://www.springframework.org/schema/util
                          http://www.springframework.org/schema/util/spring-util-3.0.xsd
                          ">

  <bean id="dpHibernateRemotingAdapter"
    class="org.springframework.flex.core.ManageableComponentFactoryBean">
    <constructor-arg value="org.dphibernate.adapters.RemotingAdapter" />
    <property name="properties">
      <value>
      {"dpHibernate" :
        {
          "serializerFactory" : "org.dphibernate.serialization.SpringContextSerializerFactory"
        }
      }
      </value>
    </property>
  </bean>
  <bean id="dpHibernateMessagingAdapter"
    class="org.springframework.flex.core.ManageableComponentFactoryBean">
    <constructor-arg value="org.dphibernate.adapters.MessagingAdapter" />
  </bean>

  <bean id="dataAccessService" class="org.dphibernate.services.SpringLazyLoadService" autowire="constructor">
    <flex:remoting-destination />
  </bean>

  <bean id="hibernateSessionFilter" class="org.dphibernate.filters.SpringHibernateSessionServletFilter" />

  <bean id="dpHibernateCache"
    class="org.dphibernate.serialization.DPHibernateCache" scope="prototype" />

  <bean id="dpHibernateSerializer"
    class="org.dphibernate.serialization.HibernateSerializer" scope="prototype">
    <property name="pageSize" value="10"/>
  </bean>
  <bean id="dpHibernateDeserializer" class="org.dphibernate.serialization.HibernateDeserializer" scope="prototype" />

  <bean id="objectChangeUpdater"
    class="org.dphibernate.persistence.state.AuthenticatedObjectChangeUpdater"
    scope="prototype">
    <property name="preProcessors" ref="dpHibernatePreProcessors" />
    <property name="postProcessors" ref="dpHibernatePostProcessors" />
  </bean>
</beans>

remoting-config.xml (imported in services-config.xml)

<service id="remoting-service"
         class="flex.messaging.services.RemotingService"
         messageTypes="flex.messaging.messages.RemotingMessage">

  <adapters>
    <adapter-definition id="hibernate-object" class="org.dphibernate.adapters.RemotingAdapter" default="true">
      <properties>
        <hibernate>
          <sessionFactory>
            <class>org.dphibernate.utils.HibernateUtil</class>
            <getCurrentSessionMethod>getCurrentSession</getCurrentSessionMethod>
          </sessionFactory>
        </hibernate>
      </properties>
    </adapter-definition>
    <adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter"/>
  </adapters>

  <default-channels>
    <channel ref="my-amf"/>
  </default-channels>
</service>

NullPointerException (on service access or rds access via FB4 DCD)

startInternal INFO: Starting Servlet
  Engine: Apache Tomcat/7.0.12
  11.04.2011 18:34:19 org.apache.catalina.core.ApplicationContext
  log INFO: Initializing Spring root
  WebApplicationContext 1027 [Thread-2]
  INFO
  org.hibernate.annotations.common.Version
  - Hibernate Commons Annotations 3.2.0.Final 1066 [Thread-2] INFO org.hibernate.cfg.Environment -
  Hibernate 3.6.2.Final 1074 [Thread-2]
  INFO org.hibernate.cfg.Environment -
  hibernate.properties not found 1085
  [Thread-2] INFO
  org.hibernate.cfg.Environment -
  Bytecode provider name : javassist
  1116 [Thread-2] INFO
  org.hibernate.cfg.Environment - using
  JDK 1.4 java.sql.Timestamp handling
  2146 [Thread-2] INFO
  org.hibernate.cfg.Configuration -
  Hibernate Validator not found:
  ignoring 2182 [Thread-2] INFO
  org.hibernate.cfg.search.HibernateSearchEventListenerRegister
  - Unable to find org.hibernate.search.event.FullTextIndexEventListener
  on the classpath. Hibernate Search is
  not enabled. 2194 [Thread-2] INFO
  org.hibernate.connection.ConnectionProviderFactory
  - Initializing connection provider: org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider
  2658 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Database ->
         name : MySQL
      version : 5.0.51a-24+lenny5-log
        major : 5
        minor : 0 2658 [Thread-2] INFO org.hibernate.cfg.SettingsFactory -
  Driver ->
         name : MySQL-AB JDBC Driver
      version : mysql-connector-java-5.1.15 (
  Revision: ${bzr.revision-id} )
        major : 5
        minor : 1 2861 [Thread-2] INFO org.hibernate.dialect.Dialect - Using
  dialect:
  org.hibernate.dialect.MySQLInnoDBDialect
  2981 [Thread-2] INFO
  org.hibernate.transaction.TransactionFactoryFactory
  - Transaction strategy: org.springframework.orm.hibernate3.SpringTransactionFactory
  2991 [Thread-2] INFO
  org.hibernate.transaction.TransactionManagerLookupFactory
  - No TransactionManagerLookup configured (in JTA environment, use of
  read-write or transactional
  second-level cache is not recommended)
  2991 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Automatic flush during
  beforeCompletion(): disabled 2991
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Automatic session close at end of
  transaction: disabled 2991 [Thread-2]
  INFO org.hibernate.cfg.SettingsFactory
  - JDBC batch size: 20 2991 [Thread-2] INFO org.hibernate.cfg.SettingsFactory
  - JDBC batch updates for versioned data: disabled 2998 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Scrollable result sets: enabled 2998
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  JDBC3 getGeneratedKeys(): enabled 2998
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Connection release mode: auto 3003
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Maximum outer join fetch depth: 2 3003
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Default batch fetch size: 1 3003
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Generate SQL with comments: disabled
  3003 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Order SQL updates by primary key:
  disabled 3003 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Order SQL inserts for batching:
  disabled 3003 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Query translator:
  org.hibernate.hql.ast.ASTQueryTranslatorFactory
  3023 [Thread-2] INFO
  org.hibernate.hql.ast.ASTQueryTranslatorFactory
  - Using ASTQueryTranslatorFactory 3023 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Query language substitutions: {} 3023
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  JPA-QL strict compliance: disabled
  3023 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Second-level cache: enabled 3023
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Query cache: disabled 3029 [Thread-2]
  INFO org.hibernate.cfg.SettingsFactory
  - Cache region factory : org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge
  3074 [Thread-2] INFO
  org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge
  - Cache provider: org.hibernate.cache.HashtableCacheProvider
  3084 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Optimize cache for minimal puts:
  disabled 3084 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Structured second-level cache entries:
  disabled 3131 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Echoing all SQL to stdout 3138
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Statistics: disabled 3138 [Thread-2]
  INFO org.hibernate.cfg.SettingsFactory
  - Deleted entity synthetic identifier rollback: disabled 3138 [Thread-2]
  INFO org.hibernate.cfg.SettingsFactory
  - Default entity-mode: pojo 3138 [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Named query checking : enabled 3138
  [Thread-2] INFO
  org.hibernate.cfg.SettingsFactory -
  Check Nullability in Core (should be
  disabled when Bean Validation is on):
  enabled 3239 [Thread-2] INFO
  org.hibernate.impl.SessionFactoryImpl
  - building session factory 3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [blob] overrides
  previous :
  org.hibernate.type.BlobType@17f7be7b
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [java.sql.Blob]
  overrides previous :
  org.hibernate.type.BlobType@17f7be7b
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [materialized_clob]
  overrides previous :
  org.hibernate.type.MaterializedClobType@9fa8988
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration
  [wrapper_materialized_blob] overrides
  previous :
  org.hibernate.type.WrappedMaterializedBlobType@1f5b44d6
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [clob] overrides
  previous :
  org.hibernate.type.ClobType@21044daf
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [java.sql.Clob]
  overrides previous :
  org.hibernate.type.ClobType@21044daf
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [characters_clob]
  overrides previous :
  org.hibernate.type.PrimitiveCharacterArrayClobType@21882d18
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration
  [wrapper_characters_clob] overrides
  previous :
  org.hibernate.type.CharacterArrayClobType@734893da
  3282 [Thread-2] INFO
  org.hibernate.type.BasicTypeRegistry -
  Type registration [materialized_blob]
  overrides previous :
  org.hibernate.type.MaterializedBlobType@21e30857
  3379 [Thread-2] INFO
  org.hibernate.impl.SessionFactoryObjectFactory
  - Not binding factory to JNDI, no JNDI name configured
  11.04.2011 18:34:36 org.apache.catalina.core.ApplicationContext
  log INFO: Initializing Spring
  FrameworkServlet 'springMessageBroker'
  11.04.2011 18:34:36 org.apache.coyote.AbstractProtocolHandler
  start INFO: Starting ProtocolHandler
  ["http-bio-8080"]
  11.04.2011 18:34:36 org.apache.coyote.AbstractProtocolHandler
  start INFO: Starting ProtocolHandler
  ["ajp-bio-8009"]
  11.04.2011 18:34:36 org.apache.catalina.startup.Catalina
  start INFO: Server startup in 21332 ms
  11.04.2011 18:49:02 org.apache.catalina.core.StandardWrapperValve
  invoke SCHWERWIEGEND:
  Servlet.service() for servlet
  [RDSDispatchServlet] in context with
  path [/myJavaServer] threw
  exception
  java.lang.NullPointerException    at
  org.dphibernate.utils.HibernateUtil.getSessionFactory(Unknown
  Source)   at
  org.dphibernate.filters.HibernateSessionServletFilter.getSessionFactory(Unknown
  Source)   at
  org.dphibernate.filters.AbstractHibernateSessionServletFilter.doFilter(Unknown
  Source)   at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
    at
  org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
    at
  org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
    at
  org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
    at
  org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at
  java.lang.Thread.run(Thread.java:662)

org.dphibernate.utils.HibernateUtil (snippet)

private static ISerializerFactory serializerFactory; // should be injected by Spring

public static SessionFactory getSessionFactory() throws HibernateException
{
    return serializerFactory.getSessionFactory(); // but is null on this call?
}


问:
Pass JMeter property value generated by JSR233 sampler to new request
JSR233 sampler with Beanshell been used to convert xml file to encoded string and the value is getting printed in Jmeter console. Able to extract the value within the same sampler using JMeter properties however unable to use the same variable to new request, it goes as null/void.

Test Plan is as below:

.jar file is configured under TestPlan>classpath (Browsed the jar file) which has all methods defined to encode

Added Thread Group>JSR233 sampler

The variable value "a" and property value "storeid" is getting printed on JMeter console, also JMeter logs successfully as "storeid value is : abcdefxcfdfd".

When trying to use this 'storeid' or 'a' value to next http request (ex: path: ${__property(storeid)}), it goes as null or tried with ${a}.

Also tried with vars.get and vars.put, in this case value goes as void.

How to get this variable value passed to the next request?

答:
If you want to set property use props

```<code>props.put("storeid", a);
</code>```

Don't use ${ syntax inside JSR223 script

Body:
If you want to set property use props

props.put("storeid", a);

Don't use ${ syntax inside JSR223 script


问:
Django, browser display filename instead of the picture
I am missing some element to display picture  attatched with each post on a blog created with Django instead of picture file name.

Many solutions to this kind of a problem were:

```<code><img src="{{Object.picture.url}}"/>
</code>```

On template I have tried:

1

```<code><img src="{{ posts.title_picture.url }}"/>
</code>```

2

```<code><img src="{{title_picture.url}}"/>
</code>```

Which resulted respectively in displaying those on the browser:

1.

pictureforpost1.png

2.

img

model:

```<code>class Post(models.Model):
    title = models.CharField(max_length=255, blank=True, null=True)
    title_picture = models.FileField(blank=True,null=True)
</code>```

view:

```<code>class IndexView(ListView):
    model = Post
    context_object_name = 'posts'
</code>```

Seems like Django is finding the file. It is just not displaying the picture.

****Solution thanks to the below answers:****

changed

```<code>STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

to

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
</code>```

and added the following

```<code>urls.py

urlpatterns = [
   ...
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# when served with STATIC_URL and STATIC_ROOT instead it
# is not working so check difference in MEDIA and STATIC.

</code>```

In general I was lacking (and still do :) ) basic knowledge on uploads and displaying the static files.

Thanks.

答:
settings.py :

```<code>'context_processors': [
                ...
                'django.template.context_processors.media',
                ...
            ],
</code>```

templates:

```<code><img src="{{ MEDIA_URL }}{{title_picture.url}}"/>
</code>```

Body:
I am missing some element to display picture  attatched with each post on a blog created with Django instead of picture file name.

Many solutions to this kind of a problem were:

On template I have tried:

1

2

Which resulted respectively in displaying those on the browser:

1.

pictureforpost1.png

2.

img

model:

class Post(models.Model):
    title = models.CharField(max_length=255, blank=True, null=True)
    title_picture = models.FileField(blank=True,null=True)

view:

class IndexView(ListView):
    model = Post
    context_object_name = 'posts'

Seems like Django is finding the file. It is just not displaying the picture.

****Solution thanks to the below answers:****

changed

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

to

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

and added the following

urls.py

urlpatterns = [
   ...
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# when served with STATIC_URL and STATIC_ROOT instead it
# is not working so check difference in MEDIA and STATIC.

In general I was lacking (and still do :) ) basic knowledge on uploads and displaying the static files.

Thanks.

Body:
settings.py :

'context_processors': [
                ...
                'django.template.context_processors.media',
                ...
            ],

templates:

<img src="{{ MEDIA_URL }}{{title_picture.url}}"/>


问:
When to use Django Permissions?
AFAIK, permissions do not filter the queryset.

Django queryset permissions

So, if i have to filter the queryset and return relevant records, what are permissions for? Is there something permission does which filtering cannot?

答:
Let me give an example to explain the difference in a simple way. Assume that you want to build a student management system to be used by both teachers and students. You want to implement a web page that lists the students. But you want to adapt two restrictions while doing that:

If the logged-in user is a student, do not show any students as it might violate privacy. This can be done by Django's built-in permissions.

If the logged-in user is a teacher, do not list all students, but only who are registered to that teacher's course. This is object-level permission and Django does not have a built-in library for that. You can either implement this logic by yourself or use libraries such as django-guardian.

Title: When to use Django Permissions?


问:
Aggregate messages using multiple fields in the message value
I have a single Kafka topic with multiple user info events for multiple different users.
I'm trying to figure out how to to aggregate these together using a number of fields from the value.

For example:

Input Topic:

```<code>1:{"SSN":"123456"}
2:{"twitterHandle":"elvis"}
3:{"SSN":"123456","twitterHandle":"elvis","accountNum": "111111"}
4:{"SSN":"123456"}
5:{"SSN":"000000"}
6:{"twitterHandle":"foo"}
7:{"SSN":"000000","twitterHandle":"foo"}
8:{"SSN":"000000"}
</code>```

I want an Output Topic (aggregated):

```<code>{"SSN":"123456","twitterHandle":"elvis","accountNum": "111111"}
{"SSN":"000000","twitterHandle":"foo"}
</code>```

How can I achieve this with Kafka Streams?
Can I create a KStream from Input Topic and convert it to a KTable to get output Topic?

Update:
The topic contains events from multiple different users. The user identifiers (SSN, twitterHandle) are not fixed. There maybe other ids for a users

答:
If you blindly want to remove message 1 & 2 and keep message 3, you can use a consumer interceptor.

The interceptor would blindly parse the json message, check if the message has both the keys present(and not null) and then successfully send the message ahead, else dont. You dont need a kstream app in that case. Just one interceptor class which needs to be used while consuming the message.

However, if you want to just stitch 1 and 2 without any common key present in between them, I dont think thats possible because we dont know which SSN needs to be merged with which twitter handle.

Let me know if I could help in any other way.

Body:
I have a single Kafka topic with multiple user info events for multiple different users.
I'm trying to figure out how to to aggregate these together using a number of fields from the value.

For example:

Input Topic:

1:{"SSN":"123456"}
2:{"twitterHandle":"elvis"}
3:{"SSN":"123456","twitterHandle":"elvis","accountNum": "111111"}
4:{"SSN":"123456"}
5:{"SSN":"000000"}
6:{"twitterHandle":"foo"}
7:{"SSN":"000000","twitterHandle":"foo"}
8:{"SSN":"000000"}

I want an Output Topic (aggregated):

{"SSN":"123456","twitterHandle":"elvis","accountNum": "111111"}
{"SSN":"000000","twitterHandle":"foo"}

How can I achieve this with Kafka Streams?
Can I create a KStream from Input Topic and convert it to a KTable to get output Topic?

Update:
The topic contains events from multiple different users. The user identifiers (SSN, twitterHandle) are not fixed. There maybe other ids for a users


问:
Append array of object in HTML on click next and previous button
I need to append object in two different div so I used array of object, each time click next button show the next object. The problem is that the next button did no work or make any action.

```<code> var myArr = [
 {id: 0 , question1 : "Question1 Question1 Question1.", question2: "Question2 Question2 Question2"},
 {id: 1 , question1 : "Question1 Question1 Question1.", question2: "Question2 Question2 Question2"},
 {id: 2 , question1 : "Question1 Question1 Question1", question2: "Question2 Question2 Question2."}
 ];

var i = 0;
display(0);

$('#prev__btn').click(function(){
    for (var i = 0; i < myArr.length; i--){
        if( i == myArr.length){
            i--;
            display(i);
        }
    }
});

$('#nxt__btn').click(function(){
    for (var i = 0; i < myArr.length; i++){
        if( i == myArr.length){
            i++;
            display(i);
        }
    }
});

function display(i) {

    $('#question1').empty();
    $('#question1').append(myArr[i].question1);
    $('#question2').empty();
    $('#question2').append(myArr[i].question2);

    if(i == 0)
        $('#prev__btn').hide();
    else
        $('#prev__btn').show();

    if(i == myArr.length-1)
        $('#nxt__btn').hide();
    else
        $('#nxt__btn').show();
}
</code>```

答:
Try

var myArr = [
  {id: 0 , question1 : "Question1-0 Question1-0 Question1-0.", question2: "Question2-0 Question2-0 Question2-0"},
  {id: 1 , question1 : "Question1-1 Question1-1 Question1-1.", question2: "Question2-1 Question2-1 Question2-1"},
  {id: 2 , question1 : "Question1-2 Question1-2 Question1-2", question2: "Question2-2 Question2-2 Question2-2."}
];

let move= n=> box.innerHTML = inj(item.innerHTML, myArr[(idx+=n+k)%k]);
let inj= (s,o)=> s.replace(/\${(.*?)}/g,(x,g)=>o[g]);
let idx= 0, k=myArr.length;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="move(-1)">Prev</button>
<button onclick="move(1)">Next</button>
<div id="box"></div>

<template id="item">
  <div>id: ${id}</div>
  <div>q1: ${question1}</div>
  <div>q2: ${question2}</div>
</template></code>```

Body:
I need to append object in two different div so I used array of object, each time click next button show the next object. The problem is that the next button did no work or make any action.

 var myArr = [
 {id: 0 , question1 : "Question1 Question1 Question1.", question2: "Question2 Question2 Question2"},
 {id: 1 , question1 : "Question1 Question1 Question1.", question2: "Question2 Question2 Question2"},
 {id: 2 , question1 : "Question1 Question1 Question1", question2: "Question2 Question2 Question2."}
 ];

var i = 0;
display(0);

$('#prev__btn').click(function(){
    for (var i = 0; i < myArr.length; i--){
        if( i == myArr.length){
            i--;
            display(i);
        }
    }
});

$('#nxt__btn').click(function(){
    for (var i = 0; i < myArr.length; i++){
        if( i == myArr.length){
            i++;
            display(i);
        }
    }
});

function display(i) {

    $('#question1').empty();
    $('#question1').append(myArr[i].question1);
    $('#question2').empty();
    $('#question2').append(myArr[i].question2);

    if(i == 0)
        $('#prev__btn').hide();
    else
        $('#prev__btn').show();

    if(i == myArr.length-1)
        $('#nxt__btn').hide();
    else
        $('#nxt__btn').show();
}

Body:
Try

var myArr = [
  {id: 0 , question1 : "Question1-0 Question1-0 Question1-0.", question2: "Question2-0 Question2-0 Question2-0"},
  {id: 1 , question1 : "Question1-1 Question1-1 Question1-1.", question2: "Question2-1 Question2-1 Question2-1"},
  {id: 2 , question1 : "Question1-2 Question1-2 Question1-2", question2: "Question2-2 Question2-2 Question2-2."}
];

let move= n=> box.innerHTML = inj(item.innerHTML, myArr[(idx+=n+k)%k]);
let inj= (s,o)=> s.replace(/\${(.*?)}/g,(x,g)=>o[g]);
let idx= 0, k=myArr.length;

<button onclick="move(-1)">Prev</button>
<button onclick="move(1)">Next</button>
<div id="box"></div>

<template id="item">
  <div>id: ${id}</div>
  <div>q1: ${question1}</div>
  <div>q2: ${question2}</div>
</template>


问:
Javascript Stuck in Cache
I have a HTML document which I am developing a .js file for. My problem is, my browser is still using an outdated version of the .js script, which it stored in the cache when it was used. Any modifications to the actual .js script make no difference. Clearing the cache didn't help... How can I fix this?

答:
Ok, sorry guys. Turns out the problem was something totally unrelated... I had some overlapping functions from an old (unneeded) .js script, which were taking priority over the one I'm editing.

Problem solved :)

Title: Javascript Stuck in Cache


问:
How can I get each reducer and its action types?
What is the easy/best way to programmatically get each reducer and its defined action types?

Is it possible to get the action types for each reduce of an NGRX store?

答:
Not sure what you're trying to do here.
The action types are only to provide type safety (and became obsolete with createAction and createReducer in NgRx 8).
When an action gets dispatched, it will be caught by all of the reducers.


问:
How to submit reactive form from outside the form [submitting on click save or update buttons outside the form]
I am working on reactive forms in angular 7, and I need to call submit from a button outside the form.

```<code><input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit()" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit()" >
</form>
</code>```

This function is working fine.

Now, I need to submit the form from multiple buttons i.e.

if user click Save button, the form should be submitted and save

if user click Update button, the form should be submitted and update

For this purpose, I want to pass a flag 'Save' or 'Update' from

```<code><input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit('Save')" />

<input type="button" form="ngForm"  class='Button' value="Update" (click)="detailForm.ngSubmit.emit('Update')" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit(flag)" >
    </form>
</code>```

But I could not submit the form with the 'Save' / 'Update' flag. How could I pass a parameter from Save and Update buttons outside the form to my submit function.

Any fruitful suggestion would be highly appreciated.

答:
Try this, it's working  for me:

in HTML:

```<code><input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit('Save')" />

<input type="button" form="ngForm"  class='Button' value="Update" (click)="detailForm.ngSubmit.emit('Update')" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit($event, detailForm)" id="ngForm" #detailForm="ngForm">
</form>
</code>```

in component.ts:

```<code>onSubmit(isPublished: string, formId: any) {
 console.log(isPublished); //Save or Update
  if (this.gDetailForm.valid) {
   // enter code here
  }
}
</code>```

Working Demo

Body:
I am working on reactive forms in angular 7, and I need to call submit from a button outside the form.

<input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit()" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit()" >
</form>

This function is working fine.

Now, I need to submit the form from multiple buttons i.e.

if user click Save button, the form should be submitted and save

if user click Update button, the form should be submitted and update

For this purpose, I want to pass a flag 'Save' or 'Update' from

<input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit('Save')" />

<input type="button" form="ngForm"  class='Button' value="Update" (click)="detailForm.ngSubmit.emit('Update')" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit(flag)" >
    </form>

But I could not submit the form with the 'Save' / 'Update' flag. How could I pass a parameter from Save and Update buttons outside the form to my submit function.

Any fruitful suggestion would be highly appreciated.

Body:
Try this, it's working  for me:

in HTML:

<input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit('Save')" />

<input type="button" form="ngForm"  class='Button' value="Update" (click)="detailForm.ngSubmit.emit('Update')" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit($event, detailForm)" id="ngForm" #detailForm="ngForm">
</form>

in component.ts:

onSubmit(isPublished: string, formId: any) {
 console.log(isPublished); //Save or Update
  if (this.gDetailForm.valid) {
   // enter code here
  }
}

Working Demo