问:
Radio button in xamarin.ios
How to create radio button in the xamarin.ios (native)? We don't want to use form approach.

We tried using creating custom control but it is not working.

答:
In iOS, we can make is possible with customization only. We can make one class where we need to manage actions and images on buttons which will look like radio b button only.
Below is the sample that how we can make radio buttons:

public class OoRadioButtonView : OoBaseSelectionView

```<code>{
    public OoRadioButtonView(bool hasTextField = false) : base(hasTextField)
    {
        _markSize = 11;

        CheckMark = new RoundCornersView()
        {
            roundedCornerRadius = (_checkMarkSize / 2),
            RoundedBottomLeftRadius = true,
            RoundedBottomRightRadius = true,
            RoundedTopLeftRadius = true,
            RoundedTopRightRadius = true,

            BackgroundColor = ColorConverter.FromHex(PclColors.Background.LightLightGray),

            borderWidth = 2,
            borderColor = ColorConverter.FromHex(PclColors.Common.DarkGray),
            BorderRadius = (_checkMarkSize / 2)
        };
        Add(CheckMark);

        Mark = new RoundCornersView()
        {
            roundedCornerRadius = (_markSize / 2),
            RoundedBottomLeftRadius = true,
            RoundedBottomRightRadius = true,
            RoundedTopLeftRadius = true,
            RoundedTopRightRadius = true,

            BackgroundColor = Colors.MAIN_RED,

            Hidden = true
        };
        Add(Mark);

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

Below is the abstract class that I am inheriting in above class

public abstract class OoBaseSelectionView : UIView, INotifyPropertyChanged

```<code>{
    public bool IsSelected
    {
        get
        {
            if (Mark != null)
                return !Mark.Hidden;

            return false;
        }
    }

    public int Value { get; set; }

    public RoundCornersView CheckMark { get; set; }
    public UIView Mark { get; set; }
    public UILabel OptionLabel { get; set; }
    public UILabel SecondaryLabel { get; set; }

    public UITextField TextField { get; set; }

    public string TextFieldHint
    {
        get
        {
            return TextField.Placeholder;
        }
        set
        {
            TextField.Placeholder = value;

        }
    }

    string _text;
    public string Text
    {
        get
        {
            return _text;
        }
        set
        {
            _text = value;

            TextField.Text = _text;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Text"));
        }
    }

    protected float _checkMarkSize;
    protected float _markSize;

    public event PropertyChangedEventHandler PropertyChanged;

    public bool HasTextFiled { get; private set; }

    protected OoBaseSelectionView(bool hasTextFiled)
    {
        HasTextFiled = hasTextFiled;

        _checkMarkSize = 22;

        CreateViews();
        CreateConstraints();
    }

    void CreateViews()
    {
        OptionLabel = new UILabel()
        {
            TextColor = Colors.TEXT_BLACK_COLOR,
            Font = UIFont.FromName(Fonts.FONT_NOTO_SANS, 14f),
            Lines = 2
        };
        Add(OptionLabel);

        SecondaryLabel = new UILabel()
        {
            TextColor = Colors.TEXT_BLACK_COLOR,
            Font = UIFont.FromName(Fonts.FONT_NOTO_SANS, 14f),
            TextAlignment = SettingsManager.IsLTR ? UITextAlignment.Right : UITextAlignment.Left
        };
        Add(SecondaryLabel);

        if (HasTextFiled)
        {
            TextField = new UITextField();
            TextField.Layer.CornerRadius = 10;
            TextField.Layer.BorderWidth = 1;
            TextField.UserInteractionEnabled = false;
            TextField.TextAlignment = UITextAlignment.Center;
            TextField.Layer.BorderColor = UIColor.Black.CGColor;
            TextField.LeftView = new UIView(new CoreGraphics.CGRect(0, 0, 10, 10));
            TextField.LeftViewMode = UITextFieldViewMode.Always;
            Add(TextField);
        }
    }

    void CreateConstraints()
    {
        this.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
        this.AddConstraints(
            OptionLabel.AtTopOf(this, Dimensions.GLOBAL_MARGIN_SMALL),

            SecondaryLabel.AtTopOf(this, Dimensions.GLOBAL_MARGIN_SMALL),
            SecondaryLabel.AtTrailingOf(this, Dimensions.GLOBAL_MARGIN_MEDIUM)
        );

        this.AddConstraints(OptionLabel.ToLeadingOf(SecondaryLabel, Dimensions.GLOBAL_MARGIN_EXTRASMALL));

        if (HasTextFiled)
        {
            this.AddConstraints(
                TextField.WithSameCenterX(this),
                TextField.Below(OptionLabel, Dimensions.GLOBAL_MARGIN_SMALL),
                TextField.Width().EqualTo(150),
                TextField.Height().EqualTo(35),
                TextField.AtBottomOf(this)
            );
        }
        else
        {
            this.AddConstraints(
                OptionLabel.AtBottomOf(this, Dimensions.GLOBAL_MARGIN_SMALL),
                SecondaryLabel.AtBottomOf(this, Dimensions.GLOBAL_MARGIN_SMALL)
            );
        }
    }

    public void CreateCheckMarkConstraints()
    {
        this.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
        this.AddConstraints(
            CheckMark.AtLeadingOf(this, Dimensions.GLOBAL_MARGIN_MEDIUM),
            CheckMark.WithSameCenterY(OptionLabel),
            CheckMark.Height().EqualTo(_checkMarkSize),
            CheckMark.Width().EqualTo(_checkMarkSize),

            Mark.Height().EqualTo(_markSize),
            Mark.Width().EqualTo(_markSize),
            Mark.WithSameCenterX(CheckMark),
            Mark.WithSameCenterY(CheckMark)
        );

        if (LangUtils.IsArabic)
            this.AddConstraints(OptionLabel.ToLeftOf(CheckMark, Dimensions.GLOBAL_MARGIN_SMALL));

        else
            this.AddConstraints(OptionLabel.ToRightOf(CheckMark, Dimensions.GLOBAL_MARGIN_SMALL));
    }

    public void UnSelect()
    {
        if (Mark != null)
            Mark.Hidden = true;

        if (HasTextFiled)
        {
            TextField.UserInteractionEnabled = false;
            TextField.Text = null;
        }
    }

    public void Select()
    {
        if (Mark != null)
            Mark.Hidden = false;

        if (HasTextFiled)
        {
            TextField.UserInteractionEnabled = true;
            TextField.BecomeFirstResponder();
        }
    }

    public void Toggle()
    {
        if (Mark != null)
            Mark.Hidden = !Mark.Hidden;
    }

    public void SetOptionLabel(string option)
    {
        OptionLabel.Text = option;
    }

    public void SetSecondaryLabel(string secondary)
    {
        SecondaryLabel.Text = secondary;
    }

    public string GetTextFieldString()
    {
        return TextField.Text ?? string.Empty;
    }

}
</code>```

Title: Radio button in xamarin.ios

Body:
In iOS, we can make is possible with customization only. We can make one class where we need to manage actions and images on buttons which will look like radio b button only.
Below is the sample that how we can make radio buttons:

public class OoRadioButtonView : OoBaseSelectionView

{
    public OoRadioButtonView(bool hasTextField = false) : base(hasTextField)
    {
        _markSize = 11;

        CheckMark = new RoundCornersView()
        {
            roundedCornerRadius = (_checkMarkSize / 2),
            RoundedBottomLeftRadius = true,
            RoundedBottomRightRadius = true,
            RoundedTopLeftRadius = true,
            RoundedTopRightRadius = true,

            BackgroundColor = ColorConverter.FromHex(PclColors.Background.LightLightGray),

            borderWidth = 2,
            borderColor = ColorConverter.FromHex(PclColors.Common.DarkGray),
            BorderRadius = (_checkMarkSize / 2)
        };
        Add(CheckMark);

        Mark = new RoundCornersView()
        {
            roundedCornerRadius = (_markSize / 2),
            RoundedBottomLeftRadius = true,
            RoundedBottomRightRadius = true,
            RoundedTopLeftRadius = true,
            RoundedTopRightRadius = true,

            BackgroundColor = Colors.MAIN_RED,

            Hidden = true
        };
        Add(Mark);

        CreateCheckMarkConstraints();
    }
}

Below is the abstract class that I am inheriting in above class

public abstract class OoBaseSelectionView : UIView, INotifyPropertyChanged

{
    public bool IsSelected
    {
        get
        {
            if (Mark != null)
                return !Mark.Hidden;

            return false;
        }
    }

    public int Value { get; set; }

    public RoundCornersView CheckMark { get; set; }
    public UIView Mark { get; set; }
    public UILabel OptionLabel { get; set; }
    public UILabel SecondaryLabel { get; set; }

    public UITextField TextField { get; set; }

    public string TextFieldHint
    {
        get
        {
            return TextField.Placeholder;
        }
        set
        {
            TextField.Placeholder = value;

        }
    }

    string _text;
    public string Text
    {
        get
        {
            return _text;
        }
        set
        {
            _text = value;

            TextField.Text = _text;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Text"));
        }
    }

    protected float _checkMarkSize;
    protected float _markSize;

    public event PropertyChangedEventHandler PropertyChanged;

    public bool HasTextFiled { get; private set; }

    protected OoBaseSelectionView(bool hasTextFiled)
    {
        HasTextFiled = hasTextFiled;

        _checkMarkSize = 22;

        CreateViews();
        CreateConstraints();
    }

    void CreateViews()
    {
        OptionLabel = new UILabel()
        {
            TextColor = Colors.TEXT_BLACK_COLOR,
            Font = UIFont.FromName(Fonts.FONT_NOTO_SANS, 14f),
            Lines = 2
        };
        Add(OptionLabel);

        SecondaryLabel = new UILabel()
        {
            TextColor = Colors.TEXT_BLACK_COLOR,
            Font = UIFont.FromName(Fonts.FONT_NOTO_SANS, 14f),
            TextAlignment = SettingsManager.IsLTR ? UITextAlignment.Right : UITextAlignment.Left
        };
        Add(SecondaryLabel);

        if (HasTextFiled)
        {
            TextField = new UITextField();
            TextField.Layer.CornerRadius = 10;
            TextField.Layer.BorderWidth = 1;
            TextField.UserInteractionEnabled = false;
            TextField.TextAlignment = UITextAlignment.Center;
            TextField.Layer.BorderColor = UIColor.Black.CGColor;
            TextField.LeftView = new UIView(new CoreGraphics.CGRect(0, 0, 10, 10));
            TextField.LeftViewMode = UITextFieldViewMode.Always;
            Add(TextField);
        }
    }

    void CreateConstraints()
    {
        this.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
        this.AddConstraints(
            OptionLabel.AtTopOf(this, Dimensions.GLOBAL_MARGIN_SMALL),

            SecondaryLabel.AtTopOf(this, Dimensions.GLOBAL_MARGIN_SMALL),
            SecondaryLabel.AtTrailingOf(this, Dimensions.GLOBAL_MARGIN_MEDIUM)
        );

        this.AddConstraints(OptionLabel.ToLeadingOf(SecondaryLabel, Dimensions.GLOBAL_MARGIN_EXTRASMALL));

        if (HasTextFiled)
        {
            this.AddConstraints(
                TextField.WithSameCenterX(this),
                TextField.Below(OptionLabel, Dimensions.GLOBAL_MARGIN_SMALL),
                TextField.Width().EqualTo(150),
                TextField.Height().EqualTo(35),
                TextField.AtBottomOf(this)
            );
        }
        else
        {
            this.AddConstraints(
                OptionLabel.AtBottomOf(this, Dimensions.GLOBAL_MARGIN_SMALL),
                SecondaryLabel.AtBottomOf(this, Dimensions.GLOBAL_MARGIN_SMALL)
            );
        }
    }

    public void CreateCheckMarkConstraints()
    {
        this.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
        this.AddConstraints(
            CheckMark.AtLeadingOf(this, Dimensions.GLOBAL_MARGIN_MEDIUM),
            CheckMark.WithSameCenterY(OptionLabel),
            CheckMark.Height().EqualTo(_checkMarkSize),
            CheckMark.Width().EqualTo(_checkMarkSize),

            Mark.Height().EqualTo(_markSize),
            Mark.Width().EqualTo(_markSize),
            Mark.WithSameCenterX(CheckMark),
            Mark.WithSameCenterY(CheckMark)
        );

        if (LangUtils.IsArabic)
            this.AddConstraints(OptionLabel.ToLeftOf(CheckMark, Dimensions.GLOBAL_MARGIN_SMALL));

        else
            this.AddConstraints(OptionLabel.ToRightOf(CheckMark, Dimensions.GLOBAL_MARGIN_SMALL));
    }

    public void UnSelect()
    {
        if (Mark != null)
            Mark.Hidden = true;

        if (HasTextFiled)
        {
            TextField.UserInteractionEnabled = false;
            TextField.Text = null;
        }
    }

    public void Select()
    {
        if (Mark != null)
            Mark.Hidden = false;

        if (HasTextFiled)
        {
            TextField.UserInteractionEnabled = true;
            TextField.BecomeFirstResponder();
        }
    }

    public void Toggle()
    {
        if (Mark != null)
            Mark.Hidden = !Mark.Hidden;
    }

    public void SetOptionLabel(string option)
    {
        OptionLabel.Text = option;
    }

    public void SetSecondaryLabel(string secondary)
    {
        SecondaryLabel.Text = secondary;
    }

    public string GetTextFieldString()
    {
        return TextField.Text ?? string.Empty;
    }

}


来源: stackexchange

问:
How to change color of options in list onclick
My HTML code:

```<code><li onclick="switchColors()">
    <a class="x" href="Faculty.php">Faculty</a>
 </li>
<li onclick="switchColors()">
   <a class="x" href="Contact.php">Contact</a>
</li>
</code>```

JavaScript Code:

```

What i want to do is that when i click on "Faculty" it loads Faculty.php page and change "Faculty" color into purple and "Faculty" remains in purple untill i click on "Contact". And when i click on "Contact" it load Contact.php page and change "Contact" color into purple, and also set "Faculty" to orange color.

I tried the above JS code but it don't work, when i click on "Faculty" it load Facult.php page but don't change "Faculty" into purple color.

How should i do that?

答:
this doesn't work with javascript "onClick" event. because your page refreshes.

you need to set a variable in your PHP and set the page name to that. and then have an "if" in PHP to declare which page you are then set class for your "li" element to change its color.

A guide is in link below:

https://alistapart.com/article/keepingcurrent/

ContentLicense: CC BY-SA 4.0

Body:
My HTML code:

    Faculty

   Contact

JavaScript Code:

What i want to do is that when i click on "Faculty" it loads Faculty.php page and change "Faculty" color into purple and "Faculty" remains in purple untill i click on "Contact". And when i click on "Contact" it load Contact.php page and change "Contact" color into purple, and also set "Faculty" to orange color.

I tried the above JS code but it don't work, when i click on "Faculty" it load Facult.php page but don't change "Faculty" into purple color.

How should i do that?


问:
The string parameter in Jenkins don't work
When I configure the string parameter in Jenkins then call this parameter from the execute shell build step, it doesn't seem to consider this parameter because in the log nothing appear (where the yellow arrows are pointing):

答:
It looks like the parameter should be called with a different syntax in Windows and Linux.

  You can try  --baseurl = %link84% for Windows and --baseurl = ${link84} for Linux.

Source:
How to add String parameter to Jenkins with optional checkbox


问:
Modification of expand.grid function in R
I need to create a matrix of all possible combinations. </p>

```<code>L<-12
vec <- c(0:21)
lst <- lapply(numeric(L), function(x) vec)
Mat1<-as.matrix(expand.grid(lst))
</code>```

<p>Result would be very big matrix and my computer cannot calculate it.
Actually, I need only combinations where value in the first column is greater then value in the second one, in the second column is greater then in the third one and so on. Can I modify expand.grid function somehow to drop unnecessary combinations? </p>

答:
You can do this quite easily using combinations from the gtools package:

result <- gtools::combinations(length(vec), L, vec)[, L:1]
```

<p>The function itself gives the columns in increasing order, so the subset is there just to get the order right.</p>

<p>It is a large matrix, so it takes some time, but only around 5 seconds on my slow work PC:</p>

```microbenchmark::microbenchmark(combinations(22, 12, 21:0)[,12:1], times = 5)
Unit: seconds
                              expr      min       lq     mean   median       uq      max neval
combinations(22, 12, 21:0)[, 12:1] 4.965595 5.211964 5.261557 5.249413 5.341981 5.538831     5
```

<p>We can see that the first 5 rows give the correct format:</p>

<pre class="lang-r prettyprint-override"><code>result[1:5,]
#>      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
#> [1,]   11   10    9    8    7    6    5    4    3     2     1     0
#> [2,]   12   10    9    8    7    6    5    4    3     2     1     0
#> [3,]   13   10    9    8    7    6    5    4    3     2     1     0
#> [4,]   14   10    9    8    7    6    5    4    3     2     1     0
#> [5,]   15   10    9    8    7    6    5    4    3     2     1     0
</code>```

And that we have the correct dimensions:

```<code>dim(result)
#> [1] 646646     12
</code>```

Body:
I need to create a matrix of all possible combinations.

L<-12
vec <- c(0:21)
lst <- lapply(numeric(L), function(x) vec)
Mat1<-as.matrix(expand.grid(lst))

Result would be very big matrix and my computer cannot calculate it.
Actually, I need only combinations where value in the first column is greater then value in the second one, in the second column is greater then in the third one and so on. Can I modify expand.grid function somehow to drop unnecessary combinations?

Body:
You can do this quite easily using combinations from the gtools package:

result <- gtools::combinations(length(vec), L, vec)[, L:1]

The function itself gives the columns in increasing order, so the subset is there just to get the order right.

It is a large matrix, so it takes some time, but only around 5 seconds on my slow work PC:

microbenchmark::microbenchmark(combinations(22, 12, 21:0)[,12:1], times = 5)
Unit: seconds
                              expr      min       lq     mean   median       uq      max neval
combinations(22, 12, 21:0)[, 12:1] 4.965595 5.211964 5.261557 5.249413 5.341981 5.538831     5

We can see that the first 5 rows give the correct format:

result[1:5,]
#>      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
#> [1,]   11   10    9    8    7    6    5    4    3     2     1     0
#> [2,]   12   10    9    8    7    6    5    4    3     2     1     0
#> [3,]   13   10    9    8    7    6    5    4    3     2     1     0
#> [4,]   14   10    9    8    7    6    5    4    3     2     1     0
#> [5,]   15   10    9    8    7    6    5    4    3     2     1     0

And that we have the correct dimensions:

dim(result)
#> [1] 646646     12


问:
Program is not running
I am writing to find out whether the user is Teen ager or not? I am getting error while executing the program.

```<code>public class TeenNumberChecker
{
    public static void main (String[] args)
    {
        System.out.println(hasteen(22,28,32));
    }

public static boolean  hasteen(int age1,int age2,int age3) {
        if ((age1>=13&&age1<=19)||(age2>=13&&age2<=19)||(age2>=13&&age2<=19))
            return true;
}
else {
           return false;
}
}
</code>```

Error i am getting is "Exception in thread "main" java.lang.Error: Unresolved compilation problem: "

答:
Your code does not compile.

There are brackets missing and

you repeated the comparison of age2 where you possibly wanted to use age3 instead.

You should quickly learn to indent your source code properly to assist your own eyes in seeing errors. The indentation style is surely a matter of taste, so find out yourself what works best for you or follow my example below.

```<code>class Main
{
    public static void main(String[] args)
    {
        System.out.println(hasteen(22, 28, 32));
    }

    public static boolean hasteen(int age1, int age2, int age3)
    {
        if (
                (age1 >= 13 && age1 <= 19) ||
                (age2 >= 13 && age2 <= 19) ||
                (age3 >= 13 && age3 <= 19)
           )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
</code>```

Using an IDE (like IntelliJ or NetBeans) which supports automatic code formatting and highlighting of errors would be helpful here.

Title: Program is not running

Body:
I am writing to find out whether the user is Teen ager or not? I am getting error while executing the program.

public class TeenNumberChecker
{
    public static void main (String[] args)
    {
        System.out.println(hasteen(22,28,32));
    }

public static boolean  hasteen(int age1,int age2,int age3) {
        if ((age1>=13&&age1<=19)||(age2>=13&&age2<=19)||(age2>=13&&age2<=19))
            return true;
}
else {
           return false;
}
}

Error i am getting is "Exception in thread "main" java.lang.Error: Unresolved compilation problem: "

Body:
Your code does not compile.

There are brackets missing and

you repeated the comparison of age2 where you possibly wanted to use age3 instead.

You should quickly learn to indent your source code properly to assist your own eyes in seeing errors. The indentation style is surely a matter of taste, so find out yourself what works best for you or follow my example below.

class Main
{
    public static void main(String[] args)
    {
        System.out.println(hasteen(22, 28, 32));
    }

    public static boolean hasteen(int age1, int age2, int age3)
    {
        if (
                (age1 >= 13 && age1 <= 19) ||
                (age2 >= 13 && age2 <= 19) ||
                (age3 >= 13 && age3 <= 19)
           )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

Using an IDE (like IntelliJ or NetBeans) which supports automatic code formatting and highlighting of errors would be helpful here.


问:
Trying to stop the momentum when re spawn
I have looked around the web for answers but can't find a working one.
I have tried changing the code and I am pretty sure it's a very easy noob mistake as this is my first game.</p>

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class respawn : MonoBehaviour
{
    [SerializeField] private Transform player;
    [SerializeField] private Transform respawnPoint;
    private Rigidbody Rigidbody;

    void FixedUpdate()
    {
        if (player.position == respawnPoint.position);
        {
            GetComponent<Rigidbody>().velocity = 0;
            Rigidbody.angularVelocity = 0;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        player.transform.position = respawnPoint.transform.position;

    }
}
</code>```

答:
The very first thing you want to do is to look at the Unity error console. Your code throws multiple errors, they will appear in red. Double-click on an error to be taken to its line in your code.

Also, try get a good editor, like VS Code, as it will help you find issues immediately by adding red wavy underlines. With above two approaches in hand, you will be able to find ~99% of your issues yourself the next time, and then can ask in forums for the remaining 1%.

Let's go through your code step by step:

```<code>private Rigidbody Rigidbody;
</code>```

In Unity you normally want the type in upper case Rigidbody, but the variable name in lowercase rigidbody (even though the C# coding conventions suggest uppercase properties). Either way, don't use the same name as the type, so write:

```<code>private Rigidbody rigidbody;
</code>```

or e.g. (I'm now omitting the default private, though you may also prefer to keep it, and I use a shorter variable name, and clarify its start value):

```<code>Rigidbody body = null;
</code>```

In the following code:

```<code>GetComponent<Rigidbody>().velocity = 0;
</code>```

... you first of all get the rigidbody component again. This isn't needed if you got it once in start (and for repeated usage, can lag), so do it like this:

```<code>void Start()
{
    rigidbody = GetComponent<Rigidbody>();
}
</code>```

And secondly, you assign a 0, but you want to assign new Vector3(0f, 0f, 0f), or just

```<code>rigidbody.velocity = Vector3.zero;
rigidbody.angularVelocity = Vector3.zero;
</code>```

Lastly, you write

```<code>player.transform.position = respawnPoint.transform.position;
</code>```

... but player and respawnPoint are already transforms, so you can use the simpler

```<code>player.position = respawnPoint.position;
</code>```

Good luck!

Body:
I have looked around the web for answers but can't find a working one.
I have tried changing the code and I am pretty sure it's a very easy noob mistake as this is my first game.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class respawn : MonoBehaviour
{
    [SerializeField] private Transform player;
    [SerializeField] private Transform respawnPoint;
    private Rigidbody Rigidbody;

    void FixedUpdate()
    {
        if (player.position == respawnPoint.position);
        {
            GetComponent<Rigidbody>().velocity = 0;
            Rigidbody.angularVelocity = 0;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        player.transform.position = respawnPoint.transform.position;

    }
}

Body:
The very first thing you want to do is to look at the Unity error console. Your code throws multiple errors, they will appear in red. Double-click on an error to be taken to its line in your code.

Also, try get a good editor, like VS Code, as it will help you find issues immediately by adding red wavy underlines. With above two approaches in hand, you will be able to find ~99% of your issues yourself the next time, and then can ask in forums for the remaining 1%.

Let's go through your code step by step:

private Rigidbody Rigidbody;

In Unity you normally want the type in upper case Rigidbody, but the variable name in lowercase rigidbody (even though the C# coding conventions suggest uppercase properties). Either way, don't use the same name as the type, so write:

private Rigidbody rigidbody;

or e.g. (I'm now omitting the default private, though you may also prefer to keep it, and I use a shorter variable name, and clarify its start value):

Rigidbody body = null;

In the following code:

GetComponent<Rigidbody>().velocity = 0;

... you first of all get the rigidbody component again. This isn't needed if you got it once in start (and for repeated usage, can lag), so do it like this:

void Start()
{
    rigidbody = GetComponent<Rigidbody>();
}

And secondly, you assign a 0, but you want to assign new Vector3(0f, 0f, 0f), or just

rigidbody.velocity = Vector3.zero;
rigidbody.angularVelocity = Vector3.zero;

Lastly, you write

player.transform.position = respawnPoint.transform.position;

... but player and respawnPoint are already transforms, so you can use the simpler

player.position = respawnPoint.position;

Good luck!


问:
Why isn't the "gets()" function declared when I include stdio.h?
```<code>#include <stdio.h>

int main() {
   char str[50];

   printf("Enter a string : ");
   gets(str);

   printf("You entered: %s", str);

   return (0);
}
</code>```

In my code, why isn't the gets() function declared? It shows me a bunch of errors such as:

```<code>In function ‘int main()’:
 error: ‘gets’ was not declared in this scope
gets(str);
    ^~~~
[Finished in 0.2s with exit code 1]
</code>```

I want to know why this kind of problem occurs?

答:
I didn't know gets was deprecated, but you can use fgets.
https://en.cppreference.com/w/c/io/fgets

Where you have to specify the maximum size available in the buffer (which protects against buffer overflow).

```<code>fgets(buffer, sizeOfBuffer, stdin)
</code>```

Be aware

That fgets also reads the newline character into the buffer while gets doesn't (as mentioned in the comments). So you have to remove the newline character afterwards if you are not interested in it.

Body:
#include <stdio.h>

int main() {
   char str[50];

   printf("Enter a string : ");
   gets(str);

   printf("You entered: %s", str);

   return (0);
}

In my code, why isn't the gets() function declared? It shows me a bunch of errors such as:

In function ‘int main()’:
 error: ‘gets’ was not declared in this scope
gets(str);
    ^~~~
[Finished in 0.2s with exit code 1]

I want to know why this kind of problem occurs?

Body:
I didn't know gets was deprecated, but you can use fgets.
https://en.cppreference.com/w/c/io/fgets

Where you have to specify the maximum size available in the buffer (which protects against buffer overflow).

fgets(buffer, sizeOfBuffer, stdin)

Be aware

That fgets also reads the newline character into the buffer while gets doesn't (as mentioned in the comments). So you have to remove the newline character afterwards if you are not interested in it.


问:
Modify one state property in two Reducers in Redux
I have a small problem with Redux in my state I need to be able to modify my counter property in two Reducers as it's value update to both reducers (INCREMENT, DECREMENT) sorry am new to Redux and try to understand this concept.

Counter Component

```<code>
        return(
            <>
                <div className="flex justify-center">
                    <div className='font-bold text-4xl text-blue-600 bg-gray-300 p-6 m-3 rounded-full'>The Result :
                        {this.props.counter}
                    </div>
                </div>
                <section className='flex p-5 m-3 justify-center'>
                    <button onClick={this.props.increment} className={`bg-green-400 ${btnDefault}`} >Increment</button>
                    <button onClick={() => this.props.decrement(this.props.counter)} className={`bg-red-400 ${btnDefault}`}>Decrement</button>
                </section>
            </>
        )
    }
}

const mapStateToProps = state => {
    return {
        counter: state.incReducer.counter,
    }
};
const mapDispatchToProps = dispatch => {
    return {
        increment: () => dispatch(counterAction('INCREMENT')),
        decrement: (counter) => dispatch(counterAction('DECREMENT',counter))
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Counter)
</code>```

Increment Reducer

```<code>const initialState = {
    counter: 0,
};

const reducer = (state = initialState, action) => action.type === actionType.INCREMENT ?
        {
        ...state,
        counter: state.counter + 1
        }
    : state;

export default reducer;
</code>```

Decrement Reducer

```<code>const initState = {

};

const reducer = (state = initState, action) => action.type === actionType.DECREMENT ?
    {
        ...state,
        counter: action.counter - 1
    }
    : state;

export default reducer;
</code>```

Index.js

```<code>const reducer = combineReducers({
    incReducer,
    decReducer
});

const store = createStore(reducer);

ReactDOM.render(<Provider store={store}><App/></Provider> , document.getElementById('root'));
</code>```

答:
You're just approaching it from the wrong angle, you should never have the same variable being modified in two reducers, you instead want to have a single counterReducer that handles all actions that modify the counter:

```<code>const initialState = {
    counter: 0,
};

const reducer = (state = initialState, action) => {
    switch(action.type) {
        case actionType.INCREMENT:
            return {
                ...state,
                counter: state.counter + 1
            };
            break;
        case actionType.DECREMENT:
            return {
                ...state,
                counter: state.counter - 1
            }
            break;
        default:
            return state;
    }
}

export default reducer;
</code>```

Splitting into multiple reducers is a way to keep your code organized, but you'd never have two reducers that could each modify the same thing.  Each reducer should instead handle a certain "section" of your overall state, e.g.

```<code>const totalState = {
    activeUser: { /* username, email, phone, etc */ },
    friends: [],
    subscriptions: [],
    history: [],
    // etc.
}
</code>```

you might then have an activeUserReducer, friendsReducer, subscriptonsReducer, historyReducer, etc.  And each one would handle that portion of the state, but would never reach into another reducers state.

If you need to modify two different properties with a single action, you would just do:

```<code>const mapDispatchToProps = dispatch => {
    return {
        increment: () => {
            dispatch(counterAction('INCREMENT'));
            dispatch(someOtherAction());
        }
    };
};
</code>```

Body:
I have a small problem with Redux in my state I need to be able to modify my counter property in two Reducers as it's value update to both reducers (INCREMENT, DECREMENT) sorry am new to Redux and try to understand this concept.

Counter Component

        return(
            <>

The Result :
                        {this.props.counter}

                    <button onClick={this.props.increment} className={`bg-green-400 ${btnDefault}`} >Increment</button>
                    <button onClick={() => this.props.decrement(this.props.counter)} className={`bg-red-400 ${btnDefault}`}>Decrement</button>

            </>
        )
    }
}

const mapStateToProps = state => {
    return {
        counter: state.incReducer.counter,
    }
};
const mapDispatchToProps = dispatch => {
    return {
        increment: () => dispatch(counterAction('INCREMENT')),
        decrement: (counter) => dispatch(counterAction('DECREMENT',counter))
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Counter)

Increment Reducer

const initialState = {
    counter: 0,
};

const reducer = (state = initialState, action) => action.type === actionType.INCREMENT ?
        {
        ...state,
        counter: state.counter + 1
        }
    : state;

export default reducer;

Decrement Reducer

const initState = {

};

const reducer = (state = initState, action) => action.type === actionType.DECREMENT ?
    {
        ...state,
        counter: action.counter - 1
    }
    : state;

export default reducer;

Index.js

const reducer = combineReducers({
    incReducer,
    decReducer
});

const store = createStore(reducer);

ReactDOM.render(<Provider store={store}><App/></Provider> , document.getElementById('root'));

Body:
You're just approaching it from the wrong angle, you should never have the same variable being modified in two reducers, you instead want to have a single counterReducer that handles all actions that modify the counter:

const initialState = {
    counter: 0,
};

const reducer = (state = initialState, action) => {
    switch(action.type) {
        case actionType.INCREMENT:
            return {
                ...state,
                counter: state.counter + 1
            };
            break;
        case actionType.DECREMENT:
            return {
                ...state,
                counter: state.counter - 1
            }
            break;
        default:
            return state;
    }
}

export default reducer;

Splitting into multiple reducers is a way to keep your code organized, but you'd never have two reducers that could each modify the same thing.  Each reducer should instead handle a certain "section" of your overall state, e.g.

const totalState = {
    activeUser: { /* username, email, phone, etc */ },
    friends: [],
    subscriptions: [],
    history: [],
    // etc.
}

you might then have an activeUserReducer, friendsReducer, subscriptonsReducer, historyReducer, etc.  And each one would handle that portion of the state, but would never reach into another reducers state.

If you need to modify two different properties with a single action, you would just do:

const mapDispatchToProps = dispatch => {
    return {
        increment: () => {
            dispatch(counterAction('INCREMENT'));
            dispatch(someOtherAction());
        }
    };
};


答:
When you enter the Trigger you will be teleported to the respawn position, but you cannot depend on FixedUpdate running on that exact pixel of the respawn position.

The most straigh forward answer is to, well, do the code as you would describe the issue: "When you enter a trigger, set the position to the respawn position and set velocity to 0":

I would change the entire script to:

public class respawn : MonoBehaviour
{
    [SerializeField] private Transform player;
    [SerializeField] private Transform respawnPoint;
    private Rigidbody rigidbody;

    void Start()
    {
        rigidbody = GetComponent<Rigidbody>()
    }

    private void OnTriggerEnter(Collider other)
    {
        player.position = respawnPoint.position;
        rigidbody.velocity = Vector3.zero;
    }
}
```

<p>and don't forget to populate the <code>player</code> and <code>respawnPoint</code> values in the inspector. </p>

<hr>

<p>Also, keep in mind that the current code is prone to errors, if you have other objects moving around. Right now, if ANY object enters the Trigger the PLAYER position will be reset. You could fix this with check for player</p>

<pre class="lang-cs prettyprint-override"><code>private void OnTriggerEnter(Collider other)
{
    if (other.transform == player)
    {
         player.position = respawnPoint.position;
         rigidbody.velocity = Vector3.zero;
    }

}
</code>```

Title: Trying to stop the momentum when re spawn

Body:
When you enter the Trigger you will be teleported to the respawn position, but you cannot depend on FixedUpdate running on that exact pixel of the respawn position.

The most straigh forward answer is to, well, do the code as you would describe the issue: "When you enter a trigger, set the position to the respawn position and set velocity to 0":

I would change the entire script to:

public class respawn : MonoBehaviour
{
    [SerializeField] private Transform player;
    [SerializeField] private Transform respawnPoint;
    private Rigidbody rigidbody;

    void Start()
    {
        rigidbody = GetComponent<Rigidbody>()
    }

    private void OnTriggerEnter(Collider other)
    {
        player.position = respawnPoint.position;
        rigidbody.velocity = Vector3.zero;
    }
}

and don't forget to populate the player and respawnPoint values in the inspector.

Also, keep in mind that the current code is prone to errors, if you have other objects moving around. Right now, if ANY object enters the Trigger the PLAYER position will be reset. You could fix this with check for player

private void OnTriggerEnter(Collider other)
{
    if (other.transform == player)
    {
         player.position = respawnPoint.position;
         rigidbody.velocity = Vector3.zero;
    }

}


问:
Why isnt Dijkstra's algorithm's (for shortest path) time complexity the same as DFS?
Can't Dijkstra's algorithm be implemented using a DFS that keeps track of the length of the current path traveled and every time it arrives in an unvisited node it updates the length of the shortest path to that node, and if the node arrived at is already visited, update the length if the current length is smaller than the length in the node?

Which is just DFS, meaning the run time should be linear ( O(|V| + |E|) ).

答:
Let's take this graph as example, where the search should start in a, and the target node is c:

DFS

Assuming children of a node are traversed in their lexical order, a DFS will visit the nodes in the order a, b, c, d, e

It will find these distances:

```<code> a: 0
 b: 5
 c: 13
 d: 8
</code>```

Then from d it will see c again, and update it to 12

Next is:

```<code> e: 1
</code>```

From e it will see b again, and update it to 3. But then a DFS falls short of also seeing the impact this change has on nodes c and d.

Dijkstra's

Dijkstra's algorithm, on the other hand, will visit nodes in this order:

```<code> a: 0
 e: 1
 b: 3
</code>```

Then it will take the edge with weight 5, but see that b was already visited, and ignore it. Then:

```<code> d: 6
 c: 10
</code>```

... and the target was found with the correct distance.

BFS

Just to answer to your comment below: BFS will also not find the correct path, because BFS does not take the (total) weights into consideration; it just minimises the number of edges on a path.

BFS will visit the nodes like this:

```<code>a: 0

b: 5
e: 1

c: 13
</code>```

... and it will stop there. If you would not stop, but continue (with potential overwriting), then the process continues:

```<code>d: 8
</code>```

Then it sees b from e, and updates:

```<code>b: 3
</code>```

However, as b was already visited, BFS will not see the impact this change has on c and d.

It also sees c from d and updates c to 12. Then there is nothing more to do for BFS, and clearly the result is wrong.

Body:
Let's take this graph as example, where the search should start in a, and the target node is c:

DFS

Assuming children of a node are traversed in their lexical order, a DFS will visit the nodes in the order a, b, c, d, e

It will find these distances:

 a: 0
 b: 5
 c: 13
 d: 8

Then from d it will see c again, and update it to 12

Next is:

 e: 1

From e it will see b again, and update it to 3. But then a DFS falls short of also seeing the impact this change has on nodes c and d.

Dijkstra's

Dijkstra's algorithm, on the other hand, will visit nodes in this order:

 a: 0
 e: 1
 b: 3

Then it will take the edge with weight 5, but see that b was already visited, and ignore it. Then:

 d: 6
 c: 10

... and the target was found with the correct distance.

BFS

Just to answer to your comment below: BFS will also not find the correct path, because BFS does not take the (total) weights into consideration; it just minimises the number of edges on a path.

BFS will visit the nodes like this:

a: 0

b: 5
e: 1

c: 13

... and it will stop there. If you would not stop, but continue (with potential overwriting), then the process continues:

d: 8

Then it sees b from e, and updates:

b: 3

However, as b was already visited, BFS will not see the impact this change has on c and d.

It also sees c from d and updates c to 12. Then there is nothing more to do for BFS, and clearly the result is wrong.


问:
Class is not added by jQuery
I need to add dark overlay to images by adding class imgoverlay using jQuery.

$("#featured .row .col-sm img").hover(
  function() {
    $(this).addClass('imgoverlay');
  },
  function() {
    $(this).removeClass('imgoverlay');
  }
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.imgoverlay {
  height: 100%;
  background-color: rgba(18, 15, 65, 0.7);
  z-index: 2000;
}</code>```

 مشاريع مميزة

  مشاريعنا الأخرى

```

答:
Pure CSS

You can use pseudo element ::after or ::before, no need to use JS or jQ just add a global class and set hover effect on ::after and active it on :hover

.thumbs:hover::after {
  content: "";
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  background-color: rgba(18, 15, 65, 0.7);
}

.thumbs {
    width: 150px;
    height: 150px;
    overflow: hidden;
    border: 1px solid red;
    position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="main" id="featured" data-aos="fade-up">
  <div class="container">

    <div class="d-flex justify-content-between justify-content-end" data-aos="fade-up">
      <div>
        <span class="sub-title"><p align="right" data-aos="fade-left" data-aos-duration="3000"> مشاريع مميزة </p></span>
      </div>
      <div>

          <p align="right"><strong>  مشاريعنا الأخرى<i class="fas fa-arrow-left"></i></strong></p>

        </a>
      </div>
    </div>

    <!-- Gallery start -->
    <div class="row ">
      <div class="col-sm">

          <div class="thumb1 thumbs"><img name="Auoya" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRoQEfG25HrwwvXqpLkQfVMQk3PxQ7Q8CEH8oZx9MGfG04JlnLd" alt=""></div>

          <div class="thumb1 thumbs"><img name="capitalHeights" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRoQEfG25HrwwvXqpLkQfVMQk3PxQ7Q8CEH8oZx9MGfG04JlnLd" alt=""></div>

      </div>
      <div class="col-sm">

          <div class="thumb2 thumbs"><img name="hai-sakani" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRoQEfG25HrwwvXqpLkQfVMQk3PxQ7Q8CEH8oZx9MGfG04JlnLd" alt=""></div>

      </div>
      <div class="col-sm">

          <div class="thumb1 thumbs"><img name="bosco" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRoQEfG25HrwwvXqpLkQfVMQk3PxQ7Q8CEH8oZx9MGfG04JlnLd" alt=""></div>

          <div class="thumb1 thumbs"><img name="armonia" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRoQEfG25HrwwvXqpLkQfVMQk3PxQ7Q8CEH8oZx9MGfG04JlnLd" alt=""></div>

      </div>
    </div>
  </div></code>```

Title: Class is not added by jQuery

Body:
I need to add dark overlay to images by adding class imgoverlay using jQuery.

$("#featured .row .col-sm img").hover(
  function() {
    $(this).addClass('imgoverlay');
  },
  function() {
    $(this).removeClass('imgoverlay');
  }
);

.imgoverlay {
  height: 100%;
  background-color: rgba(18, 15, 65, 0.7);
  z-index: 2000;
}

 مشاريع مميزة

  مشاريعنا الأخرى

Body:
Pure CSS

You can use pseudo element ::after or ::before, no need to use JS or jQ just add a global class and set hover effect on ::after and active it on :hover

.thumbs:hover::after {
  content: "";
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  background-color: rgba(18, 15, 65, 0.7);
}

.thumbs {
    width: 150px;
    height: 150px;
    overflow: hidden;
    border: 1px solid red;
    position: relative;
}

<section class="main" id="featured" data-aos="fade-up">
  <div class="container">

    <div class="d-flex justify-content-between justify-content-end" data-aos="fade-up">
      <div>
        <span class="sub-title"><p align="right" data-aos="fade-left" data-aos-duration="3000"> مشاريع مميزة </p></span>
      </div>
      <div>
        <a href="#">
          <p align="right"><strong>  مشاريعنا الأخرى<i class="fas fa-arrow-left"></i></strong></p>
        </a>
        </a>
      </div>
    </div>

    <!-- Gallery start -->
    <div class="row ">
      <div class="col-sm">
        <a href="">
          <div class="thumb1 thumbs"><img name="Auoya" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRoQEfG25HrwwvXqpLkQfVMQk3PxQ7Q8CEH8oZx9MGfG04JlnLd" alt=""></div>
        </a>
        <a href="">
          <div class="thumb1 thumbs"><img name="capitalHeights" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRoQEfG25HrwwvXqpLkQfVMQk3PxQ7Q8CEH8oZx9MGfG04JlnLd" alt=""></div>
        </a>
      </div>
      <div class="col-sm">
        <a href="">
          <div class="thumb2 thumbs"><img name="hai-sakani" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRoQEfG25HrwwvXqpLkQfVMQk3PxQ7Q8CEH8oZx9MGfG04JlnLd" alt=""></div>
        </a>
      </div>
      <div class="col-sm">
        <a href="">
          <div class="thumb1 thumbs"><img name="bosco" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRoQEfG25HrwwvXqpLkQfVMQk3PxQ7Q8CEH8oZx9MGfG04JlnLd" alt=""></div>
        </a>
        <a href="">
          <div class="thumb1 thumbs"><img name="armonia" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRoQEfG25HrwwvXqpLkQfVMQk3PxQ7Q8CEH8oZx9MGfG04JlnLd" alt=""></div>
        </a>
      </div>
    </div>
  </div>


问:
How to submit the form to a different server and from that server return to the same page php
I'm trying to verify user apiKey. so the I have a application which user installs on their server and they need to add their apiKey to activate it. so I've created a form where they can add their apiKey and it'll submit the key to my server and then my server verify the key. but I want to know how to get from which URL we recieved the request so we can send back results to that url?

```<code><form action="my-server-.com/verifyfile.php" method="post">
    <div class="form-group row">
        <label for="email" class="col-lg-2 col-form-label">Enter API Key</label>
        <div class="col-lg-6">
            <input type="text" placeholder="paste your api key here" name="apiKey" class="form-control" required="">
        </div>
        <div class="form-group col-lg-2">
            <input type="submit" value="Register" name="verify-api" class="btn btn-outline-success btn-sm">
        </div>
    </div>
</form>
</code>```

答:
You can use Curl.

```<code>  <?php
    if (isset($_POST['apiKey'])) {
                $api_key = $_POST['apiKey'];
            } else {
                $api_key = '';
            }

    //You can use Curl...
    $ch = curl_init();

                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
                curl_setopt($ch, CURLOPT_USERAGENT,
      "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_URL,"https://urltoAnotherserver.com");
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $api_key);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

                $json = curl_exec($ch);
                $response = json_decode($json, TRUE);

                print_r($response);

                curl_close($ch);
</code>```

And when you receive response you can verify the key in php

Body:
I'm trying to verify user apiKey. so the I have a application which user installs on their server and they need to add their apiKey to activate it. so I've created a form where they can add their apiKey and it'll submit the key to my server and then my server verify the key. but I want to know how to get from which URL we recieved the request so we can send back results to that url?

<form action="my-server-.com/verifyfile.php" method="post">

        Enter API Key

            <input type="text" placeholder="paste your api key here" name="apiKey" class="form-control" required="">

            <input type="submit" value="Register" name="verify-api" class="btn btn-outline-success btn-sm">

</form>

Body:
You can use Curl.

  <?php
    if (isset($_POST['apiKey'])) {
                $api_key = $_POST['apiKey'];
            } else {
                $api_key = '';
            }

    //You can use Curl...
    $ch = curl_init();

                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
                curl_setopt($ch, CURLOPT_USERAGENT,
      "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_URL,"https://urltoAnotherserver.com");
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $api_key);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

                $json = curl_exec($ch);
                $response = json_decode($json, TRUE);

                print_r($response);

                curl_close($ch);

And when you receive response you can verify the key in php


问:
How to get properties from an Object filtering by an array in Javascript
I have a JS object like this:

```<code>const myObj = {
  '$prop1': 1,
  '$prop2': 2,
  '$prop3': 3
};
</code>```

and an array of object like this:

```<code>const myArray = [
  {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop1'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop2'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop5'
  },
];
</code>```

I am trying to write a function fo filter myObj and only get the fields I can find in myArray.propKey.

this is what I tried so far with no luck:

```<code>export const filterVariantContentByColumns = (myObj, myArray) => {
  const objArray = Object.keys(myObj).map(i => myObj[i]);
  return objArray.filter(value => myArray.includes(value.key_name));

  console.log(res);
};
</code>```

any idea how to do that please?

答:
You could iterate the array and map found properties.

const
    myObj = { $prop1: 1, $prop2: 2, $prop3: 3 },
    myArray = [{ prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop1' }, { prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop2' }, { prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop5' }],
    result = myArray.flatMap(({ propKey }) => propKey in myObj ? myObj[propKey] : []);

console.log(result);```
</div>
</div>
</p>

<p>With keys</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const
    myObj = { $prop1: 1, $prop2: 2, $prop3: 3 },
    myArray = [{ prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop1' }, { prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop2' }, { prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop5' }],
    result = Object.fromEntries(myArray.flatMap(({ propKey }) => propKey in myObj ? [[propKey, myObj[propKey]]] : []));

console.log(result);</code>```

Body:
I have a JS object like this:

const myObj = {
  '$prop1': 1,
  '$prop2': 2,
  '$prop3': 3
};

and an array of object like this:

const myArray = [
  {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop1'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop2'
  },
        {
    prop1: 'some stuff',
    prop2: 'some other stuff',
    propKey: '$prop5'
  },
];

I am trying to write a function fo filter myObj and only get the fields I can find in myArray.propKey.

this is what I tried so far with no luck:

export const filterVariantContentByColumns = (myObj, myArray) => {
  const objArray = Object.keys(myObj).map(i => myObj[i]);
  return objArray.filter(value => myArray.includes(value.key_name));

  console.log(res);
};

any idea how to do that please?

Body:
You could iterate the array and map found properties.

const
    myObj = { $prop1: 1, $prop2: 2, $prop3: 3 },
    myArray = [{ prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop1' }, { prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop2' }, { prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop5' }],
    result = myArray.flatMap(({ propKey }) => propKey in myObj ? myObj[propKey] : []);

console.log(result);

With keys

const
    myObj = { $prop1: 1, $prop2: 2, $prop3: 3 },
    myArray = [{ prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop1' }, { prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop2' }, { prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop5' }],
    result = Object.fromEntries(myArray.flatMap(({ propKey }) => propKey in myObj ? [[propKey, myObj[propKey]]] : []));

console.log(result);


问:
Python Pandas Error tokenizing data
I'm trying to use pandas to manipulate a .csv file but I get this error:

pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3,  saw 12

I have tried to read the pandas docs, but found nothing.

My code is simple:

```<code>path = 'GOOG Key Ratios.csv'
#print(open(path).read())
data = pd.read_csv(path)
</code>```

How can I resolve this? Should I use the csv module or another language ?

File is from Morningstar

答:
Error tokenizing data. C error:  Expected 2 fields in line 3, saw 12

The error gives a clue to solve the problem " Expected 2 fields in line 3, saw 12", saw 12 means length of the second row is 12 and first row is 2.

When you have data like the one shown below, if you skip rows then most of the data will be skipped

```<code>data = """1,2,3
1,2,3,4
1,2,3,4,5
1,2
1,2,3,4"""
</code>```

If you dont want to skip any rows do the following

```<code>#First lets find the maximum column for all the rows
with open("file_name.csv", 'r') as temp_f:
    # get No of columns in each line
    col_count = [ len(l.split(",")) for l in temp_f.readlines() ]

### Generate column names  (names will be 0, 1, 2, ..., maximum columns - 1)
column_names = [i for i in range(max(col_count))]

import pandas as pd
# inside range set the maximum value you can see in "Expected 4 fields in line 2, saw 8"
# here will be 8
data = pd.read_csv("file_name.csv",header = None,names=column_names )
</code>```

Use range instead of manually setting names as it will be cumbersome when you have many columns.

Additionally you can fill up the NaN values with 0, if you need to use even data length. Eg. for clustering (k-means)

```<code>new_data = data.fillna(0)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python Pandas Error tokenizing data

Body:
I'm trying to use pandas to manipulate a .csv file but I get this error:

pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3,  saw 12

I have tried to read the pandas docs, but found nothing.

My code is simple:

path = 'GOOG Key Ratios.csv'
#print(open(path).read())
data = pd.read_csv(path)

How can I resolve this? Should I use the csv module or another language ?

File is from Morningstar

Body:
Error tokenizing data. C error:  Expected 2 fields in line 3, saw 12

The error gives a clue to solve the problem " Expected 2 fields in line 3, saw 12", saw 12 means length of the second row is 12 and first row is 2.

When you have data like the one shown below, if you skip rows then most of the data will be skipped

data = """1,2,3
1,2,3,4
1,2,3,4,5
1,2
1,2,3,4"""

If you dont want to skip any rows do the following

#First lets find the maximum column for all the rows
with open("file_name.csv", 'r') as temp_f:
    # get No of columns in each line
    col_count = [ len(l.split(",")) for l in temp_f.readlines() ]

### Generate column names  (names will be 0, 1, 2, ..., maximum columns - 1)
column_names = [i for i in range(max(col_count))]

import pandas as pd
# inside range set the maximum value you can see in "Expected 4 fields in line 2, saw 8"
# here will be 8
data = pd.read_csv("file_name.csv",header = None,names=column_names )

Use range instead of manually setting names as it will be cumbersome when you have many columns.

Additionally you can fill up the NaN values with 0, if you need to use even data length. Eg. for clustering (k-means)

new_data = data.fillna(0)


问:
Is it possible to animate a CSS line-through text-decoration?
I am trying to animate with CSS the a line through on a bit of text, but it's not actually animating, just going from hidden to displayed. Can anyone advise if what I'm trying is actually possible? If not, is there another way to achieve this?
HTML:

```<code><div>
    The text in the span <span class="strike">is what I want to strike out</span>.
</div>
</code>```

CSS:

```<code>@keyframes strike{
                from{text-decoration: none;}
                to{text-decoration: line-through;}
            }
 .strike{
    -webkit-animation-name: strike; /* Chrome, Safari, Opera */
    -webkit-animation-duration: 4s; /* Chrome, Safari, Opera */
    animation-name: strike;
    animation-duration: 4s;
    animation-timing-function: linear;
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
    }
</code>```

答:
Here's a variation on the accepted answer, using an image to provide an animated  "scribble" strike-through.

html {
  font-family: Helvetica;
  font-size: 24px;
}
.strike { position:relative; }
.strike::after {
  content:' ';
  position:absolute;
  top:50%; left:-3%;
  width:0; height:10px;
  opacity:80%;
  transform:translateY(-50%);
  background:repeat-x url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB0AAAAKAQMAAAByjsdvAAAABlBMVEUAAADdMzNrjRuKAAAAAXRSTlMAQObYZgAAADdJREFUCNdj+MMABP8ZGCQY/h9g+MHw/AHzDwbGD+w/GBhq6h8wMNj/b2BgkP8HVMMPUsn+gQEAsTkQNRVnI4cAAAAASUVORK5CYII=);
  animation: strike 2s linear .3s 1 forwards;
}
@keyframes strike { to { width: 106%; } }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>This thing and <span class="strike">this thing and</span> this thing.</code>```

Body:
I am trying to animate with CSS the a line through on a bit of text, but it's not actually animating, just going from hidden to displayed. Can anyone advise if what I'm trying is actually possible? If not, is there another way to achieve this?
HTML:

    The text in the span is what I want to strike out.

CSS:

@keyframes strike{
                from{text-decoration: none;}
                to{text-decoration: line-through;}
            }
 .strike{
    -webkit-animation-name: strike; /* Chrome, Safari, Opera */
    -webkit-animation-duration: 4s; /* Chrome, Safari, Opera */
    animation-name: strike;
    animation-duration: 4s;
    animation-timing-function: linear;
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
    }

Body:
Here's a variation on the accepted answer, using an image to provide an animated  "scribble" strike-through.

html {
  font-family: Helvetica;
  font-size: 24px;
}
.strike { position:relative; }
.strike::after {
  content:' ';
  position:absolute;
  top:50%; left:-3%;
  width:0; height:10px;
  opacity:80%;
  transform:translateY(-50%);
  background:repeat-x url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB0AAAAKAQMAAAByjsdvAAAABlBMVEUAAADdMzNrjRuKAAAAAXRSTlMAQObYZgAAADdJREFUCNdj+MMABP8ZGCQY/h9g+MHw/AHzDwbGD+w/GBhq6h8wMNj/b2BgkP8HVMMPUsn+gQEAsTkQNRVnI4cAAAAASUVORK5CYII=);
  animation: strike 2s linear .3s 1 forwards;
}
@keyframes strike { to { width: 106%; } }

This thing and <span class="strike">this thing and</span> this thing.


问:
Why can't I cast DateTime[] to object[]?
It seems that I can cast DateTime to object, so why can't I cast array DateTime[] to object[]?  I know this has something to do with value/reference types, but doesn't boxing allow me to do this?</p>

答:
Array covariance only applies to arrays of reference types.  DateTime is a value type so you can't assign a DateTime[] to an object[] variable.  You'll have to explicitly create an object array and copy the values over.  In other words, create a new array instance of type object[].

There are plenty of ways you can do this.  A simple use of CopyTo() should be enough.

```<code>DateTime[] x = new DateTime[] { ... };
object[] y = new object[x.Length];
x.CopyTo(y, 0);
</code>```

I ran some tests.  Probably not the best way to do it but it should give a good idea of what it would be with a proper profiler.

```<code>class Program
{
    static void Main(string[] args)
    {
        var now = DateTime.Now;
        var dates = new DateTime[5000000];
        for (int i = 0; i < dates.Length; i++)
            dates[i] = now.AddSeconds(i);
        for (int i = 0; i < 5; i++)
        {
            Test("Test1", () =>
            {
                var result = new object[dates.LongLength];
                for (long l = 0; l < result.LongLength; l++)
                    result[l] = dates[l];
                return result;
            });
            Test("Test2", () =>
            {
                var result = new object[dates.LongLength];
                dates.CopyTo(result, 0);
                return result;
            });
            Test("Test3", () =>
            {
                var result = new object[dates.LongLength];
                Array.Copy(dates, result, dates.LongLength);
                return result;
            });
            Test("Test4", () =>
            {
                var result = Array.ConvertAll(dates, d => (object)d);
                return result;
            });
            Test("Test5", () =>
            {
                var result = dates.Cast<object>().ToArray();
                return result;
            });
            Test("Test6", () =>
            {
                var result = dates.Select(d => (object)d).ToArray();
                return result;
            });
            Console.WriteLine();
        }
    }

    static void Test<T>(string name, Func<T> fn)
    {
        var startMem = GC.GetTotalMemory(true);
        var sw = Stopwatch.StartNew();
        var result = fn();
        sw.Stop();
        var endMem = GC.GetTotalMemory(false);
        var diff = endMem - startMem;
        Console.WriteLine("{0}\tMem: {1,7}/{2,7} ({3,7})", name, startMem, endMem, diff);
        Console.WriteLine("\tTime: {0,7} ({1,7})", sw.ElapsedMilliseconds, sw.ElapsedTicks);
    }
}
</code>```

Specs:

Win7Pro x64, Core2Quad Q9550@2.83GHz, 4GiB DDR2 1066 (PC2-8500)

64-bit build (32-bit is roughly the same, just less memory overall)

```
Test1   Mem: 40086256/200087360 (160001104)
        Time:     444 (1230723)
Test2   Mem: 40091352/200099272 (160007920)
        Time:     751 (2078001)
Test3   Mem: 40091416/200099256 (160007840)
        Time:     800 (2213764)
Test4   Mem: 40091480/200099256 (160007776)
        Time:     490 (1358326)
Test5   Mem: 40091608/300762328 (260670720)
        Time:    1407 (3893922)
Test6   Mem: 40091672/300762328 (260670656)
        Time:     756 (2092566)

Test1   Mem: 40091736/200099184 (160007448)
        Time:     515 (1425098)
Test2   Mem: 40091736/200099184 (160007448)
        Time:     868 (2404151)
Test3   Mem: 40091736/200099160 (160007424)
        Time:     885 (2448850)
Test4   Mem: 40091736/200099184 (160007448)
        Time:     540 (1494429)
Test5   Mem: 40091736/300762240 (260670504)
        Time:    1479 (4093676)
Test6   Mem: 40091736/300762216 (260670480)
        Time:     746 (2065095)

Test1   Mem: 40091736/200099168 (160007432)
        Time:     500 (1383656)
Test2   Mem: 40091736/200099160 (160007424)
        Time:     781 (2162711)
Test3   Mem: 40091736/200099176 (160007440)
        Time:     793 (2194605)
Test4   Mem: 40091736/200099184 (160007448)
        Time:     486 (1346549)
Test5   Mem: 40091736/300762232 (260670496)
        Time:    1448 (4008145)
Test6   Mem: 40091736/300762232 (260670496)
        Time:     749 (2075019)

Test1   Mem: 40091736/200099184 (160007448)
        Time:     487 (1349320)
Test2   Mem: 40091736/200099176 (160007440)
        Time:     781 (2162729)
Test3   Mem: 40091736/200099184 (160007448)
        Time:     800 (2214766)
Test4   Mem: 40091736/200099184 (160007448)
        Time:     506 (1400698)
Test5   Mem: 40091736/300762224 (260670488)
        Time:    1436 (3975880)
Test6   Mem: 40091736/300762232 (260670496)
        Time:     743 (2058002)

Test1   Mem: 40091736/200099184 (160007448)
        Time:     482 (1335709)
Test2   Mem: 40091736/200099184 (160007448)
        Time:     777 (2150719)
Test3   Mem: 40091736/200099184 (160007448)
        Time:     793 (2196184)
Test4   Mem: 40091736/200099184 (160007448)
        Time:     493 (1365222)
Test5   Mem: 40091736/300762240 (260670504)
        Time:    1434 (3969530)
Test6   Mem: 40091736/300762232 (260670496)
        Time:     746 (2064278)
```

Interestingly, ConvertAll() performs much the same as a plain loop.

Body:
Array covariance only applies to arrays of reference types.  DateTime is a value type so you can't assign a DateTime[] to an object[] variable.  You'll have to explicitly create an object array and copy the values over.  In other words, create a new array instance of type object[].

There are plenty of ways you can do this.  A simple use of CopyTo() should be enough.

DateTime[] x = new DateTime[] { ... };
object[] y = new object[x.Length];
x.CopyTo(y, 0);

I ran some tests.  Probably not the best way to do it but it should give a good idea of what it would be with a proper profiler.

class Program
{
    static void Main(string[] args)
    {
        var now = DateTime.Now;
        var dates = new DateTime[5000000];
        for (int i = 0; i < dates.Length; i++)
            dates[i] = now.AddSeconds(i);
        for (int i = 0; i < 5; i++)
        {
            Test("Test1", () =>
            {
                var result = new object[dates.LongLength];
                for (long l = 0; l < result.LongLength; l++)
                    result[l] = dates[l];
                return result;
            });
            Test("Test2", () =>
            {
                var result = new object[dates.LongLength];
                dates.CopyTo(result, 0);
                return result;
            });
            Test("Test3", () =>
            {
                var result = new object[dates.LongLength];
                Array.Copy(dates, result, dates.LongLength);
                return result;
            });
            Test("Test4", () =>
            {
                var result = Array.ConvertAll(dates, d => (object)d);
                return result;
            });
            Test("Test5", () =>
            {
                var result = dates.Cast<object>().ToArray();
                return result;
            });
            Test("Test6", () =>
            {
                var result = dates.Select(d => (object)d).ToArray();
                return result;
            });
            Console.WriteLine();
        }
    }

    static void Test<T>(string name, Func<T> fn)
    {
        var startMem = GC.GetTotalMemory(true);
        var sw = Stopwatch.StartNew();
        var result = fn();
        sw.Stop();
        var endMem = GC.GetTotalMemory(false);
        var diff = endMem - startMem;
        Console.WriteLine("{0}\tMem: {1,7}/{2,7} ({3,7})", name, startMem, endMem, diff);
        Console.WriteLine("\tTime: {0,7} ({1,7})", sw.ElapsedMilliseconds, sw.ElapsedTicks);
    }
}

Specs:

Win7Pro x64, Core2Quad Q9550@2.83GHz, 4GiB DDR2 1066 (PC2-8500)

64-bit build (32-bit is roughly the same, just less memory overall)

Test1   Mem: 40086256/200087360 (160001104)
        Time:     444 (1230723)
Test2   Mem: 40091352/200099272 (160007920)
        Time:     751 (2078001)
Test3   Mem: 40091416/200099256 (160007840)
        Time:     800 (2213764)
Test4   Mem: 40091480/200099256 (160007776)
        Time:     490 (1358326)
Test5   Mem: 40091608/300762328 (260670720)
        Time:    1407 (3893922)
Test6   Mem: 40091672/300762328 (260670656)
        Time:     756 (2092566)

Test1   Mem: 40091736/200099184 (160007448)
        Time:     515 (1425098)
Test2   Mem: 40091736/200099184 (160007448)
        Time:     868 (2404151)
Test3   Mem: 40091736/200099160 (160007424)
        Time:     885 (2448850)
Test4   Mem: 40091736/200099184 (160007448)
        Time:     540 (1494429)
Test5   Mem: 40091736/300762240 (260670504)
        Time:    1479 (4093676)
Test6   Mem: 40091736/300762216 (260670480)
        Time:     746 (2065095)

Test1   Mem: 40091736/200099168 (160007432)
        Time:     500 (1383656)
Test2   Mem: 40091736/200099160 (160007424)
        Time:     781 (2162711)
Test3   Mem: 40091736/200099176 (160007440)
        Time:     793 (2194605)
Test4   Mem: 40091736/200099184 (160007448)
        Time:     486 (1346549)
Test5   Mem: 40091736/300762232 (260670496)
        Time:    1448 (4008145)
Test6   Mem: 40091736/300762232 (260670496)
        Time:     749 (2075019)

Test1   Mem: 40091736/200099184 (160007448)
        Time:     487 (1349320)
Test2   Mem: 40091736/200099176 (160007440)
        Time:     781 (2162729)
Test3   Mem: 40091736/200099184 (160007448)
        Time:     800 (2214766)
Test4   Mem: 40091736/200099184 (160007448)
        Time:     506 (1400698)
Test5   Mem: 40091736/300762224 (260670488)
        Time:    1436 (3975880)
Test6   Mem: 40091736/300762232 (260670496)
        Time:     743 (2058002)

Test1   Mem: 40091736/200099184 (160007448)
        Time:     482 (1335709)
Test2   Mem: 40091736/200099184 (160007448)
        Time:     777 (2150719)
Test3   Mem: 40091736/200099184 (160007448)
        Time:     793 (2196184)
Test4   Mem: 40091736/200099184 (160007448)
        Time:     493 (1365222)
Test5   Mem: 40091736/300762240 (260670504)
        Time:    1434 (3969530)
Test6   Mem: 40091736/300762232 (260670496)
        Time:     746 (2064278)

Interestingly, ConvertAll() performs much the same as a plain loop.


问:
-129 != -129 in Java Collection of Integers (Collection<Integer>)
I was working on Java ArrayList of Integers. However, I found that after certain negative int value; Collection of Type <Integer> start behaving weirdly with == operator.

Please see the code below:

```<code>import java.util.*;

public class JavaWeirdness
{

    public static void main(String[] args)
    {
        for(int i=0;i>=-200;i--)
        {
            ArrayList<Integer> list = new ArrayList<>();

            list.add(i);
            list.add(i);
            System.out.println("For i = "+ i);
            System.out.println((list.get(0) == list.get(1)));
        }
    }

}
</code>```

When i <= -129 then it prints false for every value.

Thus it puzzled me; Is it because of Refrence Type Integer instead of primitive int?

As If we change:

```<code>list.get(0) == list.get(1);
</code>```

To:

```<code>(int) list.get(0) == (int) list.get(1));
</code>```

Everything starts working fine.

OR

Even if we use .equals() instead of == it works fine.

like:

```<code>list.get(0).equals(list.get(1));
</code>```

BUT

My question here is: WHY? Is it happening in first place?

is it because of auto-boxing and unboxing?

Or

is it because of buffer issues? If you closely observe it is -((2^7)+1) and onwards.

Or

is it because of collections issues?

Or

is it a bug? (I don't think that'll be the case)

Or

is it because of some IEEE number standards?

Or

anything else?

This is kinda weird; However, I hope experts here will help me out.

PS. please don't ask why I've written this weird code (Let us say I was just testing something :P :D)

答:
== on objects refers to an equality of same instance. On primitive int it refers on same value
equals is the right chiice to compare Integer, or Long or String or other based on values.
Not a problemi with collections</p>

Body:
I was working on Java ArrayList of Integers. However, I found that after certain negative int value; Collection of Type <Integer> start behaving weirdly with == operator.

Please see the code below:

import java.util.*;

public class JavaWeirdness
{

    public static void main(String[] args)
    {
        for(int i=0;i>=-200;i--)
        {
            ArrayList<Integer> list = new ArrayList<>();

            list.add(i);
            list.add(i);
            System.out.println("For i = "+ i);
            System.out.println((list.get(0) == list.get(1)));
        }
    }

}

When i <= -129 then it prints false for every value.

Thus it puzzled me; Is it because of Refrence Type Integer instead of primitive int?

As If we change:

list.get(0) == list.get(1);

To:

(int) list.get(0) == (int) list.get(1));

Everything starts working fine.

OR

Even if we use .equals() instead of == it works fine.

like:

list.get(0).equals(list.get(1));

BUT

My question here is: WHY? Is it happening in first place?

is it because of auto-boxing and unboxing?

Or

is it because of buffer issues? If you closely observe it is -((2^7)+1) and onwards.

Or

is it because of collections issues?

Or

is it a bug? (I don't think that'll be the case)

Or

is it because of some IEEE number standards?

Or

anything else?

This is kinda weird; However, I hope experts here will help me out.

PS. please don't ask why I've written this weird code (Let us say I was just testing something :P :D)


问:
Python Tkinter and MySQL Error: AttributeError: 'NoneType' object has no attribute 'get'
I'm getting an error : AttributeError: 'NoneType' object has no attribute 'get'.

```<code>
def submit():
    a=e1.get()
    b=e2.get()
    import mysql.connector
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      passwd="root",
      database="login"
    )
    sql="INSERT INTO log (name, password) VALUES (%s, %s)"
    val= (a,b)
    mycursor.execute(sql, val)
    mydb.commit()
    print(mycursor.rowcount, "record inserted")

form=Tk()
form.geometry("500x100")

name=Label(form,text="Enter Username").place(x=5,y=0)
e1=Entry(form).place(x=150,y=0)
password=Label(form,text="Enter Password").place(x=5,y=35)
e2=Entry(form).place(x=150,y=35)

submit=Button(form,text="Submit", command=submit).place(x=5,y=70)

form.mainloop()

</code>```

答:
DONE

```<code>
def submit():
    a=e1.get()
    b=e2.get()
    import mysql.connector
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      passwd="root",
      database="login"
    )
    mycursor = mydb.cursor()
    sql="INSERT INTO log (name, password) VALUES (%s, %s)"
    val= (a,b)
    mycursor.execute(sql, val)
    mydb.commit()
    print(mycursor.rowcount, "record inserted")

form=Tk()
form.geometry("500x100")

name=Label(form,text="Enter Username")
name.place(x=5,y=0)
e1=Entry(form)
e1.place(x=150,y=0)
password=Label(form,text="Enter Password")
password.place(x=5,y=35)
e2=Entry(form)
e2.place(x=150,y=35)

submit=Button(form,text="Submit", command=submit).place(x=5,y=70)

form.mainloop()

</code>```

Body:
I'm getting an error : AttributeError: 'NoneType' object has no attribute 'get'.

def submit():
    a=e1.get()
    b=e2.get()
    import mysql.connector
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      passwd="root",
      database="login"
    )
    sql="INSERT INTO log (name, password) VALUES (%s, %s)"
    val= (a,b)
    mycursor.execute(sql, val)
    mydb.commit()
    print(mycursor.rowcount, "record inserted")

form=Tk()
form.geometry("500x100")

name=Label(form,text="Enter Username").place(x=5,y=0)
e1=Entry(form).place(x=150,y=0)
password=Label(form,text="Enter Password").place(x=5,y=35)
e2=Entry(form).place(x=150,y=35)

submit=Button(form,text="Submit", command=submit).place(x=5,y=70)

form.mainloop()

Body:
DONE

def submit():
    a=e1.get()
    b=e2.get()
    import mysql.connector
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      passwd="root",
      database="login"
    )
    mycursor = mydb.cursor()
    sql="INSERT INTO log (name, password) VALUES (%s, %s)"
    val= (a,b)
    mycursor.execute(sql, val)
    mydb.commit()
    print(mycursor.rowcount, "record inserted")

form=Tk()
form.geometry("500x100")

name=Label(form,text="Enter Username")
name.place(x=5,y=0)
e1=Entry(form)
e1.place(x=150,y=0)
password=Label(form,text="Enter Password")
password.place(x=5,y=35)
e2=Entry(form)
e2.place(x=150,y=35)

submit=Button(form,text="Submit", command=submit).place(x=5,y=70)

form.mainloop()


问:
Replace exact matching string
I want to dynamically replace an exact sub string from a string. For ex I want to replace "dis.[Test Table]" to "dbo.[Test Table]" in the following string:

SELECT        Name FROM            dis.[Test Table].

Note that I it could be any text and any sub string. It will replace only exactly matched sub string as many times as it will occur.

答:
use String.Replace() Method

```<code>fullString = fullString.Replace("oldSubString", "newSubString");
</code>```

Just to elaborate further, your example can be written as:

```<code>var newString = "SELECT Name FROM dis.[Test Table]".Replace("dis.[Test Table]","dbo.[Test Table]");

// newString will become "SELECT Name FROM dbo.[Test Table]"
</code>```

More details are here

Title: Replace exact matching string

Body:
use String.Replace() Method

fullString = fullString.Replace("oldSubString", "newSubString");

Just to elaborate further, your example can be written as:

var newString = "SELECT Name FROM dis.[Test Table]".Replace("dis.[Test Table]","dbo.[Test Table]");

// newString will become "SELECT Name FROM dbo.[Test Table]"

More details are here


问:
Are the await / async keywords needed under Task.Run?
I have an async lambda expression wrapped under Task.Run.
However, it looks like I can drop the async and await keywords and they will produce the same result.

```<code>t1 = Task.Run(() => DoSomethingExpensiveAsync());
t2 = Task.Run(() => DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);
</code>```

vs

```<code>var t1 = Task.Run(async () => await DoSomethingExpensiveAsync());
var t2 = Task.Run(async () => await DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);
</code>```

How come the compiler let me do this and what is happening behind
the scene?

Is there a situation where adding them will make a
difference?

答:
There are actually three variants.

```<code>var task = Task.Run(() => DoSomethingExpensiveAsync());
</code>```

^ This one declares a new anonymous non-async function that calls DoSomethingExpensiveAsync() and returns its Task. The compiler compiles this anonymous function and passes it as an argument to Task.Run().

```<code>var task = Task.Run( async () => await DoSomethingExpensiveAsync() );
</code>```

^ This one declares a new anonymous async function that calls DoSomethingExpensiveAsync(). It then returns an incomplete Task, waits for  DoSomethingExpensiveAsync() to finish, and then signals the task as complete.

```<code>var task = Task.Run(DoSomethingExpensiveAsync);
</code>```

^ This one does not declare a new anonymous function at all. A direct reference to DoSomethingExpensiveAsync will be passed as an argument to Task.Run().

All of these are valid because all three versions return a Task and therefore match the overload of Task.Run() that accepts a Func<Task>.

As a black box, all three calls will end up doing the same thing. However the first two result in a new function being compiled (although I'm not certain it wouldn't be optimized away) and the second one also results in another state machine being created for it.

The difference might be clearer if we rewrite them without using lambda expressions or anonymous functions. The following code does exactly the same thing:

```<code>//This is the same as Task.Run( () => DoSomethingExpensiveAsync());
Task Foo()
{
    return DoSomethingExpensiveAsync();
}
var task = Task.Run(Foo);

//This is the same as Task.Run(async () => await DoSomethingExpensiveAsync());
async Task Bar()
{
    return await DoSomethingExpensiveAsync();
}
var task = Task.Run(Bar);
</code>```

The difference between these two is that one "elides" tasks while the other doesn't. Stephen Cleary has written a whole blog on the subject.

Body:
I have an async lambda expression wrapped under Task.Run.
However, it looks like I can drop the async and await keywords and they will produce the same result.

t1 = Task.Run(() => DoSomethingExpensiveAsync());
t2 = Task.Run(() => DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);

vs

var t1 = Task.Run(async () => await DoSomethingExpensiveAsync());
var t2 = Task.Run(async () => await DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);

How come the compiler let me do this and what is happening behind
the scene?

Is there a situation where adding them will make a
difference?

Body:
There are actually three variants.

var task = Task.Run(() => DoSomethingExpensiveAsync());

^ This one declares a new anonymous non-async function that calls DoSomethingExpensiveAsync() and returns its Task. The compiler compiles this anonymous function and passes it as an argument to Task.Run().

var task = Task.Run( async () => await DoSomethingExpensiveAsync() );

^ This one declares a new anonymous async function that calls DoSomethingExpensiveAsync(). It then returns an incomplete Task, waits for  DoSomethingExpensiveAsync() to finish, and then signals the task as complete.

var task = Task.Run(DoSomethingExpensiveAsync);

^ This one does not declare a new anonymous function at all. A direct reference to DoSomethingExpensiveAsync will be passed as an argument to Task.Run().

All of these are valid because all three versions return a Task and therefore match the overload of Task.Run() that accepts a Func<Task>.

As a black box, all three calls will end up doing the same thing. However the first two result in a new function being compiled (although I'm not certain it wouldn't be optimized away) and the second one also results in another state machine being created for it.

The difference might be clearer if we rewrite them without using lambda expressions or anonymous functions. The following code does exactly the same thing:

//This is the same as Task.Run( () => DoSomethingExpensiveAsync());
Task Foo()
{
    return DoSomethingExpensiveAsync();
}
var task = Task.Run(Foo);

//This is the same as Task.Run(async () => await DoSomethingExpensiveAsync());
async Task Bar()
{
    return await DoSomethingExpensiveAsync();
}
var task = Task.Run(Bar);

The difference between these two is that one "elides" tasks while the other doesn't. Stephen Cleary has written a whole blog on the subject.


问:
How to dynamically change part of string's color with SpannableBuilder
I am formatting strings dynamically, as the following example from Android documentation:

```<code><string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
</code>```

Then I set values like this:

```<code>var text = getString(R.string.welcome_messages, username, mailCount)
</code>```

How can I set the green color for username and red for mailCount?

I need it to work for multiple locales, too. So I can't just hardcoded positions myself.

Previously I split this string into 4 parts and then could easily use SpannableBuilder to change colors.

HTML and CDATA are not appropriate. We need to keep the same strings for Android and iOS.

答:
You can use SpannableString and setSpan based on your requirement.

```<code><string name="welcome_message">Hello, %1$s! You have %2$d new messages.</string>
</code>```

```<code>void setSpannableTextWithColor(TextView view, int resourceId, String username, int userColor, int messageCount, int countColor) {
    String fulltext = getString(resourceId, username, messageCount);

    view.setText(fulltext, TextView.BufferType.SPANNABLE);
    Spannable str = (Spannable) view.getText();

    int usernameIndex = fulltext.indexOf(username);
    str.setSpan(new ForegroundColorSpan(userColor), usernameIndex, usernameIndex + username.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    int countIndex = fulltext.indexOf(String.valueOf(messageCount));
    str.setSpan(new ForegroundColorSpan(countColor), countIndex, countIndex + String.valueOf(messageCount).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
</code>```

```<code>setSpannableTextWithColor(findViewById(R.id.text_view1), R.string.welcome_message, "Viktor Vostrikov", Color.GREEN, 122, Color.RED);
setSpannableTextWithColor(findViewById(R.id.text_view2), R.string.welcome_message, "Виктор Востриков", Color.GREEN, 2, Color.RED);
setSpannableTextWithColor(findViewById(R.id.text_view3), R.string.welcome_message, "فيكتور فوستريكوف", Color.GREEN, 2000, Color.RED);
</code>```

Output:

Body:
I am formatting strings dynamically, as the following example from Android documentation:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

Then I set values like this:

var text = getString(R.string.welcome_messages, username, mailCount)

How can I set the green color for username and red for mailCount?

I need it to work for multiple locales, too. So I can't just hardcoded positions myself.

Previously I split this string into 4 parts and then could easily use SpannableBuilder to change colors.

HTML and CDATA are not appropriate. We need to keep the same strings for Android and iOS.

Body:
You can use SpannableString and setSpan based on your requirement.

<string name="welcome_message">Hello, %1$s! You have %2$d new messages.</string>

void setSpannableTextWithColor(TextView view, int resourceId, String username, int userColor, int messageCount, int countColor) {
    String fulltext = getString(resourceId, username, messageCount);

    view.setText(fulltext, TextView.BufferType.SPANNABLE);
    Spannable str = (Spannable) view.getText();

    int usernameIndex = fulltext.indexOf(username);
    str.setSpan(new ForegroundColorSpan(userColor), usernameIndex, usernameIndex + username.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    int countIndex = fulltext.indexOf(String.valueOf(messageCount));
    str.setSpan(new ForegroundColorSpan(countColor), countIndex, countIndex + String.valueOf(messageCount).length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

setSpannableTextWithColor(findViewById(R.id.text_view1), R.string.welcome_message, "Viktor Vostrikov", Color.GREEN, 122, Color.RED);
setSpannableTextWithColor(findViewById(R.id.text_view2), R.string.welcome_message, "Виктор Востриков", Color.GREEN, 2, Color.RED);
setSpannableTextWithColor(findViewById(R.id.text_view3), R.string.welcome_message, "فيكتور فوستريكوف", Color.GREEN, 2000, Color.RED);

Output:


问:
Interlinear text editor
Is there a way in Java to display interlinear text so you can make only the alternate (odd-numbered xor even-numbered) lines editable? And, if so, would it be possible for the user to dynamically select which of the two sets of lines is editable?

Could this be simulated with two separate panels one on top of the other where the upper one has a transparent background?

答:
Such a control hardly exists, or at least hardly is publicly available.

You can imitate it with a number of one-line input fields, styling / removing their borders to taste.

Title: Interlinear text editor


问:
Spring Boot on Google Cloud SQL - org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
When I run my program in localhost connecting remotely to Google Cloud SQL (MySQL), it works. All the necessary IAM permission are in place once the program is deployed in the Google App Engine, it causes the error:

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set. Logs Below:

Caused by: org.hibernate.HibernateException: Access to
  DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at
  org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100)
  ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]     at
  org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54)
  ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]     at
  org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
  ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]     at
  org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
  ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]     at
  org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
  ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]     at
  org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:254)
  ~[hibernate-core-5.0.12.Final.jar!/:5.0.12.Final]     ... 41 common
  frames omitted

POM File:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.myapi</groupId>
 <artifactId>myapi</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>myapi</name>
 <description>My API</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.5.9.RELEASE</version>
  <relativePath/>
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>

  <INSTANCE_CONNECTION_NAME>myapi:asia-south1:myapidb</INSTANCE_CONNECTION_NAME>
  <user>root</user>
  <password>complicated password</password>
  <database>myapidb</database>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>org.springframework.security.oauth</groupId>
   <artifactId>spring-security-oauth2</artifactId>
   <version>2.2.1.RELEASE</version>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>

  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.42</version>
  </dependency>

  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-jwt</artifactId>
  </dependency>

  <dependency>
   <groupId>com.google.cloud.sql</groupId>
   <artifactId>mysql-socket-factory</artifactId>
   <version>1.0.4</version>
  </dependency>

  <dependency>
   <groupId>com.google.cloud.tools</groupId>
   <artifactId>appengine-maven-plugin</artifactId>
   <version>1.3.2</version>
  </dependency>

  <dependency>
   <groupId>com.google.guava</groupId>
   <artifactId>guava</artifactId>
   <version>23.6-jre</version>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
  </dependency>

  <dependency>
   <groupId>com.fasterxml.jackson.datatype</groupId>
   <artifactId>jackson-datatype-jsr310</artifactId>
  </dependency>

  <dependency>
   <groupId>com.fasterxml.jackson.module</groupId>
   <artifactId>jackson-module-parameter-names</artifactId>
  </dependency>
  <dependency>
   <groupId>com.fasterxml.jackson.datatype</groupId>
   <artifactId>jackson-datatype-jdk8</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-jpa</artifactId>
  </dependency>

 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>```

答:
Add in your pom.xml:

```<code><dependency>
    <groupId>com.google.cloud.sql</groupId>
    <artifactId>mysql-socket-factory-connector-j-8</artifactId>
    <version>1.0.15</version>
</dependency>

jdbc:mysql:///<DATABASE_NAME>?cloudSqlInstance=<INSTANCE_CONNECTION_NAME>&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false&user=<USER_NAME>&password=<USER_PASSWORD>

spring:
    data:
        rest:
            base-path: /api
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
</code>```

For the driver use this new one: com.mysql.cj.jdbc.Driver ,
about the SocketFactory, it gets your instances IP address base on the provided cloudSqlInstance

Body:
Add in your pom.xml:

<dependency>
    <groupId>com.google.cloud.sql</groupId>
    <artifactId>mysql-socket-factory-connector-j-8</artifactId>
    <version>1.0.15</version>
</dependency>

jdbc:mysql:///<DATABASE_NAME>?cloudSqlInstance=<INSTANCE_CONNECTION_NAME>&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false&user=<USER_NAME>&password=<USER_PASSWORD>

spring:
    data:
        rest:
            base-path: /api
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver

For the driver use this new one: com.mysql.cj.jdbc.Driver ,
about the SocketFactory, it gets your instances IP address base on the provided cloudSqlInstance