问:
SQL - safely downcast BIGINT to INT
I have a CSV I'm importing into our database. One of the "columns" contains data that should be an INT but some rows have numbers that only fall in the BIGINT range (because they're test data from one of our partners). We store INT internally and have no desire to change.

I want to safely downcast from BIGINT to INT. By safely, I mean no errors should be raised if an arithmetic overflow happens. If the cast/conversion succeeds, I want my script to go on. If it fails, I want it to short-circuit. I can't seem to figure out the proper syntax. This is what I've got:

```<code>DECLARE @UserIDBigInt BIGINT = 9723021913; -- actually provided by query param
--Setting within the INT range successfully converts
--SET @UserIDBigInt = 5;
DECLARE @UserID INT = CONVERT(INT, @UserIDBigInt);
--DECLARE @UserID INT = CAST(@UserIDBigInt AS INT);
SELECT @UserIDBigInt
SELECT @UserID
IF @UserID IS NOT NULL BEGIN
    SELECT 'Handle it as reliable data'
END
</code>```

I've thought about comparing @UserIDBigInt to the valid range of an INT (-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)), but I really don't like that approach. That's my fallback. I was hoping for some language constructs or built-in functions I could use. If I absolutely have to compare to the valid range, are there at least some built-in constants (like C#'s int.MinValue & int.MaxValue)?

EDIT: Corrected typo.

答:
I'm not sure this is the best answer but it is one I came up with earlier on my own. It is possible to catch the exception/error and gracefully continue execution.

Example:

```<code>DECLARE @UserIDBigInt BIGINT = 9723021913;
DECLARE @UserID INT;
BEGIN TRY
    SET @UserID = @UserIDBigInt;
END TRY BEGIN CATCH
END CATCH

IF @UserID IS NULL BEGIN
    SELECT 'Handle it as unreliable data'
    RETURN
END

SELECT 'Handle it as reliable data'
</code>```

Title: SQL - safely downcast BIGINT to INT

Body:
I have a CSV I'm importing into our database. One of the "columns" contains data that should be an INT but some rows have numbers that only fall in the BIGINT range (because they're test data from one of our partners). We store INT internally and have no desire to change.

I want to safely downcast from BIGINT to INT. By safely, I mean no errors should be raised if an arithmetic overflow happens. If the cast/conversion succeeds, I want my script to go on. If it fails, I want it to short-circuit. I can't seem to figure out the proper syntax. This is what I've got:

DECLARE @UserIDBigInt BIGINT = 9723021913; -- actually provided by query param
--Setting within the INT range successfully converts
--SET @UserIDBigInt = 5;
DECLARE @UserID INT = CONVERT(INT, @UserIDBigInt);
--DECLARE @UserID INT = CAST(@UserIDBigInt AS INT);
SELECT @UserIDBigInt
SELECT @UserID
IF @UserID IS NOT NULL BEGIN
    SELECT 'Handle it as reliable data'
END

I've thought about comparing @UserIDBigInt to the valid range of an INT (-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)), but I really don't like that approach. That's my fallback. I was hoping for some language constructs or built-in functions I could use. If I absolutely have to compare to the valid range, are there at least some built-in constants (like C#'s int.MinValue & int.MaxValue)?

EDIT: Corrected typo.

Body:
I'm not sure this is the best answer but it is one I came up with earlier on my own. It is possible to catch the exception/error and gracefully continue execution.

Example:

DECLARE @UserIDBigInt BIGINT = 9723021913;
DECLARE @UserID INT;
BEGIN TRY
    SET @UserID = @UserIDBigInt;
END TRY BEGIN CATCH
END CATCH

IF @UserID IS NULL BEGIN
    SELECT 'Handle it as unreliable data'
    RETURN
END

SELECT 'Handle it as reliable data'


来源: stackexchange

问:
Can I delete parts of bootstrap.min.css that I'm not using?
I have a small React app that I'm minifying with Webpack, and I noticed that ~80% of my minified index.js file is just Bootstrap css that I'm not using, plus Webpack warns me that my entry file is too big (~900kb vs ~250kb recommended). I found a few answers here from a long time ago that said to remove parts of bootstrap.min.css file that I don't need, and I'm wondering if that's still the recommended solution for a React app using react-bootstrap?

This is my production webpack config:

const path = require('path')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const FaviconsWebpackPlugin = require('favicons-webpack-plugin')

module.exports = {
    entry: '/src/index.tsx',
    output: {
        path: path.resolve(__dirname, 'prod'),
    },
    mode: 'production',
    devtool: 'source-map',
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env', '@babel/preset-react'],
                    },
                },
            },
            {
                test: /\.css$/,
                include: [
                    path.resolve(__dirname, 'src'),
                    path.resolve(__dirname, 'node_modules/react-toastify/dist'),
                    path.resolve(
                        __dirname,
                        'node_modules/bootstrap/dist/css/bootstrap.min.css'
                    ),
                    path.resolve(
                        __dirname,
                        'node_modules/react-grid-layout/css/styles.css'
                    ),
                    path.resolve(
                        __dirname,
                        'node_modules/react-resizable/css/styles.css'
                    ),
                ],
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.tsx?$/,
                exclude: /node_modules/,
                use: 'ts-loader',
            },
        ],
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: './src/index.html',
        }),
        new FaviconsWebpackPlugin('./src/logo.png'),
    ],
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
    },
}
```
<p>And at the top of my App.tsx file I have</p>
<pre class="lang-js prettyprint-override"><code>import 'bootstrap/dist/css/bootstrap.min.css'
</code>```

答:
Ok so I was able to (I think) accomplish what I was asking. I first tried to follow the instructions here:
https://medium.com/dwarves-foundation/remove-unused-css-styles-from-bootstrap-using-purgecss-88395a2c5772

So running purgecss --css [path to bootstrap css] ---content src/index.html --output public did create very minified CSS files, but either I did something wrong or purgecss removed too much, because the bootstrap styles didn't seem to be applied to anything.

Instead, I installed MiniCssExtractPlugin, and pointed webpack to the full bootstrap.min.css file. Running webpack with the below (updated) webpack.prod.js config file reduced the entry file size from ~900kb to ~360kb, which is still above the recommended limit but is about 1/3 the size of the entry before these changes.

Edit: and it also seems good that now the css styles are in their own actual main.css file, rather than for some reason being inside main.js, which is how it was before adding MiniCssExtractPlugin.

```<code>const path = require('path')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const FaviconsWebpackPlugin = require('favicons-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
    entry: '/src/index.tsx',
    output: {
        path: path.resolve(__dirname, 'prod'),
    },
    mode: 'production',
    devtool: 'source-map',
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env', '@babel/preset-react'],
                    },
                },
            },
            {
                test: /\.css$/,
                include: [
                    path.resolve(__dirname, 'src'),
                    path.resolve(__dirname, 'public')
                ],
                use: [MiniCssExtractPlugin.loader, 'css-loader'],
            },
            {
                test: /\.tsx?$/,
                exclude: /node_modules/,
                use: 'ts-loader',
            },
        ],
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: './src/index.html',
        }),
        new MiniCssExtractPlugin({filename: "[name].css", chunkFilename: "[id].css"}),
        new FaviconsWebpackPlugin('./src/logo.png'),
    ],
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
    },
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a small React app that I'm minifying with Webpack, and I noticed that ~80% of my minified index.js file is just Bootstrap css that I'm not using, plus Webpack warns me that my entry file is too big (~900kb vs ~250kb recommended). I found a few answers here from a long time ago that said to remove parts of bootstrap.min.css file that I don't need, and I'm wondering if that's still the recommended solution for a React app using react-bootstrap?

This is my production webpack config:

const path = require('path')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const FaviconsWebpackPlugin = require('favicons-webpack-plugin')

module.exports = {
    entry: '/src/index.tsx',
    output: {
        path: path.resolve(__dirname, 'prod'),
    },
    mode: 'production',
    devtool: 'source-map',
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env', '@babel/preset-react'],
                    },
                },
            },
            {
                test: /\.css$/,
                include: [
                    path.resolve(__dirname, 'src'),
                    path.resolve(__dirname, 'node_modules/react-toastify/dist'),
                    path.resolve(
                        __dirname,
                        'node_modules/bootstrap/dist/css/bootstrap.min.css'
                    ),
                    path.resolve(
                        __dirname,
                        'node_modules/react-grid-layout/css/styles.css'
                    ),
                    path.resolve(
                        __dirname,
                        'node_modules/react-resizable/css/styles.css'
                    ),
                ],
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.tsx?$/,
                exclude: /node_modules/,
                use: 'ts-loader',
            },
        ],
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: './src/index.html',
        }),
        new FaviconsWebpackPlugin('./src/logo.png'),
    ],
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
    },
}

And at the top of my App.tsx file I have

import 'bootstrap/dist/css/bootstrap.min.css'

Body:
Ok so I was able to (I think) accomplish what I was asking. I first tried to follow the instructions here:
https://medium.com/dwarves-foundation/remove-unused-css-styles-from-bootstrap-using-purgecss-88395a2c5772

So running purgecss --css [path to bootstrap css] ---content src/index.html --output public did create very minified CSS files, but either I did something wrong or purgecss removed too much, because the bootstrap styles didn't seem to be applied to anything.

Instead, I installed MiniCssExtractPlugin, and pointed webpack to the full bootstrap.min.css file. Running webpack with the below (updated) webpack.prod.js config file reduced the entry file size from ~900kb to ~360kb, which is still above the recommended limit but is about 1/3 the size of the entry before these changes.

Edit: and it also seems good that now the css styles are in their own actual main.css file, rather than for some reason being inside main.js, which is how it was before adding MiniCssExtractPlugin.

const path = require('path')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const FaviconsWebpackPlugin = require('favicons-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
    entry: '/src/index.tsx',
    output: {
        path: path.resolve(__dirname, 'prod'),
    },
    mode: 'production',
    devtool: 'source-map',
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env', '@babel/preset-react'],
                    },
                },
            },
            {
                test: /\.css$/,
                include: [
                    path.resolve(__dirname, 'src'),
                    path.resolve(__dirname, 'public')
                ],
                use: [MiniCssExtractPlugin.loader, 'css-loader'],
            },
            {
                test: /\.tsx?$/,
                exclude: /node_modules/,
                use: 'ts-loader',
            },
        ],
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: './src/index.html',
        }),
        new MiniCssExtractPlugin({filename: "[name].css", chunkFilename: "[id].css"}),
        new FaviconsWebpackPlugin('./src/logo.png'),
    ],
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
    },
}


问:
Docusign Rest API login using api credentials
Docusign rest api examples works using the manual login to docusign. The user has to enter the username and password to continue using the api's, I am looking for the method use api based on api credentials from backend config for better user experience. Can someone help on this whether we can achieve this</p>

答: You can use JWT instead of Auth Code Grant. JWT Tokens do not require user to login and it is useful for back-end processes and other programs that do not have UI for user to login.</p>


问:
How to convert ZIP to GZIP in python, in-memory (AWS Lambda)
I have managed to convert zip files to gzip, using AWS lambda's local storage /tmp. The problem is that this storage maxes out at 500Mb.

```<code>def zip_to_gzip(zip):

    # Unzip <filename>.zip
    zfile = ZipFile(zip)
    filename = zfile.namelist()[0]
    data = zfile.read(filename)
    f = open('/tmp/' + str(filename), 'wb')
    f.write(data)
    f.close()

    # Compress <filename>.gzip
    gzip_file = gzip.open(
        f'/tmp/{filename}.gz', 'wb')
    gzip_file.write(data)
    gzip_file.close()

</code>```

I would like to do this, exclusively in RAM, without using any local storage/hard drive.

Any ideas how? The io module doesn't seem to be appropriate for this use (I am not 100% sure about that though)

答:
This should do as you ask:

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

import gzip

# Make 10kB of compressible zeroes of data
data = bytearray(10240)

outfilename = 'sample.gz'
with gzip.open(outfilename, 'wb') as output:
     output.write(data)
</code>```

Adapted from Doug Hellman's excellent PYMOTW.

Check results

```<code># The size is 52 bytes:
ls -l sample.gz
-rw-r--r--  1 mark  staff  52  7 Feb 17:51 sample.gz

# The type is correct
file -b --mime  sample.gz
application/gzip; charset=binary

# It decompresses to the correct size
gunzip < sample.gz | wc -c
10240
</code>```

Body:
I have managed to convert zip files to gzip, using AWS lambda's local storage /tmp. The problem is that this storage maxes out at 500Mb.

def zip_to_gzip(zip):

    # Unzip <filename>.zip
    zfile = ZipFile(zip)
    filename = zfile.namelist()[0]
    data = zfile.read(filename)
    f = open('/tmp/' + str(filename), 'wb')
    f.write(data)
    f.close()

    # Compress <filename>.gzip
    gzip_file = gzip.open(
        f'/tmp/{filename}.gz', 'wb')
    gzip_file.write(data)
    gzip_file.close()

I would like to do this, exclusively in RAM, without using any local storage/hard drive.

Any ideas how? The io module doesn't seem to be appropriate for this use (I am not 100% sure about that though)

Body:
This should do as you ask:

#!/usr/bin/env python3

import gzip

# Make 10kB of compressible zeroes of data
data = bytearray(10240)

outfilename = 'sample.gz'
with gzip.open(outfilename, 'wb') as output:
     output.write(data)

Adapted from Doug Hellman's excellent PYMOTW.

Check results

# The size is 52 bytes:
ls -l sample.gz
-rw-r--r--  1 mark  staff  52  7 Feb 17:51 sample.gz

# The type is correct
file -b --mime  sample.gz
application/gzip; charset=binary

# It decompresses to the correct size
gunzip < sample.gz | wc -c
10240


问:
Delaying a function for transition duration
How can I make this script delay for 350 miliseconds while waiting for the css3 transition to end?

```<code>    <script type="text/javascript">
        $(document).ready(function() {
            var last = "";
            $("#thumbs a").click(function() {
                event.preventDefault();
                var graphic = $(this).attr("href");
                if(last != graphic) {
                    $("#placeholder").before( "<img src=\"" + graphic + "\" />" );
                    $("#mask").css("marginTop","-=450px");
                    last = graphic;
                }
            });
        });
    </script>
</code>```

Basically, when you click, it should check to see if its been clicked within the last 350 miliseconds, and if it has, do nothing.

I've heard of the transitionend function, but I couldn't figure out how to implement it.

答:
After document.ready, enclose your code in a function. Perhaps "function wait(){...code here...} then use a settimeout, such as var t = setTimeout(wait,350);

Hope this helps. If not, try adding a load handler to your CSS transitioning object, then putting a setTimeout function in the load callback function. It should wait for the object to load, and set a timer to start your function 350 milliseconds after the object is loaded.

ContentLicense: CC BY-SA 3.0

Body:
How can I make this script delay for 350 miliseconds while waiting for the css3 transition to end?

Basically, when you click, it should check to see if its been clicked within the last 350 miliseconds, and if it has, do nothing.

I've heard of the transitionend function, but I couldn't figure out how to implement it.


问:
Tendermint web application - customize
I am new to blockchain development and to tendermint as well.

I already have a blockchain running locally.

Using this command starport scaffold vue I could mount a local web application. Inspecting a bit I could replicate some network requests (localhost) and I can get the ballance of current wallet (hard-coded on the request), get the current wallet from the localstorage. I'm struggling on authentication (mnemonic, wallet name and password).

However I also would like to costumize it according to my needs and I thought I could start a web application from scratch. I can see that the generated web project is importing this project https://github.com/tendermint/vue which is making a lot of "magic behind the scenes" and importing UI elements as well and I would like to have my own elements.

I don't want to re-invent the wheel and I can make some imports to help me on connection to wallet, validate authentication (mnemonic, wallet name and password), create wallet and so on.

I am trying to build a web application to connect to wallet, make transations.... but I would like to control the styles and the connections (and if possible using reactjs instead of vuejs, otherwise I dont mind learn vuejs as well).

Is this possible or reasonable? Where I can find good documentation or tutorial to guide me on customize a web application using tendermint. Honestly I searched but I am kind of lost.

Thanks

UPDATE: I found good examples and here and here. It helped me to validate mnemonics and make transactions, with my stack tech.

答:
Because Starport generates both plain Javascript and VUE controllers, you have few options:

Create your own site re-using VUE components

Take plain JS part and build a website using whatever technology you like

Use a plain JS client for standard cosmos modules you can find on GitHub

Use Protobuf generator to generate light client code yourself

If you only need wallet functionality, #2 and #3 may work best for you because the bank module is stable and hasn't changed much in a long time.

You can find plain JS file for bank in your project:
vue/src/store/generated/cosmos/cosmos-sdk/cosmos.bank.v1beta1/module/index.ts

There is a link to starport discord channel related to frontend: https://discord.gg/CvbdYh9AWQ

Title: Tendermint web application - customize


问:
Webpage Parsing
I am trying to parse a webpage and store the result in a table. However, I can't proceed any further as the parse result has some unwanted text at the top, middle and bottom of the csv. http://lottery.merseyworld.com/cgi-bin/lottery?days=20&Machine=Z&Ballset=0&order=1&show=1&year=0&display=CSV

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd

URL = "http://lottery.merseyworld.com/cgi-bin/lottery?days=20&Machine=Z&Ballset=0&order=1&show=1&year=0&display=CSV"

response = requests.get(URL)
mywebpage = response.text
mysoup = BeautifulSoup(mywebpage, "html.parser")

print(mysoup)
</code>```

gives...

```<code><html>
<head>
<title> Euro Millions Winning Numbers</title>
<body>
``` Euro Millions Winning Numbers

No., Day,DD,MMM,YYYY, N1,N2,N3,N4,N5,L1,L2,  Jackpot,   Wins
1500, Fri, 4,Feb,2022, 03,25,38,43,49,03,07, 109915000,    1
1499, Tue, 1,Feb,2022, 01,19,36,38,49,06,09,  52442757,    0
1498, Fri,28,Jan,2022, 10,25,29,34,45,09,10,  42779117,    0
...
1451, Tue,17,Aug,2021, 12,31,41,42,47,04,06,  14502700,    0
1450, Fri,13,Aug,2021, 06,12,44,47,49,08,12,  96295864,    1

All lotteries below have exceeded the 180 days expiry date
No., Day,DD,MMM,YYYY, N1,N2,N3,N4,N5,L1,L2,  Jackpot,   Wins
1449, Tue,10,Aug,2021, 09,37,47,48,49,02,07,  80768518,    0
1448, Fri, 6,Aug,2021, 07,14,21,26,32,04,12,  71953143,    0
...
3, Fri,27,Feb,2004, 14,18,19,31,37,04,05,  11880304,    0
  2, Fri,20,Feb,2004, 07,13,39,47,50,02,05,  10111500,    0
  1, Fri,13,Feb,2004, 16,29,32,36,41,07,09,  10143000,    1

This page shows all the draws that used any machine and any ball set in any year.

Data obtained from http://lottery.merseyworld.com/Euro/
```
</body></head></html>

</code>```

I just want to be able to extract the 1500 rows in a pandas dataframe and get rid of the text that occurs at the beginning, middle and end! Any help is appreciated. Thanks!

Title: Webpage Parsing

Body:
I am trying to parse a webpage and store the result in a table. However, I can't proceed any further as the parse result has some unwanted text at the top, middle and bottom of the csv. http://lottery.merseyworld.com/cgi-bin/lottery?days=20&Machine=Z&Ballset=0&order=1&show=1&year=0&display=CSV

import requests
from bs4 import BeautifulSoup
import pandas as pd

URL = "http://lottery.merseyworld.com/cgi-bin/lottery?days=20&Machine=Z&Ballset=0&order=1&show=1&year=0&display=CSV"

response = requests.get(URL)
mywebpage = response.text
mysoup = BeautifulSoup(mywebpage, "html.parser")

print(mysoup)

gives...

<title> Euro Millions Winning Numbers</title>

 Euro Millions Winning Numbers

No., Day,DD,MMM,YYYY, N1,N2,N3,N4,N5,L1,L2,  Jackpot,   Wins
1500, Fri, 4,Feb,2022, 03,25,38,43,49,03,07, 109915000,    1
1499, Tue, 1,Feb,2022, 01,19,36,38,49,06,09,  52442757,    0
1498, Fri,28,Jan,2022, 10,25,29,34,45,09,10,  42779117,    0
...
1451, Tue,17,Aug,2021, 12,31,41,42,47,04,06,  14502700,    0
1450, Fri,13,Aug,2021, 06,12,44,47,49,08,12,  96295864,    1

All lotteries below have exceeded the 180 days expiry date
No., Day,DD,MMM,YYYY, N1,N2,N3,N4,N5,L1,L2,  Jackpot,   Wins
1449, Tue,10,Aug,2021, 09,37,47,48,49,02,07,  80768518,    0
1448, Fri, 6,Aug,2021, 07,14,21,26,32,04,12,  71953143,    0
...
3, Fri,27,Feb,2004, 14,18,19,31,37,04,05,  11880304,    0
  2, Fri,20,Feb,2004, 07,13,39,47,50,02,05,  10111500,    0
  1, Fri,13,Feb,2004, 16,29,32,36,41,07,09,  10143000,    1

This page shows all the draws that used any machine and any ball set in any year.

Data obtained from http://lottery.merseyworld.com/Euro/

I just want to be able to extract the 1500 rows in a pandas dataframe and get rid of the text that occurs at the beginning, middle and end! Any help is appreciated. Thanks!

Body:
You can split() your result and create a dataframe:

df = pd.DataFrame([x.split(',') for x in mysoup.pre.text.split('\n') if x.count(',') == 13])

Set the first row as your column headers:

df.columns = df.iloc[0]

Convert all values of column "No." into numbers:

df['No.'] = pd.to_numeric(df['No.'],errors='coerce').fillna(0).astype(int)

Filter only the rows where "No." is not "0":

df[df['No.'] != 0]

Output

No.
Day
DD
MMM
YYYY
N1
N2
N3
N4
N5
L1
L2
Jackpot
Wins

1500
Fri
4
Feb
2022
03
25
38
43
49
03
07
109915000
1

1499
Tue
1
Feb
2022
01
19
36
38
49
06
09
52442757
0

1498
Fri
28
Jan
2022
10
25
29
34
45
09
10
42779117
0

1497
Tue
25
Jan
2022
06
16
18
39
47
02
04
30632619
0

1496
Fri
21
Jan
2022
05
14
35
36
39
07
12
21857937
0

1495
Tue
18
Jan
2022
03
12
19
24
30
02
05
56246458
0

1494
Fri
14
Jan
2022
06
17
25
31
46
09
12
46600782
0

1493
Tue
11
Jan
2022
04
23
32
33
44
09
12
34392715
0

1492
Fri
7
Jan
2022
02
14
37
44
50
07
11
25451971
0

1491
Tue
4
Jan
2022
18
28
35
36
41
06
11
14189900
0

1490
Fri
31
Dec
2021
07
22
25
43
49
06
07
14788260
1

...


问:
VBA SMTP Libraries
Does anyone know of any SMTP libraries that I can put directly into MS Access as a class module that does not rely on the Winsock dll or ocx or any other third party products?

We are currently using the SendObject functionality in MS Access but that is interfering with the Access runtime library.

答:
Found what I was looking for at:

http://www.worksrite.com/CDOMail.htm

ContentLicense: CC BY-SA 2.5

Title: VBA SMTP Libraries


问:
Error: "Cannot send session cache limiter" related to encoding
I'm started having problems with the encoding, it seems that somehow Notepad++ changed the encoding or something. Anyway all files where encoded in UTF-8, but I checked and some changed to UTF-8 without BOM. Changing one to UTF-8 fixed the special characters issue.

"TageÃƒÂ¡" changed to "Tageá" but I started getting an error:

```<code>Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/02/6945202/html/usuario/index.php:1) in /home/content/02/6945202/html/usuario/index.php on line 1
</code>```

This is line 1:

```<code><? session_start(); ?>
</code>```

I don't understand why I'm having this issue, since using ANSI or UTF-8 without BOM the page shows with no errors.

What can be the problem? Thanks

答: convert character encoding without changing the file encoding to UTF-8 without BOM because it is generating space before session_start()</p>

Body:
I'm started having problems with the encoding, it seems that somehow Notepad++ changed the encoding or something. Anyway all files where encoded in UTF-8, but I checked and some changed to UTF-8 without BOM. Changing one to UTF-8 fixed the special characters issue.

"TageÃƒÂ¡" changed to "Tageá" but I started getting an error:

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/02/6945202/html/usuario/index.php:1) in /home/content/02/6945202/html/usuario/index.php on line 1

This is line 1:

<? session_start(); ?>

I don't understand why I'm having this issue, since using ANSI or UTF-8 without BOM the page shows with no errors.

What can be the problem? Thanks


问:
How to split a string containing date and words?
I have a bunch of string in the format "02-01-2014 10:02:01:001 abcd efgh"
If I want to split it as ["02-01-2014 10:02:01:001", "abcd efgh"], how do I do that?

Currently, I'm splitting based on the knowledge that the first 23 characters contain the date so I'm just taking a substring till there. Is there any better way?

答:
Something like:

```<code>Patter.compile("\\d{2}-\\d{2}-\\d{4}\\s\\d{2}:\\d{2}:\\d{2}:\\d{3}\\s(.*)");
</code>```

Then use matcher capturing group 1.

Body:
Something like:

Patter.compile("\\d{2}-\\d{2}-\\d{4}\\s\\d{2}:\\d{2}:\\d{2}:\\d{3}\\s(.*)");

Then use matcher capturing group 1.


问:
NuxtJS & Firebase : upgrading to NodeJS 16 engine breaks Firestore listener (Firebase rules)
I've been using NuxtJS (v2.15.8) with Nuxt Firebase (v7.6.1), running on NodeJS engine 12 (v12.21.0 to be exact) for the web application I've been developping incrementally for the past couple of years and my web app is now quite complex.

I am trying to upgrade NodeJS to the latest LTS version (v16.13.2) and encounter one major issue after switching version of NodeJS (using nvm) and changing the package.json of my five packages from node 12 to node 16 :

package.json :

```<code>"engines": {
  "node": "16",
  ..
},
</code>```

When running exactly the wame web application after these changes, it starts correctly but Firebase Rules seem to break, with this error FirebaseError:  false for 'get' @ L61, false for 'get' @ L268.

It is a cryptic error, but from experience and from all I could find online, it happens when a call to Firestore that gets blocked by defined Firebase Security rules). In my case, it happens on a "onSnapshot" call to listen to the changes of the currently logged in user. Some other calls to Firestore (using "get" and not "onSnapshot") seem to work fine, and the Firebase Authentication works well too.

Here is the full error stack :

```<code>loggedInUser.js?384a:65 Error listening to user changes
FirebaseError: false for 'get' @ L61, false for 'get' @ L268
    at new n (prebuilt-306f43d8-45d6f0b9.js?23bd:188:1)
    at eval (prebuilt-306f43d8-45d6f0b9.js?23bd:10426:1)
    at eval (prebuilt-306f43d8-45d6f0b9.js?23bd:10427:1)
    at n.onMessage (prebuilt-306f43d8-45d6f0b9.js?23bd:10449:1)
    at eval (prebuilt-306f43d8-45d6f0b9.js?23bd:10366:1)
    at eval (prebuilt-306f43d8-45d6f0b9.js?23bd:10397:1)
    at eval (prebuilt-306f43d8-45d6f0b9.js?23bd:15160:1)
    at eval (prebuilt-306f43d8-45d6f0b9.js?23bd:15218:1)
</code>```

The portion of code triggerring the error is :

```<code>  listenUser({ commit }, userId) {
    const userRef = this.$fire.firestore.collection('users').doc(userId);
    userListener = userRef.onSnapshot(function(userDoc) {
      if (userDoc.exists) {
        const user = userConverter.fromFirestoreData(userDoc.data());
        commit('SET_LOGGED_IN_USER', user);
      }
    },
    function(error) {
      console.error("Error listening to user changes", error);
    });
  },
</code>```

As soon as I revert back to Node 12, the same call works fine and isn't blocked by the Firebase rules, so the error doesn't appear.

I therefore have several questions :

Does anyone understand what's happening there ? Is there known changes in the behavior of Firebase rules directly related to the NodeJS engine ?

Do you think this issue can come from Nuxt or its Nuxt Firebase module are not working correctly under NodeJS 16 ?

It is required to also upgrade NuxtJS to a newer version or should it be possible to simply update the Node Engine ?

Is it required to update to a newer version of Firebase (modular implementation) despite the Nuxt Firebase module stating :

"This module does not support the new modular syntax from Firebase v9+. If you plan to use the new modular mode of Version 9, we advise you to implement Firebase manually as described in the following medium article. It is currently unclear when, and if, this module will support the new modular mode."

Source : their Github repo

Any help to understand what's going on here is welcome !!
Thanks a lot for your help !

答:
Long story short : upgrading to Firebase v9 worked.

Before I did that, I got stuck with rules preventing me to access firestore documents as soon as I tried running the project under Node16 engine.

So I had to do the following changes :

updating Firebase to v9

implement the configuration through a plugin rather than the nuxt-firebase module

make all the required changes in my code to make use of v9 modular (I didn't try using the compat version)

Now that I use the latest version of Firebase, I tried again switching to NodeJS 16 and it runs fine, including the Firebase security rules.

Body:
I've been using NuxtJS (v2.15.8) with Nuxt Firebase (v7.6.1), running on NodeJS engine 12 (v12.21.0 to be exact) for the web application I've been developping incrementally for the past couple of years and my web app is now quite complex.

I am trying to upgrade NodeJS to the latest LTS version (v16.13.2) and encounter one major issue after switching version of NodeJS (using nvm) and changing the package.json of my five packages from node 12 to node 16 :

package.json :

"engines": {
  "node": "16",
  ..
},

When running exactly the wame web application after these changes, it starts correctly but Firebase Rules seem to break, with this error FirebaseError:  false for 'get' @ L61, false for 'get' @ L268.

It is a cryptic error, but from experience and from all I could find online, it happens when a call to Firestore that gets blocked by defined Firebase Security rules). In my case, it happens on a "onSnapshot" call to listen to the changes of the currently logged in user. Some other calls to Firestore (using "get" and not "onSnapshot") seem to work fine, and the Firebase Authentication works well too.

Here is the full error stack :

loggedInUser.js?384a:65 Error listening to user changes
FirebaseError: false for 'get' @ L61, false for 'get' @ L268
    at new n (prebuilt-306f43d8-45d6f0b9.js?23bd:188:1)
    at eval (prebuilt-306f43d8-45d6f0b9.js?23bd:10426:1)
    at eval (prebuilt-306f43d8-45d6f0b9.js?23bd:10427:1)
    at n.onMessage (prebuilt-306f43d8-45d6f0b9.js?23bd:10449:1)
    at eval (prebuilt-306f43d8-45d6f0b9.js?23bd:10366:1)
    at eval (prebuilt-306f43d8-45d6f0b9.js?23bd:10397:1)
    at eval (prebuilt-306f43d8-45d6f0b9.js?23bd:15160:1)
    at eval (prebuilt-306f43d8-45d6f0b9.js?23bd:15218:1)

The portion of code triggerring the error is :

  listenUser({ commit }, userId) {
    const userRef = this.$fire.firestore.collection('users').doc(userId);
    userListener = userRef.onSnapshot(function(userDoc) {
      if (userDoc.exists) {
        const user = userConverter.fromFirestoreData(userDoc.data());
        commit('SET_LOGGED_IN_USER', user);
      }
    },
    function(error) {
      console.error("Error listening to user changes", error);
    });
  },

As soon as I revert back to Node 12, the same call works fine and isn't blocked by the Firebase rules, so the error doesn't appear.

I therefore have several questions :

Does anyone understand what's happening there ? Is there known changes in the behavior of Firebase rules directly related to the NodeJS engine ?

Do you think this issue can come from Nuxt or its Nuxt Firebase module are not working correctly under NodeJS 16 ?

It is required to also upgrade NuxtJS to a newer version or should it be possible to simply update the Node Engine ?

Is it required to update to a newer version of Firebase (modular implementation) despite the Nuxt Firebase module stating :

"This module does not support the new modular syntax from Firebase v9+. If you plan to use the new modular mode of Version 9, we advise you to implement Firebase manually as described in the following medium article. It is currently unclear when, and if, this module will support the new modular mode."

Source : their Github repo

Any help to understand what's going on here is welcome !!
Thanks a lot for your help !


问:
How to deserialize enum with Jackson (2.13.1)
I want to deserialize an enum with Jackson 2.13.1.

I found the following solution.

```<code>public enum Type {
    TYPEONE("Type1");

    private static Map<String, Type> typesMap = new HashMap<>(1);

    static {
        typesMap.put("type1", TYPEONE);
    }

    @JsonCreator
    public static Type forValue(String value) {
        return typesMap.get(value.toLowerCase());
    }

    private final String label;

    Type(String label) {
        this.label = label;
    }

    @JsonValue
    public String getLabel() {
        return label;
    }
}
</code>```

Still getting the following error:

```<code>java.lang.IllegalArgumentException: No enum constant com.cas.cascrt.certificate.model.enums.Type.Type1
at java.base/java.lang.Enum.valueOf(Enum.java:266) ~[na:na]
</code>```

答: You don't need to maintain a map. In @JsonCreator method stream through the Type.values(), filter the incoming value and return the enum.</p>

Body:
I want to deserialize an enum with Jackson 2.13.1.

I found the following solution.

public enum Type {
    TYPEONE("Type1");

    private static Map<String, Type> typesMap = new HashMap<>(1);

    static {
        typesMap.put("type1", TYPEONE);
    }

    @JsonCreator
    public static Type forValue(String value) {
        return typesMap.get(value.toLowerCase());
    }

    private final String label;

    Type(String label) {
        this.label = label;
    }

    @JsonValue
    public String getLabel() {
        return label;
    }
}

Still getting the following error:

java.lang.IllegalArgumentException: No enum constant com.cas.cascrt.certificate.model.enums.Type.Type1
at java.base/java.lang.Enum.valueOf(Enum.java:266) ~[na:na]


问:
i have created a stored procedure for updating a table named room but checking another table called room_status.iam gettin an error unknown room_s tab
```<code>IF(room_status.check_out<date_in) THEN
 UPDATE room SET  room.status='AVAILABLE';
 ELSE
  UPDATE room SET  room.status='BOOKED' ;
  END IF
</code>```

答:
You can't access room_status.check_out outside a query that selects from the room_status table.

If you want to do this in all rows, put the condition inside the UPDATE that joins the tables.

```<code>UPDATE room AS r
JOIN room_status AS rs ON r.id = rs.room_id
SET r.status = IF(rs.check_out < date_in, 'AVAILABLE', 'BOOKED')
</code>```

Body:
You can't access room_status.check_out outside a query that selects from the room_status table.

If you want to do this in all rows, put the condition inside the UPDATE that joins the tables.

UPDATE room AS r
JOIN room_status AS rs ON r.id = rs.room_id
SET r.status = IF(rs.check_out < date_in, 'AVAILABLE', 'BOOKED')


问:
Unable to install docker on Amazon linux
I'm trying to install docker on Amazon Linux Ec2 instance, I get the following error.

Installing docker

```<code>Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Cleaning repos: amzn2-core amzn2extra-docker amzn2extra-lamp-mariadb10.2-php7.2 amzn2extra-php7.2 docker-ce-stable
4 metadata files removed
0 sqlite files removed
0 metadata files removed
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
amzn2-core                                                                                | 3.7 kB  00:00:00
amzn2extra-docker                                                                                | 3.0 kB  00:00:00
amzn2extra-lamp-mariadb10.2-php7.2                                                                                | 3.0 kB  00:00:00
amzn2extra-php7.2                                                                                | 3.0 kB  00:00:00
https://download.docker.com/linux/centos/2/x86_64/stable/repodata/repomd.xml: [Errno 14] HTTPS Error 404 - Not Found
Trying other mirror.

 One of the configured repositories failed (Docker CE Stable - x86_64),
 and yum doesn't have enough cached data to continue. At this point the only
 safe thing yum can do is fail. There are a few ways to work "fix" this:

     1. Contact the upstream for the repository and get them to fix the problem.

     2. Reconfigure the baseurl/etc. for the repository, to point to a working
        upstream. This is most often useful if you are using a newer
        distribution release than is supported by the repository (and the
        packages for the previous distribution release still work).

     3. Run the command with the repository temporarily disabled
            yum --disablerepo=docker-ce-stable ...

     4. Disable the repository permanently, so yum won't use it by default. Yum
        will then just ignore the repository until you permanently enable it
        again or use --enablerepo for temporary usage:

            yum-config-manager --disable docker-ce-stable
        or
            subscription-manager repos --disable=docker-ce-stable

     5. Configure the failing repository to be skipped, if it is unavailable.
        Note that yum will try to contact the repo. when it runs most commands,
        so will have to try and fail each time (and thus. yum will be be much
        slower). If it is a very temporary problem though, this is often a nice
        compromise:

            yum-config-manager --save --setopt=docker-ce-stable.skip_if_unavailable=true

failure: repodata/repomd.xml from docker-ce-stable: [Errno 256] No more mirrors to try.
https://download.docker.com/linux/centos/2/x86_64/stable/repodata/repomd.xml: [Errno 14] HTTPS Error 404 - Not Found
Installation failed. Check that you have permissions to install.
[root@ip-172-31-79-10 ec2-user]# ^C
[root@ip-172-31-79-10 ec2-user]# chkconfig docker on
error reading information on service docker: No such file or directory
</code>```

答:
I just had the same problem when I tried to install docker on a centos machine
I followed the official guide here and found out the commad:

```<code>sudo yum-config-manager \
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo
</code>```

messed up the installation..

my solution was:

delete the installed docker-repo:

sudo rm /etc/yum.repos.d/docker-ce.repo

install docker: sudo yum install docker

Body:
I'm trying to install docker on Amazon Linux Ec2 instance, I get the following error.

Installing docker

Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Cleaning repos: amzn2-core amzn2extra-docker amzn2extra-lamp-mariadb10.2-php7.2 amzn2extra-php7.2 docker-ce-stable
4 metadata files removed
0 sqlite files removed
0 metadata files removed
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
amzn2-core                                                                                | 3.7 kB  00:00:00
amzn2extra-docker                                                                                | 3.0 kB  00:00:00
amzn2extra-lamp-mariadb10.2-php7.2                                                                                | 3.0 kB  00:00:00
amzn2extra-php7.2                                                                                | 3.0 kB  00:00:00
https://download.docker.com/linux/centos/2/x86_64/stable/repodata/repomd.xml: [Errno 14] HTTPS Error 404 - Not Found
Trying other mirror.

 One of the configured repositories failed (Docker CE Stable - x86_64),
 and yum doesn't have enough cached data to continue. At this point the only
 safe thing yum can do is fail. There are a few ways to work "fix" this:

     1. Contact the upstream for the repository and get them to fix the problem.

     2. Reconfigure the baseurl/etc. for the repository, to point to a working
        upstream. This is most often useful if you are using a newer
        distribution release than is supported by the repository (and the
        packages for the previous distribution release still work).

     3. Run the command with the repository temporarily disabled
            yum --disablerepo=docker-ce-stable ...

     4. Disable the repository permanently, so yum won't use it by default. Yum
        will then just ignore the repository until you permanently enable it
        again or use --enablerepo for temporary usage:

            yum-config-manager --disable docker-ce-stable
        or
            subscription-manager repos --disable=docker-ce-stable

     5. Configure the failing repository to be skipped, if it is unavailable.
        Note that yum will try to contact the repo. when it runs most commands,
        so will have to try and fail each time (and thus. yum will be be much
        slower). If it is a very temporary problem though, this is often a nice
        compromise:

            yum-config-manager --save --setopt=docker-ce-stable.skip_if_unavailable=true

failure: repodata/repomd.xml from docker-ce-stable: [Errno 256] No more mirrors to try.
https://download.docker.com/linux/centos/2/x86_64/stable/repodata/repomd.xml: [Errno 14] HTTPS Error 404 - Not Found
Installation failed. Check that you have permissions to install.
[root@ip-172-31-79-10 ec2-user]# ^C
[root@ip-172-31-79-10 ec2-user]# chkconfig docker on
error reading information on service docker: No such file or directory

Body:
I just had the same problem when I tried to install docker on a centos machine
I followed the official guide here and found out the commad:

sudo yum-config-manager \
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo

messed up the installation..

my solution was:

delete the installed docker-repo:

sudo rm /etc/yum.repos.d/docker-ce.repo

install docker: sudo yum install docker


问:
Features not within filter Encoding
I was using following filter encoding establishing new WFS connection in QGIS i.e.
https://sedac.ciesin.columbia.edu/geoserver/ows?version=1.1.0&typenames=gpw-v3:gpw-v3-coastlines&outputFormat=application/json&CQL_FILTER=dwithin(the_geom, POINT(37.696 14.964), 20, kilometers so as
to select lines within 20km from above point coordinate.

Though the output is displayed however,line features seems to be far from the 20 km distance from the above point. Why is this happening?

答: That is an old version of GeoServer which uses the units of the projection not the ones specified in the DWITHIN so you will need to use a projection that is in metres (EPSG:3035?).

Title: Features not within filter Encoding


问:
Should I use Prometheus for resource gathering?
I use Prometheus to gather k8s' resources.
The resource data pipeline is as follows:

```<code>k8s -> Prometheus -> Java app -> Elasticsearch -> (whghl) Java app
</code>```

Here I have a question.
Why use Prometheus?

Wouldn't Prometheus not be necessary if it was stored in DB like mine?
Whether I use Elasticsearch or MongoDB, wouldn't I need Prometheus?

答:
It definitely depends on what exactly you are trying to achieve by using these tools. In general, the scope of usage is quite different.

Prometheus is specifically designed for metrics collection, system monitoring and creating alerts based on those metrics. That's why it is the better choice if it is primarily required to pull metrics from services and run alerts on them.

Elasticsearch in its turn is a system with wider scope, as it is used to store and search all data types, perform different types of analytics of this data - and mostly it is used as log analysis system. But it also can be configured for monitoring, though it is not particularly made for it, unlike Prometheus.

Both tools are good to use, but Prometheus provides more simplicity in setting up monitoring for Kubernetes.

Body:
I use Prometheus to gather k8s' resources.
The resource data pipeline is as follows:

k8s -> Prometheus -> Java app -> Elasticsearch -> (whghl) Java app

Here I have a question.
Why use Prometheus?

Wouldn't Prometheus not be necessary if it was stored in DB like mine?
Whether I use Elasticsearch or MongoDB, wouldn't I need Prometheus?


问:
Await function returning undefined response object
I am not much experienced with async/await, but I have incorporated the keywords in a function which basically fetch or POST data to MongoDB database. It seems like await does not wait for the promise to be fulfilled and returns an undefined response object.

I am getting the following error:

res.error(404).json({message: e.message})
^

TypeError: Cannot read properties of undefined (reading 'error')
at Object.getAllItems (/Users/myName/Desktop/TODOList/backend/Controllers/ItemsConroller.js:12:13)

Here is my code:

ItemsController.js:

```<code>const getAllItems = async (req, res) => {
    try{
        const items =  await Item.find({})
        res.status(200).json(items)
    }
    catch(e){
        res.error(404).json({message: e.message})
    }

}
</code>```

Server.js file:

```<code>app.get('/todos', (req, res) => {
     dbItem.getAllItems().then(data => {
         console.log("entered")
         res.send(data);
     })

})
</code>```

Same problem with other functions in the controller file which incorporates await/async keywords.

Thanks.

答:
You are not passing your req and res object to your /todos endpoint:
To make you app more robust try this:

You can use getAllItems as your middleware like this

```<code>app.get('/todos', dbItem.getAllItems, (req, res) => {
     if(!req.error){
         res.send(req.items)
     }else{
       res.send(req.error)
     }
})
</code>```

And attach your variables to the req object and pass them to /todos

```<code>const getAllItems = async (req, res, next) => {
    try{
        const items =  await Item.find({})
        req.items = items
        next()
    }
    catch(e){
        req.error = e.message
        next()
    }

}
</code>```

Body:
I am not much experienced with async/await, but I have incorporated the keywords in a function which basically fetch or POST data to MongoDB database. It seems like await does not wait for the promise to be fulfilled and returns an undefined response object.

I am getting the following error:

res.error(404).json({message: e.message})
^

TypeError: Cannot read properties of undefined (reading 'error')
at Object.getAllItems (/Users/myName/Desktop/TODOList/backend/Controllers/ItemsConroller.js:12:13)

Here is my code:

ItemsController.js:

const getAllItems = async (req, res) => {
    try{
        const items =  await Item.find({})
        res.status(200).json(items)
    }
    catch(e){
        res.error(404).json({message: e.message})
    }

}

Server.js file:

app.get('/todos', (req, res) => {
     dbItem.getAllItems().then(data => {
         console.log("entered")
         res.send(data);
     })

})

Same problem with other functions in the controller file which incorporates await/async keywords.

Thanks.

Body:
You are not passing your req and res object to your /todos endpoint:
To make you app more robust try this:

You can use getAllItems as your middleware like this

app.get('/todos', dbItem.getAllItems, (req, res) => {
     if(!req.error){
         res.send(req.items)
     }else{
       res.send(req.error)
     }
})

And attach your variables to the req object and pass them to /todos

const getAllItems = async (req, res, next) => {
    try{
        const items =  await Item.find({})
        req.items = items
        next()
    }
    catch(e){
        req.error = e.message
        next()
    }

}


问:
How can I inject an image into a list of images pulling from an API using jQuery?
When viewing this url http://dl.dropbox.com/u/1550420/jquery/flickr.html, we see a list of images pulling from an API (flickr).

I’d like to inject the following image http://dl.dropbox.com/u/1550420/jquery/chicago-008.jpg into the 3rd position of my list, thus increasing the length of my list.

In summary, the list would have 1 image inserted into it at the 3rd position.  The image would come from a unique url, not from the same API.

How do I accomplish that?

Here's my code, in case the link above doesn't work:

```<code><script>
    $(document).ready(function() {
        $.getJSON("http://api.flickr.com/services/feeds/groups_pool.gne?id=675729@N22&lang=en-us&format=json&jsoncallback=?", function(data){
          $.each(data.items, function(){
            var raffie = '<a href="' + this.link + '"></a>';
            $('<li></li>')
            .append(raffie)
            .appendTo('#pic');
            $('<img />').attr('src', this.media.m)
            .appendTo('#pic');
          });
        });
    });
</script>
</code>```

and here's the hard-coded html from the body:

```<code><ul><li id="pic"></li></ul>
</code>```

答:
In your code, it looks like appending li into another li, which is not allowed.

How about this. Markup looks like this: (
 is not really necessary since we are overwriting it, but this way page validates)

```<code><ul id="pic"><li></li></ul>
</code>```

Then the JS code looks like this:

```<code><script type="text/javascript">
    $(document).ready(function() {
        $.getJSON("http://api.flickr.com/services/feeds/groups_pool.gne?id=675729@N22&lang=en-us&format=json&jsoncallback=?", function(data)
        {
            var html = '';
            $.each(data.items, function()
            {
               // Avoid appending to document DOM multiple times to improve performance
               html += '<li><a href="' + this.link + '"><img src="' + this.media.m + '"/></a></li>')
            });
            // 3rd hardcoded image
            html += '<li><a href="#"><img src="http://dl.dropbox.com/u/1550420/jquery/chicago-008.jpg"/></a></li>';

            // Now put it into the page
            $('#pic').html(html);
        });
    });
</script>
</code>```

Body:
When viewing this url http://dl.dropbox.com/u/1550420/jquery/flickr.html, we see a list of images pulling from an API (flickr).

I’d like to inject the following image http://dl.dropbox.com/u/1550420/jquery/chicago-008.jpg into the 3rd position of my list, thus increasing the length of my list.

In summary, the list would have 1 image inserted into it at the 3rd position.  The image would come from a unique url, not from the same API.

How do I accomplish that?

Here's my code, in case the link above doesn't work:

and here's the hard-coded html from the body:

Body:
In your code, it looks like appending li into another li, which is not allowed.

How about this. Markup looks like this: (<li> is not really necessary since we are overwriting it, but this way page validates)

<ul id="pic"><li></li></ul>

Then the JS code looks like this:

<script type="text/javascript">
    $(document).ready(function() {
        $.getJSON("http://api.flickr.com/services/feeds/groups_pool.gne?id=675729@N22&lang=en-us&format=json&jsoncallback=?", function(data)
        {
            var html = '';
            $.each(data.items, function()
            {
               // Avoid appending to document DOM multiple times to improve performance
               html += '<li><a href="' + this.link + '"><img src="' + this.media.m + '"/></a></li>')
            });
            // 3rd hardcoded image
            html += '<li><a href="#"><img src="http://dl.dropbox.com/u/1550420/jquery/chicago-008.jpg"/></a></li>';

            // Now put it into the page
            $('#pic').html(html);
        });
    });
</script>


问:
Better way of converting to lowercase only if it is of type string
I need to sort a table that has columns of varying data types. The problem with sorting the strings is that they are case sensitive. The original code is

```<code>const Details = sortWith(
    sortDir === 'ASC'
        ? ascend((row) => row.data[col])
        : descend((row) => row.data[col])
)
</code>```

and I updated it to the following which works

```<code>const Details = sortWith(
    sortDir === 'ASC'
        ? ascend((row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col])
        : descend((row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col])
)
</code>```

Is there a better way to do this?

答:
Welcome to Stack Overflow.  Please, in the future, try to post a Minimal Reproducible Example with your question.

I'm not sure whether this will help, but here is a configuration-based sorting function generator, built on Ramda's sorting capabilities:

const mySorter = (config) =>
  sortWith (config .map (
    ({col, sortDir  = 'ASC'}) => (sortDir == 'ASC' ? ascend : descend)
      (pipe (path (['data', col]), when (is (String), toLower)))
  ))

const data = [{data: {first: 'Fred', last: 'Flintstone', age: 31}}, {data: {first: 'Wilma', last: 'Flintstone', age: 29}}, {data: {first: 'pebbles', last: 'flintstone', age: 1}}, {data: {first: 'Barney', last: 'Rubble', age: 29}}, {data: {first: 'bambam', last: 'Rubble', age: 1.5}}, {data: {first: 'Betty', last: 'Rubble', age: 33}}]

console .log (
  mySorter ([{col: 'age'}, {col: 'last', sortDir: 'DESC'}]) (data)
)

console .log (mySorter ([{col: 'first'}]) (data))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {max-height: 100% !important; top: 0}</code>```

```

The part about lowercasing only the strings is when (is (String), toLower), which seems eminently readable.

Body:
I need to sort a table that has columns of varying data types. The problem with sorting the strings is that they are case sensitive. The original code is

const Details = sortWith(
    sortDir === 'ASC'
        ? ascend((row) => row.data[col])
        : descend((row) => row.data[col])
)

and I updated it to the following which works

const Details = sortWith(
    sortDir === 'ASC'
        ? ascend((row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col])
        : descend((row) => typeof row.data[col] === 'string' ? row.data[col].toLowerCase() : row.data[col])
)

Is there a better way to do this?

Body:
Welcome to Stack Overflow.  Please, in the future, try to post a Minimal Reproducible Example with your question.

I'm not sure whether this will help, but here is a configuration-based sorting function generator, built on Ramda's sorting capabilities:

const mySorter = (config) =>
  sortWith (config .map (
    ({col, sortDir  = 'ASC'}) => (sortDir == 'ASC' ? ascend : descend)
      (pipe (path (['data', col]), when (is (String), toLower)))
  ))

const data = [{data: {first: 'Fred', last: 'Flintstone', age: 31}}, {data: {first: 'Wilma', last: 'Flintstone', age: 29}}, {data: {first: 'pebbles', last: 'flintstone', age: 1}}, {data: {first: 'Barney', last: 'Rubble', age: 29}}, {data: {first: 'bambam', last: 'Rubble', age: 1.5}}, {data: {first: 'Betty', last: 'Rubble', age: 33}}]

console .log (
  mySorter ([{col: 'age'}, {col: 'last', sortDir: 'DESC'}]) (data)
)

console .log (mySorter ([{col: 'first'}]) (data))

.as-console-wrapper {max-height: 100% !important; top: 0}

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
<script>const {sortWith, ascend, descend, pipe, path, when, is, toLower} = R</script>

The part about lowercasing only the strings is when (is (String), toLower), which seems eminently readable.


问:
How to read data form cloud SQL in Google Cloud Function in Node JS
I am new in Google Cloud Function, Here am trying to load data from cloud SQL for that I have written a code, which has database connection as well as SQL query string however when am trying to test the function it is throwing either error or Object or sometime it says you are not returning any data. I tried many ways to send data but still doesn't work for me. Thanks in advance.

Code snippets,

```<code>exports.welcome = async (req, res) => {
  const tag = req?.body?.fulfillmentInfo?.tag;
  let message = tag || req?.query?.message || req?.body?.message || 'Hello World!';

  const pool = mysql.createPool({
    connectionLimit: 1,
    host: '10.30.48.2',
    user: 'root',
    password: 'TEST@TEST',
    database: 'hospital_assist'
  });

  const jsonResponse = {
    fulfillment_response: {
      messages: [
        {
          text: {
            //fulfillment text response to be sent to the agent
            text: [`Welcome entry point ${message}`],
          },
        },
      ],
    },
  };

  let qResult = await pool.query('SELECT * FROM Patients;');
  // pool.query('SELECT * FROM Patints', (error, result) => {
  //   console.log(error);
  //   console.log(result);
  //   console.log('In loop');
  //   res.status(200).send(jsonResponse);
  // });

  // await pool.query('select * from Patients;', (error, results) => {
  //       if (error) {
  //           console.log(error);
  //           res.status(200).send(jsonResponse);
  //       }
  //       qResult = results;
  //       // res.send(results);
  //   });

  console.log(qResult);
  console.log(`In loop ${qResult}`);
  res.status(200).send(JSON.stringify(qResult));

  // res.status(200).send(jsonResponse);
};
</code>```

答:
In your case, you have several solutions, 2 are specially recommended:

Use internal IP (your current code). With that pattern, you can remove the public IP and hide totally the database from the internet. To allow CLoud Functions accessing private IP, you have to bridge the serverless world (the server and the network is managed for you by Google Cloud, and therefore you aren't in your VPC) with your project world (especially your VPC where your database is connected). A serverless VPC connector is done for that.

With Cloud Functions you can use a built-in connector with Cloud SQL MySQL (only in version 8). It opens a linux socket and you have to use a driver/library that support that socket communication mode. The advantage here is the encryption of the database communication through the built-in connector.

Note: with a Cloud SQL public IP avoid to authorized network on your Cloud SQL database to keep a good level of security

Body:
I am new in Google Cloud Function, Here am trying to load data from cloud SQL for that I have written a code, which has database connection as well as SQL query string however when am trying to test the function it is throwing either error or Object or sometime it says you are not returning any data. I tried many ways to send data but still doesn't work for me. Thanks in advance.

Code snippets,

exports.welcome = async (req, res) => {
  const tag = req?.body?.fulfillmentInfo?.tag;
  let message = tag || req?.query?.message || req?.body?.message || 'Hello World!';

  const pool = mysql.createPool({
    connectionLimit: 1,
    host: '10.30.48.2',
    user: 'root',
    password: 'TEST@TEST',
    database: 'hospital_assist'
  });

  const jsonResponse = {
    fulfillment_response: {
      messages: [
        {
          text: {
            //fulfillment text response to be sent to the agent
            text: [`Welcome entry point ${message}`],
          },
        },
      ],
    },
  };

  let qResult = await pool.query('SELECT * FROM Patients;');
  // pool.query('SELECT * FROM Patints', (error, result) => {
  //   console.log(error);
  //   console.log(result);
  //   console.log('In loop');
  //   res.status(200).send(jsonResponse);
  // });

  // await pool.query('select * from Patients;', (error, results) => {
  //       if (error) {
  //           console.log(error);
  //           res.status(200).send(jsonResponse);
  //       }
  //       qResult = results;
  //       // res.send(results);
  //   });

  console.log(qResult);
  console.log(`In loop ${qResult}`);
  res.status(200).send(JSON.stringify(qResult));

  // res.status(200).send(jsonResponse);
};


答:
After you're done appending all your images to the DOM, you should select the 2nd image, and insert that other image after it:

```<code>$('#pic img:eq(1)').after('<li><img src="http://dl.dropbox.com/u/1550420/jquery/chicago-008.jpg" /></li>');
</code>```

Here's the fiddle: http://jsfiddle.net/LbtWJ/ .

P.S. You shouldn't be appending your images to the DOM separately, but that's besides the point.

Title: How can I inject an image into a list of images pulling from an API using jQuery?

Body:
After you're done appending all your images to the DOM, you should select the 2nd image, and insert that other image after it:

$('#pic img:eq(1)').after('<li><img src="http://dl.dropbox.com/u/1550420/jquery/chicago-008.jpg" /></li>');

Here's the fiddle: http://jsfiddle.net/LbtWJ/ .

P.S. You shouldn't be appending your images to the DOM separately, but that's besides the point.


问:
Apache internal server error for Perl scripts
I am installing a LAMP (Linux, Apache, MySQL, Perl) stack and I have an issue running some scripts on the web server. I have given full permissions (755) on the directories and files but still receive 500 internal server errors on some files.

See below browser console error & apache error log.

apache2.conf file:

答:
The error is specified in the picture, together with a fix. Fix the code: remove defined from the indicated line.

See defined for details.


答:
If you're trying to connect to your instance using public IP, you'll need to specify a Unix socket path, e.g.,

mysql.createPool({
    user: process.env.DB_USER, // e.g. 'my-db-user'
    password: process.env.DB_PASS, // e.g. 'my-db-password'
    database: process.env.DB_NAME, // e.g. 'my-database'
    // If connecting via unix domain socket, specify the path
    socketPath: "/cloudsql/my-project:us-central1:my-instance",
    // Specify additional properties here.
    ...config,
});

```

See the docs for details.

Title: How to read data form cloud SQL in Google Cloud Function in Node JS

Body:
If you're trying to connect to your instance using public IP, you'll need to specify a Unix socket path, e.g.,

mysql.createPool({
    user: process.env.DB_USER, // e.g. 'my-db-user'
    password: process.env.DB_PASS, // e.g. 'my-db-password'
    database: process.env.DB_NAME, // e.g. 'my-database'
    // If connecting via unix domain socket, specify the path
    socketPath: "/cloudsql/my-project:us-central1:my-instance",
    // Specify additional properties here.
    ...config,
});

See the docs for details.


问:
'Prophet' object has no attribute 'stan_backend'
I'm trying to use Facebook prophet for a project. The problem is that when I try to use it I have an error :

'Prophet' object has no attribute 'stan_backend'

when I initialize the prophet

```<code>from prophet import Prophet
m = Prophet()
</code>```

I have installed prophet and pystan 1.19.1.1 using a pipenv. Here is my Pipfile

```<code>numpy = "~=1.20.2"
pystan = "~=2.19.1.1"
prophet = "~=1.0.1"
</code>```

Any idea of what am I doing wrong? The strangest part is that when I make test on a jupyter notebook I don't get this problem (in that case I just used pip to install prophet)

By the way I'm on IntelliJ since I also use java in my project

答:
This method works for me :

Creating new environment and use conda install -c conda-forge prophet in cmd

Body:
I'm trying to use Facebook prophet for a project. The problem is that when I try to use it I have an error :

'Prophet' object has no attribute 'stan_backend'

when I initialize the prophet

from prophet import Prophet
m = Prophet()

I have installed prophet and pystan 1.19.1.1 using a pipenv. Here is my Pipfile

numpy = "~=1.20.2"
pystan = "~=2.19.1.1"
prophet = "~=1.0.1"

Any idea of what am I doing wrong? The strangest part is that when I make test on a jupyter notebook I don't get this problem (in that case I just used pip to install prophet)

By the way I'm on IntelliJ since I also use java in my project


问:
MacOS 12.1 cannot find my brew install of GNU binutils
I want to use GNU binutils to inspect an executable on MacOS 12.1. I did a

```<code>% brew install binutils
</code>```

and it seemed to go fine. First I tried just a

```<code>% readelf <executable>
</code>```

but was given:

```<code>zsh: command not found: readelf
</code>```

Then I tried checking on binutils itself:

```<code>% binutils -v
</code>```

which gave me

```<code>zsh: command not found: binutils
</code>```

I tried adding both

```<code>/usr/local/opt/binutils
</code>```

and

```<code>/usr/local/Cellar/binutils
</code>```

to my $PATH and restarting zsh. The filepaths were in my $PATH, and homebrew had put 'binutils' in the expected locations. But

```<code>% binutils -v
</code>```

still gives me

```<code>zsh: command not found: binutils
</code>```

.
Has anyone gotten binutils to work on Mac? What am I missing?

答:
The path /usr/local/opt/binutils/bin should be added to your PATH environment variable.

You probably didn't notice the output from brew install binutils:

binutils is keg-only, which means it was not symlinked into
/usr/local, because Apple's CLT provides the same tools.

If you need to have binutils first in your PATH, run:   echo 'export
PATH="/usr/local/opt/binutils/bin:$PATH"' >>
/Users/ipellegrini/.bash_profile

For compilers to find binutils you may need to set:   export
LDFLAGS="-L/usr/local/opt/binutils/lib"   export
CPPFLAGS="-I/usr/local/opt/binutils/include"

So should be enough to:

⤵

run echo 'export PATH="/usr/local/opt/binutils/bin:$PATH"' >> ~/.bash_profile in order to add the bin folder to PATH, automatically, every time you open a new command-line shell.

close the current shell and open a new one, for triggering the .bash_profile and making the command available for use.

run which readelf to ensure that your desired command is found & reachable

Enjoy

Body:
I want to use GNU binutils to inspect an executable on MacOS 12.1. I did a

% brew install binutils

and it seemed to go fine. First I tried just a

% readelf <executable>

but was given:

zsh: command not found: readelf

Then I tried checking on binutils itself:

% binutils -v

which gave me

zsh: command not found: binutils

I tried adding both

/usr/local/opt/binutils

and

/usr/local/Cellar/binutils

to my $PATH and restarting zsh. The filepaths were in my $PATH, and homebrew had put 'binutils' in the expected locations. But

% binutils -v

still gives me

zsh: command not found: binutils

.
Has anyone gotten binutils to work on Mac? What am I missing?


问:
keyword argument clashes with variable
Although this is most likely a newbie question I struggled to find any information online to help me with my problem

My code is meant to scrap onion sites, and despite being able to connect to TOR and the web scraper working fine as a stand-alone, when I tried combining both code blocks I kept getting numerous errors regarding the keyword argument in my code, even attempting to delete it presents me with bugs, I am a bit lost on what I'm supposed to do

```<code>import socket
import socks
import requests
from pywebcopy import save_webpage

socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket

def get_tor_session():
    session = requests.session()
    # Tor uses the 9050 port as the default socks port
    session.proxies = {'http':  'socks5h://127.0.0.1:9050',
                       'https': 'socks5h://127.0.0.1:9050'}
    return session

session = get_tor_session()
print(session.get("http://httpbin.org/ip").text)

kwargs = {'project_name': 'site folder'}

save_webpage(

        # url of the website

session.get(url="http://elfqv3zjfegus3bgg5d7pv62eqght4h6sl6yjjhe7kjpi2s56bzgk2yd.onion"),

    # folder where the copy will be saved

        project_folder=r"C:\Users\admin\Desktop\WebScraping",
        **kwargs
)
</code>```

In this case, I'm presented with the following error:

TypeError: Cannot mix str and non-str arguments

attempting to replace

```<code>project_folder=r"C:\Users\admin\Desktop\WebScraping",
**kwargs
</code>```

with

```<code>kwargs,
project_folder=r"C:\Users\admin\Desktop\WebScraping"
</code>```

presents me with this error:

TypeError: save_webpage() got multiple values for argument

traceback for the first error:

```<code>  File "C:\Users\admin\Desktop\WebScraping\tor.py", line 43, in <module>
    **kwargs

  File "C:\Users\admin\anaconda3\lib\site-packages\pywebcopy\api.py", line 58, in save_webpage
    config.setup_config(url, project_folder, project_name, **kwargs)

  File "C:\Users\admin\anaconda3\lib\site-packages\pywebcopy\configs.py", line 189, in setup_config
    SESSION.load_rules_from_url(urljoin(project_url, '/robots.txt'))

  File "C:\Users\admin\anaconda3\lib\urllib\parse.py", line 487, in urljoin
    base, url, _coerce_result = _coerce_args(base, url)

  File "C:\Users\admin\anaconda3\lib\urllib\parse.py", line 120, in _coerce_args
    raise TypeError("Cannot mix str and non-str arguments")
</code>```

I'd really appreciate an explanation on what causes such a bug and how to avoid it in the future

答:
Not sure why this hasn't been answered yet. As mentioned in my comment, simply change this:

```<code>save_webpage(
    # url of the website
    session.get(url=...),

    # folder where the copy will be saved
    project_folder=r"C:\Users\admin\Desktop\WebScraping",
    **kwargs
)
</code>```

To:

```<code>save_webpage(
    # url of the website
    url=...,

    # folder where the copy will be saved
    project_folder=r"C:\Users\admin\Desktop\WebScraping",
    **kwargs
)
</code>```

save_webpage makes the request internally.

Title: keyword argument clashes with variable

Body:
Although this is most likely a newbie question I struggled to find any information online to help me with my problem

My code is meant to scrap onion sites, and despite being able to connect to TOR and the web scraper working fine as a stand-alone, when I tried combining both code blocks I kept getting numerous errors regarding the keyword argument in my code, even attempting to delete it presents me with bugs, I am a bit lost on what I'm supposed to do

import socket
import socks
import requests
from pywebcopy import save_webpage

socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket

def get_tor_session():
    session = requests.session()
    # Tor uses the 9050 port as the default socks port
    session.proxies = {'http':  'socks5h://127.0.0.1:9050',
                       'https': 'socks5h://127.0.0.1:9050'}
    return session

session = get_tor_session()
print(session.get("http://httpbin.org/ip").text)

kwargs = {'project_name': 'site folder'}

save_webpage(

        # url of the website

session.get(url="http://elfqv3zjfegus3bgg5d7pv62eqght4h6sl6yjjhe7kjpi2s56bzgk2yd.onion"),

    # folder where the copy will be saved

        project_folder=r"C:\Users\admin\Desktop\WebScraping",
        **kwargs
)

In this case, I'm presented with the following error:

TypeError: Cannot mix str and non-str arguments

attempting to replace

project_folder=r"C:\Users\admin\Desktop\WebScraping",
**kwargs

with

kwargs,
project_folder=r"C:\Users\admin\Desktop\WebScraping"

presents me with this error:

TypeError: save_webpage() got multiple values for argument

traceback for the first error:

  File "C:\Users\admin\Desktop\WebScraping\tor.py", line 43, in <module>
    **kwargs

  File "C:\Users\admin\anaconda3\lib\site-packages\pywebcopy\api.py", line 58, in save_webpage
    config.setup_config(url, project_folder, project_name, **kwargs)

  File "C:\Users\admin\anaconda3\lib\site-packages\pywebcopy\configs.py", line 189, in setup_config
    SESSION.load_rules_from_url(urljoin(project_url, '/robots.txt'))

  File "C:\Users\admin\anaconda3\lib\urllib\parse.py", line 487, in urljoin
    base, url, _coerce_result = _coerce_args(base, url)

  File "C:\Users\admin\anaconda3\lib\urllib\parse.py", line 120, in _coerce_args
    raise TypeError("Cannot mix str and non-str arguments")

I'd really appreciate an explanation on what causes such a bug and how to avoid it in the future

Body:
Not sure why this hasn't been answered yet. As mentioned in my comment, simply change this:

save_webpage(
    # url of the website
    session.get(url=...),

    # folder where the copy will be saved
    project_folder=r"C:\Users\admin\Desktop\WebScraping",
    **kwargs
)

To:

save_webpage(
    # url of the website
    url=...,

    # folder where the copy will be saved
    project_folder=r"C:\Users\admin\Desktop\WebScraping",
    **kwargs
)

save_webpage makes the request internally.


问:
android: showquickcontact() works great on froyo, not on eclair, which throws an ActivityNotFound exception
I've done a lot of googling over the days and I haven't been able to get this problem solved. I'm writing an app and a widget in which I want the quick contact dialog displayed when the user clicks on an ImageView or some other view element by calling QuickContact.showQuickContact(). For some reason, every time I try on Eclair, I get the following error thrown:

01-02 17:51:28.869: ERROR/AndroidRuntime(657):
  java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.sx.favwidget/com.sx.favwidget.PopupActivity}:
  android.content.ActivityNotFoundException: No Activity found to handle
  Intent { act=com.android.contacts.action.QUICK_CONTACT
  dat=content://com.android.contacts/contacts/lookup/0n4D29415739
  flg=0x14200000 (has extras)

(I left out the rest of the logcat, but I can put it back if you guys need it)

When I try the exact same code on Froyo, it just works. I don't want to have my app targeted only for Froyo users - I'm targeting 2.1 as the minimum OS level. I've found some other people on Stack Overflow struggling with getting QuickContacts to display.

I could use a QuickContactBadge, and that does work on Eclair, but I'm not allowed a QuickContactBadge in an AppWidget, so I have do this instead. I dug through Android's source code and found the relevant XML files and code for creating the layout but I can't just easily compile it myself because it's a huge headache with all the private API calls.

Here is my code. It's simple.

```<code>grid.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

        String name = ((TextView)v.findViewById(R.id.grid_item_label)).getText().toString();

        Cursor sc = getContentResolver().query(Contacts.CONTENT_URI, new String[] {Contacts.LOOKUP_KEY,   Contacts._ID}, Contacts.DISPLAY_NAME + "= ?", new String[] {name}, null);

        sc.moveToFirst();

        String lookup_key = sc.getString(sc.getColumnIndex(Contacts.LOOKUP_KEY));

        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookup_key);

        QuickContact.showQuickContact(getApplicationContext(), v, uri, QuickContact.MODE_SMALL, null);

        }
}
</code>```

It's just so strange that it works on Froyo, not Eclair, but the API call has been there since Android 2.0. Can anyone help me here??

Thanks so much!!!

答:
I solved this as well some time ago but forgot to post how. What I did was launch a new activity that was transparent, and I got the rectangle from which the intent was launched. This activity had only a QuickContactBadge element, so I positioned it using the rectangle and performed a click action automatically on it. Once this was displayed, I finished the activity - but the badge remains. Therefore, when the person clicked out of the QuickContactBadge, they'd be right back to where they started.

I didn't get a chance to peruse your (Omegamon) code thoroughly - is your method similar to mine?

Body:
I've done a lot of googling over the days and I haven't been able to get this problem solved. I'm writing an app and a widget in which I want the quick contact dialog displayed when the user clicks on an ImageView or some other view element by calling QuickContact.showQuickContact(). For some reason, every time I try on Eclair, I get the following error thrown:

01-02 17:51:28.869: ERROR/AndroidRuntime(657):
  java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.sx.favwidget/com.sx.favwidget.PopupActivity}:
  android.content.ActivityNotFoundException: No Activity found to handle
  Intent { act=com.android.contacts.action.QUICK_CONTACT
  dat=content://com.android.contacts/contacts/lookup/0n4D29415739
  flg=0x14200000 (has extras)

(I left out the rest of the logcat, but I can put it back if you guys need it)

When I try the exact same code on Froyo, it just works. I don't want to have my app targeted only for Froyo users - I'm targeting 2.1 as the minimum OS level. I've found some other people on Stack Overflow struggling with getting QuickContacts to display.

I could use a QuickContactBadge, and that does work on Eclair, but I'm not allowed a QuickContactBadge in an AppWidget, so I have do this instead. I dug through Android's source code and found the relevant XML files and code for creating the layout but I can't just easily compile it myself because it's a huge headache with all the private API calls.

Here is my code. It's simple.

grid.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

        String name = ((TextView)v.findViewById(R.id.grid_item_label)).getText().toString();

        Cursor sc = getContentResolver().query(Contacts.CONTENT_URI, new String[] {Contacts.LOOKUP_KEY,   Contacts._ID}, Contacts.DISPLAY_NAME + "= ?", new String[] {name}, null);

        sc.moveToFirst();

        String lookup_key = sc.getString(sc.getColumnIndex(Contacts.LOOKUP_KEY));

        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookup_key);

        QuickContact.showQuickContact(getApplicationContext(), v, uri, QuickContact.MODE_SMALL, null);

        }
}

It's just so strange that it works on Froyo, not Eclair, but the API call has been there since Android 2.0. Can anyone help me here??

Thanks so much!!!