问:
Tensorflow LinearClassifier get individual prediction values
I am trying to write Linear classifier using Tensorflow using the following code which works.

```<code>m = LinearClassifier(model_dir = model_dir, feature_columns = wide_columns)
m.fit (input_fn=training, steps=FLAGS.train_steps)
results = h.evaluate(input_fn=test, steps=1)
for key in sorted(results):
    print ("%s: %s", key, results[key])
</code>```

However, I am interested in having an ndarray of predictions (i.e. array of 0s and 1s) for each test-feature.
I would like to compute some more values (than accuracy and precision) based on these predictions.

Following is the output I get:

```<code>accuracy: 0.931035
accuracy/baseline_label_mean: 0.931035
accuracy/threshold_0.500000_mean: 0.931035
auc: 0.5
global_step: 202
labels/actual_label_mean: 0.931035
labels/prediction_mean: 1.0
loss: 1.11758e+11
precision/positive_threshold_0.500000_mean: 0.931035
recall/positive_threshold_0.500000_mean: 1.0
</code>```

Following is the output I expect:
(first five numbers are training features and 1 and 0 is the label of classifier)

```<code>1,2,3,4,5 : 1
3,4,4,2,1 : 0
1,2,3,4,1 : 1
1,2,3,4,5 : 1
4,4,2,2,2 : 0
5,4,1,2,1 : 0
</code>```

How can I get such an output from Tensorflow APIs ?

答:
I found a solution after some research. I hope it helps someone:</p>

```<code>predictions = m.predict(input_fn = lambda:input_fn(df_test), as_iterable = False)
for p in predictions:
    print(str(p), "\n")
</code>```

Body:
I am trying to write Linear classifier using Tensorflow using the following code which works.

m = LinearClassifier(model_dir = model_dir, feature_columns = wide_columns)
m.fit (input_fn=training, steps=FLAGS.train_steps)
results = h.evaluate(input_fn=test, steps=1)
for key in sorted(results):
    print ("%s: %s", key, results[key])

However, I am interested in having an ndarray of predictions (i.e. array of 0s and 1s) for each test-feature.
I would like to compute some more values (than accuracy and precision) based on these predictions.

Following is the output I get:

accuracy: 0.931035
accuracy/baseline_label_mean: 0.931035
accuracy/threshold_0.500000_mean: 0.931035
auc: 0.5
global_step: 202
labels/actual_label_mean: 0.931035
labels/prediction_mean: 1.0
loss: 1.11758e+11
precision/positive_threshold_0.500000_mean: 0.931035
recall/positive_threshold_0.500000_mean: 1.0

Following is the output I expect:
(first five numbers are training features and 1 and 0 is the label of classifier)

1,2,3,4,5 : 1
3,4,4,2,1 : 0
1,2,3,4,1 : 1
1,2,3,4,5 : 1
4,4,2,2,2 : 0
5,4,1,2,1 : 0

How can I get such an output from Tensorflow APIs ?

Body:
I found a solution after some research. I hope it helps someone:

predictions = m.predict(input_fn = lambda:input_fn(df_test), as_iterable = False)
for p in predictions:
    print(str(p), "\n")


来源: stackexchange

答:
I'm not sure if thereis inline avg math func, but you can easily mock it up with arythmetics:

```<code>t=# select ((lower(power_range) + upper(power_range))/2)::float(2),extract(year from d) avg From rt;
 float4 | avg
--------+------
   0.06 | 1985
   0.02 | 1985
   0.08 | 1986
  0.055 | 1986
  0.065 | 1987
  0.075 | 1987
  0.055 | 1987
(7 rows)
</code>```

where rt is created from your sample:

```<code>t=# create table rt(Power_range numrange, unit text, d date);
CREATE TABLE
t=# copy rt from stdin delimiter ';';
</code>```

https://www.postgresql.org/docs/current/static/functions-range.html

ContentLicense: CC BY-SA 3.0

Title: postgresql average of numrange

Body:
I have a Postgresql table with following data

Power_range;unit; Date
[0.055,0.065];un_MW_el;14.01.1985
[0.02,0.02];un_MW_el;22.08.1985
[0.075,0.085];un_MW_el;09.04.1986
[0.055,0.055];un_MW_el;01.08.1986
[0.065,0.065];un_MW_el;19.01.1987
[0.075,0.075];un_MW_el;16.04.1987
[0.055,0.055];un_MW_el;15.05.1987

How can we query to list the average of numrange for each year/row?

The end result should be something like

0.060;1985
0.2;1985
0.80;1986
0.055;1986
0.065;1987
0.075;1987
0.055;1987

Body:
I'm not sure if thereis inline avg math func, but you can easily mock it up with arythmetics:

t=# select ((lower(power_range) + upper(power_range))/2)::float(2),extract(year from d) avg From rt;
 float4 | avg
--------+------
   0.06 | 1985
   0.02 | 1985
   0.08 | 1986
  0.055 | 1986
  0.065 | 1987
  0.075 | 1987
  0.055 | 1987
(7 rows)

where rt is created from your sample:

t=# create table rt(Power_range numrange, unit text, d date);
CREATE TABLE
t=# copy rt from stdin delimiter ';';

https://www.postgresql.org/docs/current/static/functions-range.html


问:
How to loop output in python, pandas?

I want to randomly select data on a quarterly basis and set the output in different csv files, and make this loop for several years. The following is an example of data.

Event number	Month	Year	Unauthorised activity	Theft and fraud (internal)	Theft and fraud (external)

72	1	2015	0	1	1

73	2	2015	0	0	0

74	3	2015	0	0	1

75	4	2015	0	0	0

76	5	2015	0	0	0

80	6	2015	0	0	0

81	7	2015	0	0	1

83	8	2015	0	1	0

84	9	2015	0	0	0

87	10	2015	0	0	1

90	11	2015	0	0	0

103	12	2015	1	0	0

```
</div>
</div>
</p>

<p>
Here is my current code:</p>

```df = pd.read_pickle('data.pkl')
df.set_index(['Claim  Number'], inplace = True)

df2015q1 = df[(1 <= df.Month )&(df.Month <= 3) & (df.Year == 2015)]

df2015q1_random = df2015q1.sample(n=200)
df2015q1_random.sort_index(inplace=True)
df2015q1_random = df2015q1_random.drop(['Month', 'Year'], axis = 1)
df2015q1_random = df2015q1_random.drop_duplicates()

df2015q1_random.to_csv('2015Q1.csv')
```

The expected output for 2015 quarter 1 is 2015Q1.csv，for quarter 2 is 2015Q2.csv etc.

Currently, my output for a single stage is right, but I do not know how to write a loop for this. How can I do this for several years, say 2010 to 2016, and write the output in different files? Thanks.

答:
You can use something like this   </p>

```<code>years = [2015,2016]
qtrs = [1,2,3,4]
for year in years:
    for qtr in qtrs:
        temp = df[(df.Month <= 3*qtr) (df.Month >= 3*(qtr-1)) & (df.Year == year)]
        temp_random = temp.sample(n=200)
        temp_random.sort_index(inplace=True)
        temp_random = temp_random.drop(['Month', 'Year'], axis = 1)
        temp_random = temp_random.drop_duplicates()
        temp_random.to_csv((str(year)+'Q'+str(qtr)+'.csv')
</code>```

Title: How to loop output in python, pandas?

Body:
I want to randomly select data on a quarterly basis and set the output in different csv files, and make this loop for several years. The following is an example of data.

Event number	Month	Year	Unauthorised activity	Theft and fraud (internal)	Theft and fraud (external)

72	1	2015	0	1	1

73	2	2015	0	0	0

74	3	2015	0	0	1

75	4	2015	0	0	0

76	5	2015	0	0	0

80	6	2015	0	0	0

81	7	2015	0	0	1

83	8	2015	0	1	0

84	9	2015	0	0	0

87	10	2015	0	0	1

90	11	2015	0	0	0

103	12	2015	1	0	0

Here is my current code:

df = pd.read_pickle('data.pkl')
df.set_index(['Claim  Number'], inplace = True)

df2015q1 = df[(1 <= df.Month )&(df.Month <= 3) & (df.Year == 2015)]

df2015q1_random = df2015q1.sample(n=200)
df2015q1_random.sort_index(inplace=True)
df2015q1_random = df2015q1_random.drop(['Month', 'Year'], axis = 1)
df2015q1_random = df2015q1_random.drop_duplicates()

df2015q1_random.to_csv('2015Q1.csv')

The expected output for 2015 quarter 1 is 2015Q1.csv，for quarter 2 is 2015Q2.csv etc.

Currently, my output for a single stage is right, but I do not know how to write a loop for this. How can I do this for several years, say 2010 to 2016, and write the output in different files? Thanks.

Body:
You can use something like this

years = [2015,2016]
qtrs = [1,2,3,4]
for year in years:
    for qtr in qtrs:
        temp = df[(df.Month <= 3*qtr) (df.Month >= 3*(qtr-1)) & (df.Year == year)]
        temp_random = temp.sample(n=200)
        temp_random.sort_index(inplace=True)
        temp_random = temp_random.drop(['Month', 'Year'], axis = 1)
        temp_random = temp_random.drop_duplicates()
        temp_random.to_csv((str(year)+'Q'+str(qtr)+'.csv')


问:
OuterGlow effect in WPF not working with layered window?
can any one tell me why /no/ outerglow effects are working on my WPF Window? here is an example of the code:

```<code><Window x:Class="SocialShock_WPF_Client.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        AllowsTransparency="True"
        WindowStyle='None'
        Background="Transparent"
        Loaded="Window_Loaded">
    <Grid>
        <Rectangle Margin="12" Name="rectangle1" Fill="#FFB75050">
            <Rectangle.BitmapEffect>
                <OuterGlowBitmapEffect GlowColor="Black" GlowSize="20" />
            </Rectangle.BitmapEffect>
        </Rectangle>
    </Grid>
</Window>
</code>```

and the resulting image:

http://img408.imageshack.us/img408/6213/1c1761f31ce6408d948e266.png

No glow around the edge.
not only is the glow not appearing on the rectangle, but any other controls i add to the window cannot accept glows either.

EDIT: its in .Net 4.0

答:
BitmapEffects are no longer supported in .NET 4.0.

From MSDN

Important  In the .NET Framework 4 or
  later, the BitmapEffect class is
  obsolete. If you try to use the
  BitmapEffect class, you will get an
  obsolete exception. The non-obsolete
  alternative to the BitmapEffect class
  is the Effect class. In most
  situations, the Effect class is
  significantly faster.

There isn't a really good substitute but you can try to use a DropShadowEffect with a ShadowDepth of 0. Example

```<code><Rectangle Margin="12" Name="rectangle1" Fill="#FFB75050">
    <Rectangle.Effect>
        <DropShadowEffect ShadowDepth="0"
                          Color="Black"
                          Opacity="1"
                          BlurRadius="12"/>
    </Rectangle.Effect>
</Rectangle>
</code>```

If I understood you comment correctly,

Adding the effect in code behind

```<code>DropShadowEffect dropShadowEffect = new DropShadowEffect();
dropShadowEffect.ShadowDepth = 0;
dropShadowEffect.Color = Colors.Black;
dropShadowEffect.Opacity = 1;
dropShadowEffect.BlurRadius = 12;
rectangle1.Effect = dropShadowEffect;
</code>```

Modifying the effect in code behind

```<code>DropShadowEffect dropShadowEffect = rectangle1.Effect as DropShadowEffect;
dropShadowEffect.BlurRadius = 24;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
can any one tell me why /no/ outerglow effects are working on my WPF Window? here is an example of the code:

<Window x:Class="SocialShock_WPF_Client.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        AllowsTransparency="True"
        WindowStyle='None'
        Background="Transparent"
        Loaded="Window_Loaded">
    <Grid>
        <Rectangle Margin="12" Name="rectangle1" Fill="#FFB75050">
            <Rectangle.BitmapEffect>
                <OuterGlowBitmapEffect GlowColor="Black" GlowSize="20" />
            </Rectangle.BitmapEffect>
        </Rectangle>
    </Grid>
</Window>

and the resulting image:

http://img408.imageshack.us/img408/6213/1c1761f31ce6408d948e266.png

No glow around the edge.
not only is the glow not appearing on the rectangle, but any other controls i add to the window cannot accept glows either.

EDIT: its in .Net 4.0

Body:
BitmapEffects are no longer supported in .NET 4.0.

From MSDN

Important  In the .NET Framework 4 or
  later, the BitmapEffect class is
  obsolete. If you try to use the
  BitmapEffect class, you will get an
  obsolete exception. The non-obsolete
  alternative to the BitmapEffect class
  is the Effect class. In most
  situations, the Effect class is
  significantly faster.

There isn't a really good substitute but you can try to use a DropShadowEffect with a ShadowDepth of 0. Example

<Rectangle Margin="12" Name="rectangle1" Fill="#FFB75050">
    <Rectangle.Effect>
        <DropShadowEffect ShadowDepth="0"
                          Color="Black"
                          Opacity="1"
                          BlurRadius="12"/>
    </Rectangle.Effect>
</Rectangle>

If I understood you comment correctly,

Adding the effect in code behind

DropShadowEffect dropShadowEffect = new DropShadowEffect();
dropShadowEffect.ShadowDepth = 0;
dropShadowEffect.Color = Colors.Black;
dropShadowEffect.Opacity = 1;
dropShadowEffect.BlurRadius = 12;
rectangle1.Effect = dropShadowEffect;

Modifying the effect in code behind

DropShadowEffect dropShadowEffect = rectangle1.Effect as DropShadowEffect;
dropShadowEffect.BlurRadius = 24;


问:
Extracting data from notification database in Laravel
I was saved my notification into database like this:

```<code>public function toDatabase($notifiable)
    {
        return [
            'from' => $this->message->name,
            'name'=> $this->message->email,
            'subject' => $this->message->subject,
            'body' => $this->message->body
        ];
    }
</code>```

it work fine. Now i want to extract that data into my view, so i do like this:

```<code>@foreach ( Auth::user()->unreadNotifications as $notification)
                <li><!-- start message -->
                    <a href="#">
                        <!-- Message title and timestamp -->
                        <h4>
                            {{ $notification->name }}
                            <small><i class="fa fa-clock-o"></i> 5 mins</small>
                        </h4>
                        <!-- The message -->
                        <p>{{ $notification->subject }}</p>
                    </a>
                </li>
            @endforeach
</code>```

but it give me nothing. so am i do it wrongly?

答:
Noted from the comments The Notification object has a data attribute where all your data is stored so to access it:

change:

```<code>{{ $notification->name }}
</code>```

to

```<code>{{ $notification->data['name'] }}
</code>```

and do this for all your data.

Body:
I was saved my notification into database like this:

public function toDatabase($notifiable)
    {
        return [
            'from' => $this->message->name,
            'name'=> $this->message->email,
            'subject' => $this->message->subject,
            'body' => $this->message->body
        ];
    }

it work fine. Now i want to extract that data into my view, so i do like this:

@foreach ( Auth::user()->unreadNotifications as $notification)

                            {{ $notification->name }}
                             5 mins

{{ $notification->subject }}

            @endforeach

but it give me nothing. so am i do it wrongly?

Body:
Noted from the comments The Notification object has a data attribute where all your data is stored so to access it:

change:

{{ $notification->name }}

to

{{ $notification->data['name'] }}

and do this for all your data.

ContentLicense: CC BY-SA 4.0


问:
OpenCV 3.0.0 SurfFeatureDetector and SurfDescriptorExtractor Errors
I am attempting to implement the OpenCV 3.0.0 SURF Feature Description and Detection but after running the sample code on the OpenCV site, I receive a load of errors all related to SURF. Any idea of what could be going wrong? Thanks!

```<code>#include <stdio.h>
#include <iostream>
#include "opencv2/core.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/xfeatures2d.hpp"
#include <opencv2/nonfree/nonfree.hpp>

using namespace cv;
using namespace cv::xfeatures2d;

void readme();

/** @function main */
int main(int argc, char** argv)
{
    if (argc != 3)
    {
        readme(); return -1;
    }

    Mat img_object = imread(argv[1], IMREAD_GRAYSCALE);
    Mat img_scene = imread(argv[2], IMREAD_GRAYSCALE);

    if (!img_object.data || !img_scene.data)
    {
        std::cout << " --(!) Error reading images " << std::endl; return -1;
    }

    //-- Step 1: Detect the keypoints using SURF Detector
    int minHessian = 400;

    Ptr<SURF> detector = SURF.create(minHessian);

    std::vector<KeyPoint> keypoints_object, keypoints_scene;

    detector.detect(img_object, keypoints_object);
    detector.detect(img_scene, keypoints_scene);

    //-- Step 2: Calculate descriptors (feature vectors)
    SurfDescriptorExtractor extractor;

    Mat descriptors_object, descriptors_scene;

    extractor.compute(img_object, keypoints_object, descriptors_object);
    extractor.compute(img_scene, keypoints_scene, descriptors_scene);

    //-- Step 3: Matching descriptor vectors using FLANN matcher
    FlannBasedMatcher matcher;
    std::vector< DMatch > matches;
    matcher.match(descriptors_object, descriptors_scene, matches);

    double max_dist = 0; double min_dist = 100;

    //-- Quick calculation of max and min distances between keypoints
    for (int i = 0; i < descriptors_object.rows; i++)
    {
        double dist = matches[i].distance;
        if (dist < min_dist) min_dist = dist;
        if (dist > max_dist) max_dist = dist;
    }

    printf("-- Max dist : %f \n", max_dist);
    printf("-- Min dist : %f \n", min_dist);

    //-- Draw only "good" matches (i.e. whose distance is less than 3*min_dist )
    std::vector< DMatch > good_matches;

    for (int i = 0; i < descriptors_object.rows; i++)
    {
        if (matches[i].distance < 3 * min_dist)
        {
            good_matches.push_back(matches[i]);
        }
    }

    Mat img_matches;
    drawMatches(img_object, keypoints_object, img_scene, keypoints_scene,
        good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
        std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);

    //-- Localize the object
    std::vector<Point2f> obj;
    std::vector<Point2f> scene;

    for (int i = 0; i < good_matches.size(); i++)
    {
        //-- Get the keypoints from the good matches
        obj.push_back(keypoints_object[good_matches[i].queryIdx].pt);
        scene.push_back(keypoints_scene[good_matches[i].trainIdx].pt);
    }

    Mat H = findHomography(obj, scene, RANSAC);

    //-- Get the corners from the image_1 ( the object to be "detected" )
    std::vector<Point2f> obj_corners(4);
    obj_corners[0] = cvPoint(0, 0); obj_corners[1] = cvPoint(img_object.cols, 0);
    obj_corners[2] = cvPoint(img_object.cols, img_object.rows); obj_corners[3] = cvPoint(0, img_object.rows);
    std::vector<Point2f> scene_corners(4);

    perspectiveTransform(obj_corners, scene_corners, H);

    //-- Draw lines between the corners (the mapped object in the scene - image_2 )
    line(img_matches, scene_corners[0] + Point2f(img_object.cols, 0), scene_corners[1] + Point2f(img_object.cols, 0), Scalar(0, 255, 0), 4);
    line(img_matches, scene_corners[1] + Point2f(img_object.cols, 0), scene_corners[2] + Point2f(img_object.cols, 0), Scalar(0, 255, 0), 4);
    line(img_matches, scene_corners[2] + Point2f(img_object.cols, 0), scene_corners[3] + Point2f(img_object.cols, 0), Scalar(0, 255, 0), 4);
    line(img_matches, scene_corners[3] + Point2f(img_object.cols, 0), scene_corners[0] + Point2f(img_object.cols, 0), Scalar(0, 255, 0), 4);

    //-- Show detected matches
    imshow("Good Matches & Object detection", img_matches);

    waitKey(0);
    return 0;
}

/** @function readme */
void readme()
{
    std::cout << " Usage: ./SURF_descriptor <img1> <img2>" << std::endl;
}
</code>```

Errors:

```<code>1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(34): warning C4832: token '.' is illegal after UDT 'cv::xfeatures2d::SURF'
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(111) : see declaration of 'cv::xfeatures2d::SURF'
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(34): error C2275: 'cv::xfeatures2d::SURF' : illegal use of this type as an expression
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(111) : see declaration of 'cv::xfeatures2d::SURF'
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(34): error C2228: left of '.create' must have class/struct/union
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(38): error C2039: 'detect' : is not a member of 'cv::Ptr<cv::xfeatures2d::SURF>'
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(39): error C2039: 'detect' : is not a member of 'cv::Ptr<cv::xfeatures2d::SURF>'
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(42): error C2259: 'cv::xfeatures2d::SURF' : cannot instantiate abstract class
1>          due to following members:
1>          'void cv::xfeatures2d::SURF::setHessianThreshold(double)' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(127) : see declaration of 'cv::xfeatures2d::SURF::setHessianThreshold'
1>          'double cv::xfeatures2d::SURF::getHessianThreshold(void) const' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(128) : see declaration of 'cv::xfeatures2d::SURF::getHessianThreshold'
1>          'void cv::xfeatures2d::SURF::setNOctaves(int)' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(130) : see declaration of 'cv::xfeatures2d::SURF::setNOctaves'
1>          'int cv::xfeatures2d::SURF::getNOctaves(void) const' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(131) : see declaration of 'cv::xfeatures2d::SURF::getNOctaves'
1>          'void cv::xfeatures2d::SURF::setNOctaveLayers(int)' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(133) : see declaration of 'cv::xfeatures2d::SURF::setNOctaveLayers'
1>          'int cv::xfeatures2d::SURF::getNOctaveLayers(void) const' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(134) : see declaration of 'cv::xfeatures2d::SURF::getNOctaveLayers'
1>          'void cv::xfeatures2d::SURF::setExtended(bool)' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(136) : see declaration of 'cv::xfeatures2d::SURF::setExtended'
1>          'bool cv::xfeatures2d::SURF::getExtended(void) const' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(137) : see declaration of 'cv::xfeatures2d::SURF::getExtended'
1>          'void cv::xfeatures2d::SURF::setUpright(bool)' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(139) : see declaration of 'cv::xfeatures2d::SURF::setUpright'
1>          'bool cv::xfeatures2d::SURF::getUpright(void) const' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(140) : see declaration of 'cv::xfeatures2d::SURF::getUpright'
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(87): warning C4018: '<' : signed/unsigned mismatch
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(105): warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(105): error C3861: 'line': identifier not found
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(106): warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(106): error C3861: 'line': identifier not found
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(107): warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(107): error C3861: 'line': identifier not found
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(108): warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(108): error C3861: 'line': identifier not found
</code>```

答:
I had the same problems. I managed to solve combining answers from other users and adding some more modifications:

added #include "opencv2/imgproc.hpp" otherwise line function is not recognised;

Ptr<SURF> detector = SURF.create(minHessian); substituted as Ptr<SURF> detector = SURF::create(minHessian);

detector. substituted as detector->

SurfDescriptorExtractor extractor; substitued as Ptr<SURF> extractor = SURF::create();

extractor. substituted as extractor->

Furnishing two images as input, namely a template

and a scene where to find it

I obtain the following output

VERY IMPORTANT: I'm using opencv 3.3.1 from git, which was built using opencv contrib.

Body:
I am attempting to implement the OpenCV 3.0.0 SURF Feature Description and Detection but after running the sample code on the OpenCV site, I receive a load of errors all related to SURF. Any idea of what could be going wrong? Thanks!

#include <stdio.h>
#include <iostream>
#include "opencv2/core.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/xfeatures2d.hpp"
#include <opencv2/nonfree/nonfree.hpp>

using namespace cv;
using namespace cv::xfeatures2d;

void readme();

/** @function main */
int main(int argc, char** argv)
{
    if (argc != 3)
    {
        readme(); return -1;
    }

    Mat img_object = imread(argv[1], IMREAD_GRAYSCALE);
    Mat img_scene = imread(argv[2], IMREAD_GRAYSCALE);

    if (!img_object.data || !img_scene.data)
    {
        std::cout << " --(!) Error reading images " << std::endl; return -1;
    }

    //-- Step 1: Detect the keypoints using SURF Detector
    int minHessian = 400;

    Ptr<SURF> detector = SURF.create(minHessian);

    std::vector<KeyPoint> keypoints_object, keypoints_scene;

    detector.detect(img_object, keypoints_object);
    detector.detect(img_scene, keypoints_scene);

    //-- Step 2: Calculate descriptors (feature vectors)
    SurfDescriptorExtractor extractor;

    Mat descriptors_object, descriptors_scene;

    extractor.compute(img_object, keypoints_object, descriptors_object);
    extractor.compute(img_scene, keypoints_scene, descriptors_scene);

    //-- Step 3: Matching descriptor vectors using FLANN matcher
    FlannBasedMatcher matcher;
    std::vector< DMatch > matches;
    matcher.match(descriptors_object, descriptors_scene, matches);

    double max_dist = 0; double min_dist = 100;

    //-- Quick calculation of max and min distances between keypoints
    for (int i = 0; i < descriptors_object.rows; i++)
    {
        double dist = matches[i].distance;
        if (dist < min_dist) min_dist = dist;
        if (dist > max_dist) max_dist = dist;
    }

    printf("-- Max dist : %f \n", max_dist);
    printf("-- Min dist : %f \n", min_dist);

    //-- Draw only "good" matches (i.e. whose distance is less than 3*min_dist )
    std::vector< DMatch > good_matches;

    for (int i = 0; i < descriptors_object.rows; i++)
    {
        if (matches[i].distance < 3 * min_dist)
        {
            good_matches.push_back(matches[i]);
        }
    }

    Mat img_matches;
    drawMatches(img_object, keypoints_object, img_scene, keypoints_scene,
        good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
        std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);

    //-- Localize the object
    std::vector<Point2f> obj;
    std::vector<Point2f> scene;

    for (int i = 0; i < good_matches.size(); i++)
    {
        //-- Get the keypoints from the good matches
        obj.push_back(keypoints_object[good_matches[i].queryIdx].pt);
        scene.push_back(keypoints_scene[good_matches[i].trainIdx].pt);
    }

    Mat H = findHomography(obj, scene, RANSAC);

    //-- Get the corners from the image_1 ( the object to be "detected" )
    std::vector<Point2f> obj_corners(4);
    obj_corners[0] = cvPoint(0, 0); obj_corners[1] = cvPoint(img_object.cols, 0);
    obj_corners[2] = cvPoint(img_object.cols, img_object.rows); obj_corners[3] = cvPoint(0, img_object.rows);
    std::vector<Point2f> scene_corners(4);

    perspectiveTransform(obj_corners, scene_corners, H);

    //-- Draw lines between the corners (the mapped object in the scene - image_2 )
    line(img_matches, scene_corners[0] + Point2f(img_object.cols, 0), scene_corners[1] + Point2f(img_object.cols, 0), Scalar(0, 255, 0), 4);
    line(img_matches, scene_corners[1] + Point2f(img_object.cols, 0), scene_corners[2] + Point2f(img_object.cols, 0), Scalar(0, 255, 0), 4);
    line(img_matches, scene_corners[2] + Point2f(img_object.cols, 0), scene_corners[3] + Point2f(img_object.cols, 0), Scalar(0, 255, 0), 4);
    line(img_matches, scene_corners[3] + Point2f(img_object.cols, 0), scene_corners[0] + Point2f(img_object.cols, 0), Scalar(0, 255, 0), 4);

    //-- Show detected matches
    imshow("Good Matches & Object detection", img_matches);

    waitKey(0);
    return 0;
}

/** @function readme */
void readme()
{
    std::cout << " Usage: ./SURF_descriptor <img1> <img2>" << std::endl;
}

Errors:

1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(34): warning C4832: token '.' is illegal after UDT 'cv::xfeatures2d::SURF'
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(111) : see declaration of 'cv::xfeatures2d::SURF'
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(34): error C2275: 'cv::xfeatures2d::SURF' : illegal use of this type as an expression
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(111) : see declaration of 'cv::xfeatures2d::SURF'
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(34): error C2228: left of '.create' must have class/struct/union
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(38): error C2039: 'detect' : is not a member of 'cv::Ptr<cv::xfeatures2d::SURF>'
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(39): error C2039: 'detect' : is not a member of 'cv::Ptr<cv::xfeatures2d::SURF>'
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(42): error C2259: 'cv::xfeatures2d::SURF' : cannot instantiate abstract class
1>          due to following members:
1>          'void cv::xfeatures2d::SURF::setHessianThreshold(double)' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(127) : see declaration of 'cv::xfeatures2d::SURF::setHessianThreshold'
1>          'double cv::xfeatures2d::SURF::getHessianThreshold(void) const' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(128) : see declaration of 'cv::xfeatures2d::SURF::getHessianThreshold'
1>          'void cv::xfeatures2d::SURF::setNOctaves(int)' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(130) : see declaration of 'cv::xfeatures2d::SURF::setNOctaves'
1>          'int cv::xfeatures2d::SURF::getNOctaves(void) const' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(131) : see declaration of 'cv::xfeatures2d::SURF::getNOctaves'
1>          'void cv::xfeatures2d::SURF::setNOctaveLayers(int)' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(133) : see declaration of 'cv::xfeatures2d::SURF::setNOctaveLayers'
1>          'int cv::xfeatures2d::SURF::getNOctaveLayers(void) const' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(134) : see declaration of 'cv::xfeatures2d::SURF::getNOctaveLayers'
1>          'void cv::xfeatures2d::SURF::setExtended(bool)' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(136) : see declaration of 'cv::xfeatures2d::SURF::setExtended'
1>          'bool cv::xfeatures2d::SURF::getExtended(void) const' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(137) : see declaration of 'cv::xfeatures2d::SURF::getExtended'
1>          'void cv::xfeatures2d::SURF::setUpright(bool)' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(139) : see declaration of 'cv::xfeatures2d::SURF::setUpright'
1>          'bool cv::xfeatures2d::SURF::getUpright(void) const' : is abstract
1>          c:\users\belayachiry\documents\opencv\opencv\build\include\opencv2\nonfree\nonfree.hpp(140) : see declaration of 'cv::xfeatures2d::SURF::getUpright'
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(87): warning C4018: '<' : signed/unsigned mismatch
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(105): warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(105): error C3861: 'line': identifier not found
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(106): warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(106): error C3861: 'line': identifier not found
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(107): warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(107): error C3861: 'line': identifier not found
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(108): warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data
1>c:\users\belayachiry\documents\visual studio 2013\projects\imagewatch\imagewatch\source.cpp(108): error C3861: 'line': identifier not found


问:
custom extension methods collide with framework extension methods. Why?
I have a strange behavior in our application. I want to iterate over the rows of a table (DataTable). I wanted to use the AsEnumerable() extension method from DataTableExtensions class. Sonmething like:

```<code>foreach(var thing in table.AsEnumerable())
{
...
}
</code>```

When it compiles, it complains that I need to reference some ESRI DLLs (GIS application). After some digging, I found a few extension methods from a referenced DLL that extend some of the types from ESRI (e.g. IEnumField, IEnumLayer, etc.)

Obviously, a DataTable is nothing like what those are and I can't seem to find why it is trying to bind to AsEnumerable(this IEnumLayer) instead of AsEnumerable(this DataTable). The funny thing is also that we are using Resharper (awesome tool!) and Resharper is on our side: when you navigate to the definition, it takes you to AsEnumerable(this DataTable) in the object browser.

I can't post much code sample here without posting thousands of lines of proprietary code so I am just looking for a I had the same issue once and I fixed it with... type of answer.

The obvious solution was to remove any reference to the extension methods by removing all using statements for that namespace. But this has the nasty side effect of forcing us to fully qualify any type declaration. Not pretty.

Thanks in advance for any input.

Eric.

答:
Perhaps the following would work best:</p>

```<code>foreach (DataRow dr in table.Rows)
{
}
</code>```

Body:
I have a strange behavior in our application. I want to iterate over the rows of a table (DataTable). I wanted to use the AsEnumerable() extension method from DataTableExtensions class. Sonmething like:

foreach(var thing in table.AsEnumerable())
{
...
}

When it compiles, it complains that I need to reference some ESRI DLLs (GIS application). After some digging, I found a few extension methods from a referenced DLL that extend some of the types from ESRI (e.g. IEnumField, IEnumLayer, etc.)

Obviously, a DataTable is nothing like what those are and I can't seem to find why it is trying to bind to AsEnumerable(this IEnumLayer) instead of AsEnumerable(this DataTable). The funny thing is also that we are using Resharper (awesome tool!) and Resharper is on our side: when you navigate to the definition, it takes you to AsEnumerable(this DataTable) in the object browser.

I can't post much code sample here without posting thousands of lines of proprietary code so I am just looking for a I had the same issue once and I fixed it with... type of answer.

The obvious solution was to remove any reference to the extension methods by removing all using statements for that namespace. But this has the nasty side effect of forcing us to fully qualify any type declaration. Not pretty.

Thanks in advance for any input.

Eric.

Body:
Perhaps the following would work best:

foreach (DataRow dr in table.Rows)
{
}


问:
How to customize email template in crm 2016 by code
I am using CRM 2016, and trying to customize email template by adding a dynamic data. I know that CRM allows to use only specific vanilla entities, but when I explorer an old code I found an option to use {0}, {1} etc' for injecting data from non vanilla entities (by code) - unfortunately that code cannot be tested...
Have someone heard or know about that way? is it possible? what to google for?</p>

答:
You can do this by manually typing similar marker what CRM is using. Note that this is not documented in SDK.

Dynamic Values For Custom Entities In Email Templates

In the template, where you want the value to appear, type within 2 brackets an exclamation point followed by the entity logical name. After the entity name, add a colon, and then the field logical name, ending it with a semi colon. If you’d like a default value if nothing was found, after the semi colon add the default value.

```<code>{!<entitylogicalname>: <fieldlogicalname>; <Default Text>}
</code>```

More in part 2:

The Global Template Type is what you’d want to use for custom
  entities, or any other entity not listed in the template type drop
  down menu. And just to reiterate, regardless of the way you insert
  values, whether you use the out of the box insert method or you
  manually type it in, you can only insert values from one record.

Dynamic Values For Email Templates - Part 2

Body:
You can do this by manually typing similar marker what CRM is using. Note that this is not documented in SDK.

Dynamic Values For Custom Entities In Email Templates

In the template, where you want the value to appear, type within 2 brackets an exclamation point followed by the entity logical name. After the entity name, add a colon, and then the field logical name, ending it with a semi colon. If you’d like a default value if nothing was found, after the semi colon add the default value.

{!<entitylogicalname>: <fieldlogicalname>; <Default Text>}

More in part 2:

The Global Template Type is what you’d want to use for custom
  entities, or any other entity not listed in the template type drop
  down menu. And just to reiterate, regardless of the way you insert
  values, whether you use the out of the box insert method or you
  manually type it in, you can only insert values from one record.

Dynamic Values For Email Templates - Part 2


问:
Fastest way to convert numerical table values to character arrays
I have a table which contains various data types. For instance,

```<code>chars = {'a'; 'bc'; 'de'};
nums = [1; 20; 300];
tbl = table(chars, nums);
</code>```

I want to convert all numerical columns to character array variables. By this, I mean the result should be equivalent to if I had initialised the table using:

```<code>nums = {'1'; '20', '300'};
tbl = table(chars, nums);
</code>```

I want to do this as fast as possible because I have a table with potentially millions of rows.

Current working solutions:

Firstly, I get the numerical columns, in the case of this example this will be column 2...

```<code>% Get the columns numbers which are numerical. This works fine, although a bit clunky.
numcols = find(varfun(@isnumeric, tbl(1,:), 'output', 'uniform'));
colnames = tbl.Properties.VariableNames(numcols); % Get the corresponding column names
</code>```

Then, I have a couple of methods which convert those numerical columns to character array types, they both involve looping over the numerical columns and using some other loop-in-disguise ___fun function...

arrayfun

```<code>for ii = 1:numel(colnames)
    % This arrayfun is *slow* for large tables
    tbl.(colnames{ii}) = arrayfun( @num2str, tbl.(colnames{ii}), 'uniformoutput', 0 );
end
</code>```

num2cell and cellfun

```<code>for ii = 1:numel(colnames)
    % num2cell is relatively quick
    tbl.(colnames{ii}) = num2cell( tbl.(colnames{ii}) );
    % cellfun is about as slow as arrayfun, as might be expected
    tbl.(colnames{ii}) = cellfun( @num2str, tbl.(colnames{ii}), 'uniformoutput', 0 );
end
</code>```

Speed test below, note I'm only doing one column and 1e5 elements, whilst in reality I want to do many columns and potentially ten times more rows, so you can clearly see the speed issues...

```<code>% Setup
nums = (1:1e5).'; tbl = table(nums);
% Functions
f1 = @() arrayfun( @num2str, tbl.nums, 'uni', 0 );
f2 = @() cellfun( @num2str, num2cell(tbl.nums), 'uni', 0 );
% Timing
timeit(f1) % >> 5.15 sec
timeit(f2) % >> 5.16 sec
</code>```

You can see the methods are basically equivalent, as probably expected from their similarity.

Does anyone know a faster way to convert all data in a table to character array variable type? I had thought to go via categoricals, but not sure how to proceed there.

I'd prefer a solution compatible with R2015b.

Note: It is relevant that my data contains mixed types, since I cannot (and wouldn't want to) use varfun( ... ) on the entire table.

答:
You can use sprintf to convert to large char array and then read that back using strread to put in a cell array:

```<code>% Setup
nums = (1:1e5).'; tbl = table(nums);
% Functions
f1 = @() arrayfun( @num2str, tbl.nums, 'uni', 0 );
f2 = @() cellfun( @num2str, num2cell(tbl.nums), 'uni', 0 );
f3 = @() strread ( sprintf ( '%i\n', tbl.nums ), '%s', 'delimiter', '\n' );
f4 = @() textscan ( sprintf ( '%i\n', tbl.nums ), '%s', 'delimiter', '\n' );
% Timing
timeit(f1) %
timeit(f2) %
timeit(f3) %
timeit(f4) %

r1 = feval(f1);
r2 = feval(f2);
r3 = feval(f3);
r4 = feval(f4);

% check they are equal
isequal ( r1, r2 )
isequal ( r3, r1 )
isequal ( r4{1}, r1 )
</code>```

On my computer with R2015b I get:

```<code>f1 -> 3.78 seconds
f2 -> 3.79 seconds
f3 -> 0.10 seconds
f4 -> 0.07 seconds
</code>```

And as per the isequal checks they are all the same.

If your data is non integer -> you will need to change the sprintf statement, I put it as integer to ensure that the isequal verified that the results were the same.

Body:
I have a table which contains various data types. For instance,

chars = {'a'; 'bc'; 'de'};
nums = [1; 20; 300];
tbl = table(chars, nums);

I want to convert all numerical columns to character array variables. By this, I mean the result should be equivalent to if I had initialised the table using:

nums = {'1'; '20', '300'};
tbl = table(chars, nums);

I want to do this as fast as possible because I have a table with potentially millions of rows.

Current working solutions:

Firstly, I get the numerical columns, in the case of this example this will be column 2...

% Get the columns numbers which are numerical. This works fine, although a bit clunky.
numcols = find(varfun(@isnumeric, tbl(1,:), 'output', 'uniform'));
colnames = tbl.Properties.VariableNames(numcols); % Get the corresponding column names

Then, I have a couple of methods which convert those numerical columns to character array types, they both involve looping over the numerical columns and using some other loop-in-disguise ___fun function...

arrayfun

for ii = 1:numel(colnames)
    % This arrayfun is *slow* for large tables
    tbl.(colnames{ii}) = arrayfun( @num2str, tbl.(colnames{ii}), 'uniformoutput', 0 );
end

num2cell and cellfun

for ii = 1:numel(colnames)
    % num2cell is relatively quick
    tbl.(colnames{ii}) = num2cell( tbl.(colnames{ii}) );
    % cellfun is about as slow as arrayfun, as might be expected
    tbl.(colnames{ii}) = cellfun( @num2str, tbl.(colnames{ii}), 'uniformoutput', 0 );
end

Speed test below, note I'm only doing one column and 1e5 elements, whilst in reality I want to do many columns and potentially ten times more rows, so you can clearly see the speed issues...

% Setup
nums = (1:1e5).'; tbl = table(nums);
% Functions
f1 = @() arrayfun( @num2str, tbl.nums, 'uni', 0 );
f2 = @() cellfun( @num2str, num2cell(tbl.nums), 'uni', 0 );
% Timing
timeit(f1) % >> 5.15 sec
timeit(f2) % >> 5.16 sec

You can see the methods are basically equivalent, as probably expected from their similarity.

Does anyone know a faster way to convert all data in a table to character array variable type? I had thought to go via categoricals, but not sure how to proceed there.

I'd prefer a solution compatible with R2015b.

Note: It is relevant that my data contains mixed types, since I cannot (and wouldn't want to) use varfun( ... ) on the entire table.

Body:
You can use sprintf to convert to large char array and then read that back using strread to put in a cell array:

% Setup
nums = (1:1e5).'; tbl = table(nums);
% Functions
f1 = @() arrayfun( @num2str, tbl.nums, 'uni', 0 );
f2 = @() cellfun( @num2str, num2cell(tbl.nums), 'uni', 0 );
f3 = @() strread ( sprintf ( '%i\n', tbl.nums ), '%s', 'delimiter', '\n' );
f4 = @() textscan ( sprintf ( '%i\n', tbl.nums ), '%s', 'delimiter', '\n' );
% Timing
timeit(f1) %
timeit(f2) %
timeit(f3) %
timeit(f4) %

r1 = feval(f1);
r2 = feval(f2);
r3 = feval(f3);
r4 = feval(f4);

% check they are equal
isequal ( r1, r2 )
isequal ( r3, r1 )
isequal ( r4{1}, r1 )

On my computer with R2015b I get:

f1 -> 3.78 seconds
f2 -> 3.79 seconds
f3 -> 0.10 seconds
f4 -> 0.07 seconds

And as per the isequal checks they are all the same.

If your data is non integer -> you will need to change the sprintf statement, I put it as integer to ensure that the isequal verified that the results were the same.


问:
Best practices for Spring Boot connection pool configuration
I am configuring JDBC connection pool for Spring Boot app and Postgres DB to use HikariCP connection pool and trying to find best practices for configuration setup, unfortunately there is not much info on this theme in the web.

I am preparing my own performance testing for different setups but would appreciate any help. The average throughput is around 20 req/sec for application node

I am the most interested in the most optimal values for such properties as:

```<code>    minimumIdle: ?
    maximumPoolSize: ?
    idleTimeout: ?
    maxLifetime: ?
    connectionTimeout: ?
</code>```

Especially would be great to know the most optimal value for the maximumPoolSize
There are plenty of other options available for connection pool setup would appreciate any advice about their impact on application performance.

答:
@aliaksei-stadnik 20 req/sec is, in the grand scheme of things, pretty low.  So, I wouldn't be overly concerned about pool tuning; more important is to focus on query performance.  The lower your query times, the more requests you can handle with a smaller number of connections.

We always recommend running HikariCP as a fixed-size pool for best performance (leaving minimumIdle and idleTimeout unset).  The maximumPoolSize is probably the key number you need to tune, and as the referenced link above says, it depends primarily on the number of CPU cores that your database server has.

With an average query time of 2ms, even a single connection could handle ~500 req/sec, and an average query time of 10ms would yield ~100 req/sec per connection.  However, at the cost of a single request possibly waiting up to one second to be serviced.  Additional connections would, in that case, serve to reduce the queueing time of requests.

Body:
I am configuring JDBC connection pool for Spring Boot app and Postgres DB to use HikariCP connection pool and trying to find best practices for configuration setup, unfortunately there is not much info on this theme in the web.

I am preparing my own performance testing for different setups but would appreciate any help. The average throughput is around 20 req/sec for application node

I am the most interested in the most optimal values for such properties as:

    minimumIdle: ?
    maximumPoolSize: ?
    idleTimeout: ?
    maxLifetime: ?
    connectionTimeout: ?

Especially would be great to know the most optimal value for the maximumPoolSize
There are plenty of other options available for connection pool setup would appreciate any advice about their impact on application performance.


问:
Unable to install python package "toml"
I am following this tutorial for interfacing ROS and gazebo.

When I run

make posix_sitl_default gazebo

```<code>[  0%] Built target git_driverframework
[  0%] Built target git_gps_devices
[  0%] Built target uorb_headers
[  2%] Built target df_driver_framework
[  3%] Built target git_mavlink2
[  3%] Built target git_mavlink
[  3%] Built target git_ecl
[  3%] Built target mixer_gen_legacy
[  4%] Generating mixer_multirotor_6dof.generated.h
[  4%] Generating mixer_multirotor_normalized.generated.h
[  4%] Generating mixer_multirotor.generated.h
[  5%] Built target ver_gen
('python import error: ', ImportError('No module named toml',))
('python import error: ', ImportError('No module named toml',))

Required python packages not installed.

On a GNU/Linux or MacOS system please run:
  sudo pip install numpy toml

On Windows please run:
  easy_install numpy toml

Required python packages not installed.

On a GNU/Linux or MacOS system please run:
  sudo pip install numpy toml

On Windows please run:
  easy_install numpy toml
</code>```

I am using Ubuntu 16.04, so I use sudo pip install numpy toml but:

```<code>The directory '/home/nando/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/nando/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: numpy in /opt/anaconda/lib/python2.7/site-packages
Requirement already satisfied: toml in /opt/anaconda/lib/python2.7/site-packages
</code>```

Apparently I already have the requirements satisfied, but I keep receiving the same error message when I run the first command.
How can I fix this?

答:
Apparently the problem was that I have python 2 and 3, I was installing toml in 3.
Running:

```<code>sudo -H pip2 install toml
</code>```

Solved this for me

Title: Unable to install python package "toml"

Body:
I am following this tutorial for interfacing ROS and gazebo.

When I run

make posix_sitl_default gazebo

[  0%] Built target git_driverframework
[  0%] Built target git_gps_devices
[  0%] Built target uorb_headers
[  2%] Built target df_driver_framework
[  3%] Built target git_mavlink2
[  3%] Built target git_mavlink
[  3%] Built target git_ecl
[  3%] Built target mixer_gen_legacy
[  4%] Generating mixer_multirotor_6dof.generated.h
[  4%] Generating mixer_multirotor_normalized.generated.h
[  4%] Generating mixer_multirotor.generated.h
[  5%] Built target ver_gen
('python import error: ', ImportError('No module named toml',))
('python import error: ', ImportError('No module named toml',))

Required python packages not installed.

On a GNU/Linux or MacOS system please run:
  sudo pip install numpy toml

On Windows please run:
  easy_install numpy toml

Required python packages not installed.

On a GNU/Linux or MacOS system please run:
  sudo pip install numpy toml

On Windows please run:
  easy_install numpy toml

I am using Ubuntu 16.04, so I use sudo pip install numpy toml but:

The directory '/home/nando/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/nando/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: numpy in /opt/anaconda/lib/python2.7/site-packages
Requirement already satisfied: toml in /opt/anaconda/lib/python2.7/site-packages

Apparently I already have the requirements satisfied, but I keep receiving the same error message when I run the first command.
How can I fix this?

Body:
Apparently the problem was that I have python 2 and 3, I was installing toml in 3.
Running:

sudo -H pip2 install toml

Solved this for me


问:
Ansible syntax check for undefined variable
I have a playbook like :
myplaybook.yml

```<code>---
- name: call another playbook
  hosts: 127.0.0.1

- include: "{{name}}-playbook.yml"
  when: name is defined
</code>```

Here I am passing the 'name' variable from cli as --extra-vars

It is working fine. But while trying to check the syntax with below command its giving error saying name is undefined

```<code>Ansible-playbook --syntax myplaybook.yml
</code>```

Any ideas on how to handle it ?

答:
What syntax do you want to check? If you have many playbooks like name1-playbook.yml and name2-playbook.yml, how is Ansible supposed to guess all the names and test all of them?

If you want to test just one of them, make default value for name, like:

```<code>- include: "{{ name | default('name1') }}-playbook.yml"
</code>```

Body:
I have a playbook like :
myplaybook.yml

---
- name: call another playbook
  hosts: 127.0.0.1

- include: "{{name}}-playbook.yml"
  when: name is defined

Here I am passing the 'name' variable from cli as --extra-vars

It is working fine. But while trying to check the syntax with below command its giving error saying name is undefined

Ansible-playbook --syntax myplaybook.yml

Any ideas on how to handle it ?

Body:
What syntax do you want to check? If you have many playbooks like name1-playbook.yml and name2-playbook.yml, how is Ansible supposed to guess all the names and test all of them?

If you want to test just one of them, make default value for name, like:

- include: "{{ name | default('name1') }}-playbook.yml"


问:
ESP8266: How to send TCP messages using AT+CIPSEND command
I am experimenting with Arduino and ESP8266 module, and now I am trying to send some sensor data to a TCP server. For this purposes I am using  AT+CIPSTART command (to establish a TCP connection) and AT+CIPSEND to send the data.

If I am testing it using Serial Monitor, it works fine. After entering CIPSEND command I can write some text in a terminal and this message/text will be sent to the TCP server.

When I am trying to make it inside Arduino sketch, then it sends an empty message. The connection works, but I do not see any data.

How can I send a message text (msg) with my TCP packet?

Here is a code snippet

```<code>  // ESP8266 Client
String cmd = "AT+CIPSTART=\"TCP\",\"";// Setup TCP connection
  cmd += IP;
  cmd += "\",3103";
  sendDebug(cmd);
  delay(2000);
  if( Serial.find( "Error" ) )
  {
    debug.print( "RECEIVED: Error\nExit1" );
    return;
  }

  String msg = "test";
  Serial.print( "AT+CIPSEND=" );
  Serial.println( msg.length() );
  if(Serial.find( ">" ) )
  {
    debug.print(">");
    debug.print(msg);
    Serial.print(msg);
  }
  else
  {
    sendDebug( "AT+CIPCLOSE" );//close TCP connection
  }
  if( Serial.find("OK") )
  {
    debug.println( "RECEIVED: OK" );
  }
  else
  {
    debug.println( "RECEIVED: Error\nExit2" );
  }
}
</code>```

答:
First of all, Select how much character or byte is needed to transmit. It is better to use softwareSerial library to connect with ESP8266 and send AT commands.

Suppose yow want to send 5 bytes.Type the following AT commands and must give a delay more than 100 millisecond before sending data. Here "\r" is carriage return and "\n" is new line. After including this, ESP8266 can understand you have ended the command.

```<code>esp.print("AT+CIPSEND=5\r\n");
delay(1000);
esp.print("Hello");
</code>```

Your code is not working because you are using unvarnished transmission mode. So to complete a packet you need to transmit 2048 bytes which you are not writing.

Body:
I am experimenting with Arduino and ESP8266 module, and now I am trying to send some sensor data to a TCP server. For this purposes I am using  AT+CIPSTART command (to establish a TCP connection) and AT+CIPSEND to send the data.

If I am testing it using Serial Monitor, it works fine. After entering CIPSEND command I can write some text in a terminal and this message/text will be sent to the TCP server.

When I am trying to make it inside Arduino sketch, then it sends an empty message. The connection works, but I do not see any data.

How can I send a message text (msg) with my TCP packet?

Here is a code snippet

  // ESP8266 Client
String cmd = "AT+CIPSTART=\"TCP\",\"";// Setup TCP connection
  cmd += IP;
  cmd += "\",3103";
  sendDebug(cmd);
  delay(2000);
  if( Serial.find( "Error" ) )
  {
    debug.print( "RECEIVED: Error\nExit1" );
    return;
  }

  String msg = "test";
  Serial.print( "AT+CIPSEND=" );
  Serial.println( msg.length() );
  if(Serial.find( ">" ) )
  {
    debug.print(">");
    debug.print(msg);
    Serial.print(msg);
  }
  else
  {
    sendDebug( "AT+CIPCLOSE" );//close TCP connection
  }
  if( Serial.find("OK") )
  {
    debug.println( "RECEIVED: OK" );
  }
  else
  {
    debug.println( "RECEIVED: Error\nExit2" );
  }
}

Body:
First of all, Select how much character or byte is needed to transmit. It is better to use softwareSerial library to connect with ESP8266 and send AT commands.

Suppose yow want to send 5 bytes.Type the following AT commands and must give a delay more than 100 millisecond before sending data. Here "\r" is carriage return and "\n" is new line. After including this, ESP8266 can understand you have ended the command.

esp.print("AT+CIPSEND=5\r\n");
delay(1000);
esp.print("Hello");

Your code is not working because you are using unvarnished transmission mode. So to complete a packet you need to transmit 2048 bytes which you are not writing.


问:
Can't install kgio 2.8.1 on Ubuntu 14.04
Note: I'm running Ubuntu, not Windows.

This is what happens when trying to install kgio. Am I missing dependencies, what do I install?

```<code>gilani@debris$ gem install kgio -v '2.8.1'
Building native extensions.  This could take a while...
ERROR:  Error installing kgio:
    ERROR: Failed to build gem native extension.

    /home/gilani/.rvm/rubies/ruby-2.2.1/bin/ruby -r ./siteconf20151218-13133-1dvzrlz.rb extconf.rb
checking for CLOCK_MONOTONIC in time.h... yes
checking for clockid_t in time.h... yes
checking for clock_gettime() in -lrt... yes
checking for t_open() in -lnsl... no
checking for socket() in -lsocket... no
checking for poll() in poll.h... yes
checking for getaddrinfo() in sys/types.h,sys/socket.h,netdb.h... yes
checking for getnameinfo() in sys/types.h,sys/socket.h,netdb.h... yes
checking for struct sockaddr_storage in sys/types.h,sys/socket.h... yes
checking for accept4() in sys/socket.h... yes
checking for sys/select.h... yes
checking for writev() in sys/uio.h... yes
checking for ruby/io.h... yes
checking for rb_io_t.fd in ruby.h,ruby/io.h... yes
checking for rb_io_t.mode in ruby.h,ruby/io.h... yes
checking for rb_io_t.pathv in ruby.h,ruby/io.h... yes
checking for struct RFile in ruby.h,ruby/io.h... yes
checking size of struct RFile in ruby.h,ruby/io.h... 24
checking for struct RObject... yes
checking size of struct RObject... 40
checking size of int... 4
checking for rb_io_ascii8bit_binmode()... yes
checking for rb_update_max_fd()... yes
checking for rb_fd_fix_cloexec()... yes
checking for rb_cloexec_open()... yes
checking for rb_thread_blocking_region()... no
checking for rb_thread_io_blocking_region()... yes
checking for rb_str_set_len()... yes
checking for rb_time_interval()... yes
checking for rb_wait_for_single_fd()... yes
checking for rb_str_subseq()... yes
checking for rb_ary_subseq()... yes
creating Makefile

make "DESTDIR=" clean

make "DESTDIR="
compiling wait.c
compiling autopush.c
compiling tryopen.c
tryopen.c:42:0: warning: "RUBY_UBF_IO" redefined [enabled by default]
 #  define RUBY_UBF_IO ((void *)(-1))
 ^
In file included from /home/gilani/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby/ruby.h:1710:0,
                 from /home/gilani/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby.h:33,
                 from tryopen.c:1:
/home/gilani/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby/intern.h:902:0: note: this is the location of the previous definition
 #define RUBY_UBF_IO ((rb_unblock_function_t *)-1)
 ^
In file included from tryopen.c:43:0:
/home/gilani/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby/backward/rubysig.h:14:2: warning: #warning rubysig.h is obsolete [-Wcpp]
 #warning rubysig.h is obsolete
  ^
tryopen.c: In function ‘my_thread_blocking_region’:
tryopen.c:52:2: error: ‘TRAP_BEG’ undeclared (first use in this function)
  TRAP_BEG; /* for FIFO */
  ^
tryopen.c:52:2: note: each undeclared identifier is reported only once for each function it appears in
tryopen.c:54:2: error: ‘TRAP_END’ undeclared (first use in this function)
  TRAP_END;
  ^
make: *** [tryopen.o] Error 1

make failed, exit code 2

Gem files will remain installed in /home/gilani/.rvm/gems/ruby-2.2.1/gems/kgio-2.8.1 for inspection.
Results logged to /home/gilani/.rvm/gems/ruby-2.2.1/extensions/x86_64-linux/2.2.0/kgio-2.8.1/gem_make.out
</code>```

答:
A combination of these helped me on Ubuntu 16.04:

apt-get install ruby-kgio

bundle update kgio

Body:
Note: I'm running Ubuntu, not Windows.

This is what happens when trying to install kgio. Am I missing dependencies, what do I install?

gilani@debris$ gem install kgio -v '2.8.1'
Building native extensions.  This could take a while...
ERROR:  Error installing kgio:
    ERROR: Failed to build gem native extension.

    /home/gilani/.rvm/rubies/ruby-2.2.1/bin/ruby -r ./siteconf20151218-13133-1dvzrlz.rb extconf.rb
checking for CLOCK_MONOTONIC in time.h... yes
checking for clockid_t in time.h... yes
checking for clock_gettime() in -lrt... yes
checking for t_open() in -lnsl... no
checking for socket() in -lsocket... no
checking for poll() in poll.h... yes
checking for getaddrinfo() in sys/types.h,sys/socket.h,netdb.h... yes
checking for getnameinfo() in sys/types.h,sys/socket.h,netdb.h... yes
checking for struct sockaddr_storage in sys/types.h,sys/socket.h... yes
checking for accept4() in sys/socket.h... yes
checking for sys/select.h... yes
checking for writev() in sys/uio.h... yes
checking for ruby/io.h... yes
checking for rb_io_t.fd in ruby.h,ruby/io.h... yes
checking for rb_io_t.mode in ruby.h,ruby/io.h... yes
checking for rb_io_t.pathv in ruby.h,ruby/io.h... yes
checking for struct RFile in ruby.h,ruby/io.h... yes
checking size of struct RFile in ruby.h,ruby/io.h... 24
checking for struct RObject... yes
checking size of struct RObject... 40
checking size of int... 4
checking for rb_io_ascii8bit_binmode()... yes
checking for rb_update_max_fd()... yes
checking for rb_fd_fix_cloexec()... yes
checking for rb_cloexec_open()... yes
checking for rb_thread_blocking_region()... no
checking for rb_thread_io_blocking_region()... yes
checking for rb_str_set_len()... yes
checking for rb_time_interval()... yes
checking for rb_wait_for_single_fd()... yes
checking for rb_str_subseq()... yes
checking for rb_ary_subseq()... yes
creating Makefile

make "DESTDIR=" clean

make "DESTDIR="
compiling wait.c
compiling autopush.c
compiling tryopen.c
tryopen.c:42:0: warning: "RUBY_UBF_IO" redefined [enabled by default]
 #  define RUBY_UBF_IO ((void *)(-1))
 ^
In file included from /home/gilani/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby/ruby.h:1710:0,
                 from /home/gilani/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby.h:33,
                 from tryopen.c:1:
/home/gilani/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby/intern.h:902:0: note: this is the location of the previous definition
 #define RUBY_UBF_IO ((rb_unblock_function_t *)-1)
 ^
In file included from tryopen.c:43:0:
/home/gilani/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby/backward/rubysig.h:14:2: warning: #warning rubysig.h is obsolete [-Wcpp]
 #warning rubysig.h is obsolete
  ^
tryopen.c: In function ‘my_thread_blocking_region’:
tryopen.c:52:2: error: ‘TRAP_BEG’ undeclared (first use in this function)
  TRAP_BEG; /* for FIFO */
  ^
tryopen.c:52:2: note: each undeclared identifier is reported only once for each function it appears in
tryopen.c:54:2: error: ‘TRAP_END’ undeclared (first use in this function)
  TRAP_END;
  ^
make: *** [tryopen.o] Error 1

make failed, exit code 2

Gem files will remain installed in /home/gilani/.rvm/gems/ruby-2.2.1/gems/kgio-2.8.1 for inspection.
Results logged to /home/gilani/.rvm/gems/ruby-2.2.1/extensions/x86_64-linux/2.2.0/kgio-2.8.1/gem_make.out


问:
HQL - INSERT data to one table with mysql ,hibernate
```<code> public static int add_Book(String title, String auth_name, String publisher, String genre) {
     Transaction tx = session.beginTransaction();
    Query query = session.createQuery
             ("INSERT INTO Book(title,auth_name,publisher,genre)"
                    + "SELECT "+title+", "+auth_name+", "+publisher+", "+genre);
     tx.commit();
     return query.executeUpdate();
</code>```

and this error

Exception in thread "AWT-EventQueue-0"
  java.lang.IllegalStateException: No data type for node:
  org.hibernate.hql.internal.ast.tree.IdentNode   +-[IDENT] IdentNode:
  'q' {originalText=q}...

'q' is JTextField data

insert 'q' to 'title'

... Help would BE appreciated..

答:
Just do it

```<code>public static void addBook(String title, String authName, String publisher, String genre) {
    session.save(new Book(title, authName, publisher, genre));
}
</code>```

Obviously, you should wrap that method with session/transaction control code.

And, please, always use Java Naming Convention!
auth_name, add_Book are incorrect names — use authName, addBook instead.

Body:
 public static int add_Book(String title, String auth_name, String publisher, String genre) {
     Transaction tx = session.beginTransaction();
    Query query = session.createQuery
             ("INSERT INTO Book(title,auth_name,publisher,genre)"
                    + "SELECT "+title+", "+auth_name+", "+publisher+", "+genre);
     tx.commit();
     return query.executeUpdate();

and this error

Exception in thread "AWT-EventQueue-0"
  java.lang.IllegalStateException: No data type for node:
  org.hibernate.hql.internal.ast.tree.IdentNode   +-[IDENT] IdentNode:
  'q' {originalText=q}...

'q' is JTextField data

insert 'q' to 'title'

... Help would BE appreciated..

Body:
Just do it

public static void addBook(String title, String authName, String publisher, String genre) {
    session.save(new Book(title, authName, publisher, genre));
}

Obviously, you should wrap that method with session/transaction control code.

And, please, always use Java Naming Convention!
auth_name, add_Book are incorrect names — use authName, addBook instead.


问:
"-moz-user-focus" doesn't work?
I've made this sample:

```<code><?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window width="400" height="300"
 xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

   <textbox id="textBox1"/>
   <textbox id="textBox2" style="-moz-user-focus: ignore;"/>
   <textbox id="textBox3"/>
</window>
</code>```

And, at least here, the style applied to the second textbox is doing nothing. I expected it to avoid the user focus, as the doc says.

Does someone experienced this?

--edit

To whom it may concern, the working version:

```<code><window width="400" height="300"
 onload="document.getElementById('textBox2').tabIndex='-1';"
 xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

   <textbox id="textBox1"/>
   <textbox id="textBox2" onmousedown="return false;"/>
   <textbox id="textBox3"/>
</window>
</code>```

答:
The textbox itself never takes focus. Instead, XBL creates an anonymous XHTML input element inside the textbox, and this is what takes focus. You can stop the textbox taking keyboard focus by setting its tab index to -1, and mouse focus by preventing the default action of mousedown events.

Another approach is to set the textbox to disabled or readonly, depending on why you don't want the textbox to be focused.

Title: "-moz-user-focus" doesn't work?

Body:
I've made this sample:

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window width="400" height="300"
 xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

   <textbox id="textBox1"/>
   <textbox id="textBox2" style="-moz-user-focus: ignore;"/>
   <textbox id="textBox3"/>
</window>

And, at least here, the style applied to the second textbox is doing nothing. I expected it to avoid the user focus, as the doc says.

Does someone experienced this?

--edit

To whom it may concern, the working version:

<window width="400" height="300"
 onload="document.getElementById('textBox2').tabIndex='-1';"
 xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

   <textbox id="textBox1"/>
   <textbox id="textBox2" onmousedown="return false;"/>
   <textbox id="textBox3"/>
</window>


问:
Trouble with String + RandBetween() VBA
```<code>For i = i To nr_commercial
    Cells(i, 1) = commercial & RandBetween(1, 6)
Next i
</code>```

Hi All - I have the above but I am not able to solve it. It returns a compiler error every time. I'm having issues putting a string plus a formula together.

commercial is defined as a string

I have even tried

```<code>Cells(i, 1) = commercial & = Randbetween(1,6)
</code>```

and it returns error saying expecting expression. Is there something not right with the randbetween functionality?

I need to have output in cells such like:

```<code>commercial-1
commercial-5
commercial-3
</code>```

答:
Try:

```<code>Application.WorksheetFunction.RANDBETWEEN(1,6)
</code>```

For example:

```<code>Sub qwerty()
    Dim nr_commercial As Long, commercial As String

    nr_commercial = 10
    commercial = "whatever"
    For i = 1 To nr_commercial
        Cells(i, 1) = commercial & Application.WorksheetFunction.RandBetween(1, 6)
    Next i
End Sub
</code>```

(also fixed the loop index)

Title: Trouble with String + RandBetween() VBA

Body:
For i = i To nr_commercial
    Cells(i, 1) = commercial & RandBetween(1, 6)
Next i

Hi All - I have the above but I am not able to solve it. It returns a compiler error every time. I'm having issues putting a string plus a formula together.

commercial is defined as a string

I have even tried

Cells(i, 1) = commercial & = Randbetween(1,6)

and it returns error saying expecting expression. Is there something not right with the randbetween functionality?

I need to have output in cells such like:

commercial-1
commercial-5
commercial-3

Body:
Try:

Application.WorksheetFunction.RANDBETWEEN(1,6)

For example:

Sub qwerty()
    Dim nr_commercial As Long, commercial As String

    nr_commercial = 10
    commercial = "whatever"
    For i = 1 To nr_commercial
        Cells(i, 1) = commercial & Application.WorksheetFunction.RandBetween(1, 6)
    Next i
End Sub

(also fixed the loop index)


问:
How to remove

 tags in summernote value?
While entering space in staring am getting following code from summernote textarea,

```<code><p><br></p><p><br></p><p><strong style="font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem Ipsum</strong><span style="font-family: "Open Sans", Arial, sans-serif; text-align: justify;"> is simply dummy text of the printing and typesetting industry. </span><br></p><p><br></p><p><br></p>
</code>```

but i want to remove the starting

 before storing to db.

for example i want to store like below,

```<code><p><strong style="font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem Ipsum</strong><span style="font-family: "Open Sans", Arial, sans-serif; text-align: justify;"> is simply dummy text of the printing and typesetting industry. </span><br></p>
</code>```

答:
If you are sure about the pattren than You can achieve it something like

var data='

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

';
while(data.startsWith('

')){
data=data.replace('

','')
}

while(data.endsWith('

')){
data=data.replace(new RegExp('

$'),'')
}
console.log(data)```

Title:
How to remove

 tags in summernote value?

Body:
While entering space in staring am getting following code from summernote textarea,

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

but i want to remove the starting

 before storing to db.

for example i want to store like below,

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Body:
If you are sure about the pattren than You can achieve it something like

var data='<p><br></p><p><br></p><p><strong style="font-family: &quot;Open Sans&quot;, Arial, sans-serif; text-align: justify;">Lorem Ipsum</strong><span style="font-family: &quot;Open Sans&quot;, Arial, sans-serif; text-align: justify;">&nbsp;is simply dummy text of the printing and typesetting industry. </span><br></p><p><br></p><p><br></p>';
while(data.startsWith('<p><br></p>')){
data=data.replace('<p><br></p>','')
}

while(data.endsWith('<p><br></p>')){
data=data.replace(new RegExp('<p><br></p>$'),'')
}
console.log(data)


问:
Angular 5 routing and navigation with URL Error
I am developing a small project in Angular 5, I made the router configuration in the code, if I click the menu in navbar I can navigate between components, but if I enter a component through the URL it gives me error.

If you enter the link by this https://fit.simpleclouder.com/ it works.

If you enter the link by this https://fit.simpleclouder.com/home it does not work.

If you enter the link by this https://fit.simpleclouder.com/benefics does not work.

If I click through the menu on the website, it works.

In a main folder in ftp i have this project on folder "laravel/public/fit", because i have another project Laravel on main folder.

答:
it is not angular problem it is in your IIS or your Apache server
for IIS make web.config and put

```<code><configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>
</code>```

in Apache make .htaccess file and put

```<code>RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html
</code>```

have fun and edit the routing as you need

Body:
it is not angular problem it is in your IIS or your Apache server
for IIS make web.config and put

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

in Apache make .htaccess file and put

RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

have fun and edit the routing as you need


问:
Using Youtube API for stop video by playing another one
I'm trying to stop emebed youtube video when another one is played on the same page, I found this:
stackoverflow
fiddle-example
But when i try to use it on my web page it doesn't work:
my_test

SCRIPT

```<code><script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

function onYouTubeIframeAPIReady() {
    var $ = jQuery;
    var players = [];
    $('iframe').filter(function(){return this.src.indexOf('http://www.youtube.com/') == 0}).each( function (k, v) {
        if (!this.id) { this.id='embeddedvideoiframe' + k }
        players.push(new YT.Player(this.id, {
            events: {
                'onStateChange': function(event) {
                    if (event.data == YT.PlayerState.PLAYING) {
                        $.each(players, function(k, v) {
                            if (this.getIframe().id != event.target.getIframe().id) {
                                this.pauseVideo();
                            }
                        });
                    }
                }
            }
        }))
    });
}
</script>
</code>```

HTML

```<code>One:
<iframe frameborder="0" allowfullscreen="1" title="YouTube video     player" width="160" height="100" src="http://www.youtube.com/embed    /zXV8GMSc5Vg?enablejsapi=1&origin=http%3A%2F%2Ffiddle.jshell.net">    </iframe>
<br/>
Two:
<iframe frameborder="0" allowfullscreen="1" title="YouTube video player" width="160" height="100" src="http://www.youtube.com/embed/LTy0TzA_4DQ?enablejsapi=1&origin=http%3A%2F%2Ffiddle.jshell.net">    </iframe>
</code>```

What's wrong? I've created the project on google developers, i've created the API key but i don't know where i must put that.

答: You forgot to add the jquery lib ( https://code.jquery.com/ )</p>

Body:
I'm trying to stop emebed youtube video when another one is played on the same page, I found this:
stackoverflow
fiddle-example
But when i try to use it on my web page it doesn't work:
my_test

SCRIPT

HTML

One:

Two:

What's wrong? I've created the project on google developers, i've created the API key but i don't know where i must put that.


问:
SMPP check through MONIT
I am new in linux and I need help to check SMPP binds of kannel through MONIT whether they are online or dead.
Currently in a script file named XYZ.sh using (curl --silent http://localhost:xyz/status?password=abc | grep SMPP| grep -v online) and writing in Monit as below :

```<code>check file XYZ with path /root/script/XYZ.sh if match "dead" after 5 cycles then alert
</code>```

It is not working,please guide as i am very upset.

答:
You are using the wrong check. You should use process instead of file when using custom scripts.

Also process is not able to check content so you have to return a different exit code according to the expected behaviour. So you will have to update your script to return an exit code according to your expectations

```<code>check program XYZ with path /root/script/XYZ.sh if status != 0 for 5 cycles then alert
</code>```

Documentation: https://mmonit.com/monit/documentation/monit.html#Program

Title: SMPP check through MONIT

Body:
I am new in linux and I need help to check SMPP binds of kannel through MONIT whether they are online or dead.
Currently in a script file named XYZ.sh using (curl --silent http://localhost:xyz/status?password=abc | grep SMPP| grep -v online) and writing in Monit as below :

check file XYZ with path /root/script/XYZ.sh if match "dead" after 5 cycles then alert

It is not working,please guide as i am very upset.

Body:
You are using the wrong check. You should use process instead of file when using custom scripts.

Also process is not able to check content so you have to return a different exit code according to the expected behaviour. So you will have to update your script to return an exit code according to your expectations

check program XYZ with path /root/script/XYZ.sh if status != 0 for 5 cycles then alert

Documentation: https://mmonit.com/monit/documentation/monit.html#Program


问:
Flask-admin batch action with argument via pop-up modal window
Is there any way to initiate a pop-up window from a Flask function?

I have a flask-admin + flask-sqlalchemy app. A table in the DB contains a field foo with some values. I have a UserAdmin view and I'm trying to create a batch action with some external argument.
I.e I want to:

select several elements from my DB and

substitute the old foo values for each of the element with the one new user-defined value and

the way I want to receive this new value is a modal window.

So the model is:

class User(db.Model):
    # some code
    foo = Column(Integer)
    def change_foo(self, new_foo):
        self.foo = int(new_foo)
        db.session.commit()
        return True

class UserAdmin(sqla.ModelView):
    # some code
    @action('change_foo', 'Change foo', 'Are you sure you want to change foo for selected users?')
    def action_change_foo(self, ids):
        query = tools.get_query_for_ids(self.get_query(), self.model, ids)
        count = 0
        # TODO: pop-up modal window here to get new_foo_value
        # new_foo_value = ???
        for user in query.all():
            if user.change_foo(new_foo_value):
                count += 1
        flash(ngettext('Foo was successfully changed.',
                       '%(count)s foos were successfully changed.',
                       count, count=count))
    except Exception as e:
        flash(ngettext('Failed to change foo for selected users. %(error)s', error=str(e)), 'error')
```

I admit that the whole approach is not optimal, so I'd be glad to be advised with the better one.

There are some related questions: «Batch Editing in Flask-Admin» (yet unanswered) and «Flask-Admin batch action with form» (with some workaround using WTF forms).

答:
Here's one way of achieving this. I've put the complete self-contained example on Github, flask-admin-modal.

Update 28 May 2018. The Github project has been enhanced by another user to handle form validation nicely.

In this example the SQLite database model is a Project with name (string) and cost (Integer) attributes and we will update the cost value for selected rows in the Flask-Admin list view. Note that the database is populated with random data when the Flask application is started.

Here's the model:

```<code>class Project(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False, unique=True)
    cost = db.Column(db.Integer(), nullable=False)

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return "Name: {name}; Cost : {cost}".format(name=self.name, cost=self.cost)
</code>```

Define a form with an integer cost field that accepts the new cost. This form also has a hidden field to keep track of the selected row ids.

```<code>class ChangeForm(Form):
    ids = HiddenField()
    cost = IntegerField(validators=[InputRequired()])
</code>```

Override the list template for the Project view model. We do this so we can inject a Bootstrap modal form, with an id changeModal, within the {% block body %}, making sure we call {{ super() }} first.

We also add a jQuery document ready function that will show the modal form if a template variable (change_modal) evaluates to true. The same variable is used in the modal-body to display the change_form. We use the Flask-Admin lib macros render_form to render the form in a Bootstrap style.

Note the value of the action parameter in render_form - it is a route that we define in our Project view where we can process the form's data. Also note the the "Close" button has been replaced with a link, but still styled as a button. The link is the original url (including page and filter details) where the action was initiated from.

```<code>{% extends 'admin/model/list.html' %}

{% block body %}
    {{ super() }}

    <div class="modal fade" tabindex="-1" role="dialog" id="changeModal">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <a href="{{ url }}" class="close" aria-label="Close"><span aria-hidden="true">×</span></a>
            <h4 class="modal-title">Change Project Costs</h4>
          </div>
          <div class="modal-body">
              {% if change_modal %}
                  {{ lib.render_form(change_form, action=url_for('project.update_view', url=url)) }}
              {% endif %}
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
{% endblock body %}

{% block tail %}
    {{ super() }}
    <script>
        {% if change_modal %}
            $(document).ready(function(){
                $("#changeModal").modal('show');
            });
        {% endif %}
    </script>
{% endblock tail %}
</code>```

The Project view class needs to modify the behaviour of the batch action method and define a couple of routes that accepts POST requests.

```<code>@action('change_cost', 'Change Cost', 'Are you sure you want to change Cost for selected projects?')
def action_change_cost(self, ids):
    url = get_redirect_target() or self.get_url('.index_view')
    return redirect(url, code=307)
</code>```

Instead of processing the ids directly the batch action gets the url that posted the action, this url will include any page number and filter details. It then does a redirect back to the list view with a 307. This ensures the selected rows ids are carried along in the body as well as the fact that it was a POST request.

Define a POST route to process this redirect, get the ids and url from the request body, instance a ChangeForm, set the hidden ids form field to an encoded list of the ids. Add the url, change_form and change_model variables to the template args and then render the list view again - this time the modal popup form will be shown in the view.

```<code>@expose('/', methods=['POST'])
def index(self):
    if request.method == 'POST':
        url = get_redirect_target() or self.get_url('.index_view')
        ids = request.form.getlist('rowid')
        joined_ids = ','.join(ids)
        encoded_ids = base64.b64encode(joined_ids)
        change_form = ChangeForm()
        change_form.ids.data = encoded_ids
        self._template_args['url'] = url
        self._template_args['change_form'] = change_form
        self._template_args['change_modal'] = True
        return self.index_view()
</code>```

Define a POST route to process the modal form's data. This is standard form/database processing and when finished redirect back to the original url that initiated the action.

```<code>@expose('/update/', methods=['POST'])
def update_view(self):
    if request.method == 'POST':
        url = get_redirect_target() or self.get_url('.index_view')
        change_form = ChangeForm(request.form)
        if change_form.validate():
            decoded_ids = base64.b64decode(change_form.ids.data)
            ids = decoded_ids.split(',')
            cost = change_form.cost.data
            _update_mappings = [{'id': rowid, 'cost': cost} for rowid in ids]
            db.session.bulk_update_mappings(Project, _update_mappings)
            db.session.commit()
            return redirect(url)
        else:
            # Form didn't validate
            # todo need to display the error message in the pop-up
            print change_form.errors
            return redirect(url, code=307)
</code>```

Body:
Is there any way to initiate a pop-up window from a Flask function?

I have a flask-admin + flask-sqlalchemy app. A table in the DB contains a field foo with some values. I have a UserAdmin view and I'm trying to create a batch action with some external argument.
I.e I want to:

select several elements from my DB and

substitute the old foo values for each of the element with the one new user-defined value and

the way I want to receive this new value is a modal window.

So the model is:

class User(db.Model):
    # some code
    foo = Column(Integer)
    def change_foo(self, new_foo):
        self.foo = int(new_foo)
        db.session.commit()
        return True

class UserAdmin(sqla.ModelView):
    # some code
    @action('change_foo', 'Change foo', 'Are you sure you want to change foo for selected users?')
    def action_change_foo(self, ids):
        query = tools.get_query_for_ids(self.get_query(), self.model, ids)
        count = 0
        # TODO: pop-up modal window here to get new_foo_value
        # new_foo_value = ???
        for user in query.all():
            if user.change_foo(new_foo_value):
                count += 1
        flash(ngettext('Foo was successfully changed.',
                       '%(count)s foos were successfully changed.',
                       count, count=count))
    except Exception as e:
        flash(ngettext('Failed to change foo for selected users. %(error)s', error=str(e)), 'error')

I admit that the whole approach is not optimal, so I'd be glad to be advised with the better one.

There are some related questions: «Batch Editing in Flask-Admin» (yet unanswered) and «Flask-Admin batch action with form» (with some workaround using WTF forms).

Body:
Here's one way of achieving this. I've put the complete self-contained example on Github, flask-admin-modal.

Update 28 May 2018. The Github project has been enhanced by another user to handle form validation nicely.

In this example the SQLite database model is a Project with name (string) and cost (Integer) attributes and we will update the cost value for selected rows in the Flask-Admin list view. Note that the database is populated with random data when the Flask application is started.

Here's the model:

class Project(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False, unique=True)
    cost = db.Column(db.Integer(), nullable=False)

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return "Name: {name}; Cost : {cost}".format(name=self.name, cost=self.cost)

Define a form with an integer cost field that accepts the new cost. This form also has a hidden field to keep track of the selected row ids.

class ChangeForm(Form):
    ids = HiddenField()
    cost = IntegerField(validators=[InputRequired()])

Override the list template for the Project view model. We do this so we can inject a Bootstrap modal form, with an id changeModal, within the {% block body %}, making sure we call {{ super() }} first.

We also add a jQuery document ready function that will show the modal form if a template variable (change_modal) evaluates to true. The same variable is used in the modal-body to display the change_form. We use the Flask-Admin lib macros render_form to render the form in a Bootstrap style.

Note the value of the action parameter in render_form - it is a route that we define in our Project view where we can process the form's data. Also note the the "Close" button has been replaced with a link, but still styled as a button. The link is the original url (including page and filter details) where the action was initiated from.

{% extends 'admin/model/list.html' %}

{% block body %}
    {{ super() }}

    <div class="modal fade" tabindex="-1" role="dialog" id="changeModal">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <a href="{{ url }}" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></a>
            <h4 class="modal-title">Change Project Costs</h4>
          </div>
          <div class="modal-body">
              {% if change_modal %}
                  {{ lib.render_form(change_form, action=url_for('project.update_view', url=url)) }}
              {% endif %}
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
{% endblock body %}

{% block tail %}
    {{ super() }}
    <script>
        {% if change_modal %}
            $(document).ready(function(){
                $("#changeModal").modal('show');
            });
        {% endif %}
    </script>
{% endblock tail %}

The Project view class needs to modify the behaviour of the batch action method and define a couple of routes that accepts POST requests.

@action('change_cost', 'Change Cost', 'Are you sure you want to change Cost for selected projects?')
def action_change_cost(self, ids):
    url = get_redirect_target() or self.get_url('.index_view')
    return redirect(url, code=307)

Instead of processing the ids directly the batch action gets the url that posted the action, this url will include any page number and filter details. It then does a redirect back to the list view with a 307. This ensures the selected rows ids are carried along in the body as well as the fact that it was a POST request.

Define a POST route to process this redirect, get the ids and url from the request body, instance a ChangeForm, set the hidden ids form field to an encoded list of the ids. Add the url, change_form and change_model variables to the template args and then render the list view again - this time the modal popup form will be shown in the view.

@expose('/', methods=['POST'])
def index(self):
    if request.method == 'POST':
        url = get_redirect_target() or self.get_url('.index_view')
        ids = request.form.getlist('rowid')
        joined_ids = ','.join(ids)
        encoded_ids = base64.b64encode(joined_ids)
        change_form = ChangeForm()
        change_form.ids.data = encoded_ids
        self._template_args['url'] = url
        self._template_args['change_form'] = change_form
        self._template_args['change_modal'] = True
        return self.index_view()

Define a POST route to process the modal form's data. This is standard form/database processing and when finished redirect back to the original url that initiated the action.

@expose('/update/', methods=['POST'])
def update_view(self):
    if request.method == 'POST':
        url = get_redirect_target() or self.get_url('.index_view')
        change_form = ChangeForm(request.form)
        if change_form.validate():
            decoded_ids = base64.b64decode(change_form.ids.data)
            ids = decoded_ids.split(',')
            cost = change_form.cost.data
            _update_mappings = [{'id': rowid, 'cost': cost} for rowid in ids]
            db.session.bulk_update_mappings(Project, _update_mappings)
            db.session.commit()
            return redirect(url)
        else:
            # Form didn't validate
            # todo need to display the error message in the pop-up
            print change_form.errors
            return redirect(url, code=307)


问:
Turn a few tags to one
I have this code in my page. I find it very long to write all of these tags in order to write a few words. Is there any other way to shorten it to a simple tag, while keeping the div, ul, and li activated?

```<code><div class="code">
  <ul class="codeline">
    <li>print(a)</li>
  </ul>
</div>
</code>```

Much thanks!

答:
HTML provides no such functionality. You need to find or write a tool.

There are many editors which will expand shortcodes into larger snippets of HTML. There are many template libraries you could use with many programming languages.

Title: Turn a few tags to one

Body:
I have this code in my page. I find it very long to write all of these tags in order to write a few words. Is there any other way to shorten it to a simple tag, while keeping the div, ul, and li activated?

print(a)

Much thanks!