问:
getAllCellInfo() returns empty list in honor 9n
getAllCellInfo() returns empty list in honor 9n. I am used for to get Cell id and Location area code. So what will i do to get Cell id and Location area code.

I also tried getCellLocation(). And I got Cell id and Location area code when GPS is on. I want to get Cell id and Location area code when the GPS is in off state.(OS Android Oreo).

```<code>TelephonyManager tel = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);

    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }

    CellLocation gsmCellLocation1 = tel.getCellLocation();
    if(gsmCellLocation1!=null){
        Log.e("gsmCellLocation1: ", String.valueOf(gsmCellLocation1));
    }else{
        Log.e("gsmCellLocation1: ", "nul 1");

    }

    GsmCellLocation location33 = (GsmCellLocation) tel.getCellLocation();
    if(location33!=null){
        Log.e("location33: ", String.valueOf(location33));
    }else{
        Log.e("location33: ", "nul 33");

    }

    final List<CellInfo> gsmCellLocation2 = tel.getAllCellInfo();
    if(gsmCellLocation2!=null){
        Log.e("gsmCellLocation2: ", String.valueOf(gsmCellLocation2));
    }else{
        Log.e("gsmCellLocation2: ", "nul 2");

    }
</code>```

答:
use

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</code>```

and use this instead of getCellLocation().

```<code>getNeighboringCellInfo()
</code>```

Body:
getAllCellInfo() returns empty list in honor 9n. I am used for to get Cell id and Location area code. So what will i do to get Cell id and Location area code.

I also tried getCellLocation(). And I got Cell id and Location area code when GPS is on. I want to get Cell id and Location area code when the GPS is in off state.(OS Android Oreo).

TelephonyManager tel = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);

    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }

    CellLocation gsmCellLocation1 = tel.getCellLocation();
    if(gsmCellLocation1!=null){
        Log.e("gsmCellLocation1: ", String.valueOf(gsmCellLocation1));
    }else{
        Log.e("gsmCellLocation1: ", "nul 1");

    }

    GsmCellLocation location33 = (GsmCellLocation) tel.getCellLocation();
    if(location33!=null){
        Log.e("location33: ", String.valueOf(location33));
    }else{
        Log.e("location33: ", "nul 33");

    }

    final List<CellInfo> gsmCellLocation2 = tel.getAllCellInfo();
    if(gsmCellLocation2!=null){
        Log.e("gsmCellLocation2: ", String.valueOf(gsmCellLocation2));
    }else{
        Log.e("gsmCellLocation2: ", "nul 2");

    }

Body:
use

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

and use this instead of getCellLocation().

getNeighboringCellInfo()


来源: stackexchange

问:
Chinese fonts in English Document of Latex
I would like to ask how to write some Chinese characters (simplified) within an English Latex document? I followed some methods suggested online but none of them are working for me. I am using Texworks to compile my document (pdfLatex).

```<code>\usepackage{CJKutf8}
\documentclass{article}
\usepackage{CJKutf8}

\begin{document}
\begin{CJK}{UTF8}{bsmi}
你好吗
\end{CJK}
\end{document}
</code>```

another method is mentioned here,

```<code>\usepackage{CJKutf8}
\newcommand{\zh}[1]{\begin{CJK}{UTF8}{gbsn}#1\end{CJK}}
</code>```

insert whatever Chinese characters you like into the document by typing

```<code> \zh{中文}
</code>```

The error I receive is as following when using the method of CJKutf8 with pdfLaTeX mentioned here,
The log file hopefully contains the information to get MiKTeX going again:

C:\Users\muhd_\AppData\Local\MiKTeX\2.9\miktex\log\miktex-makepk.log
 )
!pdfTeX error: miktex-pdftex.exe (file bsmiu30): Font bsmiu30 at 600 not found
 ==> Fatal error occurred, no output PDF file produced!

Log file is attached here.

答:
The first error in the log file

```<code>The process terminated due to an access violation.
</code>```

suggests that there are some problems with permissions while trying to create the necessary files to use the font for the Chinese letters.

Based on this answer https://tex.stackexchange.com/a/419809/36296 the problem can be fixed by either runing updmap from the command line or Refresh font map files from within the miktex console (in user mode).

ContentLicense: CC BY-SA 4.0

Body:
I would like to ask how to write some Chinese characters (simplified) within an English Latex document? I followed some methods suggested online but none of them are working for me. I am using Texworks to compile my document (pdfLatex).

\usepackage{CJKutf8}
\documentclass{article}
\usepackage{CJKutf8}

\begin{document}
\begin{CJK}{UTF8}{bsmi}
你好吗
\end{CJK}
\end{document}

another method is mentioned here,

\usepackage{CJKutf8}
\newcommand{\zh}[1]{\begin{CJK}{UTF8}{gbsn}#1\end{CJK}}

insert whatever Chinese characters you like into the document by typing

 \zh{中文}

The error I receive is as following when using the method of CJKutf8 with pdfLaTeX mentioned here,
The log file hopefully contains the information to get MiKTeX going again:

C:\Users\muhd_\AppData\Local\MiKTeX\2.9\miktex\log\miktex-makepk.log
 )
!pdfTeX error: miktex-pdftex.exe (file bsmiu30): Font bsmiu30 at 600 not found
 ==> Fatal error occurred, no output PDF file produced!

Log file is attached here.

Body:
The first error in the log file

The process terminated due to an access violation.

suggests that there are some problems with permissions while trying to create the necessary files to use the font for the Chinese letters.

Based on this answer https://tex.stackexchange.com/a/419809/36296 the problem can be fixed by either runing updmap from the command line or Refresh font map files from within the miktex console (in user mode).


问:
Extracing elements from a nested list based on elements of another nested list
I have two nested lists - one containing userids and their individual location and the second nested list containing product first element and list of userid who have purchased the products. I need to find the unique locations of purchasers for each product.

I am able to get the results by using nested for loops. However, i wanted to the same by list comprehension. i don't want to use dataframes or sql commands.

```<code>users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

    prod=[
        (1005,[5]),
        (1004,[2,4,1]),
        (1003,[3,5]),
        (1002,[7,5,2]),
        (1001,[6,5,1])
        ]
    for p in prod:
        prod_loc=[]
        for u in p[1]:
          for uloc in users:

            if u==uloc[0]:
                if uloc[1] not in prod_loc:
                    prod_loc.append(uloc[1])

            else:
                continue
        print (p[0],prod_loc)

</code>```

答:
With defaultdict and set objects ("to find the unique locations of purchasers for each product"):

```<code>from collections import defaultdict
...

users_dict, result = dict(users), defaultdict(set)

for prod_id, user_ids in prod:
    result[prod_id].update(set(users_dict.get(u_id) for u_id in user_ids))

result = list(result.items())
print(result)
</code>```

The output:

```<code>[(1005, {'US'}), (1004, {'EN', 'MX', 'FR'}), (1003, {'US'}), (1002, {'US', 'MX', 'EN'}), (1001, {'EN', 'US', 'MX'})]
</code>```

Body:
I have two nested lists - one containing userids and their individual location and the second nested list containing product first element and list of userid who have purchased the products. I need to find the unique locations of purchasers for each product.

I am able to get the results by using nested for loops. However, i wanted to the same by list comprehension. i don't want to use dataframes or sql commands.

users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

    prod=[
        (1005,[5]),
        (1004,[2,4,1]),
        (1003,[3,5]),
        (1002,[7,5,2]),
        (1001,[6,5,1])
        ]
    for p in prod:
        prod_loc=[]
        for u in p[1]:
          for uloc in users:

            if u==uloc[0]:
                if uloc[1] not in prod_loc:
                    prod_loc.append(uloc[1])

            else:
                continue
        print (p[0],prod_loc)

Body:
With defaultdict and set objects ("to find the unique locations of purchasers for each product"):

from collections import defaultdict
...

users_dict, result = dict(users), defaultdict(set)

for prod_id, user_ids in prod:
    result[prod_id].update(set(users_dict.get(u_id) for u_id in user_ids))

result = list(result.items())
print(result)

The output:

[(1005, {'US'}), (1004, {'EN', 'MX', 'FR'}), (1003, {'US'}), (1002, {'US', 'MX', 'EN'}), (1001, {'EN', 'US', 'MX'})]


问:
Can we have any plugin by which we can add re-run button on jenkins console
I am looking for some kind of plugin or some kind of workaround by which i can have a button to rerun a build with same parameters on console page . so we can directly click and a new build will run without passing new params.

I tried some searches but not able to find this kind of plugin.

答:
This is what i found which is helping me.

https://wiki.jenkins.io/display/JENKINS/Rebuild+Plugin


问:
Android Studio not detecting Microsoft Android Emulator
I installed Microsoft's Android Emulator from here which can now work without disabling Hyper-V on Windows 10. I was following the instructions in this post and everything was working smooth until yesterday. I was successfully able to debug my app in MS android emulator.

Today morning I closed the emulator and started it again. Now, When I start running the app to test it then the MS Android emulator is not showing up in Select Deployment Target window of Android Studio as below. Nexus 5X API 28 emulator visible under Available Virtual Devices is Google's Android emulator which doesn't work with Hyper-V enabled due to reasons mentioned here.

I've already launched the MS Android simulator and it is up and running:

I can see it running in Hyper-V as well as shown below:

Not sure what happened suddenly and it stopped working altogether. Can anyone suggest me the reason behind it or I'm missing something?

答: The adb.exe can be seen as an infected file by antivirius software.  So need to exclude once reinstated.</p>


问:
Initializing StringBuilder to use UTF-16 coder
Consider the following code in Java 11:

```<code>StringBuilder sb = new StringBuilder("one");
sb.append("δύο");  // "two"
</code>```

The first line creates a StringBuilder that uses the Latin1 coder (one byte per character). Then the second line causes the StringBuilder to realise that it needs to use the UTF16 coder instead, so it copies its current contents into a new array before appending the new UTF-16 characters.

The StringBuilder class has a constructor overload that takes an initial capacity argument, which is designed to avoid reallocation if you already know the required size of the string to be built. But if you start with an English string and then append a foreign string, this particular constructor overload is useless as it still reallocates the byte array.

Is there a way to create a StringBuilder instance that uses UTF16 right from the start?

答:
There is nothing in the Java 11 or Java 12 version of StringBuilder that would do this.

The real issue is how important to you is the performance increment that you might get from this.  Profile your application to find out if this unwanted reallocation contributes significantly to your application's overall performance.

If it is going to make a significant difference, you could implement your own version StringBuilder (extending the same interfaces for compatibility).

Alternatively, if you were prepare to wait, you could download the OpenJDK source code and develop / build / test an extension to StringBuilder ... and submit it as a patch for consideration.  (If you included benchmarks that demonstrated a clear performance benefit, that would help the chances of inclusion.)

Body:
Consider the following code in Java 11:

StringBuilder sb = new StringBuilder("one");
sb.append("δύο");  // "two"

The first line creates a StringBuilder that uses the Latin1 coder (one byte per character). Then the second line causes the StringBuilder to realise that it needs to use the UTF16 coder instead, so it copies its current contents into a new array before appending the new UTF-16 characters.

The StringBuilder class has a constructor overload that takes an initial capacity argument, which is designed to avoid reallocation if you already know the required size of the string to be built. But if you start with an English string and then append a foreign string, this particular constructor overload is useless as it still reallocates the byte array.

Is there a way to create a StringBuilder instance that uses UTF16 right from the start?


问:
How to drop rows with condition to match string value
I have this dataframe where one of the columns has values as either "TRUE" or "FALSE". I want to get rid of the rows having column value = "TRUE". The name of that column is "is_duplicate" and dataframe name is "z".

I have tried the following approach:

i=0
while(i<len(z)):
    check=z["is_duplicate"].iloc[i:i+1]
    check=check.to_string(index=False)
    if(check=="TRUE"):
        z=z.drop([i],axis=0)
    i=i+1
```

<p>I also tried 2 more approaches based on the threads given on the similar topic but none of them work for me.</p>

<pre class="lang-py prettyprint-override"><code>z = z.replace('TRUE', np.nan).dropna()
</code>```

z=z[z["is_duplicate"] == "FALSE"]
```

I'm new to coding and have not been able to get this done even though it looks like the most basic thing ever.

答:
use:

```<code>z= z[~z['is_duplicate']=='TRUE']
</code>```

or

```<code>z=z[~z['is_duplicate']=='FALSE']
</code>```

if your z['is_duplicate'].unique() returns [True False 'FALSE'], then first replace 'False' with False(Boolean):

```<code>z['is_duplicate'] = z['is_duplicate'].map({'False': False})
</code>```

Then try:

```<code>z = z[~z['is_duplicate']]
</code>```

Body:
I have this dataframe where one of the columns has values as either "TRUE" or "FALSE". I want to get rid of the rows having column value = "TRUE". The name of that column is "is_duplicate" and dataframe name is "z".

I have tried the following approach:

i=0
while(i<len(z)):
    check=z["is_duplicate"].iloc[i:i+1]
    check=check.to_string(index=False)
    if(check=="TRUE"):
        z=z.drop([i],axis=0)
    i=i+1

I also tried 2 more approaches based on the threads given on the similar topic but none of them work for me.

z = z.replace('TRUE', np.nan).dropna()

z=z[z["is_duplicate"] == "FALSE"]

I'm new to coding and have not been able to get this done even though it looks like the most basic thing ever.

Body:
use:

z= z[~z['is_duplicate']=='TRUE']

or

z=z[~z['is_duplicate']=='FALSE']

if your z['is_duplicate'].unique() returns [True False 'FALSE'], then first replace 'False' with False(Boolean):

z['is_duplicate'] = z['is_duplicate'].map({'False': False})

Then try:

z = z[~z['is_duplicate']]


问:
How to compare request.get result in if else statement
I am making a new script which will take as input list of Ethereum private keys and produce the corresponding addresses with balances, and save the balance in the file if it's found along with private key and the address.

Now, I'm almost certain that my problem lies within the conditional, but cannot figure it out.

Script steps:
 1. Take file of private keys as input (-i flag)
 2. Convert them to public addresses/decode them
 3. Trigger an API call to Etherscan for the information about the address
 4. If the json()["result"] > 0 in API call, write it in output file (-o flag), else print out and sleep for 1 second

Can anyone give a heads up on where I am making mistake?

My code:

```<code>#!/usr/bin/python
import sys, os, argparse, requests, ethereum, binascii, time
from multiprocessing import Pool

def scanether(balance):
    try:
        # Convert private key to address and print the result
        eth_address = ethereum.utils.privtoaddr(INPUTFILE)
        eth_address_hex = binascii.hexlify(eth_address).decode("utf-8")
        eth_balance = requests.get("https://api.etherscan.io/api?module=account&action=balance&address=0x" + eth_address_hex + "&tag=latest&apikey=APIKEYHERE").json()["result"]

        # Check if the result is > 0
        if ('result' != 0) in r.eth_balance:
            print("[*] Address with balance found: " + eth_address_hex + priv)
            # Write match to OUTPUTFILE
            fHandle = open(OUTPUTFILE,'a')
            fHandle.write(eth_address_hex + privkey + "\n")
            fHandle.close()
        else:
            print("balance: {} address: 0x{} privkey: {}".format(float(eth_balance)/100000000, eth_address_hex, priv))
            time.sleep(1)

    except Exception as e:
        return

if __name__ == '__main__':
    print("""
# Finding the Ethereum address with balance
        """)
    # Parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--inputfile', default='input.txt', help='input file')
    parser.add_argument('-o', '--outputfile', default='output.txt', help='output file')
    parser.add_argument('-t', '--threads', default=200, help='threads')
    args = parser.parse_args()

    INPUTFILE=args.inputfile
    OUTPUTFILE=args.outputfile
    MAXPROCESSES=int(args.threads)

    try:
        addresses = open(INPUTFILE, "r").readlines()
    except FileNotFoundError as e:
        print(e)
        exit(e.errno)

    print("Scan in progress...")
    pool = Pool(processes=MAXPROCESSES)
    pool.map(scanether, addresses)
    print("Scan finished.")
</code>```

The output is below:

答:
You can use below code for reference. Before handling the response you should be sure whether the requests you have made is successful.

Refer the below code for further reference.

```<code>import requests
url  = "https://******.com"
r = requests.get(url)
print(r.status_code)
</code>```

Always check whether the status code is 200 before working with response.

Thank You!

Body:
I am making a new script which will take as input list of Ethereum private keys and produce the corresponding addresses with balances, and save the balance in the file if it's found along with private key and the address.

Now, I'm almost certain that my problem lies within the conditional, but cannot figure it out.

Script steps:
 1. Take file of private keys as input (-i flag)
 2. Convert them to public addresses/decode them
 3. Trigger an API call to Etherscan for the information about the address
 4. If the json()["result"] > 0 in API call, write it in output file (-o flag), else print out and sleep for 1 second

Can anyone give a heads up on where I am making mistake?

My code:

#!/usr/bin/python
import sys, os, argparse, requests, ethereum, binascii, time
from multiprocessing import Pool

def scanether(balance):
    try:
        # Convert private key to address and print the result
        eth_address = ethereum.utils.privtoaddr(INPUTFILE)
        eth_address_hex = binascii.hexlify(eth_address).decode("utf-8")
        eth_balance = requests.get("https://api.etherscan.io/api?module=account&action=balance&address=0x" + eth_address_hex + "&tag=latest&apikey=APIKEYHERE").json()["result"]

        # Check if the result is > 0
        if ('result' != 0) in r.eth_balance:
            print("[*] Address with balance found: " + eth_address_hex + priv)
            # Write match to OUTPUTFILE
            fHandle = open(OUTPUTFILE,'a')
            fHandle.write(eth_address_hex + privkey + "\n")
            fHandle.close()
        else:
            print("balance: {} address: 0x{} privkey: {}".format(float(eth_balance)/100000000, eth_address_hex, priv))
            time.sleep(1)

    except Exception as e:
        return

if __name__ == '__main__':
    print("""
# Finding the Ethereum address with balance
        """)
    # Parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--inputfile', default='input.txt', help='input file')
    parser.add_argument('-o', '--outputfile', default='output.txt', help='output file')
    parser.add_argument('-t', '--threads', default=200, help='threads')
    args = parser.parse_args()

    INPUTFILE=args.inputfile
    OUTPUTFILE=args.outputfile
    MAXPROCESSES=int(args.threads)

    try:
        addresses = open(INPUTFILE, "r").readlines()
    except FileNotFoundError as e:
        print(e)
        exit(e.errno)

    print("Scan in progress...")
    pool = Pool(processes=MAXPROCESSES)
    pool.map(scanether, addresses)
    print("Scan finished.")

The output is below:

Body:
You can use below code for reference. Before handling the response you should be sure whether the requests you have made is successful.

Refer the below code for further reference.

import requests
url  = "https://******.com"
r = requests.get(url)
print(r.status_code)

Always check whether the status code is 200 before working with response.

Thank You!


问:
How to solve 'The column label 'Avg_Threat_Score' is not unique.'? issue in pandas
When running the code I am facing following error.
error - The column label 'Avg_Threat_Score' is not unique.

I was creating a pivot table and wanted to sort the value from high to low.

```<code>pt = df.pivot_table(index = 'User Name',values = ['Threat Score', 'Score'],
        aggfunc = {
                   'Threat Score': np.mean,
                   'Score' :[np.mean, lambda x: len(x.dropna())]
                  },
        margins = False)

new_col =['User Name Count', 'AVG_TH_Score', 'Avg_Threat_Score']
pt.columns = [new_col]
#befor this code is working, after that now working
df = df.reindex(pt.sort_values
                    (by = 'Avg_Threat_Score',ascending=False).index)
</code>```

need to sort the values high low for column 'Avg_Threat_Score'

答:
```<code>pt = df.pivot_table(index = 'User Name', values = ['Threat Score', 'Score','Source IP'] ,
                    aggfunc = {"Source IP" : 'count',
                              'Threat Score':np.mean,
                               'Score': np.mean})

pt = pt.sort_values('Threat Score', ascending = False)
new_cols = ['Avg_Score', 'Count', 'Avg_ThreatScore']
pt.columns = new_cols
</code>```

Body:
When running the code I am facing following error.
error - The column label 'Avg_Threat_Score' is not unique.

I was creating a pivot table and wanted to sort the value from high to low.

pt = df.pivot_table(index = 'User Name',values = ['Threat Score', 'Score'],
        aggfunc = {
                   'Threat Score': np.mean,
                   'Score' :[np.mean, lambda x: len(x.dropna())]
                  },
        margins = False)

new_col =['User Name Count', 'AVG_TH_Score', 'Avg_Threat_Score']
pt.columns = [new_col]
#befor this code is working, after that now working
df = df.reindex(pt.sort_values
                    (by = 'Avg_Threat_Score',ascending=False).index)

need to sort the values high low for column 'Avg_Threat_Score'


问:
Express handling URIError: Failed to decode param
```<code>var express = require('express');
var app = express();

app.get('*', function (req, res) {
    var host = req.get('Host');
    return res.redirect(['https://', host, req.url].join(''));
});

var server = app.listen(8080, function () {
  console.log('starting');
});
</code>```

I have a simple script that redirects http to https. This is working fine except when there is a malformed url for example: website.com/%c0%ae%c0%ae. It displays something like:

```<code>URIError: Failed to decode param '/%c0%ae%c0%ae'
   at decodeURIComponent (native)
   at decode_param (/...<PROJECT DIRECTORY>.../node_modules/express/lib/router/layer.js:167:12)
   at Layer.match (/.../node_modules/express/lib/router/layer.js:143:15)
   at matchLayer (/.../node_modules/express/lib/router/index.js:557:18)
   at next (/.../node_modules/express/lib/router/index.js:216:15)
   at expressInit (/.../node_modules/express/lib/middleware/init.js:33:5)
   at Layer.handle [as handle_request] (/.../node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (/.../node_modules/express/lib/router/index.js:312:13)
   at /.../node_modules/express/lib/router/index.js:280:7
   at Function.process_params (/.../node_modules/express/lib/router/index.js:330:12)
</code>```

It's not nice when a user can randomly see where my project files are in the server. Any way to handle this error?

答:
```<code>var express = require('express');
var app = express();

// handles 400 error
app.use((err, req, res, next) => {
  if (!err) return next();
  return res.status(400).json({
    status: 400,
    error: 'OOps! Bad request',
  });
});
</code>```

Edited:
The code snippet should be placed as the last route, it checks if there is an error that was skipped by other routes, which obviously there is, and sends a default response. This error happens when you add % as last character of an API endpoint..

ContentLicense: CC BY-SA 3.0

Body:
var express = require('express');
var app = express();

app.get('*', function (req, res) {
    var host = req.get('Host');
    return res.redirect(['https://', host, req.url].join(''));
});

var server = app.listen(8080, function () {
  console.log('starting');
});

I have a simple script that redirects http to https. This is working fine except when there is a malformed url for example: website.com/%c0%ae%c0%ae. It displays something like:

URIError: Failed to decode param '/%c0%ae%c0%ae'
   at decodeURIComponent (native)
   at decode_param (/...<PROJECT DIRECTORY>.../node_modules/express/lib/router/layer.js:167:12)
   at Layer.match (/.../node_modules/express/lib/router/layer.js:143:15)
   at matchLayer (/.../node_modules/express/lib/router/index.js:557:18)
   at next (/.../node_modules/express/lib/router/index.js:216:15)
   at expressInit (/.../node_modules/express/lib/middleware/init.js:33:5)
   at Layer.handle [as handle_request] (/.../node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (/.../node_modules/express/lib/router/index.js:312:13)
   at /.../node_modules/express/lib/router/index.js:280:7
   at Function.process_params (/.../node_modules/express/lib/router/index.js:330:12)

It's not nice when a user can randomly see where my project files are in the server. Any way to handle this error?

Body:
var express = require('express');
var app = express();

// handles 400 error
app.use((err, req, res, next) => {
  if (!err) return next();
  return res.status(400).json({
    status: 400,
    error: 'OOps! Bad request',
  });
});

Edited:
The code snippet should be placed as the last route, it checks if there is an error that was skipped by other routes, which obviously there is, and sends a default response. This error happens when you add % as last character of an API endpoint..


问:
What will we do after Access?
Microsoft seems hell-bent on deprecating the swiss-army-knife of database tools. What else comes close for facading/file-swapping/cloning/name-your-acronym-connecting arbitrary database servers/spreadsheets/CSV's/flatfiles?

What weird kinds of functionality have you squeezed out of Access? And what else is there to take its place?

答:
Access is just migrating to more of either a single user on a desktop or a few users on a shared database file without much security. If you want to take it to a slightly higher level, use Access as a frontend to SQL Server.

Well now it seems Access 2010 is looking to get the hooks into SharePoint in an attempt to "web enable" the Access application. There are even host sites catering to this technology. Maybe all those who were concerned Access couldn't scale can fear no more?

OwnerDisplayName: doofledorfer

ContentLicense: CC BY-SA 2.5

Title: What will we do after Access?

LastEditorDisplayName: le dorfier

OwnerDisplayName: Guiness


问:
Equivalent of template context in Pyramid (pylons user)
What is the equivalent of template context in Pyramid?

Does the IBeforeRender event in pyramid have anything to with this? I've gone through the official documentation but diffcult to understand what the IBeforeRender event is exactly.

答:
Pyramid already provides a tmpl_context on its Request object, so pretty simply you just have to subscribe a BeforeRender event to add it to the renderer globals:

```<code>def add_renderer_globals(event):
    event['c'] = request.tmpl_context
    event['tmpl_context'] = request.tmpl_context

config.add_subscriber(add_renderer_globals, 'pyramid.events.BeforeRender')
</code>```

From now on in your code when you receive a request, you can set parameters on it:

```<code>request.tmpl_context.name = 'Bob'
</code>```

And subsequently your template may reference the name variable:

```<code>${ c.name }
</code>```

Body:
Pyramid already provides a tmpl_context on its Request object, so pretty simply you just have to subscribe a BeforeRender event to add it to the renderer globals:

def add_renderer_globals(event):
    event['c'] = request.tmpl_context
    event['tmpl_context'] = request.tmpl_context

config.add_subscriber(add_renderer_globals, 'pyramid.events.BeforeRender')

From now on in your code when you receive a request, you can set parameters on it:

request.tmpl_context.name = 'Bob'

And subsequently your template may reference the name variable:

${ c.name }


问:
How to parse JSON file with multiple objects
I am trying to parse a JSON file which is containing multiple JSON objects. Here is my code:

```<code>{
    "obj1": {
        "type": "object",
        "permission": "r",
        "obj2": {
            "type": "param",
            "permission": "r/w"
        },
        "obj3": {
            "type": "param",
            "permission": "r"
        },
        "obj4": {
            "type": "object",
            "permission": "r",
            "obj5": {
                "type": "param",
                "permission": "r/w"
            },
            "obj6": {
                "type": "param",
                "permission": "r"
            },
            "obj7": {
                "type": "object",
                "permission": "r",
                "obj8": {
                    "type": "param",
                    "permission": "r/w"
                },
                "obj9": {
                    "type": "param",
                    "permission": "r"
                }
            }
        }
    }
}
</code>```

I had tried single object parsing response in JSON, that I able to fetch. But I don't not know how to parse the JSON object with Multiple nodes.

For each JSON obejct , I don't also know its name (obj1, obj2, ..)

I want in output as result:

```<code>obj1: has 2 param and 1 object
obj2: has 2 param and 1 object
obj3: has 2 param
</code>```

Is there any way with python to parse JSON file with multiple objects?

答:
try this:</p>

```<code>op = json.loads(json_string)
for i,(key,value) in enumerate(op.items()):
    objects = 0
    params = len(value)
    if isinstance(value,dict):
        for k,v in value.items():
            if isinstance(v,dict):
                objects +=1

    print("Object {i} has {params} params and {objects} objects".format(i=i+1,params=params-objects,objects=obj
</code>```

Body:
I am trying to parse a JSON file which is containing multiple JSON objects. Here is my code:

{
    "obj1": {
        "type": "object",
        "permission": "r",
        "obj2": {
            "type": "param",
            "permission": "r/w"
        },
        "obj3": {
            "type": "param",
            "permission": "r"
        },
        "obj4": {
            "type": "object",
            "permission": "r",
            "obj5": {
                "type": "param",
                "permission": "r/w"
            },
            "obj6": {
                "type": "param",
                "permission": "r"
            },
            "obj7": {
                "type": "object",
                "permission": "r",
                "obj8": {
                    "type": "param",
                    "permission": "r/w"
                },
                "obj9": {
                    "type": "param",
                    "permission": "r"
                }
            }
        }
    }
}

I had tried single object parsing response in JSON, that I able to fetch. But I don't not know how to parse the JSON object with Multiple nodes.

For each JSON obejct , I don't also know its name (obj1, obj2, ..)

I want in output as result:

obj1: has 2 param and 1 object
obj2: has 2 param and 1 object
obj3: has 2 param

Is there any way with python to parse JSON file with multiple objects?

Body:
try this:

op = json.loads(json_string)
for i,(key,value) in enumerate(op.items()):
    objects = 0
    params = len(value)
    if isinstance(value,dict):
        for k,v in value.items():
            if isinstance(v,dict):
                objects +=1

    print("Object {i} has {params} params and {objects} objects".format(i=i+1,params=params-objects,objects=obj


问:
PowerShell Get-WmiObject : Out of memory error?
I am trying to learn to script with WMI object & PowerShell, so I'm not sure why the simple script below does not work for some server but work for the other:

```<code>$Server = 'PRODDB17-V'

Get-WmiObject -ComputerName $Server -Class Win32_LogicalDisk -Filter "DriveType = 3" | ft -AutoSize
Get-WmiObject -Query "SELECT * FROM Win32_Service WHERE DisplayName LIKE '%SQL%'" -ErrorAction Stop -ComputerName $Server | ft -AutoSize
</code>```

I got the below error like below:

```<code>DeviceID DriveType ProviderName    FreeSpace          Size VolumeName
-------- --------- ------------    ---------          ---- ----------
C:               3               50624507904  104751689728 SYSTEM
D:               3              135013552128 1915396026368 DATA
L:               3               71224967168  167772155904 LOGS
S:               3              131093495808 2198886936576 SQL
P:               3              107122515968  644108775424 PageFile
T:               3                8489771008   42946523136 TEMPDB

Get-WmiObject : Out of memory
At line:5 char:1
+ Get-WmiObject -Query "SELECT * FROM Win32_Service WHERE DisplayName LIKE '%SQL%' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
</code>```

答:
By default, powershell will be allocated 150 MB of memory, this may cause some of the command to fail.

Use the following command to increase the limit (run from elevated PS instance) and restart the 'Windows Management Instrumentation' Service.

```<code>set-item wsman:localhost\Shell\MaxMemoryPerShellMB 512
</code>```

Increase the limit based on your Physical memory.

Body:
I am trying to learn to script with WMI object & PowerShell, so I'm not sure why the simple script below does not work for some server but work for the other:

$Server = 'PRODDB17-V'

Get-WmiObject -ComputerName $Server -Class Win32_LogicalDisk -Filter "DriveType = 3" | ft -AutoSize
Get-WmiObject -Query "SELECT * FROM Win32_Service WHERE DisplayName LIKE '%SQL%'" -ErrorAction Stop -ComputerName $Server | ft -AutoSize

I got the below error like below:

DeviceID DriveType ProviderName    FreeSpace          Size VolumeName
-------- --------- ------------    ---------          ---- ----------
C:               3               50624507904  104751689728 SYSTEM
D:               3              135013552128 1915396026368 DATA
L:               3               71224967168  167772155904 LOGS
S:               3              131093495808 2198886936576 SQL
P:               3              107122515968  644108775424 PageFile
T:               3                8489771008   42946523136 TEMPDB

Get-WmiObject : Out of memory
At line:5 char:1
+ Get-WmiObject -Query "SELECT * FROM Win32_Service WHERE DisplayName LIKE '%SQL%' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Body:
By default, powershell will be allocated 150 MB of memory, this may cause some of the command to fail.

Use the following command to increase the limit (run from elevated PS instance) and restart the 'Windows Management Instrumentation' Service.

set-item wsman:localhost\Shell\MaxMemoryPerShellMB 512

Increase the limit based on your Physical memory.


问:
Combining in a row results from two tab
I need to create a mysql query that should get only one row result from two tables.

I have a table called users and a table called users_sports.

```<code>SELECT * FROM users WHERE id = 71
SELECT user_sport_sport FROM users.sports WHERE user_sport_user = 71
</code>```

I would need a query result in only one row that has all users values from table users and all user_sport_sport values for a specific user.

For example: id=71, username="mike2"...sport1="Basketball",sport2="Soccer".

EDIT tb_user_sports

Table users

Table tb_sports

答:
You can use group_concat to fetch all the sports for that user id

```<code>select u.name, GROUP_CONCAT(ts.sport_name) sports from users u
join tb_user_sports tus ON tus.user_sport_user = u.id
left join tb_sports ts ON ts.id_sport = tus.user_sport_sport
where u.id = 72
group by u.id
</code>```

Source:  https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat

For alias: link1 and link2

Title: Combining in a row results from two tab

Body:
I need to create a mysql query that should get only one row result from two tables.

I have a table called users and a table called users_sports.

SELECT * FROM users WHERE id = 71
SELECT user_sport_sport FROM users.sports WHERE user_sport_user = 71

I would need a query result in only one row that has all users values from table users and all user_sport_sport values for a specific user.

For example: id=71, username="mike2"...sport1="Basketball",sport2="Soccer".

EDIT tb_user_sports

Table users

Table tb_sports

Body:
You can use group_concat to fetch all the sports for that user id

select u.name, GROUP_CONCAT(ts.sport_name) sports from users u
join tb_user_sports tus ON tus.user_sport_user = u.id
left join tb_sports ts ON ts.id_sport = tus.user_sport_sport
where u.id = 72
group by u.id

Source:  https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat

For alias: link1 and link2


问:
error: ALTER TYPE ... ADD cannot run inside a transaction block
I am trying to add new type value to my existing types in PostgreSQL. But I get the following error

error: ALTER TYPE ... ADD cannot run inside a transaction block

The query I used to add a new value to the type is

```<code>ALTER TYPE public.request_type ADD VALUE "Check";
</code>```

I am actually running above query in migrations file which is created using node-pg-migrate

Here public is my schema.

Any idea why this is failing?

Edit:

The below query executes fine when execute it in pgadmin

```<code>ALTER TYPE public.request_type ADD VALUE "Check";
</code>```

But when I run above command through node-pg-migrate migrations it fails and throws above error

答:
As it was mentioned above you can't edit enum within transaction block. But you can create the new one. Here are the steps:

Change type from request_type to varchar for all columns/tables which use this type:

```<code>ALTER TABLE table_name
    ALTER COLUMN column_name TYPE VARCHAR(255);
</code>```

Drop and create again request_type enum:

```<code>DROP TYPE IF EXISTS request_type;
CREATE TYPE request_type AS ENUM (
    'OLD_VALUE_1',
    'OLD_VALUE_2',
    'NEW_VALUE_1',
    'NEW_VALUE_2'
);
</code>```

Revert type from varchar to request_type for all columns/tables (revert step one):

```<code>ALTER TABLE table_name
    ALTER COLUMN column_name TYPE request_type
    USING (column_name::request_type);
</code>```

Body:
I am trying to add new type value to my existing types in PostgreSQL. But I get the following error

error: ALTER TYPE ... ADD cannot run inside a transaction block

The query I used to add a new value to the type is

ALTER TYPE public.request_type ADD VALUE "Check";

I am actually running above query in migrations file which is created using node-pg-migrate

Here public is my schema.

Any idea why this is failing?

Edit:

The below query executes fine when execute it in pgadmin

ALTER TYPE public.request_type ADD VALUE "Check";

But when I run above command through node-pg-migrate migrations it fails and throws above error

Body:
As it was mentioned above you can't edit enum within transaction block. But you can create the new one. Here are the steps:

Change type from request_type to varchar for all columns/tables which use this type:

ALTER TABLE table_name
    ALTER COLUMN column_name TYPE VARCHAR(255);

Drop and create again request_type enum:

DROP TYPE IF EXISTS request_type;
CREATE TYPE request_type AS ENUM (
    'OLD_VALUE_1',
    'OLD_VALUE_2',
    'NEW_VALUE_1',
    'NEW_VALUE_2'
);

Revert type from varchar to request_type for all columns/tables (revert step one):

ALTER TABLE table_name
    ALTER COLUMN column_name TYPE request_type
    USING (column_name::request_type);


问:
How to get values from JSON decoded PHP multidimmensionnal array ? (PayPal API)
I'm implementing PayPal payments in my website.

The Paypal API sends me the order details through JSON to my success.php script.

I want to get each variable sent and store it in my database.

So I get the JSON data with :

$RAW=file_get_contents('php://input');

```

<p>The data I get looks like this (print_r of $RAW) :</p>

```{"id":"XXXXXXXXXXXXX-XXXXXXXXX","event_version":"1.0","create_time":"2019-05-30T09:58:56.756Z","resource_type":"capture","resource_version":"2.0","event_type":"PAYMENT.CAPTURE.COMPLETED","summary":"Payment completed for EUR 10.0 EUR","resource":{"id":"XXXXXXXXXXXXXXXXXXX","amount":{"currency_code":"EUR","value":"10.00"},"final_capture":true,"seller_protection":{"status":"ELIGIBLE","dispute_categories":["ITEM_NOT_RECEIVED","UNAUTHORIZED_TRANSACTION"]},"seller_receivable_breakdown":{"gross_amount":{"currency_code":"EUR","value":"10.00"},"paypal_fee":{"currency_code":"EUR","value":"0.59"},"net_amount":{"currency_code":"EUR","value":"9.41"}},"status":"COMPLETED","create_time":"2019-05-30T09:58:52Z","update_time":"2019-05-30T09:58:52Z","links":[{"href":"https://api.sandbox.paypal.com/v2/payments/captures/XXXXXXXXXXXXXXX","rel":"self","method":"GET"},{"href":"https://api.sandbox.paypal.com/v2/payments/captures/XXXXXXXXXXXXX/refund","rel":"refund","method":"POST"},{"href":"https://api.sandbox.paypal.com/v2/checkout/orders/XXXXXXXXXXXXXX","rel":"up","method":"GET"}]},"links":[{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/XXXXXXXXXXXXX-XXXXXXXXXXX","rel":"self","method":"GET"},{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/XXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXX/resend","rel":"resend","method":"POST"}]}
```

<p>I decode it in an Array with :</p>

<pre class="lang-php prettyprint-override"><code>$response=json_decode($RAW, true);
</code>```

I get this array (print_r of $response) :

Array
(
    [id] => XXXXXXXXXXX-XXXXXXXXXX
    [event_version] => 1.0
    [create_time] => 2019-05-30T09:58:56.756Z
    [resource_type] => capture
    [resource_version] => 2.0
    [event_type] => PAYMENT.CAPTURE.COMPLETED
    [summary] => Payment completed for EUR 10.0 EUR
    [resource] => Array
        (
            [id] => XXXXXXXXXXXXX
            [amount] => Array
                (
                    [currency_code] => EUR
                    [value] => 10.00
                )

            [final_capture] => 1
            [seller_protection] => Array
                (
                    [status] => ELIGIBLE
                    [dispute_categories] => Array
                        (
                            [0] => ITEM_NOT_RECEIVED
                            [1] => UNAUTHORIZED_TRANSACTION
                        )

                )

            [seller_receivable_breakdown] => Array
                (
                    [gross_amount] => Array
                        (
                            [currency_code] => EUR
                            [value] => 10.00
                        )

                    [paypal_fee] => Array
                        (
                            [currency_code] => EUR
                            [value] => 0.59
                        )

                    [net_amount] => Array
                        (
                            [currency_code] => EUR
                            [value] => 9.41
                        )

                )

            [status] => COMPLETED
            [create_time] => 2019-05-30T09:58:52Z
            [update_time] => 2019-05-30T09:58:52Z
            [links] => Array
                (
                    [0] => Array
                        (
                            [href] => https://api.sandbox.paypal.com/v2/payments/captures/XXXXXXXXXXX
                            [rel] => self
                            [method] => GET
                        )

                    [1] => Array
                        (
                            [href] => https://api.sandbox.paypal.com/v2/payments/captures/XXXXXXXXXXXX/refund
                            [rel] => refund
                            [method] => POST
                        )

                    [2] => Array
                        (
                            [href] => https://api.sandbox.paypal.com/v2/checkout/orders/XXXXXXXXXXXXXXX
                            [rel] => up
                            [method] => GET
                        )

                )

        )
    [links] => Array
        (
            [0] => Array
                (
                    [href] => https://api.sandbox.paypal.com/v1/notifications/webhooks-events/XXXXXXXXX-XXXXXX
                    [rel] => self
                    [method] => GET
                )

            [1] => Array
                (
                    [href] => https://api.sandbox.paypal.com/v1/notifications/webhooks-events/XXXXXXX-XXXXXXXXX/resend
                    [rel] => resend
                    [method] => POST
                )

        )

)
```

<p>But when I try to insert it in the database :</p>

<pre class="lang-php prettyprint-override"><code><?php
$RAW=file_get_contents('php://input');
$response=json_decode($RAW, true);

$sqluser="xxxxxxx";
$sqlpass="xxxx";
$database="xxxxxxxx";

$query="INSERT INTO testpaypal(

        webhookId,
        event_version,
        create_time,
        resource_type,
        resource_version,
        event_type,
        summary,
        resource__id,
        resource__amount__currency_code,
        resource__amount__value,
        resource__final_capture,
        resource__seller_protection__status,
        resource__seller_protection__dispute_categories__1,
        resource__seller_protection__dispute_categories__2,
        resource__seller_receivable__gross_amount__currency_code,
        resource__seller_receivable__gross_amount__value,
        resource__seller_receivable__paypal_fee__currency_code,
        resource__seller_receivable__paypal_fee__value,
        resource__seller_receivable__net_amount__currency_code,
        resource__seller_receivable__net_amount__value,
        resource__status,
        resource__create_time,
        resource__update_time,
        resource__links__href1,
        resource__links__rel1,
        resource__links__method1,
        resource__links__href2,
        resource__links__rel2,
        resource__links__method2,
        resource__links__href3,
        resource__links__rel3,
        resource__links__method3,
        links__href1,
        links__rel1,
        links__method1,
        links__href2,
        links__rel2,
        links__method2
                                        )
                                VALUES(
        $response[id],
        $response[event_version],
        $response[create_time],
        $response[resource_type],
        $response[resource_version],
        $response[event_type],
        $response[summary],
        $response[resource][id],
        $response[resource][amount][currency_code],
        $response[resource][amount][value],
        $response[resource][final_capture],
        $response[resource][seller_protection][status],
        $response[resource][seller_protection][dispute_categories][0],
        $response[resource][seller_protection][dispute_categories][1],
        $response[resource][seller_receivable_breakdown][gross_amount][currency_code],
        $response[resource][seller_receivable_breakdown][gross_amount][value],
        $response[resource][seller_receivable_breakdown][paypal_fee][currency_code],
        $response[resource][seller_receivable_breakdown][paypal_fee][value],
        $response[resource][seller_receivable_breakdown][net_amount][currency_code],
        $response[resource][seller_receivable_breakdown][net_amount][value],
        $response[resource][status],
        $response[resource][create_time],
        $response[resource][update_time],
        $response[resource][links][0][href],
        $response[resource][links][0][rel],
        $response[resource][links][0][method],
        $response[resource][links][1][href],
        $response[resource][links][1][rel],
        $response[resource][links][1][method],
        $response[resource][links][2][href],
        $response[resource][links][2][rel],
        $response[resource][links][2][method],
        $response[links][0][href],
        $response[links][0][rel],
        $response[links][0][method],
        $response[links][1]href],
        $response[links][1][rel],
        $response[links][1][method]
                                        );";

try { $db = new PDO("mysql:host=sqlserver;dbname=$database", $sqluser, $sqlpass); }
catch(Exception $e) { echo 'Error : '.$e->getMessage().''; echo 'N° : '.$e->getCode(); }

$result = $db->query($query);

file_put_contents("post.log", print_r($_POST, true));
file_put_contents("get.log", print_r($_GET, true));
file_put_contents("RAW.log", print_r($RAW, true));
file_put_contents("array.log", print_r($response, true));

?>
</code>```

I get this warning :

log  PHP Notice:  Array to string conversion in
  /xxxxxxxxxxxxxxxxxxxxxxxx/success.php on line 57  PHP Notice:  Array
  to string conversion in /xxxxxxxxxxxxxxxxxxxxxxxx/success.php on line
  58  PHP Notice:  Array to string conversion in
  /xxxxxxxxxxxxxxxxxxxxxxxx/success.php on line 59  PHP Notice:  Array
  to string conversion in /xxxxxxxxxxxxxxxxxxxxxxxx/success.php on line
  60  PHP Notice:  Array to string conversion in
  /xxxxxxxxxxxxxxxxxxxxxxxx/success.php on line 61 [...]  PHP Notice:
  Array to string conversion in /xxxxxxxxxxxxxxxxxxxxxxxx/success.php on
  line 87

And nothing is inserted.

What do i do wrong ?

答:
I think you should call your array elements this way:

$response['summary']

You are missing the quotes

Body:
I'm implementing PayPal payments in my website.

The Paypal API sends me the order details through JSON to my success.php script.

I want to get each variable sent and store it in my database.

So I get the JSON data with :

$RAW=file_get_contents('php://input');

The data I get looks like this (print_r of $RAW) :

{"id":"XXXXXXXXXXXXX-XXXXXXXXX","event_version":"1.0","create_time":"2019-05-30T09:58:56.756Z","resource_type":"capture","resource_version":"2.0","event_type":"PAYMENT.CAPTURE.COMPLETED","summary":"Payment completed for EUR 10.0 EUR","resource":{"id":"XXXXXXXXXXXXXXXXXXX","amount":{"currency_code":"EUR","value":"10.00"},"final_capture":true,"seller_protection":{"status":"ELIGIBLE","dispute_categories":["ITEM_NOT_RECEIVED","UNAUTHORIZED_TRANSACTION"]},"seller_receivable_breakdown":{"gross_amount":{"currency_code":"EUR","value":"10.00"},"paypal_fee":{"currency_code":"EUR","value":"0.59"},"net_amount":{"currency_code":"EUR","value":"9.41"}},"status":"COMPLETED","create_time":"2019-05-30T09:58:52Z","update_time":"2019-05-30T09:58:52Z","links":[{"href":"https://api.sandbox.paypal.com/v2/payments/captures/XXXXXXXXXXXXXXX","rel":"self","method":"GET"},{"href":"https://api.sandbox.paypal.com/v2/payments/captures/XXXXXXXXXXXXX/refund","rel":"refund","method":"POST"},{"href":"https://api.sandbox.paypal.com/v2/checkout/orders/XXXXXXXXXXXXXX","rel":"up","method":"GET"}]},"links":[{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/XXXXXXXXXXXXX-XXXXXXXXXXX","rel":"self","method":"GET"},{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/XXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXX/resend","rel":"resend","method":"POST"}]}

I decode it in an Array with :

$response=json_decode($RAW, true);

I get this array (print_r of $response) :

Array
(
    [id] => XXXXXXXXXXX-XXXXXXXXXX
    [event_version] => 1.0
    [create_time] => 2019-05-30T09:58:56.756Z
    [resource_type] => capture
    [resource_version] => 2.0
    [event_type] => PAYMENT.CAPTURE.COMPLETED
    [summary] => Payment completed for EUR 10.0 EUR
    [resource] => Array
        (
            [id] => XXXXXXXXXXXXX
            [amount] => Array
                (
                    [currency_code] => EUR
                    [value] => 10.00
                )

            [final_capture] => 1
            [seller_protection] => Array
                (
                    [status] => ELIGIBLE
                    [dispute_categories] => Array
                        (
                            [0] => ITEM_NOT_RECEIVED
                            [1] => UNAUTHORIZED_TRANSACTION
                        )

                )

            [seller_receivable_breakdown] => Array
                (
                    [gross_amount] => Array
                        (
                            [currency_code] => EUR
                            [value] => 10.00
                        )

                    [paypal_fee] => Array
                        (
                            [currency_code] => EUR
                            [value] => 0.59
                        )

                    [net_amount] => Array
                        (
                            [currency_code] => EUR
                            [value] => 9.41
                        )

                )

            [status] => COMPLETED
            [create_time] => 2019-05-30T09:58:52Z
            [update_time] => 2019-05-30T09:58:52Z
            [links] => Array
                (
                    [0] => Array
                        (
                            [href] => https://api.sandbox.paypal.com/v2/payments/captures/XXXXXXXXXXX
                            [rel] => self
                            [method] => GET
                        )

                    [1] => Array
                        (
                            [href] => https://api.sandbox.paypal.com/v2/payments/captures/XXXXXXXXXXXX/refund
                            [rel] => refund
                            [method] => POST
                        )

                    [2] => Array
                        (
                            [href] => https://api.sandbox.paypal.com/v2/checkout/orders/XXXXXXXXXXXXXXX
                            [rel] => up
                            [method] => GET
                        )

                )

        )
    [links] => Array
        (
            [0] => Array
                (
                    [href] => https://api.sandbox.paypal.com/v1/notifications/webhooks-events/XXXXXXXXX-XXXXXX
                    [rel] => self
                    [method] => GET
                )

            [1] => Array
                (
                    [href] => https://api.sandbox.paypal.com/v1/notifications/webhooks-events/XXXXXXX-XXXXXXXXX/resend
                    [rel] => resend
                    [method] => POST
                )

        )

)

But when I try to insert it in the database :

<?php
$RAW=file_get_contents('php://input');
$response=json_decode($RAW, true);

$sqluser="xxxxxxx";
$sqlpass="xxxx";
$database="xxxxxxxx";

$query="INSERT INTO testpaypal(

        webhookId,
        event_version,
        create_time,
        resource_type,
        resource_version,
        event_type,
        summary,
        resource__id,
        resource__amount__currency_code,
        resource__amount__value,
        resource__final_capture,
        resource__seller_protection__status,
        resource__seller_protection__dispute_categories__1,
        resource__seller_protection__dispute_categories__2,
        resource__seller_receivable__gross_amount__currency_code,
        resource__seller_receivable__gross_amount__value,
        resource__seller_receivable__paypal_fee__currency_code,
        resource__seller_receivable__paypal_fee__value,
        resource__seller_receivable__net_amount__currency_code,
        resource__seller_receivable__net_amount__value,
        resource__status,
        resource__create_time,
        resource__update_time,
        resource__links__href1,
        resource__links__rel1,
        resource__links__method1,
        resource__links__href2,
        resource__links__rel2,
        resource__links__method2,
        resource__links__href3,
        resource__links__rel3,
        resource__links__method3,
        links__href1,
        links__rel1,
        links__method1,
        links__href2,
        links__rel2,
        links__method2
                                        )
                                VALUES(
        $response[id],
        $response[event_version],
        $response[create_time],
        $response[resource_type],
        $response[resource_version],
        $response[event_type],
        $response[summary],
        $response[resource][id],
        $response[resource][amount][currency_code],
        $response[resource][amount][value],
        $response[resource][final_capture],
        $response[resource][seller_protection][status],
        $response[resource][seller_protection][dispute_categories][0],
        $response[resource][seller_protection][dispute_categories][1],
        $response[resource][seller_receivable_breakdown][gross_amount][currency_code],
        $response[resource][seller_receivable_breakdown][gross_amount][value],
        $response[resource][seller_receivable_breakdown][paypal_fee][currency_code],
        $response[resource][seller_receivable_breakdown][paypal_fee][value],
        $response[resource][seller_receivable_breakdown][net_amount][currency_code],
        $response[resource][seller_receivable_breakdown][net_amount][value],
        $response[resource][status],
        $response[resource][create_time],
        $response[resource][update_time],
        $response[resource][links][0][href],
        $response[resource][links][0][rel],
        $response[resource][links][0][method],
        $response[resource][links][1][href],
        $response[resource][links][1][rel],
        $response[resource][links][1][method],
        $response[resource][links][2][href],
        $response[resource][links][2][rel],
        $response[resource][links][2][method],
        $response[links][0][href],
        $response[links][0][rel],
        $response[links][0][method],
        $response[links][1]href],
        $response[links][1][rel],
        $response[links][1][method]
                                        );";

try { $db = new PDO("mysql:host=sqlserver;dbname=$database", $sqluser, $sqlpass); }
catch(Exception $e) { echo 'Error : '.$e->getMessage().''; echo 'N° : '.$e->getCode(); }

$result = $db->query($query);

file_put_contents("post.log", print_r($_POST, true));
file_put_contents("get.log", print_r($_GET, true));
file_put_contents("RAW.log", print_r($RAW, true));
file_put_contents("array.log", print_r($response, true));

?>

I get this warning :

log  PHP Notice:  Array to string conversion in
  /xxxxxxxxxxxxxxxxxxxxxxxx/success.php on line 57  PHP Notice:  Array
  to string conversion in /xxxxxxxxxxxxxxxxxxxxxxxx/success.php on line
  58  PHP Notice:  Array to string conversion in
  /xxxxxxxxxxxxxxxxxxxxxxxx/success.php on line 59  PHP Notice:  Array
  to string conversion in /xxxxxxxxxxxxxxxxxxxxxxxx/success.php on line
  60  PHP Notice:  Array to string conversion in
  /xxxxxxxxxxxxxxxxxxxxxxxx/success.php on line 61 [...]  PHP Notice:
  Array to string conversion in /xxxxxxxxxxxxxxxxxxxxxxxx/success.php on
  line 87

And nothing is inserted.

What do i do wrong ?


问:
Retrieving one value from JSON works, but identical approach on the other value fails
The source .json file is as simple as this:

```<code>{
  "rates": {
    "EURUSD": {
      "rate": 1.112656,
      "timestamp": 1559200864
    }
  },
  "code": 200
}
</code>```

I can return the "timestamp" value, but using the identical approach I cannot return the "rate" value.

This runs with no problems:

```<code>Sub current_eur_usd()

  Dim scriptControl As Object
  Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
  scriptControl.Language = "JScript"
  Dim oJSON As Object

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://www.freeforexapi.com/api/live?pairs=EURUSD", False
    .send
    Set oJSON = scriptControl.Eval("(" + .responsetext + ")")
    .abort
  End With
  MsgBox oJSON.rates.EURUSD.timestamp   '<<< 'timestamp' works, 'rate' fails

  Set oJSON = Nothing
  Set scriptControl = Nothing
End Sub
</code>```

But when I try to replace timestamp with rate, I get the error message highlighting the MsgBox line.

Run-time error '438':

  Object doesn't support this property or method

I think the problem lies in VBA automatically capitalizing rate.

```<code>MsgBox oJSON.rates.EURUSD.rate
</code>```

auto-transforms into

```<code>MsgBox oJSON.rates.EURUSD.Rate
</code>```

How can I return the "rate" value?

答:
Script control will work for 32 bit rather than 64 bit.

The following have the advantage is will work on 32 and 64 bit machines

Using json parser:

I would also use jsonconverter.bas (add then add reference to Microsoft Scripting Runtime) and as it returns a dictionary inside you can test for the rate key

```<code>Option Explicit

Public Sub GetRate()
    Dim json As Object, pairs As String
    pairs = "EURUSD"
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.freeforexapi.com/api/live?pairs=" & pairs, False
        .send
        Set json = JsonConverter.ParseJson(.responseText)
        If json("rates")(pairs).Exists("rate") Then
            Debug.Print json("rates")(pairs)("rate")
        End If
    End With
End Sub
</code>```

Using regex:

```<code>Option Explicit
Public Sub GetQuoteValue()
    Dim json As Object, pairs As String, s As String, re As Object
    Set re = CreateObject("VBScript.RegExp")
    pairs = "EURUSD"
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.freeforexapi.com/api/live?pairs=" & pairs, False
        .send
        s = .responseText
        Debug.Print GetValue(re, s, """rate"":(\d+\.\d+)")
    End With
End Sub

Public Function GetValue(ByVal re As Object, inputString As String, ByVal pattern As String) As String
    With re
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .pattern = pattern
        If .Test(inputString) Then
            GetValue = .Execute(inputString)(0).SubMatches(0)
        Else
            GetValue = "Not found"
        End If
    End With
End Function
</code>```

Using string splitting:

```<code>Option Explicit
Public Sub GetQuoteValue()
    Dim json As Object, pairs As String, s As String, p As String

    pairs = "EURUSD"
    p = """rate"":"
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.freeforexapi.com/api/live?pairs=" & pairs, False
        .send
        s = .responseText
        If InStr(s, p) > 0 Then
            Debug.Print Split(Split(s, p)(1), ",")(0)
        End If
    End With
End Sub
</code>```

Body:
The source .json file is as simple as this:

{
  "rates": {
    "EURUSD": {
      "rate": 1.112656,
      "timestamp": 1559200864
    }
  },
  "code": 200
}

I can return the "timestamp" value, but using the identical approach I cannot return the "rate" value.

This runs with no problems:

Sub current_eur_usd()

  Dim scriptControl As Object
  Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
  scriptControl.Language = "JScript"
  Dim oJSON As Object

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://www.freeforexapi.com/api/live?pairs=EURUSD", False
    .send
    Set oJSON = scriptControl.Eval("(" + .responsetext + ")")
    .abort
  End With
  MsgBox oJSON.rates.EURUSD.timestamp   '<<< 'timestamp' works, 'rate' fails

  Set oJSON = Nothing
  Set scriptControl = Nothing
End Sub

But when I try to replace timestamp with rate, I get the error message highlighting the MsgBox line.

Run-time error '438':

  Object doesn't support this property or method

I think the problem lies in VBA automatically capitalizing rate.

MsgBox oJSON.rates.EURUSD.rate

auto-transforms into

MsgBox oJSON.rates.EURUSD.Rate

How can I return the "rate" value?

Body:
Script control will work for 32 bit rather than 64 bit.

The following have the advantage is will work on 32 and 64 bit machines

Using json parser:

I would also use jsonconverter.bas (add then add reference to Microsoft Scripting Runtime) and as it returns a dictionary inside you can test for the rate key

Option Explicit

Public Sub GetRate()
    Dim json As Object, pairs As String
    pairs = "EURUSD"
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.freeforexapi.com/api/live?pairs=" & pairs, False
        .send
        Set json = JsonConverter.ParseJson(.responseText)
        If json("rates")(pairs).Exists("rate") Then
            Debug.Print json("rates")(pairs)("rate")
        End If
    End With
End Sub

Using regex:

Option Explicit
Public Sub GetQuoteValue()
    Dim json As Object, pairs As String, s As String, re As Object
    Set re = CreateObject("VBScript.RegExp")
    pairs = "EURUSD"
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.freeforexapi.com/api/live?pairs=" & pairs, False
        .send
        s = .responseText
        Debug.Print GetValue(re, s, """rate"":(\d+\.\d+)")
    End With
End Sub

Public Function GetValue(ByVal re As Object, inputString As String, ByVal pattern As String) As String
    With re
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .pattern = pattern
        If .Test(inputString) Then
            GetValue = .Execute(inputString)(0).SubMatches(0)
        Else
            GetValue = "Not found"
        End If
    End With
End Function

Using string splitting:

Option Explicit
Public Sub GetQuoteValue()
    Dim json As Object, pairs As String, s As String, p As String

    pairs = "EURUSD"
    p = """rate"":"
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.freeforexapi.com/api/live?pairs=" & pairs, False
        .send
        s = .responseText
        If InStr(s, p) > 0 Then
            Debug.Print Split(Split(s, p)(1), ",")(0)
        End If
    End With
End Sub


问:
Select an expiredate field
I have created an expiredate field which is generated automatically based on the registerdate field

I've tried a regular query just like i would use for any field (it is mentioned below)

this is the model:

```<code>class UserProfile(models.Model):
    course = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
    phonenumber = models.CharField(max_length=50)
    registerdate = models.DateTimeField()
    expiredate = timezone.now().date() + timedelta(days= 70)
    user = models.OneToOneField(User, on_delete = models.CASCADE)

def __str__(self):
    return "{}" .format(self.user)
</code>```

and this is the query i'm trying to use:

```<code>expire = UserProfile.objects.values('expiredate')
</code>```

I simply want to select the expiredate and use it on my views.py function but the query generates an error:

```<code>'Cannot resolve keyword 'expiredate' into field. Choices are: course, course_id, id, phonenumber, registerdate, user, user_id'
</code>```

答:
expiredate can be a DateField.

```<code>class UserProfile(models.Model):
    expiredate = models.DateField(default=timezone.now().date() + timedelta(days= 70))
</code>```

python manage.py makemigrations

python manage.py migrate

Title: Select an expiredate field

Body:
I have created an expiredate field which is generated automatically based on the registerdate field

I've tried a regular query just like i would use for any field (it is mentioned below)

this is the model:

class UserProfile(models.Model):
    course = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
    phonenumber = models.CharField(max_length=50)
    registerdate = models.DateTimeField()
    expiredate = timezone.now().date() + timedelta(days= 70)
    user = models.OneToOneField(User, on_delete = models.CASCADE)

def __str__(self):
    return "{}" .format(self.user)

and this is the query i'm trying to use:

expire = UserProfile.objects.values('expiredate')

I simply want to select the expiredate and use it on my views.py function but the query generates an error:

'Cannot resolve keyword 'expiredate' into field. Choices are: course, course_id, id, phonenumber, registerdate, user, user_id'

Body:
expiredate can be a DateField.

class UserProfile(models.Model):
    expiredate = models.DateField(default=timezone.now().date() + timedelta(days= 70))

python manage.py makemigrations

python manage.py migrate


问:
Intel OpenCL SDK for FPGA compile kernel for emulation with aoc command gives linker error
I'm trying to compile a kernel for emulation with aoc in the Intel FPGA SDK, I have set all environment variables as possible even using the init_opencl.bat included in the SDK.
I'm running the following line using the visual studio 2017 developers command prompt in order to use visual studio linker:

```<code>aoc -march=emulator -v -board=a10gx my_kernel.cl -o my_kernel.aocx
</code>```

but it always throws a linker error (the errors are in Spanish, sorry about that).

Creando biblioteca libkernel.lib y objeto libkernel.exp

libkernel.obj : error LNK2019: símbolo externo
__imp___translate_sampler_initializer sin resolver al que se hace referencia en la función my_kernel

libkernel.obj : error LNK2019: símbolo externo floorf sin resolver al
que se hace referencia en la función __acl__copysignf

libkernel.obj : error LNK2019: símbolo externo ceilf sin resolver al
que se hace referencia en la función __acl__copysignf

libkernel.obj : error LNK2019: símbolo externo log2 sin resolver al
que se hace referencia en la función __acl__sppow_approx

libkernel.obj : error LNK2019: símbolo externo exp2 sin resolver al
que se hace referencia en la función __acl__sppow_approx

LINK : error LNK2001: símbolo externo _DllMainCRTStartup sin resolver

C:\Program Files (x86)\Microsoft Visual
Studio\2017\Community\VC\Tools\MSVC\14.16.27023\lib\x86\msvcrt.lib :
warning LNK4272: el tipo de máquina de biblioteca 'x86' está en
conflicto con el tipo de máquina de destino 'x64'

C:\Program Files (x86)\Microsoft Visual
Studio\2017\Community\VC\Tools\MSVC\14.16.27023\lib\x86\legacy_stdio_definitions.lib
: warning LNK4272: el tipo de máquina de biblioteca 'x86' está en
conflicto con el tipo de máquina de destino 'x64'

libkernel.dll : fatal error LNK1120: 6 externos sin resolver

I have no idea what else to do.

Note:
The kernel uses image2d objects which I'm not entirely sure are compatible with FPGAs. Actually that's another question.

答:
Answering your questions:

FPGA emulator is not supporting x86 platform, just x86_64 (but I see you are already resolved this I guess).

About images. The SDK isn't supporting image type indeed, but it doesn't mean that aoc will fail during compilation. You will fail later when you try to run your application.

Body:
I'm trying to compile a kernel for emulation with aoc in the Intel FPGA SDK, I have set all environment variables as possible even using the init_opencl.bat included in the SDK.
I'm running the following line using the visual studio 2017 developers command prompt in order to use visual studio linker:

aoc -march=emulator -v -board=a10gx my_kernel.cl -o my_kernel.aocx

but it always throws a linker error (the errors are in Spanish, sorry about that).

Creando biblioteca libkernel.lib y objeto libkernel.exp

libkernel.obj : error LNK2019: símbolo externo
__imp___translate_sampler_initializer sin resolver al que se hace referencia en la función my_kernel

libkernel.obj : error LNK2019: símbolo externo floorf sin resolver al
que se hace referencia en la función __acl__copysignf

libkernel.obj : error LNK2019: símbolo externo ceilf sin resolver al
que se hace referencia en la función __acl__copysignf

libkernel.obj : error LNK2019: símbolo externo log2 sin resolver al
que se hace referencia en la función __acl__sppow_approx

libkernel.obj : error LNK2019: símbolo externo exp2 sin resolver al
que se hace referencia en la función __acl__sppow_approx

LINK : error LNK2001: símbolo externo _DllMainCRTStartup sin resolver

C:\Program Files (x86)\Microsoft Visual
Studio\2017\Community\VC\Tools\MSVC\14.16.27023\lib\x86\msvcrt.lib :
warning LNK4272: el tipo de máquina de biblioteca 'x86' está en
conflicto con el tipo de máquina de destino 'x64'

C:\Program Files (x86)\Microsoft Visual
Studio\2017\Community\VC\Tools\MSVC\14.16.27023\lib\x86\legacy_stdio_definitions.lib
: warning LNK4272: el tipo de máquina de biblioteca 'x86' está en
conflicto con el tipo de máquina de destino 'x64'

libkernel.dll : fatal error LNK1120: 6 externos sin resolver

I have no idea what else to do.

Note:
The kernel uses image2d objects which I'm not entirely sure are compatible with FPGAs. Actually that's another question.


问:
Want to simultaneously open a URL on the next tab and also navigate to a route: React+ React Router V4+ semantic-ui-react
I am having this scenario where in I fetch a particular URL from backend and then on click of a button , I have to open that link in a new tab and also load a component in the current tab using react-router </p>

```<code>
import { Button } from 'semantic-ui-react';
import { Link } from 'react-router-dom';
import * as React from 'react';

this.state={ url: ''} ; // This url I am able to get using fetch

//I get URL from the backend, and then I am trying to set it to href attribute. Routing just works find but link does not get opened in the new tab.

<Link to="/path">
     <a href={this.state.url} target="_blank">
        <Button size="small" fluid >
           Continue
        </Button>
     </a>
</Link>
</code>```

答:
try this:</p>

```<code>onBtnClick = (e) => {
    window.open(this.state.url, '_blank');
    this.props.history.push('/link/to/route/in/current/tab');
}

...

<Button size="small" fluid onClick={this.onBtnClick}>
    Continue
</Button>
</code>```

Body:
I am having this scenario where in I fetch a particular URL from backend and then on click of a button , I have to open that link in a new tab and also load a component in the current tab using react-router

import { Button } from 'semantic-ui-react';
import { Link } from 'react-router-dom';
import * as React from 'react';

this.state={ url: ''} ; // This url I am able to get using fetch

//I get URL from the backend, and then I am trying to set it to href attribute. Routing just works find but link does not get opened in the new tab.

<Link to="/path">

        <Button size="small" fluid >
           Continue
        </Button>

</Link>

Body:
try this:

onBtnClick = (e) => {
    window.open(this.state.url, '_blank');
    this.props.history.push('/link/to/route/in/current/tab');
}

...

<Button size="small" fluid onClick={this.onBtnClick}>
    Continue
</Button>


问:
Cursor over WinForm control (c#, WinForm 4.0)
What is the easiest way to determine if my current cursor position is over a particular (WinForm) control?

I can - of course - calculate the control's position and then check whether the cursor position is within this rectangel. But maybe there is something already existing for this....

I cannot use OnMouseOver event for this, because the decisions must take place within (another) event. In order to further explain here is what I do (in pseudo code). The problem is, when I start the drag event, then move to another control (outside this), release the mouse to finish the drop, the context menu is displayed on the "wrong" control (the drop target). This is what I want to avoid....

```<code> private void TableControlMouseDown(object sender, MouseEventArgs e)
    {
        ...
        // this is a User control with some sub controls

        // when selected start drag and drop
        if (SOMEConditions)
        {
            // start drag and drop operation
            DragAndDropWrapper dragAndDropWrapper = new DragAndDropWrapper(this.ObjectsToDrag, this);
            this._subControl.DoDragDrop(dragAndDropWrapper, DragDropEffects.Copy);
        }

        // context menu

        // check should go here
        // something like "is pt still over "this" or over the drag target ...
        Point pt = this._subControl.PointToClient(Control.MousePosition);
        this._myContextMenu.Show(this._subControl, pt);
    }
</code>```

-- as of today --
See below for the extension method I am using at the moment ...

答:
This is the best solution I have found so far. Actually it is pretty easy (as always once you know how to do it ;-) since PointToClient gives me relative coordinates which drastically reduces the effort .... As an extension method it also is easy to use with all controls.

```<code>    /// <summary>
    ///   Is the mouse pointer over the control?
    /// </summary>
    /// <param name = "control"></param>
    /// <returns></returns>
    public static bool IsMouseOverControl(this Control control)
    {
        if (control == null) throw new ArgumentNullException("control");
        Contract.EndContractBlock();

        Point pt = control.PointToClient(Control.MousePosition);
        return (pt.X >= 0 && pt.Y >= 0 && pt.X <= control.Width && pt.Y <= control.Height);
    }
</code>```

Body:
What is the easiest way to determine if my current cursor position is over a particular (WinForm) control?

I can - of course - calculate the control's position and then check whether the cursor position is within this rectangel. But maybe there is something already existing for this....

I cannot use OnMouseOver event for this, because the decisions must take place within (another) event. In order to further explain here is what I do (in pseudo code). The problem is, when I start the drag event, then move to another control (outside this), release the mouse to finish the drop, the context menu is displayed on the "wrong" control (the drop target). This is what I want to avoid....

 private void TableControlMouseDown(object sender, MouseEventArgs e)
    {
        ...
        // this is a User control with some sub controls

        // when selected start drag and drop
        if (SOMEConditions)
        {
            // start drag and drop operation
            DragAndDropWrapper dragAndDropWrapper = new DragAndDropWrapper(this.ObjectsToDrag, this);
            this._subControl.DoDragDrop(dragAndDropWrapper, DragDropEffects.Copy);
        }

        // context menu

        // check should go here
        // something like "is pt still over "this" or over the drag target ...
        Point pt = this._subControl.PointToClient(Control.MousePosition);
        this._myContextMenu.Show(this._subControl, pt);
    }

-- as of today --
See below for the extension method I am using at the moment ...

Body:
This is the best solution I have found so far. Actually it is pretty easy (as always once you know how to do it ;-) since PointToClient gives me relative coordinates which drastically reduces the effort .... As an extension method it also is easy to use with all controls.

    /// <summary>
    ///   Is the mouse pointer over the control?
    /// </summary>
    /// <param name = "control"></param>
    /// <returns></returns>
    public static bool IsMouseOverControl(this Control control)
    {
        if (control == null) throw new ArgumentNullException("control");
        Contract.EndContractBlock();

        Point pt = control.PointToClient(Control.MousePosition);
        return (pt.X >= 0 && pt.Y >= 0 && pt.X <= control.Width && pt.Y <= control.Height);
    }


问:
Create dynamic links with JQuery - individual post id
There are quotes in a forum. I have to place a "quote-back-link" via JQuery or Javascript to the original post.

Inside of each blockquote is span tag with the class name "post_id". The ID of that span tag contains always the ID of the original post. In the example the span tag is at the end of each blockquote, but its also possible to place it on a different position.

```<code><blockquote>
  <cite>Testuser said:</cite>
    <div>This is a test</div>
    <span class="post_id" id="123"></span>
</blockquote>

<blockquote>
 <cite>Testuser2 said:</cite>
  <div>This is a test</div>
  <span class="post_id" id="1234"></span>
</blockquote>

<blockquote>
 <cite>Testuser3 said:</cite>
   <div>This is a test</div>
   <span class="post_id" id="12345"></span>
</blockquote>
</code>```

Is there any way that I can rewrite the Poster-Name that is always between

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

with a link to the original ID? The examples have to look like:

```<code><blockquote>
  <cite><a href="/post-123.html">Testuser said:</a></cite>
   <div>This is a test</div>
    <span class="post_id" id="123"></span>
</blockquote>

<blockquote>
 <cite><a href="/post-1234.html">Testuser2 said:</a></cite>
 <div>This is a test</div>
 <span class="post_id" id="1234"></span>
</blockquote>

<blockquote>
 <cite><a href="/post-12345.html">Testuser3 said:</a></cite>
 <div>This is a test</div>
 <span class="post_id" id="12345"></span>
</blockquote>
</code>```

Thank you very much.

答:
Vanilla JS Way:

var elements = document.querySelectorAll('.post_id');

elements.forEach(e => {
  var testUserID = e.getAttribute('id')
  var newlink = document.createElement('a');
newlink.setAttribute('class', 'post');
newlink.setAttribute('href', 'http://example.com/post-'+testUserID+'.html');
  newlink.innerHTML = 'test';

  var cite = e.parentNode.querySelector("cite")
  cite.appendChild(newlink)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><blockquote>
  <cite>Testuser said:</cite>
    <div>This is a test</div>
    <span class="post_id" id="123"></span>
</blockquote>

<blockquote>
 <cite>Testuser2 said:</cite>
  <div>This is a test</div>
  <span class="post_id" id="12222234"></span>
</blockquote>

<blockquote>
 <cite>Testuser3 said:</cite>
   <div>This is a test</div>
   <span class="post_id" id="12345"></span>
</blockquote></code>```

Something like that could be done like this. I suggest not using jQuery when not needed. So I believe you do not need that. Also if you need a more generic way I am pretty sure you can extend this.

Body:
There are quotes in a forum. I have to place a "quote-back-link" via JQuery or Javascript to the original post.

Inside of each blockquote is span tag with the class name "post_id". The ID of that span tag contains always the ID of the original post. In the example the span tag is at the end of each blockquote, but its also possible to place it on a different position.

  Testuser said:

This is a test

 Testuser2 said:

This is a test

 Testuser3 said:

This is a test

Is there any way that I can rewrite the Poster-Name that is always between

with a link to the original ID? The examples have to look like:

  Testuser said:

This is a test

 Testuser2 said:

This is a test

 Testuser3 said:

This is a test

Thank you very much.

Body:
Vanilla JS Way:

var elements = document.querySelectorAll('.post_id');

elements.forEach(e => {
  var testUserID = e.getAttribute('id')
  var newlink = document.createElement('a');
newlink.setAttribute('class', 'post');
newlink.setAttribute('href', 'http://example.com/post-'+testUserID+'.html');
  newlink.innerHTML = 'test';

  var cite = e.parentNode.querySelector("cite")
  cite.appendChild(newlink)
})

<blockquote>
  <cite>Testuser said:</cite>
    <div>This is a test</div>
    <span class="post_id" id="123"></span>
</blockquote>

<blockquote>
 <cite>Testuser2 said:</cite>
  <div>This is a test</div>
  <span class="post_id" id="12222234"></span>
</blockquote>

<blockquote>
 <cite>Testuser3 said:</cite>
   <div>This is a test</div>
   <span class="post_id" id="12345"></span>
</blockquote>

Something like that could be done like this. I suggest not using jQuery when not needed. So I believe you do not need that. Also if you need a more generic way I am pretty sure you can extend this.


问:
How to add a date in SQL?
How to add or sub a date?

```<code>SELECT DATEADD(month, -1, '2017-08-25') AS DATEADD
</code>```

ERROR:

Msg 242, Level 16, State 3, Line 98

  The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

答:
1- If you have date datatype of your column then you can directly do add or sub on date like below

```<code>select datecol -1 as sub_op , datecol+1 as sub_op2 from your_table
</code>```

2- If you want to convert string to date in oracle you can use to_date function as below

```<code>select to_date('28-May-2019','DD-MM-YYYY') from dual;
</code>```

or if mysql

```<code>STR_TO_DATE('2013-02-11', '%Y-%m-%d')
</code>```

Title: How to add a date in SQL?

Body:
How to add or sub a date?

SELECT DATEADD(month, -1, '2017-08-25') AS DATEADD

ERROR:

Msg 242, Level 16, State 3, Line 98

  The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Body:
1- If you have date datatype of your column then you can directly do add or sub on date like below

select datecol -1 as sub_op , datecol+1 as sub_op2 from your_table

2- If you want to convert string to date in oracle you can use to_date function as below

select to_date('28-May-2019','DD-MM-YYYY') from dual;

or if mysql

STR_TO_DATE('2013-02-11', '%Y-%m-%d')


问:
Is there any way to make Visual Studio C++ error output useful?
I find VS19 output quite useless when working on C++ project. Consider running the example code on freshly installed VS19:

```<code>#include <iostream>

using namespace std;
class My
{
    public:
    void f() noexcept
    {
        throw exception{"A problem sir!"};
    }
};

int main()
{
    try
    {
        My m;
        m.f();
    }
    catch (exception& ex)
    {
        cout << "exception caught! " << ex.what() << endl;
    }
    return 0;
}
</code>```

What I would like to receive is: "Function throws an exception while marked as noexcept", and the cursor set on the problematic line. What I get is a new window with some general text, none of which mentions the problem, or where the problem is.

答:
What compiler warning level have you specified? If I use the /W0 option there is no diagnostic but with any other value, /W1 through /W4, the compiler outputs the following lines:

```<code>1>filename.cpp(9,1): warning C4297:  'My::f': function assumed not to throw an exception but does
1>filename.cpp(9,1): message :  __declspec(nothrow), throw(), noexcept(true), or noexcept was specified on the function
</code>```

Note: the diagnostic messages include the line and column numbers. If you double-click the error message it moves the cursor to the offending line.

Body:
I find VS19 output quite useless when working on C++ project. Consider running the example code on freshly installed VS19:

#include <iostream>

using namespace std;
class My
{
    public:
    void f() noexcept
    {
        throw exception{"A problem sir!"};
    }
};

int main()
{
    try
    {
        My m;
        m.f();
    }
    catch (exception& ex)
    {
        cout << "exception caught! " << ex.what() << endl;
    }
    return 0;
}

What I would like to receive is: "Function throws an exception while marked as noexcept", and the cursor set on the problematic line. What I get is a new window with some general text, none of which mentions the problem, or where the problem is.

Body:
What compiler warning level have you specified? If I use the /W0 option there is no diagnostic but with any other value, /W1 through /W4, the compiler outputs the following lines:

1>filename.cpp(9,1): warning C4297:  'My::f': function assumed not to throw an exception but does
1>filename.cpp(9,1): message :  __declspec(nothrow), throw(), noexcept(true), or noexcept was specified on the function

Note: the diagnostic messages include the line and column numbers. If you double-click the error message it moves the cursor to the offending line.


问:
com.andorid.volley.AuthFailureError in using volley library
I am new in android studio and be going to use volley library to get data from server.
I have used following code:

```<code>JSONObject request_body = new JSONObject();
try {
    request_body.put("method", "authenticate");
    request_body.put("id", "1");
    request_body.put("jsonrpc", "2.0");
    JSONArray params = new JSONArray();
    params.put(user_name);
    params.put(password);
    request_body.put("params", params);
} catch(Exception e) {

}

RequestQueue requestQueueV1= Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest stringRequestV1 = new JsonObjectRequest(Request.Method.POST, server_url + AppConfig.VERSION1_URL, request_body, new Response.Listener<JSONObject>() {
     @Override
     public void onResponse(JSONObject response) {

     }
}, new Response.ErrorListener() {
     @Override
     public void onErrorResponse(VolleyError error) {
           Log.d("MainActivity", error.toString());
           Toast.makeText(SettingsActivity.this, "Error occurred.", Toast.LENGTH_LONG).show();
     }
});
stringRequestV1.setRetryPolicy(new DefaultRetryPolicy(4000, 2, 2f));
requestQueueV1.add(stringRequestV1);
</code>```

But I have got error: com.android.volley.AuthFailureError

Following is my postman screenshot:

答: Pass Header parameter and you will get response</p>

Body:
I am new in android studio and be going to use volley library to get data from server.
I have used following code:

JSONObject request_body = new JSONObject();
try {
    request_body.put("method", "authenticate");
    request_body.put("id", "1");
    request_body.put("jsonrpc", "2.0");
    JSONArray params = new JSONArray();
    params.put(user_name);
    params.put(password);
    request_body.put("params", params);
} catch(Exception e) {

}

RequestQueue requestQueueV1= Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest stringRequestV1 = new JsonObjectRequest(Request.Method.POST, server_url + AppConfig.VERSION1_URL, request_body, new Response.Listener<JSONObject>() {
     @Override
     public void onResponse(JSONObject response) {

     }
}, new Response.ErrorListener() {
     @Override
     public void onErrorResponse(VolleyError error) {
           Log.d("MainActivity", error.toString());
           Toast.makeText(SettingsActivity.this, "Error occurred.", Toast.LENGTH_LONG).show();
     }
});
stringRequestV1.setRetryPolicy(new DefaultRetryPolicy(4000, 2, 2f));
requestQueueV1.add(stringRequestV1);

But I have got error: com.android.volley.AuthFailureError

Following is my postman screenshot: