问:
How to format output of system function PHP?
I use function system() to run system process.

```<code>$buff = system('python excel.py ' . $handle->file_dst_pathname, $retval);
</code>```

It displays messages in line without separations.

In Python I use this line to print data:

```<code> print "# %d - article \"%s\" was inserted!" % (i, article)
</code>```

答:
Precede the output of system(...); with echo "```";</code> and follow with <code>echo "```";

Or shorter:

```<code>$buff = "```" . system('python excel.py ' . $handle->file_dst_pathname, $retval) . "```";
</code>```

You could also change all the "\n" chars of your output into "
".

Body:
I use function system() to run system process.

$buff = system('python excel.py ' . $handle->file_dst_pathname, $retval);

It displays messages in line without separations.

In Python I use this line to print data:

 print "# %d - article \"%s\" was inserted!" % (i, article)

Body:
Precede the output of system(...); with echo "<pre>"; and follow with echo "</pre>";

Or shorter:

$buff = "<pre>" . system('python excel.py ' . $handle->file_dst_pathname, $retval) . "</pre>";

You could also change all the "\n" chars of your output into "<br/>".


来源: stackexchange

问:
Custom UIButton @IBDesignable
I created a UIButton subclass that looks like a checkmark.

Here is the class:

```<code>import UIKit

@IBDesignable
class CheckedButton: UIButton {

    // MARK: - Properties
    @IBInspectable var checked: Bool = false {
        didSet {
            // Toggle the check/uncheck images
            updateImage()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    private func setup() {
        updateImage()
        self.addTarget(self, action: #selector(tapped), for: .touchUpInside)
    }

    private func updateImage() {
        let image = checked ? UIImage(named: "checked") : UIImage(named: "unchecked")
        self.setImage(image, for: .normal)
    }

    /// Called each time the button is tapped, and toggles the checked property
    @objc private func tapped() {
        checked = !checked
        print("New value: \(checked)")
    }
}
</code>```

Since I set the checkedproperty as @IBInspectable, I see it in IB :

The weird thing is:

if I let this property as default, it is correctly showing in the storyboard

but if I choose either on or off inthe inspector, the screen is not updated properly.

As the class is marked @IBDesignable, I would expect the button appearance to update in IB according to the value set for this property in the inspector tab.
Got a clue?

答:
My suggestion is in using other custom function for getting image from assets:

```<code>extension UIImage {
    public static func image(name: String, _ sender: UIView?) -> UIImage? {
        #if TARGET_INTERFACE_BUILDER
            if let sender = sender {
                let bundle = Bundle(for: sender.classForCoder)
                return UIImage(named: name, in: bundle, compatibleWith: sender.traitCollection)
            } else {
                return UIImage(named: name)
            }
        #else
            return UIImage(named: name)
        #endif
    }
}
</code>```

For your example:

```<code>private func updateImage() {
    let image = checked ? UIImage.image(name: "checked", self) : UIImage(name: "unchecked", self)
   setImage(image, for: .normal)
}
</code>```

Also, UIButton class has checked state, which you can use without creation own sub class:

```<code>let btn = UIButton(type: .custom)
btn.setImage(UIImage.image(name: "unchecked", self), for: .normal)
btn.setImage(UIImage.image(name: "checked", self), for: .selected)

btn.isSelected = true // change button state between checked and unchecked
</code>```

ContentLicense: CC BY-SA 3.0

Title: Custom UIButton @IBDesignable

Body:
I created a UIButton subclass that looks like a checkmark.

Here is the class:

import UIKit

@IBDesignable
class CheckedButton: UIButton {

    // MARK: - Properties
    @IBInspectable var checked: Bool = false {
        didSet {
            // Toggle the check/uncheck images
            updateImage()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    private func setup() {
        updateImage()
        self.addTarget(self, action: #selector(tapped), for: .touchUpInside)
    }

    private func updateImage() {
        let image = checked ? UIImage(named: "checked") : UIImage(named: "unchecked")
        self.setImage(image, for: .normal)
    }

    /// Called each time the button is tapped, and toggles the checked property
    @objc private func tapped() {
        checked = !checked
        print("New value: \(checked)")
    }
}

Since I set the checkedproperty as @IBInspectable, I see it in IB :

The weird thing is:

if I let this property as default, it is correctly showing in the storyboard

but if I choose either on or off inthe inspector, the screen is not updated properly.

As the class is marked @IBDesignable, I would expect the button appearance to update in IB according to the value set for this property in the inspector tab.
Got a clue?

Body:
My suggestion is in using other custom function for getting image from assets:

extension UIImage {
    public static func image(name: String, _ sender: UIView?) -> UIImage? {
        #if TARGET_INTERFACE_BUILDER
            if let sender = sender {
                let bundle = Bundle(for: sender.classForCoder)
                return UIImage(named: name, in: bundle, compatibleWith: sender.traitCollection)
            } else {
                return UIImage(named: name)
            }
        #else
            return UIImage(named: name)
        #endif
    }
}

For your example:

private func updateImage() {
    let image = checked ? UIImage.image(name: "checked", self) : UIImage(name: "unchecked", self)
   setImage(image, for: .normal)
}

Also, UIButton class has checked state, which you can use without creation own sub class:

let btn = UIButton(type: .custom)
btn.setImage(UIImage.image(name: "unchecked", self), for: .normal)
btn.setImage(UIImage.image(name: "checked", self), for: .selected)

btn.isSelected = true // change button state between checked and unchecked


问:
Problems with constant iterators
I'm trying write a tempate function which takes a sequence (by 2 iterators) and calculates the number of permutations of this sequence, in which there are no consecutive identical elements.
Thats what i did

```<code>    template<class Iterator>
    size_t count_perm(Iterator p, Iterator q)
    {
        if (p == q)
            return 1;
        size_t count = 0;
        while(std::next_permutation(p, q)){
              if(std::adjacent_find(p,q) != q)
              ++count;
        }
    }
/*Example

std::array<int, 3> a1 = {1,2,3};
size_t c1 = count_perm(a1.begin(), a1.end()); // 6

std::array<int, 5> a2 = {1,2,3,4,4};
size_t c2 = count_perm(a2.begin(), a2.end()); // 36*/
</code>```

This code not working if i pass const iterators. What should I change to make it work with const iterators?

答:
Solved this exercise as follows, it works with const iterators:

```<code>template<class Iterator>
size_t count_permutations(Iterator p, Iterator q)
{
    using T = typename std::iterator_traits<Iterator>::value_type;
    if (p == q)
        return 1;
    std::vector<T> v(p,q);
    std::sort(v.begin(), v.end());
    size_t count = 0;
    do{
        if(std::adjacent_find(v.begin(),v.end()) == v.end()) {
            ++count;
        }

    } while(std::next_permutation(v.begin(), v.end()));
    return count;
}
</code>```

Problem was to use std::type_traits<Iterator>::value_type instead Iterator::value_type (that not working with const iters and simple pointers (like int*))

Title: Problems with constant iterators

Body:
I'm trying write a tempate function which takes a sequence (by 2 iterators) and calculates the number of permutations of this sequence, in which there are no consecutive identical elements.
Thats what i did

    template<class Iterator>
    size_t count_perm(Iterator p, Iterator q)
    {
        if (p == q)
            return 1;
        size_t count = 0;
        while(std::next_permutation(p, q)){
              if(std::adjacent_find(p,q) != q)
              ++count;
        }
    }
/*Example

std::array<int, 3> a1 = {1,2,3};
size_t c1 = count_perm(a1.begin(), a1.end()); // 6

std::array<int, 5> a2 = {1,2,3,4,4};
size_t c2 = count_perm(a2.begin(), a2.end()); // 36*/

This code not working if i pass const iterators. What should I change to make it work with const iterators?

Body:
Solved this exercise as follows, it works with const iterators:

template<class Iterator>
size_t count_permutations(Iterator p, Iterator q)
{
    using T = typename std::iterator_traits<Iterator>::value_type;
    if (p == q)
        return 1;
    std::vector<T> v(p,q);
    std::sort(v.begin(), v.end());
    size_t count = 0;
    do{
        if(std::adjacent_find(v.begin(),v.end()) == v.end()) {
            ++count;
        }

    } while(std::next_permutation(v.begin(), v.end()));
    return count;
}

Problem was to use std::type_traits<Iterator>::value_type instead Iterator::value_type (that not working with const iters and simple pointers (like int*))


问:
Register Button is not Working
I'm creating an android application, I want to send the user information to the database by clicking on Register Button and I want it to go to login page.I have created Intent to pass this activity to login activity. When I click register button the user input gets sent to the database but doesn't take you to Login activity. I check on the Logcat and it's not throwing any error. Anyone help me to figure this out, please?

here is my code:

```<code>registerbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("HELLO", "Register Button Clicked");
            //register();

            final String first_name = etfirstname.getText().toString();
            final String last_name = etlastname.getText().toString();
            final String email = etemail.getText().toString();
            final String password = etpass.getText().toString();
            //String Password2 = etpass2.getText().toString();

            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("HELLO Hello", "Register Button Clicked");
                    try{
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");
                        if(success){
                            Intent intent = new Intent(AppRegisterActivity.this, MainActivity.class);
                            //startActivity(intent);
                            AppRegisterActivity.this.startActivity(intent);
                        }else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(AppRegisterActivity.this);
                            builder.setMessage("Register Failed")
                                    .setNegativeButton("Retry", null)
                                    .create().show();

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            };
            RegisterRequest registerRequest = new RegisterRequest(first_name, last_name, email, password, responseListener);
            RequestQueue queue = Volley.newRequestQueue(AppRegisterActivity.this);
            queue.add(registerRequest);

        }

    });
</code>```

答: Thanks to all, I figured out my problem. The problem was in the PHP script. I had declared five variables and use only four to post the user credential. </p>

Title: Register Button is not Working

Body:
I'm creating an android application, I want to send the user information to the database by clicking on Register Button and I want it to go to login page.I have created Intent to pass this activity to login activity. When I click register button the user input gets sent to the database but doesn't take you to Login activity. I check on the Logcat and it's not throwing any error. Anyone help me to figure this out, please?

here is my code:

registerbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("HELLO", "Register Button Clicked");
            //register();

            final String first_name = etfirstname.getText().toString();
            final String last_name = etlastname.getText().toString();
            final String email = etemail.getText().toString();
            final String password = etpass.getText().toString();
            //String Password2 = etpass2.getText().toString();

            Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("HELLO Hello", "Register Button Clicked");
                    try{
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");
                        if(success){
                            Intent intent = new Intent(AppRegisterActivity.this, MainActivity.class);
                            //startActivity(intent);
                            AppRegisterActivity.this.startActivity(intent);
                        }else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(AppRegisterActivity.this);
                            builder.setMessage("Register Failed")
                                    .setNegativeButton("Retry", null)
                                    .create().show();

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            };
            RegisterRequest registerRequest = new RegisterRequest(first_name, last_name, email, password, responseListener);
            RequestQueue queue = Volley.newRequestQueue(AppRegisterActivity.this);
            queue.add(registerRequest);

        }

    });


问:
How to send google script sender email to no-reply@entreprise.com?
I send 200 emails to a community of students via a google-spreadsheet attached google script.

My mailing call is as follow :

```<code>MailApp.sendEmail(
  "toto@gmail.com",             // targetEmail
  "HELLO FROM KING OF NIGERIA", // emailTitle
  "",                           // something
  // emailContentHTML
  { htmlBody:  "<b>Hello John</b><br><p>I'am king of Nigeria.<br>Got gold everywhere.<br>Need your help I'am in danger.<br>Want to share with you.<br>Could you send me 50$<br>Sinceraly, your friend.</p>"}
);
</code>```

The script being run by my google account john.Doe@entreprise.com, the 200+ participants see the email as coming from me (john.Doe@entreprise.com). I understand this is fair game to limit spamming and co, but my company has a gmail entreprise.com domain name and I would like a solution so to not get dozens of "Thanks you" alerts in the following days. For sure, I do NOT want them to keep me in their following discussion.

So I look for something such as create a no-reply@entreprise.com account, and then a js thing so the script sign email with this no-reply@entreprise.com email.

Also, is there a way to programatically sign the google-script mailing from an other account of my company (no-reply@entreprise.com) ?

Note : google-script-manual

答:
You could use the following method from the MailApp documentation

```<code>sendEmail (title, replyTo, subject, body)
</code>```

Setting the replyTo to your do-not-reply email will mean that anyone who presses reply will send their email to your do-not-reply mailbox

```<code>MailApp.sendEmail (
  "email@example.com",        // targetEmail
  "do-not-reply@example.com", // reply to email
  ...
)
</code>```

Link to MailApp Documentation

Body:
I send 200 emails to a community of students via a google-spreadsheet attached google script.

My mailing call is as follow :

MailApp.sendEmail(
  "toto@gmail.com",             // targetEmail
  "HELLO FROM KING OF NIGERIA", // emailTitle
  "",                           // something
  // emailContentHTML
  { htmlBody:  "Hello John

I'am king of Nigeria.
Got gold everywhere.
Need your help I'am in danger.
Want to share with you.
Could you send me 50$
Sinceraly, your friend.
"}
);

The script being run by my google account john.Doe@entreprise.com, the 200+ participants see the email as coming from me (john.Doe@entreprise.com). I understand this is fair game to limit spamming and co, but my company has a gmail entreprise.com domain name and I would like a solution so to not get dozens of "Thanks you" alerts in the following days. For sure, I do NOT want them to keep me in their following discussion.

So I look for something such as create a no-reply@entreprise.com account, and then a js thing so the script sign email with this no-reply@entreprise.com email.

Also, is there a way to programatically sign the google-script mailing from an other account of my company (no-reply@entreprise.com) ?

Note : google-script-manual

Body:
You could use the following method from the MailApp documentation

sendEmail (title, replyTo, subject, body)

Setting the replyTo to your do-not-reply email will mean that anyone who presses reply will send their email to your do-not-reply mailbox

MailApp.sendEmail (
  "email@example.com",        // targetEmail
  "do-not-reply@example.com", // reply to email
  ...
)

Link to MailApp Documentation


问:
show pop up when is mouse over image control
I would like show pop up when is mouse over the image control.  So I create control template, it look like this:

```<code>        <ControlTemplate x:Key="AvatarImageTemplate" TargetType="{x:Type Image}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                </Grid.RowDefinitions>

                <HERE I WANT IMAGE SOURCE  Grid.Row="0"/>
                <Popup  IsOpen="False"
                            Name="OponentImagePopUp"
                            AllowsTransparency="True"
                            PopupAnimation="Slide"
                            HorizontalOffset="-35"
                            VerticalOffset="0"
                            Grid.Row="1">
                    <Border BorderThickness="1"
                                BorderBrush="Black">
                        <Grid  Height="350" MinWidth="350">
                            <Grid.Background>
                                <LinearGradientBrush StartPoint="0,0" EndPoint="0,0.3">
                                    <LinearGradientBrush.GradientStops>
                                        <GradientStop Color="LightGray" Offset="0"/>
                                        <GradientStop Color="WhiteSmoke" Offset="1"/>
                                    </LinearGradientBrush.GradientStops>
                                </LinearGradientBrush>
                            </Grid.Background>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="75"></ColumnDefinition>
                                <ColumnDefinition Width="*"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*"></RowDefinition>
                            </Grid.RowDefinitions>

                            <Border BorderThickness="1"
                                    BorderBrush="Black"
                                    Background="White"
                                    Margin="4,4,4,4"
                                    Grid.Column="0">
                                <Image Margin="2,2,2,2">
                                    <Image.Source >
                                        <MultiBinding Converter="{StaticResource avatarConverter}">
                                            <Binding Path="ProfilePhoto"></Binding>
                                            <Binding Path="StatusInfo.IsLogged"></Binding>
                                        </MultiBinding>
                                    </Image.Source>
                                </Image>
                            </Border>
                        </Grid>
                    </Border>
                </Popup>
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter TargetName="OponentImagePopUp" Property="IsOpen" Value="True" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
</code>```

I have two problems:

I don’t how can I acces to image source in control template

Also If I try make a style on Image control and set property Template -> Image control don’t have a property template.

My aim is show pop pop window with same image only bigger.

EDIT:

I create simple control, as advice Mr. Glazkov, which have image control, here is it:

```<code><UserControl x:Class="Spirit.Controls.AvatarImageControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Image x:Name="SmallImage"
            Source="{Binding ElementName=root, Path=ImageSource}"
            Stretch="Fill"/>
    </Grid>
</UserControl>
</code>```

Code behind is the same:

```<code>  public partial class AvatarImageControl : UserControl
    {
        public AvatarImageControl()
        {
            InitializeComponent();
        }

        public ImageSource ImageSource
        {
            get { return (ImageSource)GetValue(ImageSourceProperty); }
            set { SetValue(ImageSourceProperty, value); }
        }

        public static readonly DependencyProperty ImageSourceProperty =
            DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(AvatarImageControl), new UIPropertyMetadata(null));

    }
</code>```

I try use this contol in view:

```<code><Grid Background="#99CCFF"  Margin="4,4,4,4">
      <Controls:AvatarImageControl ImageSource="{Binding Path=Oponent.Info.ProfilePhoto,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</code>```

I bind property type of Uri to ImageSource of AvatarImageControl.

What I do bad?

Also I try this in user control:

```<code><Grid>
    <Image x:Name="SmallImage"
        Source="{Binding Path=ImageSource, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
        Stretch="Fill"/>
</Grid>
</code>```

Result is same.

I use user control in view, I bind on ImageSource property property from view model type of Uri. Nothing else.

EDIT 2:
Code of Mr. Glazkov produce exception:

```<code>{"Set property 'System.Windows.Controls.Primitives.Popup.IsOpen' threw an exception."}
{"A TwoWay or OneWayToSource binding cannot work on the read-only property 'IsMouseOver' of type 'System.Windows.Controls.Image'."}
StackTrace:
   at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
   at Spirit.Controls.AvatarImageControl.InitializeComponent() in c:\Users\Jan\Documents\Visual Studio 2010\Projects\BACKUP\Pokec__Messenger\Spirit_Caliburn_Micro_v1.0\Controls\AvatarImageControl.xaml:line 1
   at Spirit.Controls.AvatarImageControl..ctor() in C:\Users\Jan\Documents\Visual Studio 2010\Projects\BACKUP\Pokec__Messenger\Spirit_Caliburn_Micro_v1.0\Controls\AvatarImageControl.xaml.cs:line 24
</code>```

Solution is :

```<code> <Popup IsOpen="{Binding ElementName=SmallImage, Path=IsMouseOver, Mode=OneWay}">
</code>```

Set binding mode  on oneway.

It works good.

Thank Mr. Glazkov for help.

答:
A general approach to this:

```<code>    <CONTROL>
        <Grid>
            <!-- Actual control content -->
            <Popup IsOpen="{Binding RelativeSource={RelativeSource AncestorType=CONTROL}, Path=IsMouseOver, Mode=OneWay}">
                <!-- Popup content -->
            </Popup>
        </Grid>
    </CONTROL>
</code>```

You can access the image source via RelativeSource-binding as well, you just search for the ancestor type Image.

Edit: Now that your question is cleaned up a bit i can try to find some code for your two specific problems..

Edit2: Too slow...

ContentLicense: CC BY-SA 2.5

Body:
I would like show pop up when is mouse over the image control.  So I create control template, it look like this:

        <ControlTemplate x:Key="AvatarImageTemplate" TargetType="{x:Type Image}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                </Grid.RowDefinitions>

                <HERE I WANT IMAGE SOURCE  Grid.Row="0"/>
                <Popup  IsOpen="False"
                            Name="OponentImagePopUp"
                            AllowsTransparency="True"
                            PopupAnimation="Slide"
                            HorizontalOffset="-35"
                            VerticalOffset="0"
                            Grid.Row="1">
                    <Border BorderThickness="1"
                                BorderBrush="Black">
                        <Grid  Height="350" MinWidth="350">
                            <Grid.Background>
                                <LinearGradientBrush StartPoint="0,0" EndPoint="0,0.3">
                                    <LinearGradientBrush.GradientStops>
                                        <GradientStop Color="LightGray" Offset="0"/>
                                        <GradientStop Color="WhiteSmoke" Offset="1"/>
                                    </LinearGradientBrush.GradientStops>
                                </LinearGradientBrush>
                            </Grid.Background>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="75"></ColumnDefinition>
                                <ColumnDefinition Width="*"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*"></RowDefinition>
                            </Grid.RowDefinitions>

                            <Border BorderThickness="1"
                                    BorderBrush="Black"
                                    Background="White"
                                    Margin="4,4,4,4"
                                    Grid.Column="0">
                                <Image Margin="2,2,2,2">
                                    <Image.Source >
                                        <MultiBinding Converter="{StaticResource avatarConverter}">
                                            <Binding Path="ProfilePhoto"></Binding>
                                            <Binding Path="StatusInfo.IsLogged"></Binding>
                                        </MultiBinding>
                                    </Image.Source>
                                </Image>
                            </Border>
                        </Grid>
                    </Border>
                </Popup>
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter TargetName="OponentImagePopUp" Property="IsOpen" Value="True" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>

I have two problems:

I don’t how can I acces to image source in control template

Also If I try make a style on Image control and set property Template -> Image control don’t have a property template.

My aim is show pop pop window with same image only bigger.

EDIT:

I create simple control, as advice Mr. Glazkov, which have image control, here is it:

<UserControl x:Class="Spirit.Controls.AvatarImageControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Image x:Name="SmallImage"
            Source="{Binding ElementName=root, Path=ImageSource}"
            Stretch="Fill"/>
    </Grid>
</UserControl>

Code behind is the same:

  public partial class AvatarImageControl : UserControl
    {
        public AvatarImageControl()
        {
            InitializeComponent();
        }

        public ImageSource ImageSource
        {
            get { return (ImageSource)GetValue(ImageSourceProperty); }
            set { SetValue(ImageSourceProperty, value); }
        }

        public static readonly DependencyProperty ImageSourceProperty =
            DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(AvatarImageControl), new UIPropertyMetadata(null));

    }

I try use this contol in view:

<Grid Background="#99CCFF"  Margin="4,4,4,4">
      <Controls:AvatarImageControl ImageSource="{Binding Path=Oponent.Info.ProfilePhoto,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
</Grid>

I bind property type of Uri to ImageSource of AvatarImageControl.

What I do bad?

Also I try this in user control:

<Grid>
    <Image x:Name="SmallImage"
        Source="{Binding Path=ImageSource, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
        Stretch="Fill"/>
</Grid>

Result is same.

I use user control in view, I bind on ImageSource property property from view model type of Uri. Nothing else.

EDIT 2:
Code of Mr. Glazkov produce exception:

{"Set property 'System.Windows.Controls.Primitives.Popup.IsOpen' threw an exception."}
{"A TwoWay or OneWayToSource binding cannot work on the read-only property 'IsMouseOver' of type 'System.Windows.Controls.Image'."}
StackTrace:
   at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
   at Spirit.Controls.AvatarImageControl.InitializeComponent() in c:\Users\Jan\Documents\Visual Studio 2010\Projects\BACKUP\Pokec__Messenger\Spirit_Caliburn_Micro_v1.0\Controls\AvatarImageControl.xaml:line 1
   at Spirit.Controls.AvatarImageControl..ctor() in C:\Users\Jan\Documents\Visual Studio 2010\Projects\BACKUP\Pokec__Messenger\Spirit_Caliburn_Micro_v1.0\Controls\AvatarImageControl.xaml.cs:line 24

Solution is :

 <Popup IsOpen="{Binding ElementName=SmallImage, Path=IsMouseOver, Mode=OneWay}">

Set binding mode  on oneway.

It works good.

Thank Mr. Glazkov for help.

Body:
A general approach to this:

    <CONTROL>
        <Grid>
            <!-- Actual control content -->
            <Popup IsOpen="{Binding RelativeSource={RelativeSource AncestorType=CONTROL}, Path=IsMouseOver, Mode=OneWay}">
                <!-- Popup content -->
            </Popup>
        </Grid>
    </CONTROL>

You can access the image source via RelativeSource-binding as well, you just search for the ancestor type Image.

Edit: Now that your question is cleaned up a bit i can try to find some code for your two specific problems..

Edit2: Too slow...


问:
Unable to serve image (png) with node.js and express
I've studied similar questions on SO but haven't found a solution to my problem... I've set up an express route to serve images but I can't get it to return an image from where it's stored.  Notice I've included a statement to allow requests from any origin. What happens is that when I make a request to http://localhost:8080/images/x10.png the response I get is an empty image element with src="http://localhost:8080/images/x10.png instead of from http://ubuntubox.dev/images/x10.png, which is where the image is actually located and is the path I'm ultimately passing to the request method. What am I missing? Thanks.

```<code>app.get('/images/*', function(req, res, path){
  var imagePath = req.url,
      url = 'http://ubuntubox.dev' + imagePath;

  request(url, function(error, response, img) {
    if(!error && response.statusCode === 200) {
      res.header('Access-Control-Allow-Origin', '*');
      res.writeHead(200, {'Content-Type': 'image/png' });
      res.end(img, 'binary');
    } else if(response.statusCode === 404) {
      res.status(404);
      res.type('txt').send('oops');
    }
  });
}).listen(8080, '127.0.0.1');
</code>```

答:
If you want to serve images and other assets in a way that makes sense and doesn't require you to write a million routes, try this:

Create a new folder "public" and move all of your assets into it.

Open server.js and add the following line:

app.use(express.static('public'))

Your assets should now be available like so:

```<code>http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
</code>```

Soure: https://expressjs.com/en/starter/static-files.html

Body:
I've studied similar questions on SO but haven't found a solution to my problem... I've set up an express route to serve images but I can't get it to return an image from where it's stored.  Notice I've included a statement to allow requests from any origin. What happens is that when I make a request to http://localhost:8080/images/x10.png the response I get is an empty image element with src="http://localhost:8080/images/x10.png instead of from http://ubuntubox.dev/images/x10.png, which is where the image is actually located and is the path I'm ultimately passing to the request method. What am I missing? Thanks.

app.get('/images/*', function(req, res, path){
  var imagePath = req.url,
      url = 'http://ubuntubox.dev' + imagePath;

  request(url, function(error, response, img) {
    if(!error && response.statusCode === 200) {
      res.header('Access-Control-Allow-Origin', '*');
      res.writeHead(200, {'Content-Type': 'image/png' });
      res.end(img, 'binary');
    } else if(response.statusCode === 404) {
      res.status(404);
      res.type('txt').send('oops');
    }
  });
}).listen(8080, '127.0.0.1');

Body:
If you want to serve images and other assets in a way that makes sense and doesn't require you to write a million routes, try this:

Create a new folder "public" and move all of your assets into it.

Open server.js and add the following line:

app.use(express.static('public'))

Your assets should now be available like so:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

Soure: https://expressjs.com/en/starter/static-files.html


问:
How can I get access to a Django Model field verbose name dynamically?
I'd like to have access to one my model field verbose_name.

I can get it by the field indice like this

```<code>model._meta._fields()[2].verbose_name
</code>```

but I need to get it dynamically. Ideally it would be something like this

```<code>model._meta._fields()['location_x'].verbose_name
</code>```

I've looked at a few things but I just can't find it.

答:
For Django 1.11 and 2.0:

```<code>MyModel._meta.get_field('my_field_name').verbose_name
</code>```

More info in the Django doc

Body:
I'd like to have access to one my model field verbose_name.

I can get it by the field indice like this

model._meta._fields()[2].verbose_name

but I need to get it dynamically. Ideally it would be something like this

model._meta._fields()['location_x'].verbose_name

I've looked at a few things but I just can't find it.

Body:
For Django 1.11 and 2.0:

MyModel._meta.get_field('my_field_name').verbose_name

More info in the Django doc


问:
Split String if length is more than a value
I have a label that contains comments and I am using iTextsharp to insert those lines into a pdf now the point where comments come in here is the box for comments int he pdf:

This is the PDF comment box

I will use this code to put in a line:

```<code>     string comment = lblComment.text;
// lets say the lblComment.text = "This is a Document where User Added new Address"
         cb.BeginText();
            cb.SetColorFill(BaseColor.DARK_GRAY);
            cb.SetFontAndSize(bf, 11);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, Comment, 215, 96, 0); // Insert the Cooments
            cb.EndText();
</code>```

Now the problem is Comment can be long and I want some way of doing this so if the Line for the Comment is more than these many charechters insert next line and take half of the comment strign to the next line. I tried looking at splitting string on google all i could find:

```<code>    string data = "THExxQUICKxxBROWNxxFOX";

return data.Split(new string[] { "xx" }, StringSplitOptions.None);
</code>```

This is where the string has xx you split it but didnt work.

答:
From your code I think you're just looking for

```<code>return Regex.Split(data, "xx");
</code>```

but from your question I think maybe you want to recursively return substrings to get numerous lines <= max line length, not actually split on a specific character.

Body:
I have a label that contains comments and I am using iTextsharp to insert those lines into a pdf now the point where comments come in here is the box for comments int he pdf:

This is the PDF comment box

I will use this code to put in a line:

     string comment = lblComment.text;
// lets say the lblComment.text = "This is a Document where User Added new Address"
         cb.BeginText();
            cb.SetColorFill(BaseColor.DARK_GRAY);
            cb.SetFontAndSize(bf, 11);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, Comment, 215, 96, 0); // Insert the Cooments
            cb.EndText();

Now the problem is Comment can be long and I want some way of doing this so if the Line for the Comment is more than these many charechters insert next line and take half of the comment strign to the next line. I tried looking at splitting string on google all i could find:

    string data = "THExxQUICKxxBROWNxxFOX";

return data.Split(new string[] { "xx" }, StringSplitOptions.None);

This is where the string has xx you split it but didnt work.

Body:
From your code I think you're just looking for

return Regex.Split(data, "xx");

but from your question I think maybe you want to recursively return substrings to get numerous lines <= max line length, not actually split on a specific character.


问:
accessing an array in a component from the layout in yii2
I need to check the records in the notifications table at every page load of every controller.

So I wrote it in a component and the component is executed in the bootstraping process.

I need the notifications to be available in the layout so that i can show them in the notification menu.

below is what I have tried so far:

component:

```<code>namespace admin\components;

use Yii;
use yii\base\Component;
use admin\models\Notification;

class NotificationManager extends \yii\base\Component{
  public function init() {

    $notifications = Notification::find()->orderBy('id DESC')->asArray()->all();
    //echo "```"; print_r($notifications);exit;

    if(count($notifications)>0){
      foreach ($notifications as $notif) {
        if($notif['type'] == 'courier')
          $courier_notifications[] = $notif;
        elseif($notif['type'] == 'order')
          $order_notifications[] = $notif;
      }

      Yii::$app->view->params['courier_notifications'] = $courier_notifications;
      Yii::$app->view->params['order_notifications'] = $order_notifications;
    }
  }
}
```

<p>Layout:</p>

```$courier_notifications = $this->params['courier_notifications'];
```

I am not sure which part am I going wrong: in component or in the layout?
I appreciate your help.

答:
If you really want to go bootstrap mode, you need to implement yii\base\BootstrapInterface and put your logic in the bootstrap($app) method in order for the param to be available site-wide by setting the value of Yii::$app->params['notifications'] to the result of your logic.

Another common approach is to add a new method public function displayNotifications or whatever you want to name it, to your component, move all the logic in it and then in your layout/view etc., call it with Yii::$app->notificationManager->displayNotifications(). You can also pass additional parameters to it and enhance your logic.

notificationManager has to be replaced with the name you registered your custom component in the Yii app config (web.php for basic app, main.php for advanced app).

LE - If you only registered your component for bootstrap, you should also register it in the components array.

'notificationManager' => [
     'class' => '\admin\components\NotificationManager'
]

Body:
I need to check the records in the notifications table at every page load of every controller.

So I wrote it in a component and the component is executed in the bootstraping process.

I need the notifications to be available in the layout so that i can show them in the notification menu.

below is what I have tried so far:

component:

namespace admin\components;

use Yii;
use yii\base\Component;
use admin\models\Notification;

class NotificationManager extends \yii\base\Component{
  public function init() {

    $notifications = Notification::find()->orderBy('id DESC')->asArray()->all();
    //echo "
"; print_r($notifications);exit;

    if(count($notifications)>0){
      foreach ($notifications as $notif) {
        if($notif['type'] == 'courier')
          $courier_notifications[] = $notif;
        elseif($notif['type'] == 'order')
          $order_notifications[] = $notif;
      }

      Yii::$app->view->params['courier_notifications'] = $courier_notifications;
      Yii::$app->view->params['order_notifications'] = $order_notifications;
    }
  }
}

Layout:

$courier_notifications = $this->params['courier_notifications'];

I am not sure which part am I going wrong: in component or in the layout?
I appreciate your help.


问:
multiple column layout inside a tabPanel
I generate a lot of input using renderUI, I would like to have a multicolumn display inside a tabPanel.

Of course the number of input is dynamic :-)

Any idea how do do this ?

```<code>   library(shiny)
ui <- fluidPage(
  titlePanel("Old Faithful Geyser Data"),
  sidebarLayout(
    sidebarPanel(
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Plot",
uiOutput("lot_of_input")
        ),
        tabPanel("Summary", verbatimTextOutput("summary"))
      )
    )
  )
)

server <- function(input, output) {

  output$lot_of_input <- renderUI({
list(
  numericInput(inputId = "A","A",1),
      numericInput(inputId = "AB","AB",1),numericInput(inputId = "B","C",1),
      numericInput(inputId = "C2","C",1),
      numericInput(inputId = "A3","A",1),
      numericInput(inputId = "AB3","AB",1),
      numericInput(inputId = "B3","C",1),
      numericInput(inputId = "C23","C",1)#, lot of other input
) # In my code this list is returned by a function
  })

  output$summary <- renderText("coucou")
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

not this :

but this :

答:
This feels like a data manipulation problem, so here is one option using dplyr :

```<code>pack <- function( inputs, nc = 4){
  n <- length(inputs)
  nrows <- ceiling( n / nc )

  tibble(
    row = head( rep(1:nrows, each = nc), n ),
    inputs = inputs
  ) %>%
    group_by(row) %>%
    summarise( list(do.call(splitLayout, inputs)) ) %>%
    pull()

}
</code>```

which you then use in your output:

```<code>output$lot_of_input <- renderUI({
  inputs <- list(
    numericInput(inputId = "A","A",1),
    numericInput(inputId = "AB","AB",1),
    numericInput(inputId = "B","C",1),
    numericInput(inputId = "C2","C",1),
    numericInput(inputId = "A3","A",1),
    numericInput(inputId = "AB3","AB",1),
    numericInput(inputId = "B3","C",1),
    numericInput(inputId = "C23","C",1)#, lot of other input
  )

  pack( inputs, 4 )
})
</code>```

Body:
I generate a lot of input using renderUI, I would like to have a multicolumn display inside a tabPanel.

Of course the number of input is dynamic :-)

Any idea how do do this ?

   library(shiny)
ui <- fluidPage(
  titlePanel("Old Faithful Geyser Data"),
  sidebarLayout(
    sidebarPanel(
    ),
    mainPanel(
      tabsetPanel(
        tabPanel("Plot",
uiOutput("lot_of_input")
        ),
        tabPanel("Summary", verbatimTextOutput("summary"))
      )
    )
  )
)

server <- function(input, output) {

  output$lot_of_input <- renderUI({
list(
  numericInput(inputId = "A","A",1),
      numericInput(inputId = "AB","AB",1),numericInput(inputId = "B","C",1),
      numericInput(inputId = "C2","C",1),
      numericInput(inputId = "A3","A",1),
      numericInput(inputId = "AB3","AB",1),
      numericInput(inputId = "B3","C",1),
      numericInput(inputId = "C23","C",1)#, lot of other input
) # In my code this list is returned by a function
  })

  output$summary <- renderText("coucou")
}

# Run the application
shinyApp(ui = ui, server = server)

not this :

but this :

Body:
This feels like a data manipulation problem, so here is one option using dplyr :

pack <- function( inputs, nc = 4){
  n <- length(inputs)
  nrows <- ceiling( n / nc )

  tibble(
    row = head( rep(1:nrows, each = nc), n ),
    inputs = inputs
  ) %>%
    group_by(row) %>%
    summarise( list(do.call(splitLayout, inputs)) ) %>%
    pull()

}

which you then use in your output:

output$lot_of_input <- renderUI({
  inputs <- list(
    numericInput(inputId = "A","A",1),
    numericInput(inputId = "AB","AB",1),
    numericInput(inputId = "B","C",1),
    numericInput(inputId = "C2","C",1),
    numericInput(inputId = "A3","A",1),
    numericInput(inputId = "AB3","AB",1),
    numericInput(inputId = "B3","C",1),
    numericInput(inputId = "C23","C",1)#, lot of other input
  )

  pack( inputs, 4 )
})


问:
C++ Output is skipping last word when reading through text file
I have a vector of a large text file that I open, and a search words file that I also open. I have two functions, isNextWord which checks if there is another word and the getNextWord which gets the next word.

I check if the search word is in the vector and then print out all the occurences at the end. My code works almost perfectly apart from the fact it skips the last word in the search word file.

For example if my words are: hello,these,are,my,search,words it will show all occurences apart from "words":

```<code>hello 5
these 2
are 5
my 7
search 9
</code>```

This is my cpp file:

```<code>string ReadWords::getNextWord()
{
//gets next word of input from file

 return theword;

}

bool ReadWords::isNextWord()
{

return !eoffound;
}
</code>```

This is my main

```<code>while (search.isNextWord()) {
        int occ= 0;
        string wordFound= search.getNextWord();
        for(int i=0; i < vct.size(); i++){
            if(vct[i] == wordFound) {
                occ++;
            }
        }

       cout << wordSearch <<  " " << occ<< endl;
    }
</code>```

Why doesn't it perform the getNext word one last time?

答:
You are activating the eof flag when it get the last word, then, the function ReadWords::isNextWord() returns false and the loop is out and the last word is never printed.
 For example, when the word search is returned, you read the last one and enable the flag.

I recommend change the function isNextWord to

bool ReadWords::isNextWord() {return !(wordfile.eof()); }

Body:
I have a vector of a large text file that I open, and a search words file that I also open. I have two functions, isNextWord which checks if there is another word and the getNextWord which gets the next word.

I check if the search word is in the vector and then print out all the occurences at the end. My code works almost perfectly apart from the fact it skips the last word in the search word file.

For example if my words are: hello,these,are,my,search,words it will show all occurences apart from "words":

hello 5
these 2
are 5
my 7
search 9

This is my cpp file:

string ReadWords::getNextWord()
{
//gets next word of input from file

 return theword;

}

bool ReadWords::isNextWord()
{

return !eoffound;
}

This is my main

while (search.isNextWord()) {
        int occ= 0;
        string wordFound= search.getNextWord();
        for(int i=0; i < vct.size(); i++){
            if(vct[i] == wordFound) {
                occ++;
            }
        }

       cout << wordSearch <<  " " << occ<< endl;
    }

Why doesn't it perform the getNext word one last time?


问:
iOS11 SearchController in NavigationBar with Scope Buttons

In iOS 11 you can put a UISearchController in the NavigationBar with a few lines of code.

I set up everything in the ViewController.swift.

```<code>func setupNavBar() {
    navigationController?.navigationBar.prefersLargeTitles = true

    let searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = wordViewController
    searchController.searchBar.scopeButtonTitles = ["French", "English"]
    searchController.searchBar.delegate = wordViewController

    navigationItem.searchController = searchController
    // Make searchbar persistent
    navigationItem.hidesSearchBarWhenScrolling = false
}
</code>```

In my delegate, the search fires and filters properly.  However, if I click either of the scope buttons, they simply disappear.  This delegate method is never called. (filter by scope is not actually implemented yet)

```<code>extension WordViewController: UISearchBarDelegate {

 func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {

    if let searchText = searchBar.text {
        print("Scoped changed: \(searchText)")
        filteredWordList = wordList.filter({$0.contains(searchText)})
    }
  }
}
</code>```

Full source is on Github:

https://github.com/melling/ios_topics/tree/master/NavBarSearch
https://github.com/melling/ios_topics/tree/master/NavBarSearch/NavBarSearch

答:
In your ViewController, you need to add this line

self.definesPresentationContext = YES;

This tells the UISearchController the presentation context it needs to use, which is defined by your ViewController.

Check this link for more details: http://asciiwwdc.com/2014/sessions/228

Body:
In iOS 11 you can put a UISearchController in the NavigationBar with a few lines of code.

I set up everything in the ViewController.swift.

func setupNavBar() {
    navigationController?.navigationBar.prefersLargeTitles = true

    let searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = wordViewController
    searchController.searchBar.scopeButtonTitles = ["French", "English"]
    searchController.searchBar.delegate = wordViewController

    navigationItem.searchController = searchController
    // Make searchbar persistent
    navigationItem.hidesSearchBarWhenScrolling = false
}

In my delegate, the search fires and filters properly.  However, if I click either of the scope buttons, they simply disappear.  This delegate method is never called. (filter by scope is not actually implemented yet)

extension WordViewController: UISearchBarDelegate {

 func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {

    if let searchText = searchBar.text {
        print("Scoped changed: \(searchText)")
        filteredWordList = wordList.filter({$0.contains(searchText)})
    }
  }
}

Full source is on Github:

https://github.com/melling/ios_topics/tree/master/NavBarSearch
https://github.com/melling/ios_topics/tree/master/NavBarSearch/NavBarSearch


问:
POSIX way to convert user input with utc offset to calendar time
Is there a POSIX way how to convert a user input with UTC offset into time_t? I was hoping for something like

```<code>strptime( buf, "%Y-%m-%d-UTC%O", &input_time );
</code>```

where %O would be the UTC offset.

Unfortunately the tm_gmtoff extention to struct tm doesn't seem to be available on Solaris (10), is it?

答:
The POSIX way to handle timezone information apparently is to set the environment variable TZ. Hence, I've chosen to set TZ with the user specified timezone prior to working with the time functions:

```<code>/* Get actual time */
time( &now );

/* Backup time zone */
old_tz = getenv( "TZ" );

/* Set user time zone */
setenv("TZ", zone_s, 1);

/* Get time components in user timezone */
comptime = localtime( &now );

/* Set time */
sscanf(time_string, "%d:%d", &x, &y) );
comptime->tm_hour = x;
comptime->tm_min = y;
comptime->tm_sec = 0;

/* Set date */
sscanf( date_string, "%d-%d-%d", &x, &y, &z );
comptime->tm_year = x-1900;
comptime->tm_mon = y-1;
comptime->tm_mday = z;

/* Restore time zone */
setenv( "TZ", old_tz, 1 );
</code>```

Cheers,

Martin.

Body:
Is there a POSIX way how to convert a user input with UTC offset into time_t? I was hoping for something like

strptime( buf, "%Y-%m-%d-UTC%O", &input_time );

where %O would be the UTC offset.

Unfortunately the tm_gmtoff extention to struct tm doesn't seem to be available on Solaris (10), is it?

Body:
The POSIX way to handle timezone information apparently is to set the environment variable TZ. Hence, I've chosen to set TZ with the user specified timezone prior to working with the time functions:

/* Get actual time */
time( &now );

/* Backup time zone */
old_tz = getenv( "TZ" );

/* Set user time zone */
setenv("TZ", zone_s, 1);

/* Get time components in user timezone */
comptime = localtime( &now );

/* Set time */
sscanf(time_string, "%d:%d", &x, &y) );
comptime->tm_hour = x;
comptime->tm_min = y;
comptime->tm_sec = 0;

/* Set date */
sscanf( date_string, "%d-%d-%d", &x, &y, &z );
comptime->tm_year = x-1900;
comptime->tm_mon = y-1;
comptime->tm_mday = z;

/* Restore time zone */
setenv( "TZ", old_tz, 1 );

Cheers,

Martin.


问:
ReactJS - How to remove whole component , by using child button
I have problem , i want to create TODO app in ReactJS and there is functionality like this:

onClick is showing/hidding AddTaskBox (form in div, where you have to write title and describtion ) - I done it.

In visable AddTaskBox is button with "x" and I want to use him to delete whole "AddTaskBox" - Can't figur it out :(

I'm greeny in React , my thinking about that library may be wrong.

My code:

```<code>import React from 'react';
import ReactDOM from 'react-dom';

class AddButton extends React.Component{

  constructor(){
      super();

      this.state = {
      isHidden: false
    }
  }

  toggleHidden () {
      this.setState({
        isHidden: !this.state.isHidden
      })
  }

  render(){
    return(
      <div>
        <div
          onClick={this.toggleHidden.bind(this)}
          className="addtask__btn">
          +
        </div>
        {this.state.isHidden && <AddTaskBox />}
      </div>
    );
  }
}

class AddTaskBox extends React.Component{
  render(){
    return(
      <div className="addtask__box" >
        <button> x </button> // here is my x to close component
        <form>
          <input type="text" placeholder="Nazwa Czynności"/>
          <textarea>
            Opis czynności do wykonania
          </textarea>
          <input className="btn" type="Submit" value="Submit"/>
        </form>
      </div>
    );
  }
}

export {AddButton, AddTaskBox};
</code>```

Thanks for help :)

答:
Assuming by AddTaskComponent you mean AddTaskBox you would pass the toggleHidden function to AddTaskBox

{this.state.isHidden && <AddTaskBox onClose={this.toggleHidden.bind(this)} />}

and then call the function from the child on click

<button onClick={this.props.onClose}> x </button>

Body:
I have problem , i want to create TODO app in ReactJS and there is functionality like this:

onClick is showing/hidding AddTaskBox (form in div, where you have to write title and describtion ) - I done it.

In visable AddTaskBox is button with "x" and I want to use him to delete whole "AddTaskBox" - Can't figur it out :(

I'm greeny in React , my thinking about that library may be wrong.

My code:

import React from 'react';
import ReactDOM from 'react-dom';

class AddButton extends React.Component{

  constructor(){
      super();

      this.state = {
      isHidden: false
    }
  }

  toggleHidden () {
      this.setState({
        isHidden: !this.state.isHidden
      })
  }

  render(){
    return(

          +

        {this.state.isHidden && <AddTaskBox />}

    );
  }
}

class AddTaskBox extends React.Component{
  render(){
    return(

        <button> x </button> // here is my x to close component
        <form>
          <input type="text" placeholder="Nazwa Czynności"/>
          <textarea>
            Opis czynności do wykonania
          </textarea>
          <input className="btn" type="Submit" value="Submit"/>
        </form>

    );
  }
}

export {AddButton, AddTaskBox};

Thanks for help :)


问:
Jquery DateTime now showing ValidationMessageFor for a field with datepicker
I have the Model with the following declaration

```<code>    [Display(Name = "lblFechaInicio", ResourceType = typeof(RecursosAdministracion))]
    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? fechaInicio { get; set; }
</code>```

In the View I have this:

```<code>        @Html.LabelFor(model => model.fechaInicio, new { @class = "control-label" })
<div class="controls">
    <div class="input-prepend">
        @Html.EditorFor(model => model.fechaInicio, new { @class = "input-small hasDatepicker" })
        <span class="add-on">
            <i class="icon-calendar"></i>
        </span>
    </div>
    <span class="help-inline">
        <span data-valmsg-replace="true" data-valmsg-for="@Model.fechaInicio" class="field-validation-error">
            @Html.ValidationMessageFor(model => model.fechaInicio)
        </span>
    </span>
</div>
</code>```

But when I type an invalid Date in fechaInicio and move to another field, the validation is not being fired and the validation message if not being shown

Below is the list of all the included scripts of the rendered page

```<code><script src="/WebSite/Scripts/jquery-1.9.1.js"></script>
<script src="/WebSite/Scripts/DataTables-1.9.4/media/js/jquery.dataTables.js"></script>
<script src="/WebSite/Scripts/ScriptsArq/jquery.dataTables.custom.js"></script>
<script src="/WebSite/Scripts/ScriptsArq/WrapperUI.js"></script>
<script src="/WebSite/Scripts/ScriptsArq/ScriptUtilitarios.js"></script>
<script src="/WebSite/Scripts/ScriptsArq/CustomDataTablesPlugin.js"></script>
<script src="/WebSite/Scripts/ScriptsArq/utf8.js"></script>
<script src="/WebSite/Scripts/ScriptsArq/jquery.fileDownload.js"></script>
<script src="/WebSite/Scripts/jquery-ui-1.9.1.js"></script>
<script src="/WebSite/Scripts/bootstrap.js"></script>
<script src="/WebSite/Scripts/ScriptsArq/metro-base.js"></script>
<script src="/WebSite/Scripts/modernizr-2.6.2.js"></script>
<script src="/WebSite/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/WebSite/Scripts/jquery.validate.js"></script>
<script src="/WebSite/Scripts/jquery.validate.unobtrusive-custom-for-bootstrap.js"></script>
<script src="/WebSite/Scripts/Vistas/Helpers.js"></script>
<script src="/WebSite/Scripts/suppt-ui-utilitarios.js"></script>
<script src="/WebSite/Scripts/select2.js"></script>
<script src="/WebSite/Scripts/select2.culture-es.js"></script>
<script src="/WebSite/Scripts/ReportViewer/jquery.multi-select.js"></script>
<script src="/WebSite/Scripts/jquery.ui.datepicker.culture-es.js"></script>
<script src="/WebSite/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/WebSite/Scripts/jquery.validate.js"></script>
<script src="/WebSite/Scripts/jquery.validate.unobtrusive-custom-for-bootstrap.js"></script>
</code>```

The file jquery.ui.datepicker.culture-es.js contains this
    $(document).ready(function() {

```<code>    $(function($) {
        $.datepicker.regional["es"] = {
            closeText: "Cerrar",
            prevText: "<Ant",
            nextText: "Sig>",
            currentText: "Hoy",
            monthNames: [
                "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre",
                "Noviembre", "Diciembre"
            ],
            monthNamesShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"],
            dayNames: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"],
            dayNamesShort: ["Dom", "Lun", "Mar", "Mié", "Juv", "Vie", "Sáb"],
            dayNamesMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sá"],
            weekHeader: "Sm",
            dateFormat: "dd/mm/yy",
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: false,
            yearSuffix: ""
        };
        $.datepicker.setDefaults($.datepicker.regional["es"]);
    });

});
</code>```

What I am expecting is this behaviour

I have searched in here and other websites without any luck to find out what is missing/wrong

答:
I knew it was something very obvious.

You need to have a @using Html.BeginForm in your view that contains the inputs/fields that you are validating

Body:
I have the Model with the following declaration

    [Display(Name = "lblFechaInicio", ResourceType = typeof(RecursosAdministracion))]
    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime? fechaInicio { get; set; }

In the View I have this:

        @Html.LabelFor(model => model.fechaInicio, new { @class = "control-label" })

        @Html.EditorFor(model => model.fechaInicio, new { @class = "input-small hasDatepicker" })

            @Html.ValidationMessageFor(model => model.fechaInicio)

But when I type an invalid Date in fechaInicio and move to another field, the validation is not being fired and the validation message if not being shown

Below is the list of all the included scripts of the rendered page

The file jquery.ui.datepicker.culture-es.js contains this
    $(document).ready(function() {

    $(function($) {
        $.datepicker.regional["es"] = {
            closeText: "Cerrar",
            prevText: "<Ant",
            nextText: "Sig>",
            currentText: "Hoy",
            monthNames: [
                "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre",
                "Noviembre", "Diciembre"
            ],
            monthNamesShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"],
            dayNames: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"],
            dayNamesShort: ["Dom", "Lun", "Mar", "Mié", "Juv", "Vie", "Sáb"],
            dayNamesMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sá"],
            weekHeader: "Sm",
            dateFormat: "dd/mm/yy",
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: false,
            yearSuffix: ""
        };
        $.datepicker.setDefaults($.datepicker.regional["es"]);
    });

});

What I am expecting is this behaviour

I have searched in here and other websites without any luck to find out what is missing/wrong


答:
The easiest way to send email from the no-reply@enterprise.com account is having the Apps Script will have to run under the authority of that account.

How you achieve this depends on how the script is being executed. If it is being executed by a Trigger, the Trigger must be created by the no-reply account.

If the script is published as a web-app, it should be deployed from the no-reply account, and set to execute as no-reply@enterprise.com.

If the script is triggered manually, it will have to be triggered by somebody logged in as the no-reply user.

A simpler option is to set a reply-to address, as shown in Edward Wall's answer.

Title: How to send google script sender email to no-reply@entreprise.com?

Body:
I send 200 emails to a community of students via a google-spreadsheet attached google script.

My mailing call is as follow :

MailApp.sendEmail(
  "toto@gmail.com",             // targetEmail
  "HELLO FROM KING OF NIGERIA", // emailTitle
  "",                           // something
  // emailContentHTML
  { htmlBody:  "Hello John

I'am king of Nigeria.
Got gold everywhere.
Need your help I'am in danger.
Want to share with you.
Could you send me 50$
Sinceraly, your friend.
"}
);

The script being run by my google account john.Doe@entreprise.com, the 200+ participants see the email as coming from me (john.Doe@entreprise.com). I understand this is fair game to limit spamming and co, but my company has a gmail entreprise.com domain name and I would like a solution so to not get dozens of "Thanks you" alerts in the following days. For sure, I do NOT want them to keep me in their following discussion.

So I look for something such as create a no-reply@entreprise.com account, and then a js thing so the script sign email with this no-reply@entreprise.com email.

Also, is there a way to programatically sign the google-script mailing from an other account of my company (no-reply@entreprise.com) ?

Note : google-script-manual


问:
Can you perform math functions inside of a PHP if statement?
I am currently trying to create a "quiz" using a PHP form that will tell the user how similar their answers are to another user's. My first step is trying to display if the answer is the same as an answer that I  have already set.
My questions is if there is a way to perform math inside of an if statement? Or do I have to redefine the variable?

```<code>$color = $_POST['color'];

$score = 0;

if ($color=='lime'){
    $score + 1;
}

echo "You had $score answers matching the computer."
</code>```

答:
$score + 1; is a perfectly valid statement... but it immediately discards the result.

```<code>++$score;
</code>```

or

```<code>$score = $score + 1;
</code>```

or

```<code>$score += 1;
</code>```

Body:
I am currently trying to create a "quiz" using a PHP form that will tell the user how similar their answers are to another user's. My first step is trying to display if the answer is the same as an answer that I  have already set.
My questions is if there is a way to perform math inside of an if statement? Or do I have to redefine the variable?

$color = $_POST['color'];

$score = 0;

if ($color=='lime'){
    $score + 1;
}

echo "You had $score answers matching the computer."

Body:
$score + 1; is a perfectly valid statement... but it immediately discards the result.

++$score;

or

$score = $score + 1;

or

$score += 1;


问:
Set thresholds in PySpark multinomial logistic regression
I would like to perform a multinomial logistic regression but I can't set threshold and thresholds parameters correctly. Consider the following DF:

from pyspark.ml.linalg import DenseVector

test_train_df = (
sqlc
.createDataFrame([(0, DenseVector([-1.0, 1.2, 0.7])),
                  (0, DenseVector([3.1, -2.0, -2.9])),
                  (1, DenseVector([1.0, 0.8, 0.3])),
                  (1, DenseVector([4.2, 1.4, -1.7])),
                  (0, DenseVector([-1.9, 2.5, -2.3])),
                  (2, DenseVector([2.6, -0.2, 0.2])),
                  (1, DenseVector([0.3, -3.4, 1.8])),
                  (2, DenseVector([-1.0, -3.5, 4.7]))],
                 ['label', 'features'])
)
```

<p>My label has 3 classes, so I have to set <code>thresholds</code> (plural, which default is <code>None</code>) rather than <code>threshold</code> (singular, which default is <code>0.5</code>). Then I write:</p>

<pre class="lang-python prettyprint-override"><code>from pyspark.ml import classification as cl

test_logit_abst = (
    cl.LogisticRegression()
    .setFamily('multinomial')
    .setThresholds([.5, .5, .5])
)
</code>```

Then I would like to fit the model on my DF:

test_logit = test_logit_abst.fit(test_train_df)
```

<p>but when executing this last command I get an error:</p>

<pre class="lang-python prettyprint-override"><code>---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
~/anaconda3/lib/python3.6/site-packages/pyspark/sql/utils.py in deco(*a, **kw)
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:

~/anaconda3/lib/python3.6/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    318                     "An error occurred while calling {0}{1}{2}.\n".
--> 319                     format(target_id, ".", name), value)
    320             else:

Py4JJavaError: An error occurred while calling o3769.fit.
: java.lang.IllegalArgumentException: requirement failed: Logistic Regression found inconsistent values for threshold and thresholds.  Param threshold is set (0.5), indicating binary classification, but Param thresholds is set with length 3. Clear one Param value to fix this problem.

During handling of the above exception, another exception occurred:

IllegalArgumentException                  Traceback (most recent call last)
<ipython-input-211-8f3443f41b6b> in <module>()
----> 1 test_logit = test_logit_abst.fit(test_train_df)

~/anaconda3/lib/python3.6/site-packages/pyspark/ml/base.py in fit(self, dataset, params)
     62                 return self.copy(params)._fit(dataset)
     63             else:
---> 64                 return self._fit(dataset)
     65         else:
     66             raise ValueError("Params must be either a param map or a list/tuple of param maps, "

~/anaconda3/lib/python3.6/site-packages/pyspark/ml/wrapper.py in _fit(self, dataset)
263
    264     def _fit(self, dataset):
--> 265         java_model = self._fit_java(dataset)
    266         return self._create_model(java_model)
267

~/anaconda3/lib/python3.6/site-packages/pyspark/ml/wrapper.py in _fit_java(self, dataset)
    260         """
    261         self._transfer_params_to_java()
--> 262         return self._java_obj.fit(dataset._jdf)
263
    264     def _fit(self, dataset):

~/anaconda3/lib/python3.6/site-packages/py4j/java_gateway.py in __call__(self, *args)
   1131         answer = self.gateway_client.send_command(command)
   1132         return_value = get_return_value(
-> 1133             answer, self.gateway_client, self.target_id, self.name)
1134
   1135         for temp_arg in temp_args:

~/anaconda3/lib/python3.6/site-packages/pyspark/sql/utils.py in deco(*a, **kw)
     77                 raise QueryExecutionException(s.split(': ', 1)[1], stackTrace)
     78             if s.startswith('java.lang.IllegalArgumentException: '):
---> 79                 raise IllegalArgumentException(s.split(': ', 1)[1], stackTrace)
     80             raise
     81     return deco

IllegalArgumentException: 'requirement failed: Logistic Regression found inconsistent values for threshold and thresholds.  Param threshold is set (0.5), indicating binary classification, but Param thresholds is set with length 3. Clear one Param value to fix this problem.'
</code>```

The error says threshold is set. This looks strange, as the documentation says that setting thresholds (plural) clears threshold (singular), so that the value 0.5 should be deleted.
So, how to clear threshold since no clearThreshold() exists?

In order to achieve this I tried to clear threshold this way:

logit_abst = (
    cl.LogisticRegression()
    .setFamily('multinomial')
    .setThresholds([.5, .5, .5])
    .setThreshold(None)
)
```

<p>This time the fit command works, I even obtain the model intercept and coefficients:</p>

<pre class="lang-python prettyprint-override"><code>test_logit.interceptVector
DenseVector([65.6445, 31.6369, -97.2814])

test_logit.coefficientMatrix
DenseMatrix(3, 3, [-76.4534, -19.4797, -79.4949, 12.3659, 4.642, 4.1057, 64.0876, 14.8377, 75.3892], 1)
</code>```

But if I try to get thresholds (plural) from test_logit_abst I get an error:

test_logit_abst.getThresholds()

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-214-fc1c8617ce80> in <module>()
----> 1 test_logit_abst.getThresholds()

~/anaconda3/lib/python3.6/site-packages/pyspark/ml/classification.py in getThresholds(self)
    363         if not self.isSet(self.thresholds) and self.isSet(self.threshold):
    364             t = self.getOrDefault(self.threshold)
--> 365             return [1.0-t, t]
    366         else:
    367             return self.getOrDefault(self.thresholds)

TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'
```

<p>What does this mean?</p>

<hr>

<p>As a further detail, curiously (and incomprehensibly to me) inverting the order of the parameters settings produces the first error I posted above:</p>

<pre class="lang-python prettyprint-override"><code>logit_abst = (
    cl.LogisticRegression()
    .setFamily('multinomial')
    .setThreshold(None)
    .setThresholds([.5, .5, .5])
)
</code>```

Why does changing the order of the "set" instructions change the output as well?

答:
It is a messy situation indeed...

The short answer is:

setThresholds (plural) not clearing the threshold (singular) seems to be a bug

For multinomial classification (i.e. number of classes > 2), setThresholds does not do what you expect (and arguably you don't need it)

If all you need is having some "thresholds" in the "default" value of 0.5, you don't have a problem - simply don't use any relevant argument or setThresholds statement

If you really need to apply different decision thresholds to different classes in multinomial classification, you will have to do it manually, by post-processing the respective probabilities, i.e. the probability column in the transformed dataframe (it works OK though with setThreshold(s) for binary classification)

And now for the long answer...

Let's start with binary classification, adapting the toy data from the docs:

spark.version
# u'2.2.0'

from pyspark.ml.classification import LogisticRegression
from pyspark.sql import Row
from pyspark.ml.linalg import Vectors
bdf = sc.parallelize([
     Row(label=1.0, features=Vectors.dense(0.0, 5.0)),
     Row(label=0.0, features=Vectors.dense(1.0, 2.0)),

blor = LogisticRegression(threshold=0.7, thresholds=[0.3, 0.7])
     Row(label=1.0, features=Vectors.dense(2.0, 1.0)),
     Row(label=0.0, features=Vectors.dense(3.0, 3.0))]).toDF()
```

<p>We don't need to set <code>thresholds</code> (plural) here - <code>threshold=0.7</code> is enough, but it will be useful when illustrating the differences with <code>setThreshold</code> below.</p>

<pre class="lang-python prettyprint-override"><code>blorModel = blor.fit(bdf) # works OK
blor.getThreshold()
# 0.7
blor.getThresholds()
# [0.3, 0.7]
blorModel.transform(bdf).show(truncate=False) # transform the training data
</code>```

Here is the result:

+---------+-----+------------------------------------------+----------------------------------------+----------+
|features |label|rawPrediction                             |probability                             |prediction|
+---------+-----+------------------------------------------+----------------------------------------+----------+
|[0.0,5.0]|1.0  |[-1.138455151184087,1.138455151184087]    |[0.242604109995602,0.757395890004398]   |1.0       |
|[1.0,2.0]|0.0  |[-0.6056346859838877,0.6056346859838877]  |[0.35305562698104337,0.6469443730189567]|0.0       |
|[2.0,1.0]|1.0  |[0.26586039040308496,-0.26586039040308496]|[0.5660763559614698,0.4339236440385302] |0.0       |
|[3.0,3.0]|0.0  |[1.6453673835702176,-1.6453673835702176]  |[0.8382639556951765,0.16173604430482344]|0.0       |
+---------+-----+------------------------------------------+----------------------------------------+----------+
```

<p>What is the meaning of <code>thresholds=[0.3, 0.7]</code>? The answer lies in the 2nd row, where the prediction is <code>0.0</code>, despite the fact that the the probability is higher for <code>1.0</code> (0.65): 0.65 is indeed higher that 0.35, but it is lower than the threshold we have set <em>for this class</em> (0.7), hence it is not classified as such.</p>

<p>Let's now try the <em>seemingly identical operation</em>, but with <code>setThreshold(s)</code> instead:</p>

<pre class="lang-python prettyprint-override"><code>blor2 = (LogisticRegression()
  .setThreshold(0.7)
  .setThresholds([0.3, 0.7]) ) # works OK

blorModel2 = blor2.fit(bdf)
[...]
IllegalArgumentException: u'requirement failed: Logistic Regression getThreshold found inconsistent values for threshold (0.5) and thresholds (equivalent to 0.7)'
</code>```

Nice, eh?

setThresholds (plural) seems indeed to have cleared our value of threshold (0.7) set in the previous line, as claimed in the docs, but it seemingly did so only to restore it to its default value of 0.5...

Omitting .setThreshold(0.7) gives the first error you report yourself (not shown).

Inverting the order of the parameter settings resolves the issue (!!!) and, moreover, renders both getThreshold (singular) and getThresholds (plural) operational (in contrast with your case):

blor2 = (LogisticRegression()
  .setThresholds([0.3, 0.7])
  .setThreshold(0.7) )

blorModel2 = blor2.fit(bdf) # works OK
blor2.getThreshold()
# 0.7
blor2.getThresholds()
# [0.30000000000000004, 0.7]
```

<hr>

<p>Let's move now to the <em>multinomial</em> case; we'll stick again to the example in the docs, with data from the Spark Github repo (they should also be available locally, in your <code>$SPARK_HOME/data/mllib/sample_multiclass_classification_data.txt</code>, but I am working on a Databricks notebook); it is a 3-class case, with labels in <code>{0.0, 1.0, 2.0}</code>.</p>

<pre class="lang-python prettyprint-override"><code>data_path ="/FileStore/tables/sample_multiclass_classification_data.txt"
mdf = spark.read.format("libsvm").load(data_path)
</code>```

Similarly with the binary case above, where the elements of our thresholds (plural) sum up to 1, let's ask for a threshold of 0.8 for class 2:

mlor = (LogisticRegression()
       .setFamily("multinomial")
       .setThresholds([0, 0.2, 0.8])
       .setThreshold(0.8) )
mlorModel= mlor.fit(mdf)  # works OK
mlor.getThreshold()
# 0.8
mlor.getThresholds()
# [0.19999999999999996, 0.8]
```

<p>Looks fine, but let's ask for a <em>prediction</em> in the (training) dataset:</p>

<pre class="lang-python prettyprint-override"><code>mlorModel.transform(mdf).show(truncate=False)
</code>```

I have singled out only one row - it should be the 2nd from the end of the full output:

+-----+----------------------------------------------------+---------------------------------------------------------+---------------------------------------------------------------+----------+
|label|features                                            |rawPrediction                                            |probability                                                    |prediction|
+-----+----------------------------------------------------+---------------------------------------------------------+---------------------------------------------------------------+----------+
[...]
|0.0  |(4,[0,1,2,3],[0.111111,-0.333333,0.38983,0.166667]) |[36.67790353804905,-74.71196613173531,38.034062593686244]|[0.20486526556822454,8.619113376801409E-50,0.7951347344317755] |2.0       |
[...]
+-----+----------------------------------------------------+---------------------------------------------------------+---------------------------------------------------------------+----------+
```

<p>Scrolling to the right, you'll see that despite the fact that the prediction for class <code>2.0</code> here is <em>below</em> the threshold we have set (0.8), the row is indeed predicted as <code>2.0</code> - in contrast with the binary case demonstrated above...</p>

<p>So, what to do? Simply <strong>remove all the threshold-related statements</strong>; you don't need them - even <code>setFamily</code> is unnecessary, as the algorithm will detect by itself that you have more than 2 classes. This will give identical results with the above:</p>

<pre class="lang-python prettyprint-override"><code>mlor = LogisticRegression() # works OK - no family, no threshold(s)
</code>```

To summarize:

In both the binary & multinomial cases, what is actually returned by the algorithm is a vector of probabilities of length equal to the number of classes, with elements summing up to 1.

In the binary case only, Spark allows you to go one step further and not naively selecting the highest probability class as the prediction, but applying a user-defined threshold instead; this setting might be useful e.g. in cases with imbalanced data.

This threshold(s) setting has actually no effect in the multinomial case, where Spark will always return as prediction the class with the highest probability.

Despite the mess in the documentation (about which I have argued elsewhere) and the possibility of some bugs, let me say about (3) that this design choice is not unjustifiable; as it has been nicely argued elsewhere (emphasis in the original):

the statistical component of your exercise ends when you output a probability for each class of your new sample. Choosing a threshold beyond which you classify a new observation as 1 vs. 0 is not part of the statistics any more. It is part of the decision component.

Although the above argument was made for the binary case, it fully holds for the multinomial one, too...

Body:
I would like to perform a multinomial logistic regression but I can't set threshold and thresholds parameters correctly. Consider the following DF:

from pyspark.ml.linalg import DenseVector

test_train_df = (
sqlc
.createDataFrame([(0, DenseVector([-1.0, 1.2, 0.7])),
                  (0, DenseVector([3.1, -2.0, -2.9])),
                  (1, DenseVector([1.0, 0.8, 0.3])),
                  (1, DenseVector([4.2, 1.4, -1.7])),
                  (0, DenseVector([-1.9, 2.5, -2.3])),
                  (2, DenseVector([2.6, -0.2, 0.2])),
                  (1, DenseVector([0.3, -3.4, 1.8])),
                  (2, DenseVector([-1.0, -3.5, 4.7]))],
                 ['label', 'features'])
)

My label has 3 classes, so I have to set thresholds (plural, which default is None) rather than threshold (singular, which default is 0.5). Then I write:

from pyspark.ml import classification as cl

test_logit_abst = (
    cl.LogisticRegression()
    .setFamily('multinomial')
    .setThresholds([.5, .5, .5])
)

Then I would like to fit the model on my DF:

test_logit = test_logit_abst.fit(test_train_df)

but when executing this last command I get an error:

---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
~/anaconda3/lib/python3.6/site-packages/pyspark/sql/utils.py in deco(*a, **kw)
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:

~/anaconda3/lib/python3.6/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    318                     "An error occurred while calling {0}{1}{2}.\n".
--> 319                     format(target_id, ".", name), value)
    320             else:

Py4JJavaError: An error occurred while calling o3769.fit.
: java.lang.IllegalArgumentException: requirement failed: Logistic Regression found inconsistent values for threshold and thresholds.  Param threshold is set (0.5), indicating binary classification, but Param thresholds is set with length 3. Clear one Param value to fix this problem.

During handling of the above exception, another exception occurred:

IllegalArgumentException                  Traceback (most recent call last)
<ipython-input-211-8f3443f41b6b> in <module>()
----> 1 test_logit = test_logit_abst.fit(test_train_df)

~/anaconda3/lib/python3.6/site-packages/pyspark/ml/base.py in fit(self, dataset, params)
     62                 return self.copy(params)._fit(dataset)
     63             else:
---> 64                 return self._fit(dataset)
     65         else:
     66             raise ValueError("Params must be either a param map or a list/tuple of param maps, "

~/anaconda3/lib/python3.6/site-packages/pyspark/ml/wrapper.py in _fit(self, dataset)
263
    264     def _fit(self, dataset):
--> 265         java_model = self._fit_java(dataset)
    266         return self._create_model(java_model)
267

~/anaconda3/lib/python3.6/site-packages/pyspark/ml/wrapper.py in _fit_java(self, dataset)
    260         """
    261         self._transfer_params_to_java()
--> 262         return self._java_obj.fit(dataset._jdf)
263
    264     def _fit(self, dataset):

~/anaconda3/lib/python3.6/site-packages/py4j/java_gateway.py in __call__(self, *args)
   1131         answer = self.gateway_client.send_command(command)
   1132         return_value = get_return_value(
-> 1133             answer, self.gateway_client, self.target_id, self.name)
1134
   1135         for temp_arg in temp_args:

~/anaconda3/lib/python3.6/site-packages/pyspark/sql/utils.py in deco(*a, **kw)
     77                 raise QueryExecutionException(s.split(': ', 1)[1], stackTrace)
     78             if s.startswith('java.lang.IllegalArgumentException: '):
---> 79                 raise IllegalArgumentException(s.split(': ', 1)[1], stackTrace)
     80             raise
     81     return deco

IllegalArgumentException: 'requirement failed: Logistic Regression found inconsistent values for threshold and thresholds.  Param threshold is set (0.5), indicating binary classification, but Param thresholds is set with length 3. Clear one Param value to fix this problem.'

The error says threshold is set. This looks strange, as the documentation says that setting thresholds (plural) clears threshold (singular), so that the value 0.5 should be deleted.
So, how to clear threshold since no clearThreshold() exists?

In order to achieve this I tried to clear threshold this way:

logit_abst = (
    cl.LogisticRegression()
    .setFamily('multinomial')
    .setThresholds([.5, .5, .5])
    .setThreshold(None)
)

This time the fit command works, I even obtain the model intercept and coefficients:

test_logit.interceptVector
DenseVector([65.6445, 31.6369, -97.2814])

test_logit.coefficientMatrix
DenseMatrix(3, 3, [-76.4534, -19.4797, -79.4949, 12.3659, 4.642, 4.1057, 64.0876, 14.8377, 75.3892], 1)

But if I try to get thresholds (plural) from test_logit_abst I get an error:

test_logit_abst.getThresholds()

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-214-fc1c8617ce80> in <module>()
----> 1 test_logit_abst.getThresholds()

~/anaconda3/lib/python3.6/site-packages/pyspark/ml/classification.py in getThresholds(self)
    363         if not self.isSet(self.thresholds) and self.isSet(self.threshold):
    364             t = self.getOrDefault(self.threshold)
--> 365             return [1.0-t, t]
    366         else:
    367             return self.getOrDefault(self.thresholds)

TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'

What does this mean?

As a further detail, curiously (and incomprehensibly to me) inverting the order of the parameters settings produces the first error I posted above:

logit_abst = (
    cl.LogisticRegression()
    .setFamily('multinomial')
    .setThreshold(None)
    .setThresholds([.5, .5, .5])
)

Why does changing the order of the "set" instructions change the output as well?

Body:
It is a messy situation indeed...

The short answer is:

setThresholds (plural) not clearing the threshold (singular) seems to be a bug

For multinomial classification (i.e. number of classes > 2), setThresholds does not do what you expect (and arguably you don't need it)

If all you need is having some "thresholds" in the "default" value of 0.5, you don't have a problem - simply don't use any relevant argument or setThresholds statement

If you really need to apply different decision thresholds to different classes in multinomial classification, you will have to do it manually, by post-processing the respective probabilities, i.e. the probability column in the transformed dataframe (it works OK though with setThreshold(s) for binary classification)

And now for the long answer...

Let's start with binary classification, adapting the toy data from the docs:

spark.version
# u'2.2.0'

from pyspark.ml.classification import LogisticRegression
from pyspark.sql import Row
from pyspark.ml.linalg import Vectors
bdf = sc.parallelize([
     Row(label=1.0, features=Vectors.dense(0.0, 5.0)),
     Row(label=0.0, features=Vectors.dense(1.0, 2.0)),

blor = LogisticRegression(threshold=0.7, thresholds=[0.3, 0.7])
     Row(label=1.0, features=Vectors.dense(2.0, 1.0)),
     Row(label=0.0, features=Vectors.dense(3.0, 3.0))]).toDF()

We don't need to set thresholds (plural) here - threshold=0.7 is enough, but it will be useful when illustrating the differences with setThreshold below.

blorModel = blor.fit(bdf) # works OK
blor.getThreshold()
# 0.7
blor.getThresholds()
# [0.3, 0.7]
blorModel.transform(bdf).show(truncate=False) # transform the training data

Here is the result:

+---------+-----+------------------------------------------+----------------------------------------+----------+
|features |label|rawPrediction                             |probability                             |prediction|
+---------+-----+------------------------------------------+----------------------------------------+----------+
|[0.0,5.0]|1.0  |[-1.138455151184087,1.138455151184087]    |[0.242604109995602,0.757395890004398]   |1.0       |
|[1.0,2.0]|0.0  |[-0.6056346859838877,0.6056346859838877]  |[0.35305562698104337,0.6469443730189567]|0.0       |
|[2.0,1.0]|1.0  |[0.26586039040308496,-0.26586039040308496]|[0.5660763559614698,0.4339236440385302] |0.0       |
|[3.0,3.0]|0.0  |[1.6453673835702176,-1.6453673835702176]  |[0.8382639556951765,0.16173604430482344]|0.0       |
+---------+-----+------------------------------------------+----------------------------------------+----------+

What is the meaning of thresholds=[0.3, 0.7]? The answer lies in the 2nd row, where the prediction is 0.0, despite the fact that the the probability is higher for 1.0 (0.65): 0.65 is indeed higher that 0.35, but it is lower than the threshold we have set for this class (0.7), hence it is not classified as such.

Let's now try the seemingly identical operation, but with setThreshold(s) instead:

blor2 = (LogisticRegression()
  .setThreshold(0.7)
  .setThresholds([0.3, 0.7]) ) # works OK

blorModel2 = blor2.fit(bdf)
[...]
IllegalArgumentException: u'requirement failed: Logistic Regression getThreshold found inconsistent values for threshold (0.5) and thresholds (equivalent to 0.7)'

Nice, eh?

setThresholds (plural) seems indeed to have cleared our value of threshold (0.7) set in the previous line, as claimed in the docs, but it seemingly did so only to restore it to its default value of 0.5...

Omitting .setThreshold(0.7) gives the first error you report yourself (not shown).

Inverting the order of the parameter settings resolves the issue (!!!) and, moreover, renders both getThreshold (singular) and getThresholds (plural) operational (in contrast with your case):

blor2 = (LogisticRegression()
  .setThresholds([0.3, 0.7])
  .setThreshold(0.7) )

blorModel2 = blor2.fit(bdf) # works OK
blor2.getThreshold()
# 0.7
blor2.getThresholds()
# [0.30000000000000004, 0.7]

Let's move now to the multinomial case; we'll stick again to the example in the docs, with data from the Spark Github repo (they should also be available locally, in your $SPARK_HOME/data/mllib/sample_multiclass_classification_data.txt, but I am working on a Databricks notebook); it is a 3-class case, with labels in {0.0, 1.0, 2.0}.

data_path ="/FileStore/tables/sample_multiclass_classification_data.txt"
mdf = spark.read.format("libsvm").load(data_path)

Similarly with the binary case above, where the elements of our thresholds (plural) sum up to 1, let's ask for a threshold of 0.8 for class 2:

mlor = (LogisticRegression()
       .setFamily("multinomial")
       .setThresholds([0, 0.2, 0.8])
       .setThreshold(0.8) )
mlorModel= mlor.fit(mdf)  # works OK
mlor.getThreshold()
# 0.8
mlor.getThresholds()
# [0.19999999999999996, 0.8]

Looks fine, but let's ask for a prediction in the (training) dataset:

mlorModel.transform(mdf).show(truncate=False)

I have singled out only one row - it should be the 2nd from the end of the full output:

+-----+----------------------------------------------------+---------------------------------------------------------+---------------------------------------------------------------+----------+
|label|features                                            |rawPrediction                                            |probability                                                    |prediction|
+-----+----------------------------------------------------+---------------------------------------------------------+---------------------------------------------------------------+----------+
[...]
|0.0  |(4,[0,1,2,3],[0.111111,-0.333333,0.38983,0.166667]) |[36.67790353804905,-74.71196613173531,38.034062593686244]|[0.20486526556822454,8.619113376801409E-50,0.7951347344317755] |2.0       |
[...]
+-----+----------------------------------------------------+---------------------------------------------------------+---------------------------------------------------------------+----------+

Scrolling to the right, you'll see that despite the fact that the prediction for class 2.0 here is below the threshold we have set (0.8), the row is indeed predicted as 2.0 - in contrast with the binary case demonstrated above...

So, what to do? Simply remove all the threshold-related statements; you don't need them - even setFamily is unnecessary, as the algorithm will detect by itself that you have more than 2 classes. This will give identical results with the above:

mlor = LogisticRegression() # works OK - no family, no threshold(s)

To summarize:

In both the binary & multinomial cases, what is actually returned by the algorithm is a vector of probabilities of length equal to the number of classes, with elements summing up to 1.

In the binary case only, Spark allows you to go one step further and not naively selecting the highest probability class as the prediction, but applying a user-defined threshold instead; this setting might be useful e.g. in cases with imbalanced data.

This threshold(s) setting has actually no effect in the multinomial case, where Spark will always return as prediction the class with the highest probability.

Despite the mess in the documentation (about which I have argued elsewhere) and the possibility of some bugs, let me say about (3) that this design choice is not unjustifiable; as it has been nicely argued elsewhere (emphasis in the original):

the statistical component of your exercise ends when you output a probability for each class of your new sample. Choosing a threshold beyond which you classify a new observation as 1 vs. 0 is not part of the statistics any more. It is part of the decision component.

Although the above argument was made for the binary case, it fully holds for the multinomial one, too...