问:
Items in linear layout don't fit properly on screen
I am using a linear layout to display image views wrappedh inside a relative layout. I want the image views to appear occupy to the whole width of the screen horizontally with no spaces in between for all screen types.
However, i still get unwanted spaces between the views. I need help on this.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/back_main"
    tools:context="com.example.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1"
        android:layout_alignParentBottom="true">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_audio"/>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_event"/>

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_video" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_more"/>
    </LinearLayout>

</RelativeLayout>
</code>```

答:
use: android:scaleType="fitXY"

replace your code of imageview with

```<code>  <ImageView
        android:layout_width="0dp"
        android:layout_height="56dp"
        android:layout_weight="0.25"
        android:scaleType="fitXY"
        android:src="@drawable/img_audio"/>
</code>```

Body:
I am using a linear layout to display image views wrappedh inside a relative layout. I want the image views to appear occupy to the whole width of the screen horizontally with no spaces in between for all screen types.
However, i still get unwanted spaces between the views. I need help on this.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/back_main"
    tools:context="com.example.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1"
        android:layout_alignParentBottom="true">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_audio"/>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_event"/>

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_video" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_more"/>
    </LinearLayout>

</RelativeLayout>

Body:
use: android:scaleType="fitXY"

replace your code of imageview with

  <ImageView
        android:layout_width="0dp"
        android:layout_height="56dp"
        android:layout_weight="0.25"
        android:scaleType="fitXY"
        android:src="@drawable/img_audio"/>


来源: stackexchange

问:
How to convert a K&R function declaration to an ANSI function declaration automatically?
```<code>// K&R syntax
int foo(a, p)
int a;
char *p;
{
    return 0;
}

// ANSI syntax
int foo(int a, char *p)
{
    return 0;
}
</code>```

As you see, in K&R style, the types of variables are declared in new lines instead of in the braces. How to convert a K&R function declaration to an ANSI function declaration automatically? Does anybody know such an easy-to-use tool in Linux?

答:
if you want to create standard C prototypes for a .h file use mkproto.c

mkproto thisoldfile.c > thisoldfile.h

You then could also paste over the old K&R code in the C file definition if desired.

Another answer by Robert contained the following (useful) information before it was deleted for being a 'link-only' answer:

You can find mkproto.c at:

https://www.pcorner.com/list/C

There are plenty of other utilities there.

The site hosts two versions of "mkproto" — MKPROTO.ZIP dated 1989-09-07 and MKPROTOB.ZIP dated 1992-06-27.  You have to register with the host site, The Programmer's Corner, to download the files.  The files appear about 2/3 of the way down a long page of possible downloads.

ContentLicense: CC BY-SA 3.0

Body:
// K&R syntax
int foo(a, p)
int a;
char *p;
{
    return 0;
}

// ANSI syntax
int foo(int a, char *p)
{
    return 0;
}

As you see, in K&R style, the types of variables are declared in new lines instead of in the braces. How to convert a K&R function declaration to an ANSI function declaration automatically? Does anybody know such an easy-to-use tool in Linux?

ContentLicense: CC BY-SA 4.0


问:
Overlapping multi-column indices
Consider a table like so (contrived example; I am trying to make it vaguely relatable):

CREATE TABLE `roles` (
  `host` varchar(50) NOT NULL,
  `port` smallint(6) NOT NULL,
  `user_id` varchar(50) NOT NULL,
  `role` varchar(50) NOT NULL
) ENGINE=InnoDB
```

<p>Typical data:</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO TABLE `roles`
(host, port, user_id, role)
VALUES
('localhost', 8080, 'root', 'admin'),
('localhost', 8080, 'guest', 'readonly');
</code>```

I know that the data is unique and non-null on:

(host, port, user_id)

I intend to use that multi-column index as my primary key.

But I would also like the covering index optimization for my SELECTs, which select all columns. To that end, I am considering adding also a wider multi-column index on:

(host, port, user_id, role)

So here's the question… if I create two indices, (a,b,c) and (a,b,c,d): is MySQL/InnoDB smart enough to implement that as a single index under-the-hood?

Or will it create & maintain both indices, wasting space and time — and fail to notice that (a,b,c,d) is a superset of (a,b,c)?

I am tempted to avoid the problem and just make the primary key (a,b,c,d), so that there's only one index. But that seems like a sub-optimal primary key (it considers more columns than necessary to guarantee uniqueness).

答:
If you create tow index So  (a,b,c) and (a,b,c,d) the query optimizer  can't choose the better  .. in this case you should explicitally assingn the index to use addin using clause to you join ..

but if you really need  you shoul consider the creation of not overlapping columns indexes eg:

```<code> (a,b,c)
</code>```

and

```<code>(d,c,b,a)
</code>```

od other combinatio not starting with the same sequence

in this case the indexes  are choosed  by the grade of matching respect the query column

anyway you can find useful info here https://dev.mysql.com/doc/refman/5.7/en/mysql-indexes.html

Title: Overlapping multi-column indices

Body:
Consider a table like so (contrived example; I am trying to make it vaguely relatable):

CREATE TABLE `roles` (
  `host` varchar(50) NOT NULL,
  `port` smallint(6) NOT NULL,
  `user_id` varchar(50) NOT NULL,
  `role` varchar(50) NOT NULL
) ENGINE=InnoDB

Typical data:

INSERT INTO TABLE `roles`
(host, port, user_id, role)
VALUES
('localhost', 8080, 'root', 'admin'),
('localhost', 8080, 'guest', 'readonly');

I know that the data is unique and non-null on:

(host, port, user_id)

I intend to use that multi-column index as my primary key.

But I would also like the covering index optimization for my SELECTs, which select all columns. To that end, I am considering adding also a wider multi-column index on:

(host, port, user_id, role)

So here's the question… if I create two indices, (a,b,c) and (a,b,c,d): is MySQL/InnoDB smart enough to implement that as a single index under-the-hood?

Or will it create & maintain both indices, wasting space and time — and fail to notice that (a,b,c,d) is a superset of (a,b,c)?

I am tempted to avoid the problem and just make the primary key (a,b,c,d), so that there's only one index. But that seems like a sub-optimal primary key (it considers more columns than necessary to guarantee uniqueness).

Body:
If you create tow index So  (a,b,c) and (a,b,c,d) the query optimizer  can't choose the better  .. in this case you should explicitally assingn the index to use addin using clause to you join ..

but if you really need  you shoul consider the creation of not overlapping columns indexes eg:

 (a,b,c)

and

(d,c,b,a)

od other combinatio not starting with the same sequence

in this case the indexes  are choosed  by the grade of matching respect the query column

anyway you can find useful info here https://dev.mysql.com/doc/refman/5.7/en/mysql-indexes.html


问:
Formdata is empty - laravel 5.4
Hi Friends,

I am trying to upload an image using ajax in laravel 5.4

Issue :

Formdata is empty on server-side

CODE :

View :

```<code><form role="form" action="{{route('auth.upload')}}" method="post" enctype="multipart/form-data" id="form3">
     {{ csrf_field() }}
     <h3>Upload Logo</h3>

     <div class="form-group">
          <label class="custom-file upload-image">
          <input type="file" id="image" name="image" class="custom-file-input">
          <span class="custom-file-control"></span>
          </label>
      </div>
      <button type="submit" class="btn btn-upload">Save Image</button>
</form>
</code>```

JS :

```<code>$('#form3').on('submit',function(e){
    e.preventDefault();

    var url = $(this).attr('action'),
    post = $(this).attr('method'),
    data = new FormData(this);

    $.ajax({
        url: url,
        method: post,
        data: data,
        success: function(data){
            console.log(data);
        },
        error: function(xhr, status, error){
            alert(xhr.responseText);
        },
        processData: false,
        contentType: false
    });
});
</code>```

Route :

```<code>Route::post('home/form3', 'HomeController@store')->name('auth.upload');
</code>```

Controller :

```<code>public function store(Request $request){
    if ($request->ajax()) {

        return $request->all(); // THIS IS RETURNING EMPTY OBJECT

        if ($request->hasFile('image')) {

            $name = $request->image->getClientOriginalName();
            $request->image->storeAs('public/upload',$name);

            $company = new Company;
            $url = Storage::url($name);
            $company->update(['image'=>$url]);

            return response(['msg'=>'image uploaded']);
        }else{
            return response(['msg'=>'No file has selected']);
        }
    }
}
</code>```

return response from server side is :

```<code>Object {_token: "zFKgoBkdjaIswMG5X0fOyVtaGSYMs84iPDtJA4F5", image: Object}
   image : Object
   _token : "zFKgoBkdjaIswMG5X0fOyVtaGSYMs84iPDtJA4F5"
   __proto__ : Object
</code>```

I can see only token is returning but not data of uploaded image. If I submit form without using ajax then it is working fine.

Output if submitted without using ajax (this is the output I am expecting even submitted using ajax):

```<code>array:2 [▼
  "_token" => "eVEjl9UW4rU69oz1lIIiuNABZVpRJFldDST02Nje"
  "image" => UploadedFile {#229 ▼
    -test: false
    -originalName: "empty-normal.png"
    -mimeType: "image/png"
    -size: 85494
    -error: 0
    #hashName: null
    path: "C:\xampp\tmp"
    filename: "php917E.tmp"
    basename: "php917E.tmp"
    pathname: "C:\xampp\tmp\php917E.tmp"
    extension: "tmp"
    realPath: "C:\xampp\tmp\php917E.tmp"
    aTime: 2017-05-18 11:17:11
    mTime: 2017-05-18 11:17:11
    cTime: 2017-05-18 11:17:11
    inode: 0
    size: 85494
    perms: 0100666
    owner: 0
    group: 0
    type: "file"
    writable: true
    readable: true
    executable: false
    file: true
    dir: false
    link: false
    linkTarget: "C:\xampp\tmp\php917E.tmp"
</code>```

}
    ]

Can any one help me in solving this issue ?

**THANKS IN ADVANCE...

答:
Try this, it will help you.

```<code>$(document).on('submit', 'yourformId', function (event) {
    event.stopPropagation();
    event.preventDefault();
    var data = new FormData($(this)[0]);

    if (xhr && xhr.readyState !== 400 && xhr.status !== 200) {
        xhr.abort();
    }

    var xhr = $.ajax({
        url: "urltoUpload",
        method: "POST",
        cache: false,
        data: data,
        contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
        processData: false, // NEEDED, DON'T OMIT THIS
        // dataType: 'json',
        statusCode: {
            404: function () {
                alert("status message")
            },
            500: function () {
                alert("server down");
            }
        },
        beforeSend: function (jqXHR, setting) {
            if (setting.status !== 200) {
                console.log("You can put here")
            }
        },
        error: function (jaXHR, textStatus, errorThrown) {
            // Now it will get parse error because dataType is json and response is html
            // console.log(errorThrown);
        },
        success: function (data, textStatus, jqXHR) {
            console.log(data);

            if (typeof data.error === 'undefined') {
                // Success so call function to process the form
                console.log('SUCCESS: ' + data.success);
            }
            else {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        complete: function (jqXHE, textStatus) {
            document.body.innerHTML = "dfafsaf";
        }

    });
});
</code>```

In you controller you can use

```<code>dd($request->all());
</code>```

for your sure !!

Title: Formdata is empty - laravel 5.4

Body:
Hi Friends,

I am trying to upload an image using ajax in laravel 5.4

Issue :

Formdata is empty on server-side

CODE :

View :

<form role="form" action="{{route('auth.upload')}}" method="post" enctype="multipart/form-data" id="form3">
     {{ csrf_field() }}

Upload Logo

          <input type="file" id="image" name="image" class="custom-file-input">

      <button type="submit" class="btn btn-upload">Save Image</button>
</form>

JS :

$('#form3').on('submit',function(e){
    e.preventDefault();

    var url = $(this).attr('action'),
    post = $(this).attr('method'),
    data = new FormData(this);

    $.ajax({
        url: url,
        method: post,
        data: data,
        success: function(data){
            console.log(data);
        },
        error: function(xhr, status, error){
            alert(xhr.responseText);
        },
        processData: false,
        contentType: false
    });
});

Route :

Route::post('home/form3', 'HomeController@store')->name('auth.upload');

Controller :

public function store(Request $request){
    if ($request->ajax()) {

        return $request->all(); // THIS IS RETURNING EMPTY OBJECT

        if ($request->hasFile('image')) {

            $name = $request->image->getClientOriginalName();
            $request->image->storeAs('public/upload',$name);

            $company = new Company;
            $url = Storage::url($name);
            $company->update(['image'=>$url]);

            return response(['msg'=>'image uploaded']);
        }else{
            return response(['msg'=>'No file has selected']);
        }
    }
}

return response from server side is :

Object {_token: "zFKgoBkdjaIswMG5X0fOyVtaGSYMs84iPDtJA4F5", image: Object}
   image : Object
   _token : "zFKgoBkdjaIswMG5X0fOyVtaGSYMs84iPDtJA4F5"
   __proto__ : Object

I can see only token is returning but not data of uploaded image. If I submit form without using ajax then it is working fine.

Output if submitted without using ajax (this is the output I am expecting even submitted using ajax):

array:2 [▼
  "_token" => "eVEjl9UW4rU69oz1lIIiuNABZVpRJFldDST02Nje"
  "image" => UploadedFile {#229 ▼
    -test: false
    -originalName: "empty-normal.png"
    -mimeType: "image/png"
    -size: 85494
    -error: 0
    #hashName: null
    path: "C:\xampp\tmp"
    filename: "php917E.tmp"
    basename: "php917E.tmp"
    pathname: "C:\xampp\tmp\php917E.tmp"
    extension: "tmp"
    realPath: "C:\xampp\tmp\php917E.tmp"
    aTime: 2017-05-18 11:17:11
    mTime: 2017-05-18 11:17:11
    cTime: 2017-05-18 11:17:11
    inode: 0
    size: 85494
    perms: 0100666
    owner: 0
    group: 0
    type: "file"
    writable: true
    readable: true
    executable: false
    file: true
    dir: false
    link: false
    linkTarget: "C:\xampp\tmp\php917E.tmp"

}
    ]

Can any one help me in solving this issue ?

**THANKS IN ADVANCE...

Body:
Try this, it will help you.

$(document).on('submit', 'yourformId', function (event) {
    event.stopPropagation();
    event.preventDefault();
    var data = new FormData($(this)[0]);

    if (xhr && xhr.readyState !== 400 && xhr.status !== 200) {
        xhr.abort();
    }

    var xhr = $.ajax({
        url: "urltoUpload",
        method: "POST",
        cache: false,
        data: data,
        contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
        processData: false, // NEEDED, DON'T OMIT THIS
        // dataType: 'json',
        statusCode: {
            404: function () {
                alert("status message")
            },
            500: function () {
                alert("server down");
            }
        },
        beforeSend: function (jqXHR, setting) {
            if (setting.status !== 200) {
                console.log("You can put here")
            }
        },
        error: function (jaXHR, textStatus, errorThrown) {
            // Now it will get parse error because dataType is json and response is html
            // console.log(errorThrown);
        },
        success: function (data, textStatus, jqXHR) {
            console.log(data);

            if (typeof data.error === 'undefined') {
                // Success so call function to process the form
                console.log('SUCCESS: ' + data.success);
            }
            else {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        complete: function (jqXHE, textStatus) {
            document.body.innerHTML = "dfafsaf";
        }

    });
});

In you controller you can use

dd($request->all());

for your sure !!


问:
how validation works in mongoose
I was reading documentation of mongoose: http://mongoosejs.com/docs/guide.html

It is said that validation occurs before saving document in the database.

And to turn this feature off we have to set option: validateBeforeSave to false.

However I have another decent Node.js tutorial example where they just use .validate as follows:

```<code>      var course = new Course({});

      course.validate(function(err) {
        assert.ok(err);
        assert.equal(err.errors['title'].kind, 'required');

        course.title = 'Introduction to Computer Science';
        assert.equal(course.title, 'Introduction to Computer Science');

        var s = '0123456789';
        course.title = '';
        while (course.title.length < 150) {
          course.title += s;
        }

        course.validate(function(err) {
          assert.ok(err);
          assert.equal(err.errors['title'].kind, 'maxlength');

          ++succeeded;
          done();
        });
      });
</code>```

I can't understand the underlying reason for using validate without setting validateBeforeSave option to false? Could someone please clarify how the provided code above works?

答:
validateBeforeSave, as the name implies, validates the mongoose object before persisting it to database. This is a schema level check, which, if not set to false, will validate every document. It includes both built-in (like a Number cannot contain string or a required field should exist etc.) and custom defined validations.

validate does the same, only it has no concern with saving the document afterwards. It's the method on the object which you invoke, like course.validate(callback), and get to know if the object is valid or not through err in the callback.

Both are doing one and the same thing but at different times and different level. Also, both are not mutually exclusive, so one does not need to be set off for other to work.

As for the use case of validate, unit testing is one example. You may want to test your validators without the trouble of mocking save or setting up a test database. I believe the example is trying to do something like that, though not in a structured way.

Title: how validation works in mongoose

Body:
I was reading documentation of mongoose: http://mongoosejs.com/docs/guide.html

It is said that validation occurs before saving document in the database.

And to turn this feature off we have to set option: validateBeforeSave to false.

However I have another decent Node.js tutorial example where they just use .validate as follows:

      var course = new Course({});

      course.validate(function(err) {
        assert.ok(err);
        assert.equal(err.errors['title'].kind, 'required');

        course.title = 'Introduction to Computer Science';
        assert.equal(course.title, 'Introduction to Computer Science');

        var s = '0123456789';
        course.title = '';
        while (course.title.length < 150) {
          course.title += s;
        }

        course.validate(function(err) {
          assert.ok(err);
          assert.equal(err.errors['title'].kind, 'maxlength');

          ++succeeded;
          done();
        });
      });

I can't understand the underlying reason for using validate without setting validateBeforeSave option to false? Could someone please clarify how the provided code above works?


问:
Flex chart not displaying right values along x axis
I don't know of any better way to ask this question.

If the below code is run
(i know the cData sections are not visible in the preview, something causes it to be ignored).

The result does not represent the data correctly.
1. Flex ignores missing date 24 aug for DECKER.
2. It wrongly associates 42.77 to 23-Aug instead of 24-AUG.

Is there a way in flex,
where the x-axis is a union of all available points ?

The below code is entirely from :
Adobe website link

I have only commented 2 data points.
//{date:"23-Aug-05", close:45.74},
and
//{date:"24-Aug-05", close:150.71},

```<code><?xml version="1.0"?>
</code>```

```<code> [Bindable]
  public var SMITH:ArrayCollection = new ArrayCollection([
    {date:"22-Aug-05", close:41.87},
    //{date:"23-Aug-05", close:45.74},
    {date:"24-Aug-05", close:42.77},
    {date:"25-Aug-05", close:48.06},
 ]);

 [Bindable]
  public var DECKER:ArrayCollection = new ArrayCollection([
    {date:"22-Aug-05", close:157.59},
    {date:"23-Aug-05", close:160.3},
    //{date:"24-Aug-05", close:150.71},
    {date:"25-Aug-05", close:156.88},
 ]);

[Bindable]
public var deckerColor:Number = 0x224488;

[Bindable]
public var smithColor:Number = 0x884422;
</code>```

]]>

```<code>    <mx:horizontalAxisRenderers>
        <mx:AxisRenderer placement="bottom" axis="{h1}"/>
    </mx:horizontalAxisRenderers>

    <mx:verticalAxisRenderers>
        <mx:AxisRenderer placement="left" axis="{v1}">
            <mx:axisStroke>{h1Stroke}</mx:axisStroke>
        </mx:AxisRenderer>
        <mx:AxisRenderer placement="left" axis="{v2}">
            <mx:axisStroke>{h2Stroke}</mx:axisStroke>
        </mx:AxisRenderer>
    </mx:verticalAxisRenderers>

    <mx:series>
       <mx:ColumnSeries id="cs1"
            horizontalAxis="{h1}"
            dataProvider="{SMITH}"
            yField="close"
            displayName="SMITH"
        >
            <mx:fill>
                <mx:SolidColor color="{smithColor}"/>
            </mx:fill>

            <mx:verticalAxis>
               <mx:LinearAxis id="v1" minimum="40" maximum="50"/>
            </mx:verticalAxis>
       </mx:ColumnSeries>
       <mx:LineSeries id="cs2"
            horizontalAxis="{h1}"
            dataProvider="{DECKER}"
            yField="close"
            displayName="DECKER"
        >
            <mx:verticalAxis>
                <mx:LinearAxis id="v2" minimum="150" maximum="170"/>
            </mx:verticalAxis>

            <mx:lineStroke>
                <mx:Stroke
                    color="{deckerColor}"
                    weight="4"
                    alpha="1"
                />
            </mx:lineStroke>
       </mx:LineSeries>
    </mx:series>
 </mx:ColumnChart>
 <mx:Legend dataProvider="{myChart}"/>
</code>```

答:
After much searching ,

The above source used 2 different datasources and 2 different series.
Each of datasource is associated with one series. So, there is a 1:1 between datasource : series.

However,

The accepted way to seams to be to use one data source and 2 series.
The datasource has one field associated with each of the series. So , there is a 1:1 between dataField : series.

I resolved the problem using the second approach, but that means we have to manually construct a single datasource with right values.

ContentLicense: CC BY-SA 2.5

Body:
I don't know of any better way to ask this question.

If the below code is run
(i know the cData sections are not visible in the preview, something causes it to be ignored).

The result does not represent the data correctly.
1. Flex ignores missing date 24 aug for DECKER.
2. It wrongly associates 42.77 to 23-Aug instead of 24-AUG.

Is there a way in flex,
where the x-axis is a union of all available points ?

The below code is entirely from :
Adobe website link

I have only commented 2 data points.
//{date:"23-Aug-05", close:45.74},
and
//{date:"24-Aug-05", close:150.71},

<?xml version="1.0"?>

 [Bindable]
  public var SMITH:ArrayCollection = new ArrayCollection([
    {date:"22-Aug-05", close:41.87},
    //{date:"23-Aug-05", close:45.74},
    {date:"24-Aug-05", close:42.77},
    {date:"25-Aug-05", close:48.06},
 ]);

 [Bindable]
  public var DECKER:ArrayCollection = new ArrayCollection([
    {date:"22-Aug-05", close:157.59},
    {date:"23-Aug-05", close:160.3},
    //{date:"24-Aug-05", close:150.71},
    {date:"25-Aug-05", close:156.88},
 ]);

[Bindable]
public var deckerColor:Number = 0x224488;

[Bindable]
public var smithColor:Number = 0x884422;

]]>

    <mx:horizontalAxisRenderers>
        <mx:AxisRenderer placement="bottom" axis="{h1}"/>
    </mx:horizontalAxisRenderers>

    <mx:verticalAxisRenderers>
        <mx:AxisRenderer placement="left" axis="{v1}">
            <mx:axisStroke>{h1Stroke}</mx:axisStroke>
        </mx:AxisRenderer>
        <mx:AxisRenderer placement="left" axis="{v2}">
            <mx:axisStroke>{h2Stroke}</mx:axisStroke>
        </mx:AxisRenderer>
    </mx:verticalAxisRenderers>

    <mx:series>
       <mx:ColumnSeries id="cs1"
            horizontalAxis="{h1}"
            dataProvider="{SMITH}"
            yField="close"
            displayName="SMITH"
        >
            <mx:fill>
                <mx:SolidColor color="{smithColor}"/>
            </mx:fill>

            <mx:verticalAxis>
               <mx:LinearAxis id="v1" minimum="40" maximum="50"/>
            </mx:verticalAxis>
       </mx:ColumnSeries>
       <mx:LineSeries id="cs2"
            horizontalAxis="{h1}"
            dataProvider="{DECKER}"
            yField="close"
            displayName="DECKER"
        >
            <mx:verticalAxis>
                <mx:LinearAxis id="v2" minimum="150" maximum="170"/>
            </mx:verticalAxis>

            <mx:lineStroke>
                <mx:Stroke
                    color="{deckerColor}"
                    weight="4"
                    alpha="1"
                />
            </mx:lineStroke>
       </mx:LineSeries>
    </mx:series>
 </mx:ColumnChart>
 <mx:Legend dataProvider="{myChart}"/>


问:
Disable picker video functionality Swift 3
Image picker is working great! However I had like to disable the video option so the user can only take photos?
Any inputs and suggestions will be highly appreciated.</p>

答:
Thanks Lawliet for the input!

Anyone stack at this question, here is what I did.
I removed mediaTypes or comment it out.
When done so, only photos can be taken.
The Apple documentation Lawliet suggested above says this, but indirectly.

Anyway, problem has been solved :)


问:
C++ a class to be used only by another class
I'm building a class (class A) which needs to be able to create a number of instances of another class (class B) in the course of its operation, but class B is only used by a few member functions of class A, and never used outside of the class. How should class B best be defined? Is it practical / reasonable to make it a private member of Class A? Is this the intended purpose of nested classes, or am I parting with the spirit of the construct?

Thanks,
Wyatt

EDIT: On further consideration, I'm not really asking about best practice, as this is for a personal project. I want to include class B as a member of class A from an encapsulation standpoint - it just seems reasonable that a class which is wholly subordinate should in fact be a part of its owning class.

What I'm wondering is whether or not this is a reasonable use-case for nested classes? If not, what is the purpose of nested classes?

答:
One possibility is to define a namespace called detail inside the namespace where you put your classes. e.g.

```<code>// public_namespace_detail.hpp
namespace public_namespace
{
    namespace detail
    {
        class B
        {
          ...
        };

    }
}

// public_namespace.hpp
#include "public_namespace_detail.hpp"

namespace public_namespace
{
    class A
    {
       detail::B b;
       ...
    };
}
</code>```

Body:
One possibility is to define a namespace called detail inside the namespace where you put your classes. e.g.

// public_namespace_detail.hpp
namespace public_namespace
{
    namespace detail
    {
        class B
        {
          ...
        };

    }
}

// public_namespace.hpp
#include "public_namespace_detail.hpp"

namespace public_namespace
{
    class A
    {
       detail::B b;
       ...
    };
}


问:
can't find snap7 library - linux
I'm running Rapbian on a Raspberry Pi Revision B.

I downloaded the module python-snap7 as instructed on this webpage: Snap7 Installation

I tried it twice: One time using pip and another doing it manually.
However, I installed it then via setup.py build and then  setup.py install.

If i try to create a client, I get the following error:

```<code>Python 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import snap7
>>> c = snap7.client.Client()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "/usr/local/lib/python2.7/dist-packages/snap7/client.py", line 29, in __init__
   self.library = load_library()
   File "/usr/local/lib/python2.7/dist-packages/snap7/common.py", line 48, in  load_library
    return Snap7Library(lib_location).cdll
   File "/usr/local/lib/python2.7/dist-packages/snap7/common.py", line 40, in __init__
    raise Snap7Exception(msg)
snap7.exceptions.Snap7Exception: can't find snap7 library. If installed, try running ldconfig
</code>```

I did the following after getting this error:

I added some lines to the file so it looks like the following:

```<code>include /etc/ld.so.conf.d/*.conf
include /usr/local/lib/python2.7/dist-packages/snap7-full-1.2.1/
include /usr/local/lib/python2.7/dist-packages/snap7-full-1.2.1/release/Linux/ARMHF/Raspberry/
include /usr/local/lib/python2.7/dist-packages/snap7-full-1.2.1/src/lib/
include /usr/local/lib/python2.7/dist-packages/snap7-python/build/lib.linux-armv6l-2.7/snap7/
include /usr/local/lib/python2.7/dist-packages/snap7-python/
</code>```

Then I issued the command sudo ldconfig to update the cache file /etc/ld.so.cache, but the error stays :(

Is it right to have the include instruction in fornt of each line?

Is there any kind of critical error I just don't see?

Which library do i need to include ?
I just thought of the provided ones over here: SourceForge Link. I have choosen the first .tar.gz package.

Sorry for my english and thanks in advance!

答:
I got a solution:

```<code>sudo chown -R $USER /usr/local/lib/python2.7/dist-packages/snap7
</code>```

To give permissions to edit files in the snap7 library directory.

Then edit the complaining files, below the init with an additional line like this:

```<code>def __init__(self):
    lib_location='/usr/local/lib/libsnap7.so' # add this line here
</code>```

Title: can't find snap7 library - linux

Body:
I'm running Rapbian on a Raspberry Pi Revision B.

I downloaded the module python-snap7 as instructed on this webpage: Snap7 Installation

I tried it twice: One time using pip and another doing it manually.
However, I installed it then via setup.py build and then  setup.py install.

If i try to create a client, I get the following error:

Python 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import snap7
>>> c = snap7.client.Client()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "/usr/local/lib/python2.7/dist-packages/snap7/client.py", line 29, in __init__
   self.library = load_library()
   File "/usr/local/lib/python2.7/dist-packages/snap7/common.py", line 48, in  load_library
    return Snap7Library(lib_location).cdll
   File "/usr/local/lib/python2.7/dist-packages/snap7/common.py", line 40, in __init__
    raise Snap7Exception(msg)
snap7.exceptions.Snap7Exception: can't find snap7 library. If installed, try running ldconfig

I did the following after getting this error:

I added some lines to the file so it looks like the following:

include /etc/ld.so.conf.d/*.conf
include /usr/local/lib/python2.7/dist-packages/snap7-full-1.2.1/
include /usr/local/lib/python2.7/dist-packages/snap7-full-1.2.1/release/Linux/ARMHF/Raspberry/
include /usr/local/lib/python2.7/dist-packages/snap7-full-1.2.1/src/lib/
include /usr/local/lib/python2.7/dist-packages/snap7-python/build/lib.linux-armv6l-2.7/snap7/
include /usr/local/lib/python2.7/dist-packages/snap7-python/

Then I issued the command sudo ldconfig to update the cache file /etc/ld.so.cache, but the error stays :(

Is it right to have the include instruction in fornt of each line?

Is there any kind of critical error I just don't see?

Which library do i need to include ?
I just thought of the provided ones over here: SourceForge Link. I have choosen the first .tar.gz package.

Sorry for my english and thanks in advance!

Body:
I got a solution:

sudo chown -R $USER /usr/local/lib/python2.7/dist-packages/snap7

To give permissions to edit files in the snap7 library directory.

Then edit the complaining files, below the init with an additional line like this:

def __init__(self):
    lib_location='/usr/local/lib/libsnap7.so' # add this line here


问:
AuthenticationProvider and UserDetailsService used by default by Spring Security
If i did not misunderstand, AuthenticationProvider uses UserDetailsService to retreive a user's attributes in order to authenticate an Authentication object.

Problem is that in the next code there is no configuration for an AuthenticationProvider neither for a UserDetailsService.

```<code>@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("user").password("pass").roles("ADMIN").and().withUser("user1")
            .password("pass").roles("USER");
}
</code>```

Yet the authentication service has been set.

My question is, was there an implementation for AuthenticationProvider and another one for UserDetailsService that were added to the spring context internally? In this case, what are the used implementations (in the case of memoryAuthentication).

Does the *.withUser("user").password("pass").roles("ADMIN")* part of the configuration represent a UserDetailsService implementation ?

答:
Yes, for such a configuration AuthenticationProvider and UserDetailsService beans are configured implicitly.

.inMemoryAuthentication() configures Spring Security to use InMemoryUserDetailsManager which (indirectly) implements UserDetailsService interface, so it is a UserDetailsService itself.

DaoAuthenticationProvider is used as AuthenticationProvider implementation by default with inMemoryAuthentication().

.withUser("user").password("pass").roles("ADMIN") configures user known to InMemoryUserDetailsManager. This can be used to populate it with users you'd like to use for logging in.

One more thing: not all AuthenticationProviders use UserDetailsService to obtain user details. Actually, among the standard AuthenticationProvider implementations, only DaoAuthenticationProvider class uses UserDetailsService.

Body:
If i did not misunderstand, AuthenticationProvider uses UserDetailsService to retreive a user's attributes in order to authenticate an Authentication object.

Problem is that in the next code there is no configuration for an AuthenticationProvider neither for a UserDetailsService.

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("user").password("pass").roles("ADMIN").and().withUser("user1")
            .password("pass").roles("USER");
}

Yet the authentication service has been set.

My question is, was there an implementation for AuthenticationProvider and another one for UserDetailsService that were added to the spring context internally? In this case, what are the used implementations (in the case of memoryAuthentication).

Does the *.withUser("user").password("pass").roles("ADMIN")* part of the configuration represent a UserDetailsService implementation ?


问:
How to get Active status based on status field in sql?

Suppose there is active and inactive state in 2 rows

```<code>select * from table name where status in (Active,Inactive);
</code>```

If active status is there need to consider that as 1st priority else need to get Inactive state

Could any one suggest some solution

```<code>    SCH_NAME,   STATE,  VER
</code>```

1   pk  Planned 2

2   pk  Active 1

答:
Not sure what you mean by Priority but I think you meant to use a CASE condition like

```<code>WHERE Status = CASE
                          WHEN Status = 'Active'
                               THEN 'Active'
                          ELSE NULL
                     END
</code>```

Body:
Suppose there is active and inactive state in 2 rows

select * from table name where status in (Active,Inactive);

If active status is there need to consider that as 1st priority else need to get Inactive state

Could any one suggest some solution

    SCH_NAME,   STATE,  VER

1   pk  Planned 2

2   pk  Active 1

Body:
Not sure what you mean by Priority but I think you meant to use a CASE condition like

WHERE Status = CASE
                          WHEN Status = 'Active'
                               THEN 'Active'
                          ELSE NULL
                     END


问:
Elo rating system alternative for non competitor vs competitor ladder
I'm working on a ladder system that will have let's say 100 contestants pitted against each other. But these contestants do not battle each other as groups or individually. Instead, they battle each other based on their own individual performance.

For example. A beer brewing competition. Each beer made by each contestant is not being compared directly against another beer. But instead each beer will be rated on 4 stats. Taste, Look, Smell, Feel.

The problem is, some contestants may only submit 1 beer and some may submit a lot more beers.

If contestant #1 submitted only 1 beer but it rated really high in all 4 stats but contestant #2 submitted 6 beers that rated fairly high in all stats, if I just averaged for each contestant, #1 would win. In this situation it should be taken into account that contestant #2 submitted 6 beers in the same time frame.

I'm looking for an algorithm or rating system that takes into account the quantity as well. Or even if the elo system could work in this situation, some help on how to tweak / use it properly to balance the competition considering some contestants may have less submissions than others.

答: You may want to check out the math behind the ELO rating system used in chess.  Check the wikipedia article.</p>


问:
React generates divs without class atribute
Server-side rendering React generates divs without class  attribute...

```<code><div data-reactroot="" data-reactid="1" data-react-checksum="-2115370602">
<div data-reactid="2"> <div data-reactid="3">...etc
</code>```

How to put class attribute into divs?

It's bad when you loading page, some period of time (less than 0.5-1 second), before binding classes, all divs without styles.

答: I solved this problem by css-modules-require-hook https://github.com/css-modules/css-modules-require-hook</p>

Body:
Server-side rendering React generates divs without class  attribute...

...etc

How to put class attribute into divs?

It's bad when you loading page, some period of time (less than 0.5-1 second), before binding classes, all divs without styles.


问:
No package autocomplete in asp.net core .csproj?
Previously, we used the project.json to setup our projects dependencies. The Asp.net Core team moved away from that and went back to using .csproj. However, when trying to type in the name of a package, it no longer auto-completes like it used to.

For instance, typing in the following line would show intellisense when I typed the . after Microsoft, providing me with the packages within that namespace.

```<code><PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" PrivateAssets="All" />
</code>```

How do I get this functionality back?

答:
It's still there in a Editor Extension called "Project File Tools" which is a Microsoft Extension and I am pretty certain this should be installed by default, but on VS 15.3 Preview it didn't seem to be working (was installed, but I didn't had any other extensions there). Somewhere in between disabling/restarting/enabling it and/or installing the Web Essentials it started working again.

As for Ctrl+. doing a reverse package search, it's there too but disabled by default:

Go to Tools > Options > Text Editor > C# > Advanced (or hit Ctrl+Q and type "C# Adv" + Enter) and check "Suggest usings for types in NuGet packages".

If you already have a highlighted error before setting the changes you got to remove the piece of code and add it again before it gets recognized (read: it only applies for red-squiggles that happen after the change).

Body:
Previously, we used the project.json to setup our projects dependencies. The Asp.net Core team moved away from that and went back to using .csproj. However, when trying to type in the name of a package, it no longer auto-completes like it used to.

For instance, typing in the following line would show intellisense when I typed the . after Microsoft, providing me with the packages within that namespace.

<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" PrivateAssets="All" />

How do I get this functionality back?


问:
AngularUI Bootstrap Carousel not working properly when binding HTML content with $compile

AngularUI Bootstrap version ^2.4.22

AngularJS version 1.6.4

Angular Sanitize version ^1.6.1

I'm having trouble using AngularUI Bootstrap's Carousel plugin. In my scenario, i need to read an external file containing some template paths, and load each of them as a slide. See example below:

index.html (where directive is being called)

```<code>     <body id="body" ng-app="homePage">
        <div id="miolo">
            <div example-directive class="ng-hide"></div>
            <div banner-rotativo></div>
            <div id="menu-footer"></div>
        </div>
     </body>
</code>```

banner-rotativo.directive.js - Basically, in this directive, I have a template following the structure of AngularUI Bootstrap's demo, and i'm binding the response data to $scope.slides array. When i push into htmlContent property the $compile(objResponseInner)($scope) result, the carousel behavior works okay, but it renders [[object HTMLDivElement]] and things like that as an item.

```<code>angular.module('homePage')
.directive('bannerRotativo', ['$compile', '$http', 'moduleUrl', '$templateRequest', function ($compile, $http, moduleUrl, $templateRequest) {
    return {
        template:   '<div style="height: 305px" ng-controller="bannerHomeController" class="" >\
                        <div uib-carousel active="active" interval="myInterval" no-wrap="noWrapSlides">\
                            <div uib-slide ng-repeat="slide in slides track by slide.id" index="slide.id">\
                                <div ng-bind-html="slide.htmlContent">\
                                </div>\
                            </div>\
                        </div>\
                    </div>',

        link: function (scope, element, attributes, controller) {

            //Carousel
            scope.myInterval = 5000;
            scope.noWrapSlides = false;
            scope.active = 0;
            scope.slides = [];
            var intCurrentIndex = 0;

            $http({
                method: 'GET',
                url: moduleUrl.getUrl('homepage', '../config/banner-rotativo.conf')
            }).then(function success(objResponse, status, headers, config) {
                var objData = objResponse.data;
                if (objData.slides) {
                    angular.forEach(objData.slides, function (objItem, strObjectName) {
                        var strTemplatePath = moduleUrl.getUrl('homepage', '..' + objItem.caminho);
                        if (strTemplatePath) {
                            $templateRequest(strTemplatePath).then(function success(objResponseInner) {
                                var objContent = $compile(objResponseInner)(scope);
                                scope.slides.push({
                                    htmlContent: objContent,
                                    id: intCurrentIndex++
                                });
                            });
                        }
                    });
                }
            });
        }
    }

}]);
</code>```

banner-rotativo.conf

```<code>{
"slides": {
    "banner-ex-one": {
        "titulo": "exone",
        "caminho-imagem": "assets/one.jpg",
        "caminho": "/html/components/banner-rotativo/banner-ex-one.view.html"
    },
    "banner-ex-two" : {
        "titulo": "extwo",
        "caminho-imagem": "assets/two.jpg",
        "caminho": "/html/components/banner-rotativo/banner-ex-two.view.html"
    },
    "banner-rav" : {
        "title": "rav",
        "caminho-imagem": "assets/rav.jpg",
        "caminho": "/html/components/banner-rotativo/banner-rav.view.html"
    },
    "banner-aviso" : {
        "title": "Quadro de comunicações 1",
        "caminho-imagem": "assets/aviso.jpg",
        "caminho": "/html/components/banner-rotativo/banner-aviso.view.html"
    },
    "banner-custom" : {
        "title": "Quadro de comunicações 2",
        "caminho-imagem": "assets/custom.jpg",
        "caminho": "/html/components/banner-rotativo/banner-custom.view.html"
    }
  }
}
</code>```

Loaded template example:

```<code><div id="frameOne" ng-controller="slideOneController" class="varejo-clique-promocao-one" title="Conteúdo Varejo - Quadro One">
<div class="item">
    <div id="dados">

        <!-- Imagem banner one -->
        <img id="one" ng-click="enviarFormOne()" class="one" alt="" ng-if="1==1" ng-src="caminhoImagem"
        />
        <!-- End imagem banner -->
        <span ng-if="hasText">{{bannerText}}</span>
    </div>
    <div id="excecao" class="excecao" ng-if="typeof(one.excecao) !== 'undefined'">
        DEU EXCECAO
    </div>
    <div class="carousel-title" id="tituloOne" ng-if="1==1" title="{{bannerTitle}}">
        {{bannerTitle}}
    </div>
</div>
</code>```

Some important points:

I'm using $compile because my injected templates have controllers too. If i don't use it, my controllers aren't processed. When i simply insert the HTML without the $compile, it renders okay.

What's wrong?

答:
The problem is that ng-bind-html expects html string and you are giving it the result from $compile that is actually an element object. You could take the HTML string from the compiled element and pass that instead, but you would probably run into all kind of trouble with that.

But you can actually just skip the hassle with $compile by using ngInclude instead of ng-bind-html. It will handle both the template request and the compilation for you.

So instead of requesting and compiling strTemplatePath, store that to the slide list:

```<code>var strTemplatePath = moduleUrl.getUrl('homepage', '..' + objItem.caminho);
if (strTemplatePath) {
    scope.slides.push({
        htmlUrl: strTemplatePath,
        id: intCurrentIndex++
    });
}
</code>```

And then use that in the template:

```<code><div uib-slide ng-repeat="slide in slides track by slide.id" index="slide.id">
    <div ng-include="slide.htmlUrl"></div>
</div>
</code>```

Here's a somewhat working fiddle: jsfiddle.net, although I had to fill in a few blanks here and there.

Body:
AngularUI Bootstrap version ^2.4.22

AngularJS version 1.6.4

Angular Sanitize version ^1.6.1

I'm having trouble using AngularUI Bootstrap's Carousel plugin. In my scenario, i need to read an external file containing some template paths, and load each of them as a slide. See example below:

index.html (where directive is being called)

banner-rotativo.directive.js - Basically, in this directive, I have a template following the structure of AngularUI Bootstrap's demo, and i'm binding the response data to $scope.slides array. When i push into htmlContent property the $compile(objResponseInner)($scope) result, the carousel behavior works okay, but it renders [[object HTMLDivElement]] and things like that as an item.

angular.module('homePage')
.directive('bannerRotativo', ['$compile', '$http', 'moduleUrl', '$templateRequest', function ($compile, $http, moduleUrl, $templateRequest) {
    return {
        template:   '
\

\

\

\

\

\

\

',

        link: function (scope, element, attributes, controller) {

            //Carousel
            scope.myInterval = 5000;
            scope.noWrapSlides = false;
            scope.active = 0;
            scope.slides = [];
            var intCurrentIndex = 0;

            $http({
                method: 'GET',
                url: moduleUrl.getUrl('homepage', '../config/banner-rotativo.conf')
            }).then(function success(objResponse, status, headers, config) {
                var objData = objResponse.data;
                if (objData.slides) {
                    angular.forEach(objData.slides, function (objItem, strObjectName) {
                        var strTemplatePath = moduleUrl.getUrl('homepage', '..' + objItem.caminho);
                        if (strTemplatePath) {
                            $templateRequest(strTemplatePath).then(function success(objResponseInner) {
                                var objContent = $compile(objResponseInner)(scope);
                                scope.slides.push({
                                    htmlContent: objContent,
                                    id: intCurrentIndex++
                                });
                            });
                        }
                    });
                }
            });
        }
    }

}]);

banner-rotativo.conf

{
"slides": {
    "banner-ex-one": {
        "titulo": "exone",
        "caminho-imagem": "assets/one.jpg",
        "caminho": "/html/components/banner-rotativo/banner-ex-one.view.html"
    },
    "banner-ex-two" : {
        "titulo": "extwo",
        "caminho-imagem": "assets/two.jpg",
        "caminho": "/html/components/banner-rotativo/banner-ex-two.view.html"
    },
    "banner-rav" : {
        "title": "rav",
        "caminho-imagem": "assets/rav.jpg",
        "caminho": "/html/components/banner-rotativo/banner-rav.view.html"
    },
    "banner-aviso" : {
        "title": "Quadro de comunicações 1",
        "caminho-imagem": "assets/aviso.jpg",
        "caminho": "/html/components/banner-rotativo/banner-aviso.view.html"
    },
    "banner-custom" : {
        "title": "Quadro de comunicações 2",
        "caminho-imagem": "assets/custom.jpg",
        "caminho": "/html/components/banner-rotativo/banner-custom.view.html"
    }
  }
}

Loaded template example:

        {{bannerText}}

        DEU EXCECAO

        {{bannerTitle}}

Some important points:

I'm using $compile because my injected templates have controllers too. If i don't use it, my controllers aren't processed. When i simply insert the HTML without the $compile, it renders okay.

What's wrong?

Body:
The problem is that ng-bind-html expects html string and you are giving it the result from $compile that is actually an element object. You could take the HTML string from the compiled element and pass that instead, but you would probably run into all kind of trouble with that.

But you can actually just skip the hassle with $compile by using ngInclude instead of ng-bind-html. It will handle both the template request and the compilation for you.

So instead of requesting and compiling strTemplatePath, store that to the slide list:

var strTemplatePath = moduleUrl.getUrl('homepage', '..' + objItem.caminho);
if (strTemplatePath) {
    scope.slides.push({
        htmlUrl: strTemplatePath,
        id: intCurrentIndex++
    });
}

And then use that in the template:

<div uib-slide ng-repeat="slide in slides track by slide.id" index="slide.id">
    <div ng-include="slide.htmlUrl"></div>
</div>

Here's a somewhat working fiddle: jsfiddle.net, although I had to fill in a few blanks here and there.


问:
Jenkins workflow job: limit where it can run
I have two Jenkins workflow jobs that start the same job with different parameters, namely, the branch they build. The latter job builds the project on several platforms. The "head" job, that is the worklflow job may start on different machines. Also, there are two linux machines in the setup.

And sometimes it so happens that one of them (say, master) starts on one of the linux machines, and the other one starts on the other. Both of them have to build a target on a linux machine, and since both of them are busy, both jobs stall.

With usual jobs, one can limit where they can run, however, I couldn't find how to limit where a workflow job can run. Obviously, it should be done using the groovy script, but it escapes me how exactly.

Is there a solution to that?

答:
here's a Jenkinsfile to do it globally (this is telling jenkins the entire pipeline must be run on a slave with these three labels):

```<code>pipeline {
  agent { label 'docker && git && rbenv' }
  stages {
    stage('commit_stage') {
      steps {
        echo 'building stuff'
      }
    }
  }
}
</code>```

you can also select a certain slave or certain capabilities via the node step for any stage or part of a stage:

```<code>pipeline {
  agent { label 'docker && git && rbenv' }
  stages {
    stage('commit_stage') {
      steps {
        // this overrides the top-level agent requirements
        node('linux_with_zsh') {
          echo 'building stuff'
        }
      }
    }
  }
}
</code>```

Body:
here's a Jenkinsfile to do it globally (this is telling jenkins the entire pipeline must be run on a slave with these three labels):

pipeline {
  agent { label 'docker && git && rbenv' }
  stages {
    stage('commit_stage') {
      steps {
        echo 'building stuff'
      }
    }
  }
}

you can also select a certain slave or certain capabilities via the node step for any stage or part of a stage:

pipeline {
  agent { label 'docker && git && rbenv' }
  stages {
    stage('commit_stage') {
      steps {
        // this overrides the top-level agent requirements
        node('linux_with_zsh') {
          echo 'building stuff'
        }
      }
    }
  }
}


问:
How do I delete the current git remote add origin link I typed?
A word is missspelled and I noticed when I tried to push something to my GitHub. Im trying to make a markdown file and push it to my GitHub but I keep getting errors. The username is right and so is the email. I entered git pull remote master and then I saw the misspelling in the error. How do I fix it or delete it and enter a new one?</p>

答: I don't think you can erase it, but you can either make a new correct commit then push (preferred) or branch out a new commit (complicate the history, less preferred).</p>


问:
Why must I import before I can call a module
I am new to Python and am not sure why you must import before you can call a module or function. Does anyone have an answer to this? And thanks in advance. An example would look like:</p>

```<code>import random
randomNum = random.randint(0,1)
</code>```

答:
Practically, random and math and all of those classes that you need to import are actually other Python files. They are code, written by the people that made Python, and designed to make your job easier.

Think of import as just copy-and-pasting the source code from those modules to the top of your program. It just means that your code can now use all of that code, too. The reason that it is not all imported by default is thus because there would be a lot of overhead from all of those modules, when you might not even use them.

Without importing, the interpreter wouldn't know what to do when you used a function from random (or any other imported module), because it wouldn't have the code to do it.

Likewise, you can actually import your own code if you wanted to. So if, for example, you made a really cool implementation of a stack, you could import that code that you wrote into your other Python files so that you can also use it in those.

Read more about import: https://docs.python.org/3/reference/import.html

Body:
I am new to Python and am not sure why you must import before you can call a module or function. Does anyone have an answer to this? And thanks in advance. An example would look like:

import random
randomNum = random.randint(0,1)


问:
Multiple or Single Try Catch
I'm working on cleaning up some of my code and I came to a point where I wasn't sure which route would be better.

Currently I have a single try catch block over the majority of my method and it handles a few separate exceptions at the end, but I figured having more try catch blocks would be better just for maintenance. However, while breaking down the code I came to a point where I was writing multiple blocks for the same type of exception. I can see the up side to writing a block for each part since I can then give more specifics to why it failed.

My question is this... is there a downside to doing this? Could there be performance issues or some other hidden monster that I'm not seeing?

Also, what is the preferred way of handling multiple exceptions in a method, is there an industry standard?

Just to better illustrate my point here's some pseudo code

```<code>//multiple try catch for same exception
try {
     //some code here
} catch (MyException e) {
     //specific error message here
}
try {
     //some different code here
} catch (MyException e) {
     //more specific error message indicating a different issue
}
</code>```

答: To be safe always use individual try catch blocks for every exception throwing statement because if you write all in one try block then if any statement throws an exception then statements written below it will not be executed.</p>

Title: Multiple or Single Try Catch

Body:
I'm working on cleaning up some of my code and I came to a point where I wasn't sure which route would be better.

Currently I have a single try catch block over the majority of my method and it handles a few separate exceptions at the end, but I figured having more try catch blocks would be better just for maintenance. However, while breaking down the code I came to a point where I was writing multiple blocks for the same type of exception. I can see the up side to writing a block for each part since I can then give more specifics to why it failed.

My question is this... is there a downside to doing this? Could there be performance issues or some other hidden monster that I'm not seeing?

Also, what is the preferred way of handling multiple exceptions in a method, is there an industry standard?

Just to better illustrate my point here's some pseudo code

//multiple try catch for same exception
try {
     //some code here
} catch (MyException e) {
     //specific error message here
}
try {
     //some different code here
} catch (MyException e) {
     //more specific error message indicating a different issue
}


问:
create multiple Azure VMs in single powershell script parallely
I am able to create Azure VM using powershell.

I have to create 4 VM's parallel.

Does any feature in powershell to do create multiple VMs parallel ? Something like background jobs or call the same function for all different VMs using threads kind of ?

答:
No, there is no built-in Azure powershell cmdlets or features enabling you to do so. You can create your own routine for that. I'm using PS jobs for that.

You need to use Save-AzureRmContext and Import-AzureRmContext to authenticate powershell inside jobs or use any form of automated login.


问:
Cannot Remove Attribute Javascript
If I try the code below on the console in Chrome, it is working. But the code is not working in my Javascript extension in Chrome.

```<code>var region = document.getElementById("physicalDeliveryOfficeName");
region.removeAttribute("onchange");
</code>```

Any thoughts what am I doing wrong? Tried to add this line in my function and on the top of my script but it is not working.

答:
This is due to the execution environment that it is isolated in a Chrome extension.

You have to inject the code into the page to do modify the page context handlers.

Please see Insert code into the page context using a content script

Title: Cannot Remove Attribute Javascript

Body:
If I try the code below on the console in Chrome, it is working. But the code is not working in my Javascript extension in Chrome.

var region = document.getElementById("physicalDeliveryOfficeName");
region.removeAttribute("onchange");

Any thoughts what am I doing wrong? Tried to add this line in my function and on the top of my script but it is not working.


问:
How can I make short random unique keys, like YouTube video IDs, in PHP?
Is there any way to create unique keys like those used in YouTube video urls (ex: https://www.youtube.com/watch?v=nWChTnkVdKE)?</p>

答:
Here is a small function that generates unique key randomly each time. It has very fewer chances to repeat same unique ID.</p>
```<code>function uniqueKey($limit = 10) {

    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    $randstring = '';

    for ($i = 0; $i < $limit; $i++) {

        $randstring .= $characters[rand(0, strlen($characters))];
    }

    return $randstring;
}
</code>```

Body:
Here is a small function that generates unique key randomly each time. It has very fewer chances to repeat same unique ID.

function uniqueKey($limit = 10) {

    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    $randstring = '';

    for ($i = 0; $i < $limit; $i++) {

        $randstring .= $characters[rand(0, strlen($characters))];
    }

    return $randstring;
}


问:
foobar Google - Error 403 permission denied - programming challenge
I am doing a challenge for Google FooBar, and am having trouble submitting my code.  My code is correct, and I have checked my program output against the answers provided by Google, and my output is correct.  However, when I try and submit, I get a Error 403: Permission denied message.  I cannot submit feedback either because I receive the same error message.  Does any one have any advice?  </p>

答:
I also faced the same issue. You can solve this by closing the current foobar session and opening a new in another tab.
This will definitely solve this problem.</p>


问:
What is the internal processing of $* and $@
Actually, I am fully understand the use of $* and $@.

For example, if I run the script using: my_script *

Then, for ONE_FILE in $@ will really get each file into ONE_FILE for processing.

Even there is space(s) in the filenames, ONE_FILE will get the correct filename.

If, however, using for ONE_FILE in $*, the story is different.

I think you guys understand the difference and I do not need to go further.

Now, what I am interested is HOW.

How the KornShell (ksh) interprets the my_scrpt *

and then pass the filenames into $@ correctly

and pass the filenames into $*.

For example, when the ksh see my_script *

, does it put the filenames one by one into an array,

and then put the array[1][2][3]... into $@ for processing ?

And, when seeing $*, does it just concat

filename1+space+filename2+space+... ?

I know that this may relate more to the internal coding of ksh.

Any insight?

答:
For example, when the korn shell see my_script *, does it put the filenames one by one into an array,
  and then put the array[1][2][3]... into $@ for processing ?
  And, when seeing $*, does it just concat
  filename1+space+filename2+space+... ?

Yes, pretty much.

One important thing to realize here are that there are two separate processes involved: the calling shell, which expands my_script * into myscript arg1 arg2 arg3 and the subprocess which gets the array of arguments. If that subprocess is ksh (or sh, bash, or a similar shell) then $* is just syntax for "get argv[1...] as a concatenated string" while $@ is syntax for "get argv[1...] as an array". It's also important to note that $* and $@ are only meaningfully different when quoted.

In bash, a cousin of ksh, this idea of array variables has actually been generalized. (Perhaps ksh has done this too -- I haven't used ksh for about a decade...)

In bash, this creates an array of 3 elements called a. Note that the first element contains a space:

```<code>[~]$ a=("foo bar" baz quux)
[~]$ for i in ${a[*]}; do echo $i; done
foo
bar
baz
quux
[~]$ for i in ${a[@]}; do echo $i; done
foo
bar
baz
quux
[~]$ for i in "${a[*]}"; do echo $i; done
foo bar baz quux
[~]$ for i in "${a[@]}"; do echo $i; done
foo bar
baz
quux
</code>```

As you can see from the example, "${a[*]}" concatenates the array while "${a[@]}" actually gives you the individual elements.

Body:
For example, when the korn shell see my_script *, does it put the filenames one by one into an array,
  and then put the array[1][2][3]... into $@ for processing ?
  And, when seeing $*, does it just concat
  filename1+space+filename2+space+... ?

Yes, pretty much.

One important thing to realize here are that there are two separate processes involved: the calling shell, which expands my_script * into myscript arg1 arg2 arg3 and the subprocess which gets the array of arguments. If that subprocess is ksh (or sh, bash, or a similar shell) then $* is just syntax for "get argv[1...] as a concatenated string" while $@ is syntax for "get argv[1...] as an array". It's also important to note that $* and $@ are only meaningfully different when quoted.

In bash, a cousin of ksh, this idea of array variables has actually been generalized. (Perhaps ksh has done this too -- I haven't used ksh for about a decade...)

In bash, this creates an array of 3 elements called a. Note that the first element contains a space:

[~]$ a=("foo bar" baz quux)
[~]$ for i in ${a[*]}; do echo $i; done
foo
bar
baz
quux
[~]$ for i in ${a[@]}; do echo $i; done
foo
bar
baz
quux
[~]$ for i in "${a[*]}"; do echo $i; done
foo bar baz quux
[~]$ for i in "${a[@]}"; do echo $i; done
foo bar
baz
quux

As you can see from the example, "${a[*]}" concatenates the array while "${a[@]}" actually gives you the individual elements.


问:
Why XPath can't find tags?
I have xml file and PHP script o process this XML. Why script can't find tags? Why xpath is failing with warnings:

```<code>PHP Warning:  DOMXPath::query(): Invalid predicate in test.php on line 7
PHP Warning:  DOMXPath::query(): Invalid expression in test.php on line 7
PHP Warning:  Invalid argument supplied for foreach() in test.php on line 9
</code>```

doc.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<rootTag>
    <div id="tag-id"></div>
    <div id="tag-id"></div>
    <div id="tag-id"></div>
    <div id="tag-id"></div>
    <div id="tag-id"></div>
</rootTag>
</code>```

test.php

```<code><?php

$doc = new DOMDocument();
$doc->load('./doc.xml');

$xpath = new DOMXPath($doc);
$tags = $xpath->query('//div[@id="tag-id"');

foreach ($tags as $node) {
    print($node->nodeName);
}

?>
</code>```

答:
Well, you query is almost correct. You have just forgotten putting last closing "]" char.

It ought to be:

```<code>$tags = $xpath->query('//div[@id="tag-id"]');
</code>```

instead:

```<code>$tags = $xpath->query('//div[@id="tag-id"');
</code>```

Title: Why XPath can't find tags?

Body:
I have xml file and PHP script o process this XML. Why script can't find tags? Why xpath is failing with warnings:

PHP Warning:  DOMXPath::query(): Invalid predicate in test.php on line 7
PHP Warning:  DOMXPath::query(): Invalid expression in test.php on line 7
PHP Warning:  Invalid argument supplied for foreach() in test.php on line 9

doc.xml

<?xml version="1.0" encoding="UTF-8"?>
<rootTag>

</rootTag>

test.php

<?php

$doc = new DOMDocument();
$doc->load('./doc.xml');

$xpath = new DOMXPath($doc);
$tags = $xpath->query('//div[@id="tag-id"');

foreach ($tags as $node) {
    print($node->nodeName);
}

?>

Body:
Well, you query is almost correct. You have just forgotten putting last closing "]" char.

It ought to be:

$tags = $xpath->query('//div[@id="tag-id"]');

instead:

$tags = $xpath->query('//div[@id="tag-id"');


问:
Get unique value from an array php
I want to display only unique strings and I have this code:

```<code>$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
    $array = array_filter(explode(',', $rez['tags']));
    $array = array_unique($array);
    foreach ($array as $value) {
        $value = ltrim($value);
        $value = str_replace(" ", "-", $value);
        echo '<a href="http://example.com/' . $value . '">' . $value . '</a><br>';
    }
}
</code>```

I have put an array_unique like this:

```<code>$array = array_unique($array);
</code>```

But it returns this:

```<code>word-word
word
word2
word3
word-word
</code>```

It doesn't print only unique values. What is wrong?

答:
I have resolved, i will post code may be will be good for someone!</p>

```<code>$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
$alltags=array();
while ($rez = $result->fetch_assoc()) {
    $array = array_filter(explode(',', $rez['tags']));
    foreach ($array as $key => $value) {
        $value = ltrim($value);
        $value = str_replace(" ", "-", $value);
        $alltags[]=$value;
    }
}
$array=array_unique($alltags);
foreach ($array as $value) {
    echo '<a href="http://example.com/' . $value . '">' . $value . '</a><br>';
}
</code>```

Title: Get unique value from an array php

Body:
I want to display only unique strings and I have this code:

$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
while ($rez = $result->fetch_assoc()) {
    $array = array_filter(explode(',', $rez['tags']));
    $array = array_unique($array);
    foreach ($array as $value) {
        $value = ltrim($value);
        $value = str_replace(" ", "-", $value);
        echo '' . $value . '
';
    }
}

I have put an array_unique like this:

$array = array_unique($array);

But it returns this:

word-word
word
word2
word3
word-word

It doesn't print only unique values. What is wrong?

Body:
I have resolved, i will post code may be will be good for someone!

$sql = "SELECT tags FROM videos";
$result = mysqli_query($mysqli, $sql);
$alltags=array();
while ($rez = $result->fetch_assoc()) {
    $array = array_filter(explode(',', $rez['tags']));
    foreach ($array as $key => $value) {
        $value = ltrim($value);
        $value = str_replace(" ", "-", $value);
        $alltags[]=$value;
    }
}
$array=array_unique($alltags);
foreach ($array as $value) {
    echo '<a href="http://example.com/' . $value . '">' . $value . '</a><br>';
}


问:
Is it possible to instantiate a SQL connection via a `SqlDataConnection` that is defined in a referenced assembly?
I have a project that contains MSSQL database queries that are defined via SqlDataConnection.  I would like to import those queries into another (several) project(s) along with the DatabaseContext type that is defined for the connection object.

However, when I try to instantiate a database connection in the second project with let databaseContext = ImportedSchema.GetDataContext() I'm told that the GetDataContext method cannot be found.

Furthermore, I cannot recreate the SqlDataConnection types in the calling module because I will then get a type mismatch when passing the new DatabaseContext object to the previously defined queries.

The projects in question are referenced and compiled; my only issue seems to be with how the type-providers resolve the connection methods.

答:
So I've found that there was a bug that was preventing the first project from compiling and linking the dll correctly.  I can now see and call the respective functions.

:-/


问:
How to find records ONLY having multiple rows in SQL Server 2014?
Customers have accounts with us for their vehicles. Some accounts have multiple vehicles.

I would like to create a report of accounts ONLY with multiple vehicles (i.e. Multiple AccountIDs and Licence Plate numbers.)

Table Account A

Table Plate P

A.AccountId = P.AccountId

```<code>SELECT A.AccountNumber
      ,A.AccountId
      ,P.LicPlateNo

FROM Account A
INNER JOIN Plate P ON A.AccountId = P.AccountId

WHERE A.RegDate > '2017-01-01'
  AND (Select Count(P.LicPlateNo) GROUP BY A.AccountNumber) > 1
   -- HAVING Count(P.LicPlateNo) > 1 ????

ORDER BY A.AccountNumber
</code>```

答:
You could use having directly</p>

```<code>    SELECT A.AccountNumber
          ,A.AccountId
          ,P.LicPlateNo

    FROM Account A
    INNER JOIN Plate P ON A.AccountId = P.AccountId
    WHERE A.RegDate > '2017-01-01'
    GROUP BY A.AccountNumber
    HAVING Count(P.LicPlateNo) > 1
    ORDER BY A.AccountNumber
</code>```

Body:
Customers have accounts with us for their vehicles. Some accounts have multiple vehicles.

I would like to create a report of accounts ONLY with multiple vehicles (i.e. Multiple AccountIDs and Licence Plate numbers.)

Table Account A

Table Plate P

A.AccountId = P.AccountId

SELECT A.AccountNumber
      ,A.AccountId
      ,P.LicPlateNo

FROM Account A
INNER JOIN Plate P ON A.AccountId = P.AccountId

WHERE A.RegDate > '2017-01-01'
  AND (Select Count(P.LicPlateNo) GROUP BY A.AccountNumber) > 1
   -- HAVING Count(P.LicPlateNo) > 1 ????

ORDER BY A.AccountNumber

Body:
You could use having directly

    SELECT A.AccountNumber
          ,A.AccountId
          ,P.LicPlateNo

    FROM Account A
    INNER JOIN Plate P ON A.AccountId = P.AccountId
    WHERE A.RegDate > '2017-01-01'
    GROUP BY A.AccountNumber
    HAVING Count(P.LicPlateNo) > 1
    ORDER BY A.AccountNumber


问:
DAL executesql parameterized queries
I've been looking, but I can't find the information I'm looking for anywhere.

How do I use parameterized queries with custom sql using DAL in web2py? For example, I have the following query:

```<code>sql = "SELECT * FROM Users WHERE Username = %s"
</code>```

And I call it like

```<code>user = db.executesql(sql, username, as_dict=True)
</code>```

which I thought would use parameters for the query, but if I pass "' or 1=1; --;" as the username, the code crashes saying it is invalid SQL.

What is the correct way to use parameterized queries with custom SQL using DAL, as this is obviously not escaping in the way I thought it was?

Thanks,

Travis

答:
Use the placeholders parameter:

```<code>user = db.executesql(sql, placeholders=(username,), as_dict=True)
</code>```

Title: DAL executesql parameterized queries

Body:
I've been looking, but I can't find the information I'm looking for anywhere.

How do I use parameterized queries with custom sql using DAL in web2py? For example, I have the following query:

sql = "SELECT * FROM Users WHERE Username = %s"

And I call it like

user = db.executesql(sql, username, as_dict=True)

which I thought would use parameters for the query, but if I pass "' or 1=1; --;" as the username, the code crashes saying it is invalid SQL.

What is the correct way to use parameterized queries with custom SQL using DAL, as this is obviously not escaping in the way I thought it was?

Thanks,

Travis

Body:
Use the placeholders parameter:

user = db.executesql(sql, placeholders=(username,), as_dict=True)


问:
How to have border color change on image hover/mousover?
I know how to add a border to images, but how do I change the color of the border on image hover/mouseover, I would like to to this to multiple images on the same page, so far I have failed to find a plugin that does this.

I spent like 5 hours looking for a plugin to do this, feel my pain!!!

Basically, I want an image to do what a button does. When user hovers the mouse over the button the color of the border changes.

答:
You can use the :hover psuedo selector:

```<code>img:hover {
  border-color: red;
}
</code>```

Also, if you want it to be like a button, consider these styles as well:

```<code>img {
  cursor: pointer;
}
img:active {
  border-color: blue;
}
</code>```

img {
  border: 2px solid black;
  cursor: pointer;
}
img:hover {
  border-color: red;
}
img:active {
  border-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://via.placeholder.com/150x150" alt="">
<img src="http://via.placeholder.com/150x150" alt="">
<img src="http://via.placeholder.com/150x150" alt=""></code>```

And using box-shadow is just as simple:

img {
  border: 2px solid black;
  cursor: pointer;
}
img:hover {
  box-shadow: 0 0 6px black;
}
img:active {
  box-shadow: 0 0 6px blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://via.placeholder.com/150x150" alt="">
<img src="http://via.placeholder.com/150x150" alt="">
<img src="http://via.placeholder.com/150x150" alt=""></code>```

and to make the image a bit bigger, use transform: scale(1.1);

img {
  border: 2px solid black;
  cursor: pointer;
}
img:hover {
  box-shadow: 0 0 6px black;
  transform: scale(1.1);
}
img:active {
  box-shadow: 0 0 6px blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://via.placeholder.com/150x150" alt="">
<img src="http://via.placeholder.com/150x150" alt="">
<img src="http://via.placeholder.com/150x150" alt=""></code>```

Body:
You can use the :hover psuedo selector:

img:hover {
  border-color: red;
}

Also, if you want it to be like a button, consider these styles as well:

img {
  cursor: pointer;
}
img:active {
  border-color: blue;
}

img {
  border: 2px solid black;
  cursor: pointer;
}
img:hover {
  border-color: red;
}
img:active {
  border-color: blue;
}

<img src="http://via.placeholder.com/150x150" alt="">
<img src="http://via.placeholder.com/150x150" alt="">
<img src="http://via.placeholder.com/150x150" alt="">

And using box-shadow is just as simple:

img {
  border: 2px solid black;
  cursor: pointer;
}
img:hover {
  box-shadow: 0 0 6px black;
}
img:active {
  box-shadow: 0 0 6px blue;
}

<img src="http://via.placeholder.com/150x150" alt="">
<img src="http://via.placeholder.com/150x150" alt="">
<img src="http://via.placeholder.com/150x150" alt="">

and to make the image a bit bigger, use transform: scale(1.1);

img {
  border: 2px solid black;
  cursor: pointer;
}
img:hover {
  box-shadow: 0 0 6px black;
  transform: scale(1.1);
}
img:active {
  box-shadow: 0 0 6px blue;
}

<img src="http://via.placeholder.com/150x150" alt="">
<img src="http://via.placeholder.com/150x150" alt="">
<img src="http://via.placeholder.com/150x150" alt="">


问:
Why leaflet marker on click event is not working when using cluster?
As jsfiddle shows, a single marker can be bound to a on-click event while cluster markers cannot: http://jsfiddle.net/kdnxcwda/

Why, and how to make it work?

My Javascript code:

```<code>//An extract of address points from the LINZ bulk extract: http://www.linz.govt.nz/survey-titles/landonline-data/landonline-bde
//Should be this data set: http://data.linz.govt.nz/#/layer/779-nz-street-address-electoral/
var addressPoints = [[-37.793167, 175.211862,"the one"],
    [-37.8210922667, 175.2209316333, "2"],
    [-37.8210819833, 175.2213903167, "3"]
    /* many more coordinates, see JSFiddle link */
];

var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Points &copy 2012 LINZ'
}),
    latlng = L.latLng(-37.82, 175.24);

var map = L.map('map', {center: latlng, zoom: 13, layers: [tiles]});

var markers = L.markerClusterGroup();

for (var i = 0; i < addressPoints.length; i++) {
    var a = addressPoints[i];
    var title = a[2];
    var marker = L.marker(new L.LatLng(a[0], a[1]), {title: title});
    marker.bindPopup(title);
    markers.addLayer(marker);
}

map.addLayer(markers);

$( ".leaflet-marker-pane img").on( "click", function() {
    console.log("click");
});
</code>```

HTML:

```<code><div id="map"></div>`
</code>```

答:
You need to listen for the clusterclick event, check the documentation about events:

```<code>markers.on('clusterclick', function (a) {
    console.log('cluster with ' + a.layer.getAllChildMarkers().length + ' markers in it');
});
</code>```

JSFiddle: http://jsfiddle.net/q0Lkuzks/

Body:
As jsfiddle shows, a single marker can be bound to a on-click event while cluster markers cannot: http://jsfiddle.net/kdnxcwda/

Why, and how to make it work?

My Javascript code:

//An extract of address points from the LINZ bulk extract: http://www.linz.govt.nz/survey-titles/landonline-data/landonline-bde
//Should be this data set: http://data.linz.govt.nz/#/layer/779-nz-street-address-electoral/
var addressPoints = [[-37.793167, 175.211862,"the one"],
    [-37.8210922667, 175.2209316333, "2"],
    [-37.8210819833, 175.2213903167, "3"]
    /* many more coordinates, see JSFiddle link */
];

var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: '© OpenStreetMap contributors, Points &copy 2012 LINZ'
}),
    latlng = L.latLng(-37.82, 175.24);

var map = L.map('map', {center: latlng, zoom: 13, layers: [tiles]});

var markers = L.markerClusterGroup();

for (var i = 0; i < addressPoints.length; i++) {
    var a = addressPoints[i];
    var title = a[2];
    var marker = L.marker(new L.LatLng(a[0], a[1]), {title: title});
    marker.bindPopup(title);
    markers.addLayer(marker);
}

map.addLayer(markers);

$( ".leaflet-marker-pane img").on( "click", function() {
    console.log("click");
});

HTML:

`

Body:
You need to listen for the clusterclick event, check the documentation about events:

markers.on('clusterclick', function (a) {
    console.log('cluster with ' + a.layer.getAllChildMarkers().length + ' markers in it');
});

JSFiddle: http://jsfiddle.net/q0Lkuzks/


问:
Overload string [] operator in C++ to return string&
I'm re-writing a string class (called XXXString) that implements many Pythonic operations like ==.
When overloading the [] operator I want it to return a XXXString& to its ith character, rather than a char& like in std::string.
In this way, I can do both

```<code>a_string[0] = "a"
</code>```

and

```<code>a_string[0] == "a"
</code>```

(assuming I have defined the == operator to compare a XXXString with a char*).
I know many C++ enthusiastic people will say no your "a" is not a 'a'. There is a '\0' in there balabala. I just want to ignore this and think Pythonic.

答:
If you really want to do this, the solution should be to use a proxy and not return the actual XXXString itself.

```<code>#include <iostream>
#include <string>
#include <cassert>

class XXXString {
public:
    class StringRefProxy {
    public:
        StringRefProxy(char& ch_in) : ch{ch_in} {}
        bool operator==(const std::string& other) {
            assert(other.length() == 1);
            return other[0] == this->ch;
        }
        StringRefProxy& operator=(const std::string& other) {
            assert(other.length() == 1);
            this->ch = other[0];
            return *this;
        }

    private:
        char& ch;
    };

    XXXString(const std::string& str_in) : str{str_in} {}
    StringRefProxy operator[](std::size_t index) {
        return StringRefProxy{this->str[index]};
    }
    operator std::string() {
        return this->str;
    }
private:
    std::string str;
};

int main() {
    auto str = XXXString{"something"};
    assert(str[0] == "s");
    str[0] = "a";
    assert(static_cast<std::string>(str) == "aomething");
}
</code>```

Note that when C++17 is freely available, you can substitute all the const std::string& with std::string_view in the above code for better performance

Also note that as most approaches go that extract references that point to elements inside container.  This too is subject to invalidation issues.

Body:
I'm re-writing a string class (called XXXString) that implements many Pythonic operations like ==.
When overloading the [] operator I want it to return a XXXString& to its ith character, rather than a char& like in std::string.
In this way, I can do both

a_string[0] = "a"

and

a_string[0] == "a"

(assuming I have defined the == operator to compare a XXXString with a char*).
I know many C++ enthusiastic people will say no your "a" is not a 'a'. There is a '\0' in there balabala. I just want to ignore this and think Pythonic.

Body:
If you really want to do this, the solution should be to use a proxy and not return the actual XXXString itself.

#include <iostream>
#include <string>
#include <cassert>

class XXXString {
public:
    class StringRefProxy {
    public:
        StringRefProxy(char& ch_in) : ch{ch_in} {}
        bool operator==(const std::string& other) {
            assert(other.length() == 1);
            return other[0] == this->ch;
        }
        StringRefProxy& operator=(const std::string& other) {
            assert(other.length() == 1);
            this->ch = other[0];
            return *this;
        }

    private:
        char& ch;
    };

    XXXString(const std::string& str_in) : str{str_in} {}
    StringRefProxy operator[](std::size_t index) {
        return StringRefProxy{this->str[index]};
    }
    operator std::string() {
        return this->str;
    }
private:
    std::string str;
};

int main() {
    auto str = XXXString{"something"};
    assert(str[0] == "s");
    str[0] = "a";
    assert(static_cast<std::string>(str) == "aomething");
}

Note that when C++17 is freely available, you can substitute all the const std::string& with std::string_view in the above code for better performance

Also note that as most approaches go that extract references that point to elements inside container.  This too is subject to invalidation issues.


问:
CSS: Let a child element with variable height and position absolute end at the top of the parent element?
In a website I have a "dropup" menu at the bottom of a website.

Have a look at the following fiddle:

body {
    background-color: #ccc;
}
ul {
    list-style-type:none;
    width:200px;
}
.spacer {
    height:150px;
    width:auto;
}
ul,li {
    margin:0;
    padding:0;
}
a {
    color:#fff;
    width:200px;
    background-color:#e4003d;
}
ul li a {
    text-decoration: none;
    display: block;
    padding: 10px;
}

ul li ul {
    z-index: 8888;
    position: absolute;
    background-color: #fff;
    display: none;
}

ul:hover li ul, ul:focus li ul {
    display:block;
}

ul li ul li {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}
ul li ul li a {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}

ul li ul li a:hover, ul li ul li a:focus {
    background-color: #e4003d;
    color: #fff !important;
}

ul li ul {
    margin-top: -100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="spacer"></div>
<ul class="page-switcher">
  <li>
    Sitamet
    <ul>
      <li>Lorem</li>
      <li>Ipsum</li>
      <li>Dolor</li>
    </ul>
  </li>
</ul>
<div class="spacer"></div></code>```

When the menu is hovered I want the submenu to end exactly at the top of the ul.page-switcher. There is no information about the number of items within the menu or their height.

In the example I have used margin-top:-100px; but this is just for demonstration as the number of pixels is not fixed.

Need a CSS only solution and should keep the position absolute. How would you solve this?

答:
Make the ul.page-switcher position: relative and give the hidden ul position bottom: 100%

With this it won't matter the height of the page-switcher or the amount/height of the popup items.

Why this works is based on the fact that the absolute positioned ul's bottom: 100% will be relative to its first ancestor having a position other than static, which in this case is the page-switcher.

Updated/Added CSS rules

```<code>ul.page-switcher {
    position: relative;
}

ul li ul {
    bottom: 100%;
}
</code>```

Stack snippet

body {
    background-color: #ccc;
}
ul {
    list-style-type:none;
    width:200px;
}
.spacer {
    height:150px;
    width:auto;
}
ul,li {
    margin:0;
    padding:0;
}
a {
    color:#fff;
    width:200px;
    background-color:#e4003d;
}
ul li a {
    text-decoration: none;
    display: block;
    padding: 10px;
}

ul li ul {
    z-index: 8888;
    position: absolute;
    background-color: #fff;
    display: none;
}

ul:hover li ul, ul:focus li ul {
    display:block;
}

ul li ul li {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}
ul li ul li a {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}

ul li ul li a:hover, ul li ul li a:focus {
    background-color: #e4003d;
    color: #fff !important;
}

ul.page-switcher {
    position: relative;
}

ul li ul {
    bottom: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="spacer"></div>
<ul class="page-switcher">
  <li>
    Sitamet
    <ul>
      <li>Lorem</li>
      <li>Ipsum</li>
      <li>Dolor</li>
    </ul>
  </li>
</ul>
<div class="spacer"></div></code>```

Body:
In a website I have a "dropup" menu at the bottom of a website.

Have a look at the following fiddle:

body {
    background-color: #ccc;
}
ul {
    list-style-type:none;
    width:200px;
}
.spacer {
    height:150px;
    width:auto;
}
ul,li {
    margin:0;
    padding:0;
}
a {
    color:#fff;
    width:200px;
    background-color:#e4003d;
}
ul li a {
    text-decoration: none;
    display: block;
    padding: 10px;
}

ul li ul {
    z-index: 8888;
    position: absolute;
    background-color: #fff;
    display: none;
}

ul:hover li ul, ul:focus li ul {
    display:block;
}

ul li ul li {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}
ul li ul li a {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}

ul li ul li a:hover, ul li ul li a:focus {
    background-color: #e4003d;
    color: #fff !important;
}

ul li ul {
    margin-top: -100px;
}

    Sitamet

Lorem

Ipsum

Dolor

When the menu is hovered I want the submenu to end exactly at the top of the ul.page-switcher. There is no information about the number of items within the menu or their height.

In the example I have used margin-top:-100px; but this is just for demonstration as the number of pixels is not fixed.

Need a CSS only solution and should keep the position absolute. How would you solve this?

Body:
Make the ul.page-switcher position: relative and give the hidden ul position bottom: 100%

With this it won't matter the height of the page-switcher or the amount/height of the popup items.

Why this works is based on the fact that the absolute positioned ul's bottom: 100% will be relative to its first ancestor having a position other than static, which in this case is the page-switcher.

Updated/Added CSS rules

ul.page-switcher {
    position: relative;
}

ul li ul {
    bottom: 100%;
}

Stack snippet

body {
    background-color: #ccc;
}
ul {
    list-style-type:none;
    width:200px;
}
.spacer {
    height:150px;
    width:auto;
}
ul,li {
    margin:0;
    padding:0;
}
a {
    color:#fff;
    width:200px;
    background-color:#e4003d;
}
ul li a {
    text-decoration: none;
    display: block;
    padding: 10px;
}

ul li ul {
    z-index: 8888;
    position: absolute;
    background-color: #fff;
    display: none;
}

ul:hover li ul, ul:focus li ul {
    display:block;
}

ul li ul li {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}
ul li ul li a {
    background-color: #fff;
    color: #e4003d;
    background-image: none;
}

ul li ul li a:hover, ul li ul li a:focus {
    background-color: #e4003d;
    color: #fff !important;
}

ul.page-switcher {
    position: relative;
}

ul li ul {
    bottom: 100%;
}

<div class="spacer"></div>
<ul class="page-switcher">
  <li>
    <a href="#">Sitamet</a>
    <ul>
      <li><a href="http://#">Lorem</a></li>
      <li><a href="http://#">Ipsum</a></li>
      <li><a href="http://#">Dolor</a></li>
    </ul>
  </li>
</ul>
<div class="spacer"></div>