问:
Find the average of similar dataframe columns
I have a python dataframe and some columns refer to repeated samples as below:

In [3]: df = pd.DataFrame(
   ...:     [[89, 89, 12, 34, 32],
   ...:      [788, 25, 55, 65, 55],
   ...:      [588, 23, 58, 8, 55],
   ...:      [25, 14, 45, 123, 58]],
   ...:     columns = ['sample1','sample2.1','sample2.2','sample3','sample4'],
   ...: )
In [4]: df
   sample1  sample2.1  sample2.2  sample3  sample4
0       89         89         12       34       32
1      788         25         55       65       55
2      588         23         58        8       55
3       25         14         45      123       58
```

<p>for the repeated samples, <code>sample2.1</code> and <code>sample2.2</code>, I want to remain with an average of the two, i.e</p>

<pre class="lang-py prettyprint-override"><code>   sample1  sample2_averaged  sample3  sample4
0       89              50.5       34       32
1      788              40.0       65       55
2      588              40.5        8       55
3       25              29.5      123       58
</code>```

I am thinking of using regex but I have never used them on python dataframes

答:
Try:

import re
from itertools import groupby

res=pd.DataFrame(index=df.index, columns=[])
for k,v in groupby(df.columns, key=lambda el: re.sub(r"\.[^\.]+$", "", el)):
    v=list(v)
    if(len(v)==1):
        res[k]=df[v[0]]
    else:
        res[k]=df[v].mean(axis=1)
```

<p>Outputs:</p>

<pre class="lang-py prettyprint-override"><code>>>> res

   sample1  sample2  sample3  sample4
0       89     50.5       34       32
1      788     40.0       65       55
2      588     40.5        8       55
3       25     29.5      123       58
</code>```

Body:
I have a python dataframe and some columns refer to repeated samples as below:

In [3]: df = pd.DataFrame(
   ...:     [[89, 89, 12, 34, 32],
   ...:      [788, 25, 55, 65, 55],
   ...:      [588, 23, 58, 8, 55],
   ...:      [25, 14, 45, 123, 58]],
   ...:     columns = ['sample1','sample2.1','sample2.2','sample3','sample4'],
   ...: )
In [4]: df
   sample1  sample2.1  sample2.2  sample3  sample4
0       89         89         12       34       32
1      788         25         55       65       55
2      588         23         58        8       55
3       25         14         45      123       58

for the repeated samples, sample2.1 and sample2.2, I want to remain with an average of the two, i.e

   sample1  sample2_averaged  sample3  sample4
0       89              50.5       34       32
1      788              40.0       65       55
2      588              40.5        8       55
3       25              29.5      123       58

I am thinking of using regex but I have never used them on python dataframes

Body:
Try:

import re
from itertools import groupby

res=pd.DataFrame(index=df.index, columns=[])
for k,v in groupby(df.columns, key=lambda el: re.sub(r"\.[^\.]+$", "", el)):
    v=list(v)
    if(len(v)==1):
        res[k]=df[v[0]]
    else:
        res[k]=df[v].mean(axis=1)

Outputs:

>>> res

   sample1  sample2  sample3  sample4
0       89     50.5       34       32
1      788     40.0       65       55
2      588     40.5        8       55
3       25     29.5      123       58


来源: stackexchange

问:
"The account name or password that you have entered is incorrect" Steam Api error
I got "The account name or password that you have entered is incorrect" error when trying login using this api endpoint: https://steamcommunity.com/login/dologin/

I am using the credentials I use when logging in via Steam app or Steam web, so I don't think I have a problem with my credentials.

Here code which code I use:

```<code>public bool DoLogin(string username, string password)
{
    var data = new NameValueCollection { { "username", username } };
    // First get the RSA key with which we will encrypt our password.
    string response = Fetch("https://steamcommunity.com/login/getrsakey", "POST", data, false);
    GetRsaKey rsaJson = JsonConvert.DeserializeObject<GetRsaKey>(response);

    // Validate, if we could get the rsa key.
    if (!rsaJson.success)
    {
        return false;
    }

    // RSA Encryption.
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    RSAParameters rsaParameters = new RSAParameters
    {
        Exponent = HexToByte(rsaJson.publickey_exp),
        Modulus = HexToByte(rsaJson.publickey_mod)
    };

    rsa.ImportParameters(rsaParameters);

    // Encrypt the password and convert it.
    byte[] bytePassword = Encoding.ASCII.GetBytes(password);
    byte[] encodedPassword = rsa.Encrypt(bytePassword, false);
    string encryptedBase64Password = Convert.ToBase64String(encodedPassword);

    SteamResult loginJson = null;
    CookieCollection cookieCollection;
    string steamGuardText = "";
    string steamGuardId = "";

    // Do this while we need a captcha or need email authentification. Probably you have misstyped the captcha or the SteamGaurd code if this comes multiple times.
    do
    {
        Console.WriteLine("SteamWeb: Logging In...");

        bool captcha = loginJson != null && loginJson.captcha_needed;
        bool steamGuard = loginJson != null && loginJson.emailauth_needed;

        string time = Uri.EscapeDataString(rsaJson.timestamp);

        string capGid = string.Empty;
        // Response does not need to send if captcha is needed or not.
        // ReSharper disable once MergeSequentialChecks
        if (loginJson != null && loginJson.captcha_gid != null)
        {
            capGid = Uri.EscapeDataString(loginJson.captcha_gid);
        }

        data = new NameValueCollection { { "password", encryptedBase64Password }, { "username", username } };

        // Captcha Check.
        string capText = "";
        if (captcha)
        {
            Console.WriteLine("SteamWeb: Captcha is needed.");
            System.Diagnostics.Process.Start("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid);
            Console.WriteLine("SteamWeb: Type the captcha:");
            string consoleText = Console.ReadLine();
            if (!string.IsNullOrEmpty(consoleText))
            {
                capText = Uri.EscapeDataString(consoleText);
            }
        }

        data.Add("captchagid", captcha ? capGid : "-1");
        data.Add("captcha_text", captcha ? capText : "");
        // Captcha end.
        // Added Header for two factor code.
        data.Add("twofactorcode", "");

        // Added Header for remember login. It can also set to true.
        data.Add("remember_login", "false");

        // SteamGuard check. If SteamGuard is enabled you need to enter it. Care probably you need to wait 7 days to trade.
        // For further information about SteamGuard see: https://support.steampowered.com/kb_article.php?ref=4020-ALZM-5519&l=english.
        if (steamGuard)
        {
            Console.WriteLine("SteamWeb: SteamGuard is needed.");
            Console.WriteLine("SteamWeb: Type the code:");
            string consoleText = Console.ReadLine();
            if (!string.IsNullOrEmpty(consoleText))
            {
                steamGuardText = Uri.EscapeDataString(consoleText);
            }
            steamGuardId = loginJson.emailsteamid;

            // Adding the machine name to the NameValueCollection, because it is requested by steam.
            Console.WriteLine("SteamWeb: Type your machine name:");
            consoleText = Console.ReadLine();
            var machineName = string.IsNullOrEmpty(consoleText) ? "" : Uri.EscapeDataString(consoleText);
            data.Add("loginfriendlyname", machineName != "" ? machineName : "defaultSteamBotMachine");
        }

        data.Add("emailauth", steamGuardText);
        data.Add("emailsteamid", steamGuardId);
        // SteamGuard end.

        // Added unixTimestamp. It is included in the request normally.
        var unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        // Added three "0"'s because Steam has a weird unix timestamp interpretation.
        data.Add("donotcache", unixTimestamp + "000");

        data.Add("rsatimestamp", time);

        // Sending the actual login.
        using (HttpWebResponse webResponse = Request("https://steamcommunity.com/login/dologin/", "POST", data, false))
        {
            var stream = webResponse.GetResponseStream();
            if (stream == null)
            {
                return false;
            }
            using (StreamReader reader = new StreamReader(stream))
            {
                string json = reader.ReadToEnd();
                loginJson = JsonConvert.DeserializeObject<SteamResult>(json);
                cookieCollection = webResponse.Cookies;
            }
        }
    } while (loginJson.captcha_needed || loginJson.emailauth_needed);

    // If the login was successful, we need to enter the cookies to steam.
    if (loginJson.success)
    {
        _cookies = new CookieContainer();
        foreach (Cookie cookie in cookieCollection)
        {
            _cookies.Add(cookie);
        }
        SubmitCookies(_cookies);
        return true;
    }
    else
    {
        Console.WriteLine("SteamWeb Error: " + loginJson.message);
        return false;
    }

}
</code>```

enter image description here

Is there another solution how to login to steam and get html?

答:
Ok, so I checked your encrypting and it looks fine. It is a little bit of chaos in your code so i will explain it with my:

I prefer to use RestSharp and Newton Soft JSON to do this, so a little mandatory stuff in Class body:

```<code> private IRestClient restClientTemporary;
 private string getKeysURL = "/login/getrsakey/";
 private string loginWithKey = "/login/dologin/";
</code>```

Create RestClient, and RestRequests:

```<code>restClientTemporary = new RestClient("https://steamcommunity.com");
var request = new RestRequest(getKeysURL, Method.POST);
request.AddParameter("username", "YourSteamLogin");

var resp = restClientTemporary.Execute(request);
GetRsaResult response = Newtonsoft.Json.JsonConvert.DeserializeObject<GetRsaResult>(resp.Content);

</code>```

Then i used your code as method to encrypt:

```<code>    public static string EncryptionSof(string password, GetRsaResult response)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            RSAParameters rsaParameters = new RSAParameters
            {
                Exponent = HexToByte(response.publickey_exp),
                Modulus = HexToByte(response.publickey_mod)
            };

            rsa.ImportParameters(rsaParameters);

            // Encrypt the password and convert it.
            byte[] bytePassword = Encoding.ASCII.GetBytes(password);
            byte[] encodedPassword = rsa.Encrypt(bytePassword, false);
            return Convert.ToBase64String(encodedPassword);
        }

</code>```

And then used this method:

```<code>string password = EncryptionSof("admin123/*its your steam password i think*/", response);
</code>```

Next step is make request to get login data:

```<code>var loginRequest = new RestRequest(loginWithKey);
loginRequest.AddParameter("username", "YourSteamLogin");
loginRequest.AddParameter("password", password);
loginRequest.AddParameter("rsatimestamp", response.timestamp);
loginRequest.AddParameter("remember_login", false);
//Captcha stuff if needed:
loginRequest.AddParameter("captchagid", 3086601225255895896);
loginRequest.AddParameter("captcha_text", "LHYJ2P");

</code>```

And finally execute it:

```<code>var responseFinal = restClientTemporary.Execute(loginRequest);
</code>```

In response i received everything i need in responseFinal.Content:

```<code>{
   "success":true,
   "requires_twofactor":false,
   "login_complete":true,
   "transfer_urls":[
      "https:\\/\\/store.steampowered.com\\/login\\/transfer",
      "https:\\/\\/help.steampowered.com\\/login\\/transfer"
   ],
   "transfer_parameters":{
      "steamid":"12344567898765432",
      "token_secure":"xDDDDDDDDD",
      "auth":"LOOOOOL",
      "remember_login":false
   }
}

</code>```

GetRsaResult model looks like:

```<code>    public class GetRsaResult
    {
        public bool success { get; set; }
        public string publickey_mod { get; set; }
        public string publickey_exp { get; set; }
        public string timestamp { get; set; }
        public string token_gid { get; set; }
    }
</code>```

Ah, and i forget about changing 16-string to byte[], its method found on Stackoverflow:

```<code>public static byte[] HexToByte(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                             .Where(x => x % 2 == 0)
                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }
</code>```

And you have to remember one thing You never want to send plaintext password to steam. First request /login/getrsakey/ is just only for get keys to encrypt password. Steam gives you key to encrypt your password. So, you will use your plaintext password (in my sample its admin123 ) in your program to encrypt it with keys you received from Steam.

In second request /login/dologin/ you must send encrypted password (result of EncryptionSoF method)

ContentLicense: CC BY-SA 4.0

Body:
I got "The account name or password that you have entered is incorrect" error when trying login using this api endpoint: https://steamcommunity.com/login/dologin/

I am using the credentials I use when logging in via Steam app or Steam web, so I don't think I have a problem with my credentials.

Here code which code I use:

public bool DoLogin(string username, string password)
{
    var data = new NameValueCollection { { "username", username } };
    // First get the RSA key with which we will encrypt our password.
    string response = Fetch("https://steamcommunity.com/login/getrsakey", "POST", data, false);
    GetRsaKey rsaJson = JsonConvert.DeserializeObject<GetRsaKey>(response);

    // Validate, if we could get the rsa key.
    if (!rsaJson.success)
    {
        return false;
    }

    // RSA Encryption.
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    RSAParameters rsaParameters = new RSAParameters
    {
        Exponent = HexToByte(rsaJson.publickey_exp),
        Modulus = HexToByte(rsaJson.publickey_mod)
    };

    rsa.ImportParameters(rsaParameters);

    // Encrypt the password and convert it.
    byte[] bytePassword = Encoding.ASCII.GetBytes(password);
    byte[] encodedPassword = rsa.Encrypt(bytePassword, false);
    string encryptedBase64Password = Convert.ToBase64String(encodedPassword);

    SteamResult loginJson = null;
    CookieCollection cookieCollection;
    string steamGuardText = "";
    string steamGuardId = "";

    // Do this while we need a captcha or need email authentification. Probably you have misstyped the captcha or the SteamGaurd code if this comes multiple times.
    do
    {
        Console.WriteLine("SteamWeb: Logging In...");

        bool captcha = loginJson != null && loginJson.captcha_needed;
        bool steamGuard = loginJson != null && loginJson.emailauth_needed;

        string time = Uri.EscapeDataString(rsaJson.timestamp);

        string capGid = string.Empty;
        // Response does not need to send if captcha is needed or not.
        // ReSharper disable once MergeSequentialChecks
        if (loginJson != null && loginJson.captcha_gid != null)
        {
            capGid = Uri.EscapeDataString(loginJson.captcha_gid);
        }

        data = new NameValueCollection { { "password", encryptedBase64Password }, { "username", username } };

        // Captcha Check.
        string capText = "";
        if (captcha)
        {
            Console.WriteLine("SteamWeb: Captcha is needed.");
            System.Diagnostics.Process.Start("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid);
            Console.WriteLine("SteamWeb: Type the captcha:");
            string consoleText = Console.ReadLine();
            if (!string.IsNullOrEmpty(consoleText))
            {
                capText = Uri.EscapeDataString(consoleText);
            }
        }

        data.Add("captchagid", captcha ? capGid : "-1");
        data.Add("captcha_text", captcha ? capText : "");
        // Captcha end.
        // Added Header for two factor code.
        data.Add("twofactorcode", "");

        // Added Header for remember login. It can also set to true.
        data.Add("remember_login", "false");

        // SteamGuard check. If SteamGuard is enabled you need to enter it. Care probably you need to wait 7 days to trade.
        // For further information about SteamGuard see: https://support.steampowered.com/kb_article.php?ref=4020-ALZM-5519&l=english.
        if (steamGuard)
        {
            Console.WriteLine("SteamWeb: SteamGuard is needed.");
            Console.WriteLine("SteamWeb: Type the code:");
            string consoleText = Console.ReadLine();
            if (!string.IsNullOrEmpty(consoleText))
            {
                steamGuardText = Uri.EscapeDataString(consoleText);
            }
            steamGuardId = loginJson.emailsteamid;

            // Adding the machine name to the NameValueCollection, because it is requested by steam.
            Console.WriteLine("SteamWeb: Type your machine name:");
            consoleText = Console.ReadLine();
            var machineName = string.IsNullOrEmpty(consoleText) ? "" : Uri.EscapeDataString(consoleText);
            data.Add("loginfriendlyname", machineName != "" ? machineName : "defaultSteamBotMachine");
        }

        data.Add("emailauth", steamGuardText);
        data.Add("emailsteamid", steamGuardId);
        // SteamGuard end.

        // Added unixTimestamp. It is included in the request normally.
        var unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        // Added three "0"'s because Steam has a weird unix timestamp interpretation.
        data.Add("donotcache", unixTimestamp + "000");

        data.Add("rsatimestamp", time);

        // Sending the actual login.
        using (HttpWebResponse webResponse = Request("https://steamcommunity.com/login/dologin/", "POST", data, false))
        {
            var stream = webResponse.GetResponseStream();
            if (stream == null)
            {
                return false;
            }
            using (StreamReader reader = new StreamReader(stream))
            {
                string json = reader.ReadToEnd();
                loginJson = JsonConvert.DeserializeObject<SteamResult>(json);
                cookieCollection = webResponse.Cookies;
            }
        }
    } while (loginJson.captcha_needed || loginJson.emailauth_needed);

    // If the login was successful, we need to enter the cookies to steam.
    if (loginJson.success)
    {
        _cookies = new CookieContainer();
        foreach (Cookie cookie in cookieCollection)
        {
            _cookies.Add(cookie);
        }
        SubmitCookies(_cookies);
        return true;
    }
    else
    {
        Console.WriteLine("SteamWeb Error: " + loginJson.message);
        return false;
    }

}

enter image description here

Is there another solution how to login to steam and get html?

Body:
Ok, so I checked your encrypting and it looks fine. It is a little bit of chaos in your code so i will explain it with my:

I prefer to use RestSharp and Newton Soft JSON to do this, so a little mandatory stuff in Class body:

 private IRestClient restClientTemporary;
 private string getKeysURL = "/login/getrsakey/";
 private string loginWithKey = "/login/dologin/";

Create RestClient, and RestRequests:

restClientTemporary = new RestClient("https://steamcommunity.com");
var request = new RestRequest(getKeysURL, Method.POST);
request.AddParameter("username", "YourSteamLogin");

var resp = restClientTemporary.Execute(request);
GetRsaResult response = Newtonsoft.Json.JsonConvert.DeserializeObject<GetRsaResult>(resp.Content);

Then i used your code as method to encrypt:

    public static string EncryptionSof(string password, GetRsaResult response)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            RSAParameters rsaParameters = new RSAParameters
            {
                Exponent = HexToByte(response.publickey_exp),
                Modulus = HexToByte(response.publickey_mod)
            };

            rsa.ImportParameters(rsaParameters);

            // Encrypt the password and convert it.
            byte[] bytePassword = Encoding.ASCII.GetBytes(password);
            byte[] encodedPassword = rsa.Encrypt(bytePassword, false);
            return Convert.ToBase64String(encodedPassword);
        }

And then used this method:

string password = EncryptionSof("admin123/*its your steam password i think*/", response);

Next step is make request to get login data:

var loginRequest = new RestRequest(loginWithKey);
loginRequest.AddParameter("username", "YourSteamLogin");
loginRequest.AddParameter("password", password);
loginRequest.AddParameter("rsatimestamp", response.timestamp);
loginRequest.AddParameter("remember_login", false);
//Captcha stuff if needed:
loginRequest.AddParameter("captchagid", 3086601225255895896);
loginRequest.AddParameter("captcha_text", "LHYJ2P");

And finally execute it:

var responseFinal = restClientTemporary.Execute(loginRequest);

In response i received everything i need in responseFinal.Content:

{
   "success":true,
   "requires_twofactor":false,
   "login_complete":true,
   "transfer_urls":[
      "https:\\/\\/store.steampowered.com\\/login\\/transfer",
      "https:\\/\\/help.steampowered.com\\/login\\/transfer"
   ],
   "transfer_parameters":{
      "steamid":"12344567898765432",
      "token_secure":"xDDDDDDDDD",
      "auth":"LOOOOOL",
      "remember_login":false
   }
}

GetRsaResult model looks like:

    public class GetRsaResult
    {
        public bool success { get; set; }
        public string publickey_mod { get; set; }
        public string publickey_exp { get; set; }
        public string timestamp { get; set; }
        public string token_gid { get; set; }
    }

Ah, and i forget about changing 16-string to byte[], its method found on Stackoverflow:

public static byte[] HexToByte(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                             .Where(x => x % 2 == 0)
                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }

And you have to remember one thing You never want to send plaintext password to steam. First request /login/getrsakey/ is just only for get keys to encrypt password. Steam gives you key to encrypt your password. So, you will use your plaintext password (in my sample its admin123 ) in your program to encrypt it with keys you received from Steam.

In second request /login/dologin/ you must send encrypted password (result of EncryptionSoF method)


问:
Whats the issue in reset button of JS counter?
This is the script, it work fine as you can see but this reset functionality have some issue, it turns the value to 0 but when again increase the value it starts from the last stored value, whats the issue?

This is the CSS of the counter application this we help you to run this file.

Ans this is the html file is pretty much good but just in issue with script

    var counter = 0;
    $("#box").text(counter);

    function reset() {
        counter = 0;
        $("#box").text(counter);
    }

    function inc() {
        counter = counter + 1;
        $("#box").text(counter);

    }

    function dec() {
        counter = counter - 1;
        $("#box").text(counter);

    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

body {
    height: 100vh;
}

.main {
    background: #efefef;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    padding: 30px;
}

.main h1 {
    margin-bottom: 50px;
}

#box {
    height: 50px;
    line-height: 50px;
    background: #efefef;
    text-align: center;
    margin-top: 40px;
    box-shadow: 1px 1px 5px #000;
    font-size: 30px;
}

.btn {
    display: flex;
}

.inc,
.dec {
    margin: 10px;
    padding: 10px;
    background: #fcfbfc;
    margin-top: 30px;
    text-transform: uppercase;
    cursor: pointer;
}

.reset {
    background: orange;
    padding: 5px;
    margin-top: 10px;
    cursor: pointer;
}</code>```

<!DOCTYPE html>

    <link rel="stylesheet" href="counter.css" type="text/css">

    <title>Counter</title>

Counter App

                Increase

                Decrease

            RESET

```

答:
Now i have write a new script for it. Check it out all!

    var a = 0;
    var displayValue = document.getElementById('box');

    var updateValue = function() {
        displayValue.innerHTML = a;
    };

    var add = function(valueToAdd) {
        a += valueToAdd;
        updateValue();
    };
    var sub = function(valueToAdd) {
        a -= valueToAdd;
        updateValue();
    };

    var reset = function() {
        a = 0;
        updateValue();
    };```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

body {
    height: 100vh;
}

.main {
    background: #efefef;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    padding: 30px;
}

.main h1 {
    margin-bottom: 50px;
}

#box {
    height: 50px;
    line-height: 50px;
    background: #efefef;
    text-align: center;
    margin-top: 40px;
    box-shadow: 1px 1px 5px #000;
    font-size: 30px;
}

.btn {
    display: flex;
}

.inc,
.dec {
    margin: 10px;
    padding: 10px;
    background: #fcfbfc;
    margin-top: 30px;
    text-transform: uppercase;
    cursor: pointer;
}

.reset {
    background: orange;
    padding: 5px;
    margin-top: 10px;
    cursor: pointer;
}</code>```

<!DOCTYPE html>

    <link rel="stylesheet" href="counter.css" type="text/css">

    <title>Counter</title>

Counter App

                Increment

                Decrement

            RESET

```

Body:
This is the script, it work fine as you can see but this reset functionality have some issue, it turns the value to 0 but when again increase the value it starts from the last stored value, whats the issue?

This is the CSS of the counter application this we help you to run this file.

Ans this is the html file is pretty much good but just in issue with script

    var counter = 0;
    $("#box").text(counter);

    function reset() {
        counter = 0;
        $("#box").text(counter);
    }

    function inc() {
        counter = counter + 1;
        $("#box").text(counter);

    }

    function dec() {
        counter = counter - 1;
        $("#box").text(counter);

    }

* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

body {
    height: 100vh;
}

.main {
    background: #efefef;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    padding: 30px;
}

.main h1 {
    margin-bottom: 50px;
}

#box {
    height: 50px;
    line-height: 50px;
    background: #efefef;
    text-align: center;
    margin-top: 40px;
    box-shadow: 1px 1px 5px #000;
    font-size: 30px;
}

.btn {
    display: flex;
}

.inc,
.dec {
    margin: 10px;
    padding: 10px;
    background: #fcfbfc;
    margin-top: 30px;
    text-transform: uppercase;
    cursor: pointer;
}

.reset {
    background: orange;
    padding: 5px;
    margin-top: 10px;
    cursor: pointer;
}

<!DOCTYPE html>

    <link rel="stylesheet" href="counter.css" type="text/css">

    <title>Counter</title>

Counter App

                Increase

                Decrease

            RESET

Body:
Now i have write a new script for it. Check it out all!

    var a = 0;
    var displayValue = document.getElementById('box');

    var updateValue = function() {
        displayValue.innerHTML = a;
    };

    var add = function(valueToAdd) {
        a += valueToAdd;
        updateValue();
    };
    var sub = function(valueToAdd) {
        a -= valueToAdd;
        updateValue();
    };

    var reset = function() {
        a = 0;
        updateValue();
    };

* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

body {
    height: 100vh;
}

.main {
    background: #efefef;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    padding: 30px;
}

.main h1 {
    margin-bottom: 50px;
}

#box {
    height: 50px;
    line-height: 50px;
    background: #efefef;
    text-align: center;
    margin-top: 40px;
    box-shadow: 1px 1px 5px #000;
    font-size: 30px;
}

.btn {
    display: flex;
}

.inc,
.dec {
    margin: 10px;
    padding: 10px;
    background: #fcfbfc;
    margin-top: 30px;
    text-transform: uppercase;
    cursor: pointer;
}

.reset {
    background: orange;
    padding: 5px;
    margin-top: 10px;
    cursor: pointer;
}

<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="counter.css" type="text/css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <title>Counter</title>
</head>

<body>
    <div class="main">
        <h1 style="font-family: sans-serif;">Counter App</h1>

        <div id="box">

        </div>
        <div class="btn">
            <div class="inc" id="inc" onclick="add(1);">
                Increment
            </div>
            <div class="dec" id="dec" onclick="sub(1);">
                Decrement
            </div>
        </div>

        <div class="reset" onclick="reset();">
            RESET
        </div>
    </div>

</body>
</html>


问:
How to display user's inputted text from textarea on the same page?
So here's the idea:
Someone inputs a text on my textarea:

Then upon clicking on the COUNT button, I want the inputted text to display here:

Here's my code:

HTML:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Word Counter</title>
  </head>
  <body>
    <div id="input-text-page">
      <h1>Word Counter</h1>
      <form action="">
        <textarea id="inputted-user-text" type="text" rows="22" cols="60"></textarea>
        <br />
      </form>
      <button onclick="countPage()">COUNT</button>
    </div>
    <div id="count-page" style="display: none;">
      <h1>Your Text:</h1>
      <p id=display-user-text></p>
    </div>
  </body>
  <script src="app.js"></script>
</html>
</code>```

JavaScript:

```<code>const countPage = () => {
  const inputTextPage = document.getElementById("input-text-page");
  const countPage = document.getElementById("count-page");

  inputTextPage.style.display = "none";
  countPage.style.display = "block";
};
</code>```

I really don't know how to do this, and I tried googling for the answer. So any help would be appreciated.

答:
Why are you hiding the elements? Also do you want the word count or the actual text? You change it from title to description to code

Also changed a few html elements and names.

<!DOCTYPE html>

        <title>Word Counter</title>

Word Counter

            <textarea id="input-text" type="text" rows="22" cols="60"></textarea>

            <button onclick="showResult()">COUNT</button>

Your Text:

```

<pre class="lang-js prettyprint-override"><code>const showResult = () => {
    //might wanna put these variables somewhere else
    const byId = id => document.getElementById(id);
    const textArea = byId("input-text");
    const output = byId("display-text");

    //if you want the text content and not the count just use textArea.value
    output.textContent = textArea.value.split(" ").length;
};
</code>```

Body:
So here's the idea:
Someone inputs a text on my textarea:

Then upon clicking on the COUNT button, I want the inputted text to display here:

Here's my code:

HTML:

<!DOCTYPE html>

    <title>Word Counter</title>

Word Counter

      <form action="">
        <textarea id="inputted-user-text" type="text" rows="22" cols="60"></textarea>

      </form>
      <button onclick="countPage()">COUNT</button>

Your Text:

JavaScript:

const countPage = () => {
  const inputTextPage = document.getElementById("input-text-page");
  const countPage = document.getElementById("count-page");

  inputTextPage.style.display = "none";
  countPage.style.display = "block";
};

I really don't know how to do this, and I tried googling for the answer. So any help would be appreciated.

Body:
Why are you hiding the elements? Also do you want the word count or the actual text? You change it from title to description to code

Also changed a few html elements and names.

<!DOCTYPE html>
<html>

    <head>
        <title>Word Counter</title>
    </head>

    <body>
        <div id="input-text-page">
            <h1>Word Counter</h1>
            <textarea id="input-text" type="text" rows="22" cols="60"></textarea><br>
            <button onclick="showResult()">COUNT</button>
        </div>
        <div id="count-page">
            <h1>Your Text: <span id="display-text"></span></h1>
        </div>
    </body>
    <script src="app.js"></script>

</html>

const showResult = () => {
    //might wanna put these variables somewhere else
    const byId = id => document.getElementById(id);
    const textArea = byId("input-text");
    const output = byId("display-text");

    //if you want the text content and not the count just use textArea.value
    output.textContent = textArea.value.split(" ").length;
};


问:
Incorrectly removing sprite group enemies in the right order
I have 2 sprite groups, one for the enemies, and one for the players weapon. An example of how I set up the enemy sprite group... (The weapon sprite group is done the same way)

```<code>class Bat(pygame.sprite.Sprite):
    def __init__(self, bat_x, bat_y, bat_image, bat_health, bat_immune, const, dash_counter, dash, dash_time, fly_count, fly_time):
        pygame.sprite.Sprite.__init__(self)
        self.bat_health = bat_health
        self.bat_immune = bat_immune
        self.const = const
        self.dash_counter = dash_counter
        self.dash = dash
        self.dash_time = dash_time
        self.fly_count = fly_count
        self.fly_time = fly_time
        self.image = bat_image
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)
        self.rect.topleft = (bat_x, bat_y)
        self.bat_x = bat_x
        self.bat_y = bat_y
    def update(self):
        if pygame.sprite.groupcollide(all_bats, all_sword, False, True):
            self.bat_health -= 1
        if self.bat_health == 0:
            self.kill()
        ... #Irrelevant
all_bats = pygame.sprite.Group()

def bat_create():
    bat_x = r_x*40
    bat_y = r_y*40
    bat_health = 5
    bat_immune = False
    const = 3
    dash_counter = 0
    dash = False
    dash_time = 0
    fly_count = 0
    fly_time = 0
    new_bat = Bat(bat_x, bat_y, bat_image, bat_health, bat_immune, const, dash_counter, dash, dash_time, fly_count, fly_time)
    all_bats.add(new_bat)
</code>```

When the players weapon hits a bat, regardless of which is being hit, after 5 hits the first bat to spawn is killed. I have no clue why this is happening.

答:
It looks like this is the issue:

```<code>def update(self):
    if pygame.sprite.groupcollide(all_bats, all_sword, False, True):
        self.bat_health -= 1
</code>```

groupcollide returns a list of collisions. The above code is checking all_bats against all_swords, so everything Vs everything. And if ( non-empty-list ) always returns True.

So if any bat+sword collision is made, this sprite's health is is decreased.  This is probably decreasing every bat's self.bat_health each time any bat collides.  Thus the first item created will reach zero first.

You need to check if "this sprite" is part of the collision.  It's a fairly simply change:

```<code>def update(self):
    hit_list = pygame.sprite.groupcollide(all_bats, all_sword, False, True):
    if ( self in hit_list ):
        self.bat_health -= 1
</code>```

But it's not efficient to do a groupcollide for every bat, during each bat's update().  Perhaps move the groupcollide call to somewhere outside the .update() function, and just perform these calculations once.  Pass the collision result to the sprite-update function, or suchlike.

Body:
I have 2 sprite groups, one for the enemies, and one for the players weapon. An example of how I set up the enemy sprite group... (The weapon sprite group is done the same way)

class Bat(pygame.sprite.Sprite):
    def __init__(self, bat_x, bat_y, bat_image, bat_health, bat_immune, const, dash_counter, dash, dash_time, fly_count, fly_time):
        pygame.sprite.Sprite.__init__(self)
        self.bat_health = bat_health
        self.bat_immune = bat_immune
        self.const = const
        self.dash_counter = dash_counter
        self.dash = dash
        self.dash_time = dash_time
        self.fly_count = fly_count
        self.fly_time = fly_time
        self.image = bat_image
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)
        self.rect.topleft = (bat_x, bat_y)
        self.bat_x = bat_x
        self.bat_y = bat_y
    def update(self):
        if pygame.sprite.groupcollide(all_bats, all_sword, False, True):
            self.bat_health -= 1
        if self.bat_health == 0:
            self.kill()
        ... #Irrelevant
all_bats = pygame.sprite.Group()

def bat_create():
    bat_x = r_x*40
    bat_y = r_y*40
    bat_health = 5
    bat_immune = False
    const = 3
    dash_counter = 0
    dash = False
    dash_time = 0
    fly_count = 0
    fly_time = 0
    new_bat = Bat(bat_x, bat_y, bat_image, bat_health, bat_immune, const, dash_counter, dash, dash_time, fly_count, fly_time)
    all_bats.add(new_bat)

When the players weapon hits a bat, regardless of which is being hit, after 5 hits the first bat to spawn is killed. I have no clue why this is happening.

Body:
It looks like this is the issue:

def update(self):
    if pygame.sprite.groupcollide(all_bats, all_sword, False, True):
        self.bat_health -= 1

groupcollide returns a list of collisions. The above code is checking all_bats against all_swords, so everything Vs everything. And if ( non-empty-list ) always returns True.

So if any bat+sword collision is made, this sprite's health is is decreased.  This is probably decreasing every bat's self.bat_health each time any bat collides.  Thus the first item created will reach zero first.

You need to check if "this sprite" is part of the collision.  It's a fairly simply change:

def update(self):
    hit_list = pygame.sprite.groupcollide(all_bats, all_sword, False, True):
    if ( self in hit_list ):
        self.bat_health -= 1

But it's not efficient to do a groupcollide for every bat, during each bat's update().  Perhaps move the groupcollide call to somewhere outside the .update() function, and just perform these calculations once.  Pass the collision result to the sprite-update function, or suchlike.


问:
SwiftUI ForEach -- I can't limit number of iterations
This is my first time posting but I've been using this wonderful resource for awhile. I've looked at a number of posts on here as well as the internet in general and haven't come across a solution yet (or maybe I've missed them).

I am a novice coder working on an app in SwiftUI to help users learn phrases in a couple of Alaska Native languages. One portion of this app is a "quiz" feature that asks the user match a spoken phrase with one of four photos.  I'm running into an issue with my ForEach loop. I can't pass in my array of objects, it wants a range of integers...but I can't just say ForEach(0...3) because it crashes with an 'out of range' error. I think maybe it's because my parameter is an @State variable that gets computed?

I tried changing it to a regular var but then had some compiler errors I had to deal with including changing the function calls to mutating, but then I wasn't able to use my .onAppear(perform:) because I can't mutate the struct.

I tried wrapping the ForEach portion in a "While" loop thinking maybe that would work, but that gave me a different compiler error.  I'm not sure how to proceed.

A bit of background that may help:  the 'lesson' portion of my app has a number of flashcards per category (food, clothing, etc).  Each flashcard presents the phrase, text and sounds in two languages other than English.  In the 'quiz' portion of the app the user has selected the language they want to be quizzed on, the category and the quiz style. He/she is then directed to the appropriate view with the appropriate parameters passed in. That's working great.  The reason my parameter in the ForEach is computed is the not every phrase on the flashcards works in each style of quiz or with with each language. So although I may have 15 flashcards, only 12 of them might have a valid sound-photo match in Yup'ik but all 15 might in Dena'ina. So my 'correctQuizCards' parameter has been filtered to account for that. I suspect that's part of my problem but I'm just not sure how to make this work and only show 4 photos in the quiz. The code works fine with ForEach(0..

I've shared the code below. Hopefully I did it correct.  I removed a couple of functions and variables that are irrelevant for this question (presenting an alert, etc).  Thanks in advance for any help!

```<code>

import SwiftUI

struct MatchSoundToPhotoQuizView2: View {

    @Environment(\.presentationMode) private var presentationMode

       @State private var questionNumber = 1
       @State private var correctAnswer = Int.random(in: 0...3)

    @State private var correctQuizCards = [QuizCard]()

    @State private var allQuizCards = [QuizCard]()

    var category: String
    var language: String
    // to implement later - var quizStyle: String

    var body: some View {

        VStack{
            Button(action: {
                self.presentationMode.wrappedValue.dismiss()
            }){
                Text("Dismiss this quiz")}

            Text("This is a \(language) based quiz.  Match the sound you hear with one of the pictures.")
            .layoutPriority(1)

            Button(action: {

                switch self.language {
                case "Dena'ina":
                    playSound(sound: "\(self.correctQuizCards[self.correctAnswer].denainaAudio)", type: "mp3")
                default:
                    playSound(sound: "\(self.correctQuizCards[self.correctAnswer].yupikAudio)", type: "mp3")
                }
                    }) {
                        Image(systemName: "play.circle")
                            .font(.title)
                            .padding(8)
                            .foregroundColor(.white)
                            .background(Color.blue)
                            .clipShape(Circle())
                    }

            ForEach(0..<correctQuizCards.count, id: \.self) {number in
                        Button(action: {
                            self.photoTapped(number)
                        })

                        {
                            Image("\(self.correctQuizCards[number].imageName)")
                                .resizable()
                                .renderingMode(.original)
                                .scaledToFit()
                        }
                    }
                }
                .onAppear(perform: getCards)

            }

    func getQuizCards() {
       switch language {
        case "Dena'ina":
            correctQuizCards = allQuizCards.filter{$0.soundMatchesPhotoDenaina == true && $0.category == category}
        default:
            correctQuizCards = allQuizCards.filter{$0.soundMatchesPhotoYupik == true && $0.category == category}
        }
    }

    func askQuestion() {
        correctQuizCards.shuffle()
        correctAnswer = Int.random(in: 0...3)
    }

    func getCards() {
        allQuizCards = Bundle.main.decode("\(category)Phrases.json")
        getQuizCards()
    }

}

</code>```

答:
If you can make your QuizCard conform to Hashable you don't have to use ranges.

```<code>struct QuizCard: Hashable { ...
</code>```

Then you can use correctQuizCards in a ForEach loop without using a range:

```<code>ForEach(correctQuizCards, id: \.self) { card in ...
</code>```

Note that now you don't have a number in the loop. You have a card. Which means that instead of:

```<code>Image("\(self.correctQuizCards[number].imageName)")
</code>```

you can use your card directly:

```<code>Image("\(card.imageName)")
</code>```

Body:
This is my first time posting but I've been using this wonderful resource for awhile. I've looked at a number of posts on here as well as the internet in general and haven't come across a solution yet (or maybe I've missed them).

I am a novice coder working on an app in SwiftUI to help users learn phrases in a couple of Alaska Native languages. One portion of this app is a "quiz" feature that asks the user match a spoken phrase with one of four photos.  I'm running into an issue with my ForEach loop. I can't pass in my array of objects, it wants a range of integers...but I can't just say ForEach(0...3) because it crashes with an 'out of range' error. I think maybe it's because my parameter is an @State variable that gets computed?

I tried changing it to a regular var but then had some compiler errors I had to deal with including changing the function calls to mutating, but then I wasn't able to use my .onAppear(perform:) because I can't mutate the struct.

I tried wrapping the ForEach portion in a "While" loop thinking maybe that would work, but that gave me a different compiler error.  I'm not sure how to proceed.

A bit of background that may help:  the 'lesson' portion of my app has a number of flashcards per category (food, clothing, etc).  Each flashcard presents the phrase, text and sounds in two languages other than English.  In the 'quiz' portion of the app the user has selected the language they want to be quizzed on, the category and the quiz style. He/she is then directed to the appropriate view with the appropriate parameters passed in. That's working great.  The reason my parameter in the ForEach is computed is the not every phrase on the flashcards works in each style of quiz or with with each language. So although I may have 15 flashcards, only 12 of them might have a valid sound-photo match in Yup'ik but all 15 might in Dena'ina. So my 'correctQuizCards' parameter has been filtered to account for that. I suspect that's part of my problem but I'm just not sure how to make this work and only show 4 photos in the quiz. The code works fine with ForEach(0..

I've shared the code below. Hopefully I did it correct.  I removed a couple of functions and variables that are irrelevant for this question (presenting an alert, etc).  Thanks in advance for any help!

import SwiftUI

struct MatchSoundToPhotoQuizView2: View {

    @Environment(\.presentationMode) private var presentationMode

       @State private var questionNumber = 1
       @State private var correctAnswer = Int.random(in: 0...3)

    @State private var correctQuizCards = [QuizCard]()

    @State private var allQuizCards = [QuizCard]()

    var category: String
    var language: String
    // to implement later - var quizStyle: String

    var body: some View {

        VStack{
            Button(action: {
                self.presentationMode.wrappedValue.dismiss()
            }){
                Text("Dismiss this quiz")}

            Text("This is a \(language) based quiz.  Match the sound you hear with one of the pictures.")
            .layoutPriority(1)

            Button(action: {

                switch self.language {
                case "Dena'ina":
                    playSound(sound: "\(self.correctQuizCards[self.correctAnswer].denainaAudio)", type: "mp3")
                default:
                    playSound(sound: "\(self.correctQuizCards[self.correctAnswer].yupikAudio)", type: "mp3")
                }
                    }) {
                        Image(systemName: "play.circle")
                            .font(.title)
                            .padding(8)
                            .foregroundColor(.white)
                            .background(Color.blue)
                            .clipShape(Circle())
                    }

            ForEach(0..<correctQuizCards.count, id: \.self) {number in
                        Button(action: {
                            self.photoTapped(number)
                        })

                        {
                            Image("\(self.correctQuizCards[number].imageName)")
                                .resizable()
                                .renderingMode(.original)
                                .scaledToFit()
                        }
                    }
                }
                .onAppear(perform: getCards)

            }

    func getQuizCards() {
       switch language {
        case "Dena'ina":
            correctQuizCards = allQuizCards.filter{$0.soundMatchesPhotoDenaina == true && $0.category == category}
        default:
            correctQuizCards = allQuizCards.filter{$0.soundMatchesPhotoYupik == true && $0.category == category}
        }
    }

    func askQuestion() {
        correctQuizCards.shuffle()
        correctAnswer = Int.random(in: 0...3)
    }

    func getCards() {
        allQuizCards = Bundle.main.decode("\(category)Phrases.json")
        getQuizCards()
    }

}

Body:
If you can make your QuizCard conform to Hashable you don't have to use ranges.

struct QuizCard: Hashable { ...

Then you can use correctQuizCards in a ForEach loop without using a range:

ForEach(correctQuizCards, id: \.self) { card in ...

Note that now you don't have a number in the loop. You have a card. Which means that instead of:

Image("\(self.correctQuizCards[number].imageName)")

you can use your card directly:

Image("\(card.imageName)")


问:
How can I shorten these repetitive while/try/except/else input blocks?
I am trying to make an exchange app and I am trying to make it shorter (mostly by changing those whiles). </p>

```<code>def key_check(currency):
    import re
    rates = website["rates"]
    rates.update({"EUR": 1})
    rates = json.dumps(rates)
    if not re.search(currency, rates):
        raise Exception(
            "This is not a currency")
    else:
        rates = json.loads(rates)

while True:
    try:
        yourCurrency = input("Which currency do you have?: ").upper()
        key_check(yourCurrency)
    except Exception as error:
        print(error)
    else:
        break

while True:
    try:
        yourMoney = float(input("How much money do you have?: "))
    except:
        print("This is not a float!")
    else:
        break

while True:
    try:
        exchangeCurrency = input(
            "Which currency would you like to buy?: ").upper()
        key_check(exchangeCurrency)
    except Exception as error:
        print(error)
    else:
        break
</code>```

答:
The following code doesn't work exactly like the provided sample, but very similar (the difference is in what it prints in case of an exception)

# Always place your imports at the very top of file
import re
from traceback import format_exc

def key_check(currency):
    rates = website["rates"]
    rates.update({"EUR": 1})
    rates = json.dumps(rates)
    if not re.search(currency, rates):
        raise Exception("This is not a currency")
    else:
        rates = json.loads(rates)

    # Make key_check return the given value back to make our life easier :)
    return currency

def want_input(s, handler=None):
    if handler is None:
        handler = lambda x: x

    while True:
        try:
            var = handler(input(s))
        #except KeyboardInterrupt:
            #print("In your place I would handle KeyboardInterrupt separately and make it stop the execution of the program")
        except:
            print(format_exc())
        else:
            return var

yourCurrency = want_input("Which currency do you have?: ", lambda x: key_check(x.upper()))

yourMoney = want_input("How much money do you have?: ", lambda x: float(x))

exchangeCurrency = want_input("Which currency would you like to buy?: ", lambda x: key_check(x.upper()))
```

(didn't run it, but must work)

Body:
I am trying to make an exchange app and I am trying to make it shorter (mostly by changing those whiles).

def key_check(currency):
    import re
    rates = website["rates"]
    rates.update({"EUR": 1})
    rates = json.dumps(rates)
    if not re.search(currency, rates):
        raise Exception(
            "This is not a currency")
    else:
        rates = json.loads(rates)

while True:
    try:
        yourCurrency = input("Which currency do you have?: ").upper()
        key_check(yourCurrency)
    except Exception as error:
        print(error)
    else:
        break

while True:
    try:
        yourMoney = float(input("How much money do you have?: "))
    except:
        print("This is not a float!")
    else:
        break

while True:
    try:
        exchangeCurrency = input(
            "Which currency would you like to buy?: ").upper()
        key_check(exchangeCurrency)
    except Exception as error:
        print(error)
    else:
        break

Body:
The following code doesn't work exactly like the provided sample, but very similar (the difference is in what it prints in case of an exception)

# Always place your imports at the very top of file
import re
from traceback import format_exc

def key_check(currency):
    rates = website["rates"]
    rates.update({"EUR": 1})
    rates = json.dumps(rates)
    if not re.search(currency, rates):
        raise Exception("This is not a currency")
    else:
        rates = json.loads(rates)

    # Make key_check return the given value back to make our life easier :)
    return currency

def want_input(s, handler=None):
    if handler is None:
        handler = lambda x: x

    while True:
        try:
            var = handler(input(s))
        #except KeyboardInterrupt:
            #print("In your place I would handle KeyboardInterrupt separately and make it stop the execution of the program")
        except:
            print(format_exc())
        else:
            return var

yourCurrency = want_input("Which currency do you have?: ", lambda x: key_check(x.upper()))

yourMoney = want_input("How much money do you have?: ", lambda x: float(x))

exchangeCurrency = want_input("Which currency would you like to buy?: ", lambda x: key_check(x.upper()))

(didn't run it, but must work)


问:
laravel one to many relationship , not showing data
i have two classes named academy and pitch
the pitch can have many academies and the acdemy belongs to one pitch
in my show view of the academy i can see the pitch name using this

```<code>{{$academy->pitch->name}}
</code>```

but in reverse it sont work , i mean i want to list names of acadmies in each pitch

my models

academy model

```<code>public function pitch(){
        return $this->belongsTo(Pitch::class ,'pitch_id');
    }
</code>```

pitch model

```<code>public function academies()
    {
        return $this->hasMany(Academy::class);
    }
</code>```

i tried this but it dont work

```<code> @foreach ($pitch->academies as $academy)
                        <li></li>
                    @endforeach
</code>```

the error

```<code>Column not found: 1054 Unknown column 'academies.pitch_pitch_id' in 'where clause' (SQL: select * from `academies` where `academies`.`pitch_pitch_id` = 5 and `academies`.`pitch_pitch_id` is not null)
</code>```

答:
```<code>public function academies()
    {
        return $this->hasMany(Academy::class, 'academy_id');
    }

 public function pitch(){
        return $this->belongsTo(Pitch::class ,'pitch_id');
    }
</code>```

in my view

```<code>@foreach ($pitch->academies as $academy)

                    {{$academy->name}}
                    @endforeach
</code>```

i works now

Body:
i have two classes named academy and pitch
the pitch can have many academies and the acdemy belongs to one pitch
in my show view of the academy i can see the pitch name using this

{{$academy->pitch->name}}

but in reverse it sont work , i mean i want to list names of acadmies in each pitch

my models

academy model

public function pitch(){
        return $this->belongsTo(Pitch::class ,'pitch_id');
    }

pitch model

public function academies()
    {
        return $this->hasMany(Academy::class);
    }

i tried this but it dont work

 @foreach ($pitch->academies as $academy)

                    @endforeach

the error

Column not found: 1054 Unknown column 'academies.pitch_pitch_id' in 'where clause' (SQL: select * from `academies` where `academies`.`pitch_pitch_id` = 5 and `academies`.`pitch_pitch_id` is not null)

Body:
public function academies()
    {
        return $this->hasMany(Academy::class, 'academy_id');
    }

 public function pitch(){
        return $this->belongsTo(Pitch::class ,'pitch_id');
    }

in my view

@foreach ($pitch->academies as $academy)

                    {{$academy->name}}
                    @endforeach

i works now


问:
How in R, can you create new columns using existing columns as variables?
I am new to R, and so would greatly appreciate more explanation for any code you might have to help solve my issue.

I have a data.frame with groups of columns related to each other and I want to perform a calculation on each of those many groups to get new output columns. For example, many biological replicates in an experiment where I want to perform the calculations on each replicate independently before collapsing them.

I know I could use mutate in dplyr to create new columns, but I am not sure how to do this in a loop or how to use lapply type strategy to avoid re-tying the columns names each time. My biggest issue is understanding how to convert the column names into something usable by one of these strategies.

For example:

```<code>> A.1 <- c(11,12,13,4,15,6,17,18)
> A.2 <- c(2,4,5,5,19,7,5,1)
>
> B.1 <- c (3,4,5,1,31,76,13,70)
> B.2 <- c (10,9,8,15,31,12,13,12)
>
> C.1 <- c(1,2,3,4,5,6,7,8)
> C.2 <- c(2,4,5,8,10,12,15,18)
>
> df <- data.frame(A.1, A.2, B.1, B.2, C.1, C.2)
>
> df
A.1 A.2 B.1 B.2 C.1 C.2
1  11   2   3  10   1   2
2  12   4   4   9   2   4
3  13   5   5   8   3   5
4   4   5   1  15   4   8
5  15  19  31  31   5  10
6   6   7  76  12   6  12
7  17   5  13  13   7  15
8  18   1  70  12   8  18
>
</code>```

Where I want to create new columns where A.new = A.1/A.2, B.new = B.1/B.2 etc. without typing out each column name explicitly. Also note the "A" and "B" are really character strings, so typing all of them would be very messy and time consuming.

Something like this, but a general case for many column groups:

```<code>> df <- df %>% mutate(A.new = A.1/A.2)
> df <- df %>% mutate(B.new = B.1/B.2)
> df <- df %>% mutate(C.new = C.1/C.2)
>
> df
 A.1 A.2 B.1 B.2 C.1 C.2      A.new      B.new     C.new
1  11   2   3  10   1   2  5.5000000 0.30000000 0.5000000
2  12   4   4   9   2   4  3.0000000 0.44444444 0.5000000
3  13   5   5   8   3   5  2.6000000 0.62500000 0.6000000
4   4   5   1  15   4   8  0.8000000 0.06666667 0.5000000
5  15  19  31  31   5  10  0.7894737 1.00000000 0.5000000
6   6   7  76  12   6  12  0.8571429 6.33333333 0.5000000
7  17   5  13  13   7  15  3.4000000 1.00000000 0.4666667
8  18   1  70  12   8  18 18.0000000 5.83333333 0.4444444
>
</code>```

I don't see the answer to my question on here already, but if you could point me to existing answers that would be much appreciated! I am currently thinking about the column names as containing the variable, but maybe that is not the correct way to approach this (R is also the first programming language I am learning) and so my searches for answers haven't yielded much yet.

Thank you for your guidance in advance!

Body:
I am new to R, and so would greatly appreciate more explanation for any code you might have to help solve my issue.

I have a data.frame with groups of columns related to each other and I want to perform a calculation on each of those many groups to get new output columns. For example, many biological replicates in an experiment where I want to perform the calculations on each replicate independently before collapsing them.

I know I could use mutate in dplyr to create new columns, but I am not sure how to do this in a loop or how to use lapply type strategy to avoid re-tying the columns names each time. My biggest issue is understanding how to convert the column names into something usable by one of these strategies.

For example:

> A.1 <- c(11,12,13,4,15,6,17,18)
> A.2 <- c(2,4,5,5,19,7,5,1)
>
> B.1 <- c (3,4,5,1,31,76,13,70)
> B.2 <- c (10,9,8,15,31,12,13,12)
>
> C.1 <- c(1,2,3,4,5,6,7,8)
> C.2 <- c(2,4,5,8,10,12,15,18)
>
> df <- data.frame(A.1, A.2, B.1, B.2, C.1, C.2)
>
> df
A.1 A.2 B.1 B.2 C.1 C.2
1  11   2   3  10   1   2
2  12   4   4   9   2   4
3  13   5   5   8   3   5
4   4   5   1  15   4   8
5  15  19  31  31   5  10
6   6   7  76  12   6  12
7  17   5  13  13   7  15
8  18   1  70  12   8  18
>

Where I want to create new columns where A.new = A.1/A.2, B.new = B.1/B.2 etc. without typing out each column name explicitly. Also note the "A" and "B" are really character strings, so typing all of them would be very messy and time consuming.

Something like this, but a general case for many column groups:

> df <- df %>% mutate(A.new = A.1/A.2)
> df <- df %>% mutate(B.new = B.1/B.2)
> df <- df %>% mutate(C.new = C.1/C.2)
>
> df
 A.1 A.2 B.1 B.2 C.1 C.2      A.new      B.new     C.new
1  11   2   3  10   1   2  5.5000000 0.30000000 0.5000000
2  12   4   4   9   2   4  3.0000000 0.44444444 0.5000000
3  13   5   5   8   3   5  2.6000000 0.62500000 0.6000000
4   4   5   1  15   4   8  0.8000000 0.06666667 0.5000000
5  15  19  31  31   5  10  0.7894737 1.00000000 0.5000000
6   6   7  76  12   6  12  0.8571429 6.33333333 0.5000000
7  17   5  13  13   7  15  3.4000000 1.00000000 0.4666667
8  18   1  70  12   8  18 18.0000000 5.83333333 0.4444444
>

I don't see the answer to my question on here already, but if you could point me to existing answers that would be much appreciated! I am currently thinking about the column names as containing the variable, but maybe that is not the correct way to approach this (R is also the first programming language I am learning) and so my searches for answers haven't yielded much yet.

Thank you for your guidance in advance!

Body:
We can do this much more easily with split.default

lst1 <- lapply(split.default(df, sub("\\.\\d+$", "", names(df))),
        function(x) x[[1]]/x[[2]])
df[paste0(names(lst1), ".new")] <- lst1
df
#  A.1 A.2 B.1 B.2 C.1 C.2      A.new      B.new     C.new
#1  11   2   3  10   1   2  5.5000000 0.30000000 0.5000000
#2  12   4   4   9   2   4  3.0000000 0.44444444 0.5000000
#3  13   5   5   8   3   5  2.6000000 0.62500000 0.6000000
#4   4   5   1  15   4   8  0.8000000 0.06666667 0.5000000
#5  15  19  31  31   5  10  0.7894737 1.00000000 0.5000000
#6   6   7  76  12   6  12  0.8571429 6.33333333 0.5000000
#7  17   5  13  13   7  15  3.4000000 1.00000000 0.4666667
#8  18   1  70  12   8  18 18.0000000 5.83333333 0.4444444

NOTE: We don't need any packages and can be done much easily

data

df <- structure(list(A.1 = c(11, 12, 13, 4, 15, 6, 17, 18), A.2 = c(2,
4, 5, 5, 19, 7, 5, 1), B.1 = c(3, 4, 5, 1, 31, 76, 13, 70), B.2 = c(10,
9, 8, 15, 31, 12, 13, 12), C.1 = c(1, 2, 3, 4, 5, 6, 7, 8), C.2 = c(2,
4, 5, 8, 10, 12, 15, 18)), class = "data.frame", row.names = c(NA,
-8L))


问:
Tic tac toe Minimax Algorithm Having Weird Behavior (C++)
The other day, I wrote a console game of Tic-Tac-Toe in c++ for my son. He wanted me to add a computer, and I ended us using the minimax algorithm for the first time. I did some quick testing, but really just gave my laptop to my son as soon as it was printing stuff, who played with it for a couple minuets. I looked over his sholder once or twice, and noticed that it wasn't playing optimally, iv'e been trying to debug it, but I can't see where it goes wrong. I tried getting rid of alpha beta prunning, but that did not change anything.

For context, on the board the computer is -1, blank is 0, and the player is 1.

Here is the minimax function:

```<code>int minimax(int board[9], int depth, int alpha, int beta, bool isMaxizimaizingPlayer)
{
    bool found = false;
    for (int i = 0; i < 9; i++)
    {
        if (board[i] == 0)
        {
            found = true;
        }
    }
    if (!found)
    {
        return eval(board);
    }
    if (depth == 0 || eval(board) != 0)
    {
        return eval(board);
    }
    if (isMaxizimaizingPlayer)
    {
        int maxEval = -2;
        for (int spot = 0; spot < 9; spot++)
        {
            if (board[spot] == 0)
            {
                board[spot] = 1;
                int e = minimax(board, depth - 1, alpha, beta, false);
                if (e > maxEval)
                {
                    maxEval = e;
                }
                //if (beta < alpha)
                //{
                //  break;
                //}
                board[spot] = 0;
            }
        }
        return maxEval;
    }
    else {
        int minEval = 2;
        for (int spot = 0; spot < 9; spot++)
        {
            if (board[spot] == 0)
            {
                board[spot] = -1;
                int e = minimax(board, depth - 1, alpha, beta, true);
                if (e < minEval)
                {
                    minEval = e;
                }
                //if (beta < alpha)
                //{
                //  break;
                //}
                board[spot] = 0;
            }
        }
        return minEval;
    }
}
</code>```

To be compleate, here is my eval function:

```<code>int eval(int board[9])
{
    /*horizontial*/
    for (int i = 0; i < 3; i++)
    {
        if (board[i * 3] == board[i * 3 + 1] && board[i * 3 + 2] == board[i * 3] && board[i * 3] != 0)
        {
            return board[i * 3];
        }
    }
    /*vertical*/
    for (int i = 0; i < 3; i++)
    {
        if (board[i] == board[i + 3] && board[i] == board[i + 6] && board[i] != 0)
        {
            return board[i];
        }
    }
    /*Both diags*/
    if (board[4] != 0) {
        if (board[0] == board[4] && board[0] == board[8])
        {
            return board[4];
        }
        if (board[2] == board[4] && board[4] == board[6])
        {
            return board[4];
        }
    }
    return 0;
}

</code>```

And here is the inital call:

```<code>            int spot = 0;
            int minEval = 2;
            for (int i = 0; i < 9; i++)
            {
                if (board[i] == 0)
                {
                    board[i] = -1;
                    int score = minimax(board, 3, -2, 2, false);
                    if (score < minEval) {
                        minEval = score;
                        spot = i;
                    }
                    board[i] = 0;
                }
            }
            std::cout << "The computer went in spot " << spot + 1 << std::endl;
            board[spot] = -1;
            printBoard(board);
</code>```

答: It looks like you only call minimax with a depth of three, so the algorithm will only look up to three moves ahead, if you want optimal play you need to set the depth to > 9, so that the agent is always looking ahead to the end of the game.</p>

Body:
The other day, I wrote a console game of Tic-Tac-Toe in c++ for my son. He wanted me to add a computer, and I ended us using the minimax algorithm for the first time. I did some quick testing, but really just gave my laptop to my son as soon as it was printing stuff, who played with it for a couple minuets. I looked over his sholder once or twice, and noticed that it wasn't playing optimally, iv'e been trying to debug it, but I can't see where it goes wrong. I tried getting rid of alpha beta prunning, but that did not change anything.

For context, on the board the computer is -1, blank is 0, and the player is 1.

Here is the minimax function:

int minimax(int board[9], int depth, int alpha, int beta, bool isMaxizimaizingPlayer)
{
    bool found = false;
    for (int i = 0; i < 9; i++)
    {
        if (board[i] == 0)
        {
            found = true;
        }
    }
    if (!found)
    {
        return eval(board);
    }
    if (depth == 0 || eval(board) != 0)
    {
        return eval(board);
    }
    if (isMaxizimaizingPlayer)
    {
        int maxEval = -2;
        for (int spot = 0; spot < 9; spot++)
        {
            if (board[spot] == 0)
            {
                board[spot] = 1;
                int e = minimax(board, depth - 1, alpha, beta, false);
                if (e > maxEval)
                {
                    maxEval = e;
                }
                //if (beta < alpha)
                //{
                //  break;
                //}
                board[spot] = 0;
            }
        }
        return maxEval;
    }
    else {
        int minEval = 2;
        for (int spot = 0; spot < 9; spot++)
        {
            if (board[spot] == 0)
            {
                board[spot] = -1;
                int e = minimax(board, depth - 1, alpha, beta, true);
                if (e < minEval)
                {
                    minEval = e;
                }
                //if (beta < alpha)
                //{
                //  break;
                //}
                board[spot] = 0;
            }
        }
        return minEval;
    }
}

To be compleate, here is my eval function:

int eval(int board[9])
{
    /*horizontial*/
    for (int i = 0; i < 3; i++)
    {
        if (board[i * 3] == board[i * 3 + 1] && board[i * 3 + 2] == board[i * 3] && board[i * 3] != 0)
        {
            return board[i * 3];
        }
    }
    /*vertical*/
    for (int i = 0; i < 3; i++)
    {
        if (board[i] == board[i + 3] && board[i] == board[i + 6] && board[i] != 0)
        {
            return board[i];
        }
    }
    /*Both diags*/
    if (board[4] != 0) {
        if (board[0] == board[4] && board[0] == board[8])
        {
            return board[4];
        }
        if (board[2] == board[4] && board[4] == board[6])
        {
            return board[4];
        }
    }
    return 0;
}

And here is the inital call:

            int spot = 0;
            int minEval = 2;
            for (int i = 0; i < 9; i++)
            {
                if (board[i] == 0)
                {
                    board[i] = -1;
                    int score = minimax(board, 3, -2, 2, false);
                    if (score < minEval) {
                        minEval = score;
                        spot = i;
                    }
                    board[i] = 0;
                }
            }
            std::cout << "The computer went in spot " << spot + 1 << std::endl;
            board[spot] = -1;
            printBoard(board);


问:
return type deduction of recursive function
Recently, I read Barry's answer to this question Recursive lambda functions in C++11:

template <class F>
struct y_combinator {
    F f; // the lambda will be stored here

    // a forwarding operator():
    template <class... Args>
    decltype(auto) operator()(Args&&... args) const {
        // we pass ourselves to f, then the arguments.
        // [edit: Barry] pass in std::ref(*this) instead of *this
        return f(std::ref(*this), std::forward<Args>(args)...);
    }
};
// deduction guide
template <class F> y_combinator(F) -> y_combinator<F>;
```

<p>Basically, <code>y_combinator</code> allows one to write a recursive lambda expression more easily (e.g. without having to delcare a <code>std::function</code>). When I played with <code>y_combinator</code>, I found something strange:</p>

<pre class="lang-cpp prettyprint-override"><code>int main() {
   // Case #1 compiles fine
   y_combinator{[](auto g, int a, int b) {
      if (a >= b) return 0;
      return 1 + g(a + 1, b);
    }}(1, 2);

    // Case #2 deos not compile
    y_combinator{[](auto g, int a) {
      if (a >= 0) return 0;
      return 1 + g(a + 1);
    }}(1);

    // Case #3 compiles just fine
    y_combinator{[](auto g, int a)->int {
      if (a >= 0) return 0;
      return 1 + g(a + 1);
    }}(1);
}
</code>```

Case #1 and Case #3 compile fine while Case #2 does not compile. I got the same result with Clang 10.0 and GCC 9.3.
For Case #2, Clang says

```<code>prog.cc:25:18: error: no matching function for call to object of type 'std::__1::reference_wrapper<const y_combinator<(lambda at prog.cc:23:18)> >'
      return 1 + g(a + 1);
                 ^
</code>```

How is the different results between Case #1 and Case #2?

Why does the trailing return type make a difference between Case #2 and Case #3?

You can check it on Wandbox.

答:
The difference is that in #1 the initial and recursive calls to y_combinator have different argument types, whereas in #2 they have the same argument types (including value category).

In #1, the initial arguments (1, 2) are both int prvalue, whereas the recursive arguments g(a + 1, b) are respectively int prvalue and int lvalue. Meanwhile in #2 the initial argument (1) and recursive argument g(a + 1) are both int prvalue. You can check that making a change to #1 such that both recursive arguments are int prvalue (e.g. calling g(a + 1, b + 0)) will break it, while changing #2 to pass int lvalue as the recursive argument (e.g. g(++a)) will fix it.

This means that the return type deduction for the initial call is self-referential, in that it depends on the type of precisely the same call to y_combinator<lambda #2>::operator()<int>(int&&) (whereas in #1 the initial call to y_combinator<lambda #1>::operator()<int, int>(int&&, int&&) depends on y_combinator<lambda #1>::operator()<int, int&>(int&&, int&)).

Supplying the return type explicitly as in #3 means there is no self-referential type deduction, and everything is fine.

You might ask, why is #1 OK given that the recursive case is still self-referential (noting that all 3 compilers agree). This is because once we can get into the lambda's own type deduction, [dcl.spec.auto]/10 kicks in and the first return statement gives a return type to the lambda, so when it recursively calls g, that type deduction has already succeeded.

A diagram usually helps:

y_combinator<lambda #1>::operator()<int, int>
 -> forwards to [lambda #1]::operator()<y_combinator<lambda #1>> {
     has return type int by [dcl.spec.auto]/10
     calls y_combinator<lambda #1>::operator()<int, int&> (not previously seen)
      -> forwards to [lambda #1]::operator()<y_combinator<lambda #1>>
      -> already deduced to return int
      -> this is OK
 }

y_combinator<lambda #2>::operator()<int>
  -> forwards to [lambda #2]::operator()<y_combinator<lambda #2>> {
     has return type int by [dcl.spec.auto]/10
     calls y_combinator<lambda #2>::operator()<int>
     but y_combinator<lambda #2>::operator()<int> has incomplete return type at this point
      -> error
  }
```

<p>A fix (thanks to @aschepler) is to remember the argument lists that the lambda has been called with already, and provide a "clean" wrapper whose functional call operator(s) are not yet undergoing return type deduction for each new set of argument types:</p>

```template<class...> struct typelist {};

template<class T, class... Ts>
constexpr bool any_same = (std::is_same_v<T, Ts> || ...);

template <class F>
struct y_combinator {
    template <class... TLs>
    struct ref {
        y_combinator& self;
        template <class... Args>
        decltype(auto) operator()(Args&&... args) const {
            using G = std::conditional_t<
                any_same<typelist<Args...>, TLs...>,
                ref<TLs...>,
                ref<TLs..., typelist<Args...>>>;
            return self.f(G{self}, std::forward<Args>(args)...);
        }
    };
    F f;
    template <class... Args>
    decltype(auto) operator()(Args&&... args) {
        return ref<>{*this}(std::forward<Args>(args)...);
    }
};
template <class F> y_combinator(F) -> y_combinator<F>;
```

Body:
Recently, I read Barry's answer to this question Recursive lambda functions in C++11:

template <class F>
struct y_combinator {
    F f; // the lambda will be stored here

    // a forwarding operator():
    template <class... Args>
    decltype(auto) operator()(Args&&... args) const {
        // we pass ourselves to f, then the arguments.
        // [edit: Barry] pass in std::ref(*this) instead of *this
        return f(std::ref(*this), std::forward<Args>(args)...);
    }
};
// deduction guide
template <class F> y_combinator(F) -> y_combinator<F>;

Basically, y_combinator allows one to write a recursive lambda expression more easily (e.g. without having to delcare a std::function). When I played with y_combinator, I found something strange:

int main() {
   // Case #1 compiles fine
   y_combinator{[](auto g, int a, int b) {
      if (a >= b) return 0;
      return 1 + g(a + 1, b);
    }}(1, 2);

    // Case #2 deos not compile
    y_combinator{[](auto g, int a) {
      if (a >= 0) return 0;
      return 1 + g(a + 1);
    }}(1);

    // Case #3 compiles just fine
    y_combinator{[](auto g, int a)->int {
      if (a >= 0) return 0;
      return 1 + g(a + 1);
    }}(1);
}

Case #1 and Case #3 compile fine while Case #2 does not compile. I got the same result with Clang 10.0 and GCC 9.3.
For Case #2, Clang says

prog.cc:25:18: error: no matching function for call to object of type 'std::__1::reference_wrapper<const y_combinator<(lambda at prog.cc:23:18)> >'
      return 1 + g(a + 1);
                 ^

How is the different results between Case #1 and Case #2?

Why does the trailing return type make a difference between Case #2 and Case #3?

You can check it on Wandbox.

Body:
The difference is that in #1 the initial and recursive calls to y_combinator have different argument types, whereas in #2 they have the same argument types (including value category).

In #1, the initial arguments (1, 2) are both int prvalue, whereas the recursive arguments g(a + 1, b) are respectively int prvalue and int lvalue. Meanwhile in #2 the initial argument (1) and recursive argument g(a + 1) are both int prvalue. You can check that making a change to #1 such that both recursive arguments are int prvalue (e.g. calling g(a + 1, b + 0)) will break it, while changing #2 to pass int lvalue as the recursive argument (e.g. g(++a)) will fix it.

This means that the return type deduction for the initial call is self-referential, in that it depends on the type of precisely the same call to y_combinator<lambda #2>::operator()<int>(int&&) (whereas in #1 the initial call to y_combinator<lambda #1>::operator()<int, int>(int&&, int&&) depends on y_combinator<lambda #1>::operator()<int, int&>(int&&, int&)).

Supplying the return type explicitly as in #3 means there is no self-referential type deduction, and everything is fine.

You might ask, why is #1 OK given that the recursive case is still self-referential (noting that all 3 compilers agree). This is because once we can get into the lambda's own type deduction, [dcl.spec.auto]/10 kicks in and the first return statement gives a return type to the lambda, so when it recursively calls g, that type deduction has already succeeded.

A diagram usually helps:

y_combinator<lambda #1>::operator()<int, int>
 -> forwards to [lambda #1]::operator()<y_combinator<lambda #1>> {
     has return type int by [dcl.spec.auto]/10
     calls y_combinator<lambda #1>::operator()<int, int&> (not previously seen)
      -> forwards to [lambda #1]::operator()<y_combinator<lambda #1>>
      -> already deduced to return int
      -> this is OK
 }

y_combinator<lambda #2>::operator()<int>
  -> forwards to [lambda #2]::operator()<y_combinator<lambda #2>> {
     has return type int by [dcl.spec.auto]/10
     calls y_combinator<lambda #2>::operator()<int>
     but y_combinator<lambda #2>::operator()<int> has incomplete return type at this point
      -> error
  }

A fix (thanks to @aschepler) is to remember the argument lists that the lambda has been called with already, and provide a "clean" wrapper whose functional call operator(s) are not yet undergoing return type deduction for each new set of argument types:

template<class...> struct typelist {};

template<class T, class... Ts>
constexpr bool any_same = (std::is_same_v<T, Ts> || ...);

template <class F>
struct y_combinator {
    template <class... TLs>
    struct ref {
        y_combinator& self;
        template <class... Args>
        decltype(auto) operator()(Args&&... args) const {
            using G = std::conditional_t<
                any_same<typelist<Args...>, TLs...>,
                ref<TLs...>,
                ref<TLs..., typelist<Args...>>>;
            return self.f(G{self}, std::forward<Args>(args)...);
        }
    };
    F f;
    template <class... Args>
    decltype(auto) operator()(Args&&... args) {
        return ref<>{*this}(std::forward<Args>(args)...);
    }
};
template <class F> y_combinator(F) -> y_combinator<F>;


问:
Does anyone have an example of how to plot an mplfinance candlestick chart to a tkinter gui?
I can make many kinds of plots to tkinter canvases using matplotlib, but I'm unable to figure out how to do this using the mplfinance plot types, in which as I understand plotting is rather automated and high level such that the call 'owns' fig and ax. Has anyone had any luck getting these excellent plots to appear in tkinter guis?  </p>

答:
Daniel Goldfarb, in the latest release of mplfinance has added functionality (returnfig = True) to return the plot elements as objects. The call for, say, a candlestick chart for use with tkinter looks as follows:

```<code>    fig, ax = mplfinance.plot(
            <dataframe>,
            type='candle',
            style='charles',
            title=<plot title>,
            ylabel='Price ($)',
            volume=True,
            ylabel_lower='Shares\nTraded',
            show_nontrading=True,
            returnfig = True
            )
</code>```

It works beautifully.

Body:
Daniel Goldfarb, in the latest release of mplfinance has added functionality (returnfig = True) to return the plot elements as objects. The call for, say, a candlestick chart for use with tkinter looks as follows:

    fig, ax = mplfinance.plot(
            <dataframe>,
            type='candle',
            style='charles',
            title=<plot title>,
            ylabel='Price ($)',
            volume=True,
            ylabel_lower='Shares\nTraded',
            show_nontrading=True,
            returnfig = True
            )

It works beautifully.


问:
Unable to display parent table with child table in a for loop with template tagging in Django
I want to display an unordered list of NBA teams from my teams table database. Within each team, I want an ordered list of players on that team. So basically I want to produce a list of all objects from my parent table and for each object from the parent table I want a list of all objects from the child table related the parent table. I understand that the problem is methods are not allowed in template tagging, so 'team.players_set.all()' would not be allowed. How else can I get the results that I want?</p>

```<code>class Teams(models.Model):
    name = models.CharField(max_length=20, unique=True)
    num_of_plyrs = models.IntegerField()

    def __str__(self):
        return f"{self.name} have {self.num_of_plyrs} players."

    class Meta:
        verbose_name_plural = "Teams"

class Players(models.Model):
    name = models.CharField(max_length=20)
    team = models.ForeignKey(Teams, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.name} plays for {self.team}"

    class Meta:
        verbose_name_plural = 'Players'
__________________________________________________________________________________

def teams(request):
teams = Teams.objects.all()
context = {'teams': teams}
return render(request, 'one_app/teams.html', context)
__________________________________________________________________________________

<h3>NBA Teams</h3>
<ul>
  {% for team in teams %}
    <li>
  <p>Team: {{ team.name }}</p>
  <p>Number of players: {{ team.num_of_plyrs }}</p>
  <ol>
  {% for plyr in team.players_set.all() %}
    <li>{{ plyr.name }}</li>
  {% endfor %}
  </ol>
</li>
  {% empty %}
    <li>There are no teams listed.</li>
  {% endfor %}
</ul>
</code>```

答:
One way to achieve this is:

```<code>class PlayersView(ListView):
    model = Team
    ...

    def get_queryset(self, **kwargs):
        teams = []
        queryset = super().get_queryset()
        for team in queryset:
             players = team.player_set.all()
             for player in players:
                 teams.append([team, (player.name, ...)]
        return teams
</code>```

And in your template:

```<code> {% for team, players in teams %}
     ...
     {% for player in players %}
           ...
     {% endfor %}
 {% endfor %}
</code>```

ALTERNATIVE

If you know this is something you might be using a lot and to simplify your view, you can also create a manager:

```<code>from your_app.managers import TeamManager

class Team(models.Model):
     ...

     objects = Manager()
     team_manager = managers.TeamManager.as_manager()

     ...
</code>```

In a file manager.py or anything you want:

```<code> from django.db.models import QuerySet

 class TeamManager(QuerySet):
     def table_queryset(self):
        queryset = self.all()
        teams = []
        for team in queryset:
             players = team.player_set.all()
             for player in players:
                 teams.append([team, (player.name, ...)]
        return teams
</code>```

And then in your view:

```<code>class PlayersView(ListView):
    model = Team
    queryset = Team.player_manager.table_queryset()
</code>```

Body:
I want to display an unordered list of NBA teams from my teams table database. Within each team, I want an ordered list of players on that team. So basically I want to produce a list of all objects from my parent table and for each object from the parent table I want a list of all objects from the child table related the parent table. I understand that the problem is methods are not allowed in template tagging, so 'team.players_set.all()' would not be allowed. How else can I get the results that I want?

class Teams(models.Model):
    name = models.CharField(max_length=20, unique=True)
    num_of_plyrs = models.IntegerField()

    def __str__(self):
        return f"{self.name} have {self.num_of_plyrs} players."

    class Meta:
        verbose_name_plural = "Teams"

class Players(models.Model):
    name = models.CharField(max_length=20)
    team = models.ForeignKey(Teams, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.name} plays for {self.team}"

    class Meta:
        verbose_name_plural = 'Players'
__________________________________________________________________________________

def teams(request):
teams = Teams.objects.all()
context = {'teams': teams}
return render(request, 'one_app/teams.html', context)
__________________________________________________________________________________

NBA Teams

  {% for team in teams %}

Team: {{ team.name }}

Number of players: {{ team.num_of_plyrs }}

  {% for plyr in team.players_set.all() %}

{{ plyr.name }}

  {% endfor %}

  {% empty %}

There are no teams listed.

  {% endfor %}

Body:
One way to achieve this is:

class PlayersView(ListView):
    model = Team
    ...

    def get_queryset(self, **kwargs):
        teams = []
        queryset = super().get_queryset()
        for team in queryset:
             players = team.player_set.all()
             for player in players:
                 teams.append([team, (player.name, ...)]
        return teams

And in your template:

 {% for team, players in teams %}
     ...
     {% for player in players %}
           ...
     {% endfor %}
 {% endfor %}

ALTERNATIVE

If you know this is something you might be using a lot and to simplify your view, you can also create a manager:

from your_app.managers import TeamManager

class Team(models.Model):
     ...

     objects = Manager()
     team_manager = managers.TeamManager.as_manager()

     ...

In a file manager.py or anything you want:

 from django.db.models import QuerySet

 class TeamManager(QuerySet):
     def table_queryset(self):
        queryset = self.all()
        teams = []
        for team in queryset:
             players = team.player_set.all()
             for player in players:
                 teams.append([team, (player.name, ...)]
        return teams

And then in your view:

class PlayersView(ListView):
    model = Team
    queryset = Team.player_manager.table_queryset()


答:
Using this code:

```<code>template <class F>
struct y_combinator {
    F f; // the lambda will be stored here

    // a forwarding operator():
    template <class... Args>
    decltype(auto) operator()(Args&&... args) const {
        // we pass ourselves to f, then the arguments.
        // [edit: Barry] pass in std::ref(*this) instead of *this
        return f(*this, std::forward<Args>(args)...);
    }
};
</code>```

without the std::ref (which is used for efficiency i believe, because you don't copy the object over and over) errors changes to

```<code>prog.cc:23:18: error: function 'operator()<int>' with deduced return type cannot be used before it is defined
</code>```

So probably the compiler can't figure out the return type, but i can't tell you how in the first case it can deduce it

Title: return type deduction of recursive function

Body:
Using this code:

template <class F>
struct y_combinator {
    F f; // the lambda will be stored here

    // a forwarding operator():
    template <class... Args>
    decltype(auto) operator()(Args&&... args) const {
        // we pass ourselves to f, then the arguments.
        // [edit: Barry] pass in std::ref(*this) instead of *this
        return f(*this, std::forward<Args>(args)...);
    }
};

without the std::ref (which is used for efficiency i believe, because you don't copy the object over and over) errors changes to

prog.cc:23:18: error: function 'operator()<int>' with deduced return type cannot be used before it is defined

So probably the compiler can't figure out the return type, but i can't tell you how in the first case it can deduce it


问:
What is the significance of using a bracket on the node of the linked list in c++?
In the below code there is a node pointer naya in the mn function. In the if condition first time the naya pointer is pointing to the null and we are trying to access its data. If we try to do the same code without the brackets around the naya pointer, then it gives error such as:

```<code>prog.cpp: In function ‘void mn(Node*, Node**)’:
prog.cpp:66:50: error: request for member ‘data’ in ‘* naya’, which is of pointer type ‘Node*’ (maybe you meant to use ‘->’ ?)
     if(*naya == NULL || temp -> data <= *naya -> data)
                                             ^*
</code>```

But when we are using the brackets its' working fine. Why?

Below is the whole code:

```<code>#include <bits/stdc++.h>
using namespace std;
class Node {
 public:
  int data;
  Node* next = NULL;
  Node(int x) {
    data = x;
    next = NULL;
  }
};

void mn(Node* temp, Node** naya) {
  Node* current;

  if (*naya == NULL || temp->data <= (*naya)->data) {
    temp->next = *naya;
    *naya = temp;
  } else {
    current = *naya;
    while (current->next != NULL && (current->next->data < temp->data)) {
      current = current->next;
    }
    temp->next = current->next;
    current->next = temp;
  }
}
Node* isort(Node* head) {
  Node* temp = head;
  Node* naya = NULL;
  while (temp != NULL) {
    Node* nex1 = temp->next;
    mn(temp, &naya);
    temp = nex1;
  }
  return naya;
}
void printll(Node* head) {
  Node* temp = head;
  while (temp != NULL) {
    cout << temp->data;
    temp = temp->next;
  }
}
int main() {
  Node *head = NULL, *temp = NULL;
  int a;
  cin >> a;
  for (int i = 0; i < a; i++) {
    int x;
    cin >> x;
    Node* newnode = new Node(x);
    if (head == NULL) {
      head = newnode;
      temp = head;
    } else {
      temp->next = newnode;
      temp = temp->next;
    }
  }
  head = isort(head);
  printll(head);
}
</code>```

答:
The reason it has to be written this way is because of operator precedence, which decides which operations are executed using which operands. You can see from that link that 'member access' or -> is bound before 'Indirection (dereference)' or *a by default. By enclosing the dereference operation in brackets you can specify that you want it to be bound first before the member access.

To make this more concrete, in your example naya is a pointer to a pointer. C++ by default tries to bind the operands for the member access operation first (i.e. naya->data). If we were to add brackets to make the order explicit here, it would look like this:

```<code>*(naya->data)
</code>```

This has the effect of dereferencing naya and then looking for a data member variable in the dereferenced object. The dereferenced object is pointer though, so it has no data member. If it didn't error out there, it would go on to try and dereference the value of the data member (the * part of the expression).

When you put (*naya)->data, you are telling C++ that it should dereference naya with * specifically, not (naya->data) as it does by default. (*naya) is a pointer to a Node object, so -> will successfully find the data member.

Body:
In the below code there is a node pointer naya in the mn function. In the if condition first time the naya pointer is pointing to the null and we are trying to access its data. If we try to do the same code without the brackets around the naya pointer, then it gives error such as:

prog.cpp: In function ‘void mn(Node*, Node**)’:
prog.cpp:66:50: error: request for member ‘data’ in ‘* naya’, which is of pointer type ‘Node*’ (maybe you meant to use ‘->’ ?)
     if(*naya == NULL || temp -> data <= *naya -> data)
                                             ^*

But when we are using the brackets its' working fine. Why?

Below is the whole code:

#include <bits/stdc++.h>
using namespace std;
class Node {
 public:
  int data;
  Node* next = NULL;
  Node(int x) {
    data = x;
    next = NULL;
  }
};

void mn(Node* temp, Node** naya) {
  Node* current;

  if (*naya == NULL || temp->data <= (*naya)->data) {
    temp->next = *naya;
    *naya = temp;
  } else {
    current = *naya;
    while (current->next != NULL && (current->next->data < temp->data)) {
      current = current->next;
    }
    temp->next = current->next;
    current->next = temp;
  }
}
Node* isort(Node* head) {
  Node* temp = head;
  Node* naya = NULL;
  while (temp != NULL) {
    Node* nex1 = temp->next;
    mn(temp, &naya);
    temp = nex1;
  }
  return naya;
}
void printll(Node* head) {
  Node* temp = head;
  while (temp != NULL) {
    cout << temp->data;
    temp = temp->next;
  }
}
int main() {
  Node *head = NULL, *temp = NULL;
  int a;
  cin >> a;
  for (int i = 0; i > x;
    Node* newnode = new Node(x);
    if (head == NULL) {
      head = newnode;
      temp = head;
    } else {
      temp->next = newnode;
      temp = temp->next;
    }
  }
  head = isort(head);
  printll(head);
}

Body:
The reason it has to be written this way is because of operator precedence, which decides which operations are executed using which operands. You can see from that link that 'member access' or -> is bound before 'Indirection (dereference)' or *a by default. By enclosing the dereference operation in brackets you can specify that you want it to be bound first before the member access.

To make this more concrete, in your example naya is a pointer to a pointer. C++ by default tries to bind the operands for the member access operation first (i.e. naya->data). If we were to add brackets to make the order explicit here, it would look like this:

*(naya->data)

This has the effect of dereferencing naya and then looking for a data member variable in the dereferenced object. The dereferenced object is pointer though, so it has no data member. If it didn't error out there, it would go on to try and dereference the value of the data member (the * part of the expression).

When you put (*naya)->data, you are telling C++ that it should dereference naya with * specifically, not (naya->data) as it does by default. (*naya) is a pointer to a Node object, so -> will successfully find the data member.


问:
Oracle TABLE_PRIVILEGES Column Explanation
I queried the data dictionary TABLE_PRIVILEGES for one my user table to check the grants. It listed me 34 rows out of which for some of the records the value of SELECT_PRIV column is Y and for few of them it's G. I believe Y stands for YES but I am not clear on the G value. Can anyone please explain me what's does G mean here?

```<code>SELECT owner,
       table_name,
       select_priv,
       insert_priv,
       delete_priv,
       update_priv,
       references_priv,
       alter_priv,
       index_priv
FROM table_privileges
WHERE grantee = <SCHEMA_NAME>
ORDER BY owner, table_name
</code>```

答:
G Stands for grant.  It allows the grantee to grant others privileges on a given table

see: https://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_9013.htm

ContentLicense: CC BY-SA 3.0

Body:
I queried the data dictionary TABLE_PRIVILEGES for one my user table to check the grants. It listed me 34 rows out of which for some of the records the value of SELECT_PRIV column is Y and for few of them it's G. I believe Y stands for YES but I am not clear on the G value. Can anyone please explain me what's does G mean here?

SELECT owner,
       table_name,
       select_priv,
       insert_priv,
       delete_priv,
       update_priv,
       references_priv,
       alter_priv,
       index_priv
FROM table_privileges
WHERE grantee = <SCHEMA_NAME>
ORDER BY owner, table_name