text:
Q: Validating Recaptcha 2 (No CAPTCHA reCAPTCHA) in ASP.NET's server side The new Recaptcha 2 looks promising, but i didn't find a way to validate it in ASP.NET's server side,
if(Page.IsValid) in This answer, is valid for the old Recaptcha, but not the new one,
How to validate the new reCAPTCHA in server side?

A: You can use "IsValidCaptcha()" method to validate your google recaptcha on server side. Replace your secret key with "YourRecaptchaSecretkey" in the following method.
Public bool IsValidCaptcha()
 {
  string resp = Request["g-recaptcha-response"];
  var req = (HttpWebRequest)WebRequest.Create
            (https://www.google.com/recaptcha/api/siteverify?secret=+ YourRecaptchaSecretkey + "&response=" + resp);
     using (WebResponse wResponse = req.GetResponse())
       {
       using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
         {
          string jsonResponse = readStream.ReadToEnd();
          JavaScriptSerializer js = new JavaScriptSerializer();
          // Deserialize Json
          CaptchaResult data = js.Deserialize<CaptchaResult>(jsonResponse);
            if (Convert.ToBoolean(data.success))
              {
               return true;
              }
         }
      }
     return false;
 }

Also create following class as well.
public class CaptchaResult
  {
   public string success { get; set; }
  }

A: Here's a version that uses the JavaScriptSerializer. Thanks Ala for the basis for this code.
WebConfig App Setting -
I've added the secret key to the Web.Config in my case to allow transforms between environments. It can also be easily encrypted here if required.
<add key="Google.ReCaptcha.Secret" value="123456789012345678901234567890" />

The ReCaptcha Class - A simple class to post the response parameter along with your secret to Google and validate it. The response is deserialized using the .Net JavaScriptSerializer class and from that true or false returned.
using System.Collections.Generic;
using System.Configuration;

public class ReCaptcha
{
    public bool Success { get; set; }
    public List<string> ErrorCodes { get; set; }

    public static bool Validate(string encodedResponse)
    {
        if (string.IsNullOrEmpty(encodedResponse)) return false;

        var client = new System.Net.WebClient();
        var secret = ConfigurationManager.AppSettings["Google.ReCaptcha.Secret"];

        if (string.IsNullOrEmpty(secret)) return false;

        var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, encodedResponse));

        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        var reCaptcha = serializer.Deserialize<ReCaptcha>(googleReply);

        return reCaptcha.Success;
    }
}

Validate The Response - Check the validity of the g-Recaptcha-Response form parameter in your Controller (or code behind for a web form) and take appropriate action.
var encodedResponse = Request.Form["g-Recaptcha-Response"];
var isCaptchaValid = ReCaptcha.Validate(encodedResponse);

if (!isCaptchaValid)
{
    // E.g. Return to view or set an error message to visible
}

A: According to the doc you just post your secret key and user's answer to API and read returned "success" property
SHORT ANSWER:
        var webClient = new WebClient();
        string verification = webClient.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, userResponse));
        if (JObject.Parse(verification)["success"].Value<bool>())
        {
            // SUCCESS!!!

FULL EXAMPLE:
Suppose, you implement this page in IamNotARobotLogin.cshtml.

<form action="Login" method="POST">

  <input type="submit" value="Log In">
</form>

And suppose you wish the controller saved, let's say, "I_AM_NOT_ROBOT" flag in the session if the verification succeeded:
    public ActionResult IamNotARobotLogin()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Login()
    {
        const string secretKey = "6LcH-v8SerfgAPlLLffghrITSL9xM7XLrz8aeory";
        string userResponse = Request.Form["g-Recaptcha-Response"];

        var webClient = new System.Net.WebClient();
        string verification = webClient.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, userResponse));

        var verificationJson = Newtonsoft.Json.Linq.JObject.Parse(verification);
        if (verificationJson["success"].Value<bool>())
        {
            Session["I_AM_NOT_A_ROBOT"] = "true";
            return RedirectToAction("Index", "Demo");
        }

        // try again:
        return RedirectToAction("IamNotARobotLogin");
    }

A: Here's my fork of Ala's solution in order to:

*

*send paramter in POST

*to sanitize the form input

*include the requester IP address

*store the secret in Web.Config:

In the controller:
bool isCaptchaValid = await ReCaptchaClass.Validate(this.Request);
if (!isCaptchaValid)
{
    ModelState.AddModelError("", "Invalid captcha");
    return View(model);
}

The utility class:
public class ReCaptchaClass
{
    private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    private static string SecretKey = System.Configuration.ConfigurationManager.AppSettings["Google.ReCaptcha.Secret"];
    [JsonProperty("success")]
    public bool Success { get; set; }
    [JsonProperty("error-codes")]
    public List<string> ErrorCodes { get; set; }

    public static async Task<bool> Validate(HttpRequestBase Request)
    {
        string encodedResponse = Request.Form["g-Recaptcha-Response"];
        string remoteIp = Request.UserHostAddress;
        using (var client = new HttpClient())
        {
            var values = new Dictionary<string, string>
            {
               {"secret", SecretKey},
               {"remoteIp", remoteIp},
               {"response", encodedResponse}
            };
            var content = new FormUrlEncodedContent(values);
            var response = await client.PostAsync("https://www.google.com/recaptcha/api/siteverify", content);
            var responseString = await response.Content.ReadAsStringAsync();
            var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ReCaptchaClass>(responseString);
            if ((captchaResponse.ErrorCodes?.Count ?? 0) != 0)
            {
                log.Warn("ReCaptcha errors: " + string.Join("\n", captchaResponse.ErrorCodes));
            }
            return captchaResponse.Success;
        }
    }
}

A: This article give clear step by step explication on how to implement a ReCaptcha validation attribute on your model.
First, create the Recaptcha validation attribute.
namespace Sample.Validation
{
    public class GoogleReCaptchaValidationAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            Lazy<ValidationResult> errorResult = new Lazy<ValidationResult>(() => new ValidationResult("Google reCAPTCHA validation failed", new String[] { validationContext.MemberName }));

            if (value == null || String.IsNullOrWhiteSpace( value.ToString()))
            {
                return errorResult.Value;
            }

            IConfiguration configuration = (IConfiguration)validationContext.GetService(typeof(IConfiguration));
            String reCaptchResponse = value.ToString();
            String reCaptchaSecret = configuration.GetValue<String>("GoogleReCaptcha:SecretKey");

            HttpClient httpClient = new HttpClient();
            var httpResponse = httpClient.GetAsync($"https://www.google.com/recaptcha/api/siteverify?secret={reCaptchaSecret}&response={reCaptchResponse}").Result;
            if (httpResponse.StatusCode != HttpStatusCode.OK)
            {
                return errorResult.Value;
            }

            String jsonResponse = httpResponse.Content.ReadAsStringAsync().Result;
            dynamic jsonData = JObject.Parse(jsonResponse);
            if (jsonData.success != true.ToString().ToLower())
            {
                return errorResult.Value;
            }

            return ValidationResult.Success;
        }
    }
}

Then add the validation attribute on your model.
namespace Sample.Models
{
    public class XModel
    {
        // ...
        [Required]
        [GoogleReCaptchaValidation]
        public String GoogleReCaptchaResponse { get; set; }
    }
}

Finally, you have just to call the ModelState.IsValid method
namespace Sample.Api.Controllers
{
    [ApiController]
    public class XController : ControllerBase
    {
        [HttpPost]
        public IActionResult Post(XModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            // ...
        }
    }
}

Et voilà ! :)

A: Most of these answers seem more complex than needed. They also dont specify the IP which will help prevent a interception attack (https://security.stackexchange.com/questions/81865/is-there-any-reason-to-include-the-remote-ip-when-using-recaptcha). Here's what I settled on
public bool CheckCaptcha(string captchaResponse, string ipAddress)
{
    using (var client = new WebClient())
    {
        var response = client.DownloadString($"https://www.google.com/recaptcha/api/siteverify?secret={ ConfigurationManager.AppSettings["Google.ReCaptcha.Secret"] }&response={ captchaResponse }&remoteIp={ ipAddress }");
        return (bool)JObject.Parse(response)["success"];
    }
}

A: After reading many resources, I ended up with writing this class to handle the validation of the new ReCaptcha :
As mentioned Here : When a reCAPTCHA is solved by end user, a new field (g-recaptcha-response) will be populated in HTML.
We need to read this value and pass it to the class below to validate it:
In C#:
In the code behind of your page :
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "true" ? true : false);

if (IsCaptchaValid) {
    //Valid Request
}

The Class:
  using Newtonsoft.Json;

    public class ReCaptchaClass
    {
        public static string Validate(string EncodedResponse)
        {
            var client = new System.Net.WebClient();

            string PrivateKey = "6LcH-v8SerfgAPlLLffghrITSL9xM7XLrz8aeory";

            var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, EncodedResponse));

            var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ReCaptchaClass>(GoogleReply);

            return captchaResponse.Success.ToLower();
        }

        [JsonProperty("success")]
        public string Success
        {
            get { return m_Success; }
            set { m_Success = value; }
        }

        private string m_Success;
        [JsonProperty("error-codes")]
        public List<string> ErrorCodes
        {
            get { return m_ErrorCodes; }
            set { m_ErrorCodes = value; }
        }

        private List<string> m_ErrorCodes;
    }

In VB.NET:
In the code behind of your page :
Dim EncodedResponse As String = Request.Form("g-Recaptcha-Response")
    Dim IsCaptchaValid As Boolean = IIf(ReCaptchaClass.Validate(EncodedResponse) = "True", True, False)

    If IsCaptchaValid Then
        'Valid Request
    End If

The Class:
Imports Newtonsoft.Json

Public Class ReCaptchaClass
    Public Shared Function Validate(ByVal EncodedResponse As String) As String
        Dim client = New System.Net.WebClient()

        Dim PrivateKey As String = "6dsfH-v8SerfgAPlLLffghrITSL9xM7XLrz8aeory"

        Dim GoogleReply = client.DownloadString(String.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, EncodedResponse))

        Dim captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(Of ReCaptchaClass)(GoogleReply)

        Return captchaResponse.Success
    End Function

    <JsonProperty("success")> _
    Public Property Success() As String
        Get
            Return m_Success
        End Get
        Set(value As String)
            m_Success = value
        End Set
    End Property
    Private m_Success As String

    <JsonProperty("error-codes")> _
    Public Property ErrorCodes() As List(Of String)
        Get
            Return m_ErrorCodes
        End Get
        Set(value As List(Of String))
            m_ErrorCodes = value
        End Set
    End Property

    Private m_ErrorCodes As List(Of String)

End Class

A: Another example is posted here:
RecaptchaV2.NET (Github)
It also implements the secure token option of Recaptcha 2.0 (look at full source code for that bit, I have stripped out relevant pieces of code ONLY for validating a result).
This one doesn't rely on newtonsoft's json parser and instead uses the built in .NET one.
Here is the relevant snippet of code from the RecaptchaV2.NET library (from recaptcha.cs):
namespace RecaptchaV2.NET
{
  ///
  /// Helper Methods for the Google Recaptcha V2 Library
  ///
  public class Recaptcha
  {

    public string SiteKey { get; set; }
    public string SecretKey { get; set; }
    public Guid SessionId { get; set; }

    ///
    /// Validates a Recaptcha V2 response.
    ///
    /// <param name="recaptchaResponse">g-recaptcha-response form response variable (HttpContext.Current.Request.Form["g-recaptcha-response"])</param>
    /// <returns>RecaptchaValidationResult</returns>
    public RecaptchaValidationResult Validate(string recaptchaResponse)
    {
      RecaptchaValidationResult result = new RecaptchaValidationResult();

      HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" + SecretKey + "&response="
        + recaptchaResponse + "&remoteip=" + GetClientIp());
      //Google recaptcha Response
      using (WebResponse wResponse = req.GetResponse())
      {
        using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
        {
          string jsonResponse = readStream.ReadToEnd();

          JavaScriptSerializer js = new JavaScriptSerializer();
          result = js.Deserialize<RecaptchaValidationResult>(jsonResponse.Replace("error-codes", "ErrorMessages").Replace("success", "Succeeded"));// Deserialize Json
        }
      }

      return result;
    }

    private string GetClientIp()
    {
      // Look for a proxy address first
      String _ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

      // If there is no proxy, get the standard remote address
      if (string.IsNullOrWhiteSpace(_ip) || _ip.ToLower() == "unknown")
        _ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

      return _ip;
    }
  }

  public class RecaptchaValidationResult
  {
    public RecaptchaValidationResult()
    {
      ErrorMessages = new List<string>();
      Succeeded = false;
    }

    public List<string> ErrorMessages { get; set; }
    public bool Succeeded { get; set; }

    public string GetErrorMessagesString()
    {
      return string.Join("
", ErrorMessages.ToArray());
    }
  }
}

A: Google's ReCaptcha API no longer accepts the payload as query string parameters in a GET request.  Google always returned a "false" success response unless I sent the data via HTTP POST.  Here is an update to Ala's (excellent!) class which POSTs the payload to the Google service endpoint:
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Text;

public class RecaptchaHandler
{
    public static string Validate(string EncodedResponse, string RemoteIP)
    {
        var client = new WebClient();

        string PrivateKey = "PRIVATE KEY";

        WebRequest req = WebRequest.Create("https://www.google.com/recaptcha/api/siteverify");
        string postData = String.Format("secret={0}&response={1}&remoteip={2}",
                                         PrivateKey,
                                         EncodedResponse,
                                         RemoteIP);

        byte[] send = Encoding.Default.GetBytes(postData);
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = send.Length;

        Stream sout = req.GetRequestStream();
        sout.Write(send, 0, send.Length);
        sout.Flush();
        sout.Close();

        WebResponse res = req.GetResponse();
        StreamReader sr = new StreamReader(res.GetResponseStream());
        string returnvalue = sr.ReadToEnd();

        var captchaResponse = JsonConvert.DeserializeObject<RecaptchaHandler>(returnvalue);

        return captchaResponse.Success;
    }

    [JsonProperty("success")]
    public string Success
    {
        get { return m_Success; }
        set { m_Success = value; }
    }

    private string m_Success;
    [JsonProperty("error-codes")]
    public List<string> ErrorCodes
    {
        get { return m_ErrorCodes; }
        set { m_ErrorCodes = value; }
    }

    private List<string> m_ErrorCodes;
}

A: Using dynamic to validate recaptcha at server side
Calling Function
[HttpPost]
public ActionResult ClientOrderDetail(FormCollection collection, string EncodedResponse)
{
    Boolean Validation = myFunction.ValidateRecaptcha(EncodedResponse);

    return View();
}

Function Declaration
public static Boolean ValidateRecaptcha(string EncodedResponse)
{
    string PrivateKey = "YourSiteKey";

    var client = new System.Net.WebClient();

    var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, EncodedResponse));

    var serializer = new JavaScriptSerializer();
    dynamic data = serializer.Deserialize(GoogleReply, typeof(object));

    Boolean Status = data["success"];
    string challenge_ts = data["challenge_ts"];
    string hostname = data["hostname"];

    return Status;
}

A: the example I posted in this so post uses Newtonsoft.JSON to deserialize the full returned JSON, posts the data  to Google(as opposed to using a querystring) stores the relevant variables in the web.config rather than hard coded.


text:
Q: CSS background picture not showing I have the code bellow in the html file and the problem is the background picture is not showing, nor when I try doing it from the css file. Can somebody help me out what am I doing wrong? Thanks in advance!
<head>
  <style>
  body{
    background-image: url("trees.jpg");
  }
  </style>
</head>

A: try using !important
<head>
  <style>
  body{
    background-image: url("trees.jpg") !important;
  }
  </style>
</head>

A: First of all you need to set height of your body if their is no-content in the body then the image will not show
secondly, this code will only work if your html file and image are both in same folder
<head>
  <style>
  body{
    background-image: url("trees.jpg");
  }
  </style>
</head>

if the image is in say img folder then you need to do this
body{
    background-image: url("img/trees.jpg");
}

but if the img folder is not in the same directory as html but is in it's parent directory. you need to do this
body{
    background-image: url("../img/trees.jpg");
}

A: Most likely it can't find the file destination, try to check if you typed the file name right, even the file extension. Sometimes is the file extension in uppercase, like ".JPG".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a word or expression for someone who takes an over-optimistic view of things? Someone who takes an over-optimistic view of himself, his own country and all other things that have meaning/value to him. And who doesn't see or admit the smaller, yet not insignificant, things. E.g. as well in an attempt to win other people over of something or give them the impression of his own greatness (by leaving out whichever isn't going to benefit that impression he wants to make.)

A: One who wears rose-coloured glasses may be a useful expression.

A: Such a person is a partisan [OxfordDictionaries defines the adjective: prejudiced in favour of a particular cause:
newspapers have become increasingly partisan] or even a bigot [U.D.:  One who is narrowly or intolerantly devoted to his or her opinions and prejudices].
They are also narrow-minded, blinkered, and parochial.

A: What comes to mind is the expression see things through rose-colored glasses.

rose-colored glasses: with an attitude that things are better than they really are

Alternately, consider be in an ivory tower, have blinders on, and have a tin ear for.

ivory tower: an attitude of aloofness or disdain or disregard for worldly or practical affairs
have blinders on: to not be able to accept or recognize what's happening around you
a tin ear: an insensitivity to the appropriateness or subtlety of verbal expression

A: I guess the word could be Polyanna, some girl character from a novel.

A: A panglossian.
Which the good folks at http://dictionary.reference.com/browse/panglossian define as

a person who views a situation with unwarranted optimism

A: Such a person can be said to have an inflated view of themselves [their country, etc.]. They can also be termed a blusterer or blowhard (the latter term being commoner in the USA than in the UK).

A: Depending on the context a person is either megalomaniac of narcissistic. Whereas the latter has a more negative connotation. Personally I rather be megalomaniac then narcissistic.

an attempt to win other people over of something or give them the impression of his own greatness

In this case the person is definitely narcissistic.

Someone who takes an over-optimistic view of himself, his own country and all other things that have meaning/value to him.

If the over-optimistic view isn't necessarily  egoistically driven, I would go for megalomaniac

A: In the sense of my country (or culture) right or wrong (and there's nothing wrong, so there's no point bringing it up in the first place), either chauvinist or jingoist would fit, depending on whether it is merely objectionable or actually hostile/bellicose. It may even be safe to use the word chauvinist again outside of the sphere of "gender" relations¹, though that would have been nearly impossible in my youth.
While either term might naturally cause the hearer/reader to infer that the subject is also a self-satisfied blowhard git, it is at least theoretically possible for chauvinists to be narrowly modest about their own personal accomplishments, situations and possessions. It is therefore necessary to add something personal to the mix in order to avoid relying on inference.

¹ I truly hate using a term referring to grammatical categories when the correct word is sexual, but creeping euphemisms have done damage to the language that I fear is irreparable.


text:
Q: Are my proofs consistent/non-circular/correct? I am slowly working my way trough "Mathematical Analysis" by Apostol, and I decided to try my hand at a few proofs. (I asked related questions here and here, so some of the work here might be from the answers there)
So far we are only given the axioms:
Axiom 1:
Commutative Laws
$x+y = y + x$ , $xy=yx$
Axiom 2: Associative Laws
$x+(y+x) = (x+y)+z$ , $x(yz) = (xy)z$
Axiom 3
Distributive Law
$x(y+z)=xy+yz$
Axiom 4
Given any two real numbers x and y, there exists a real number z such that x + z = y. This z is denoted by y-x; the number x-x is denoted by 0. (It can be proved that 0 is independent of x.) We write -x for 0-x and call -x the negative of x

Proof 1: $x + 0 = x$
From axiom 4, we are guaranteed a $z$ such that $x+z = x$.
That $z$ is equal to $x-x=0$,
By substitution, $x + 0 = x$
Comments/concerns: I am not sure weather the $0$ in Axiom 4 is used just as a symbol/placeholder for $x-x$, or if it is actually meant to be the actual integer between $-1$ and $1$. That is, I am not sure if it's implied that $x-x$ evaluates to the same thing as $y-y$. I;m not sure that this is what is meant in axiom 4 by"it can be proved that $0$ is independent of $x$".

Proof 2: Proof that $0$ is a constant, not just a symbol placeholder
From proof 1, we have that
$y + 0 = y$
$y + (x-x) = y$
From axiom 4,
$x-x = y-y$
We know that $x-x = 0$, and therefore $y-y=0$ as well, so for the equation
$x+0=x$
$0$ is a constant and therefore the same for any $x$.

Proof 3: Axiom 4 can be reduced to: There is a number $-x$ such that $x + (-x) = 0$
So basically we are trying to prove that for any numbers $x$ and $y$, there exists $z$ such that $x + z = y$
Now we work backwards a little bit:
Take any two real numbers $x, z$, and let their sum be denoted by $y$
$x + y = z$
Add $(-x)$ to both sides:
$(x + z) + (-x) = y +(-x)$
Commutative Propriety
$(z+(-x)) + (-x) = y +(-x)$
Associative Propriety
$z+(x+(-x))=y+(-x)$
$x+(-x) = 0$
$z+0=y+(-x)$
$z = y+(-x)$
So $z$ exists as is denoted by $y+(-x)$
Comments/concerns: I just realized that this proof is circular, because it is dependent on proof 1 ($x+0=x$), which is dependent on axiom 4. So I don't know what to do with this. I am aware that in this version of axiom 4 we haven't introduced the subtraction operator, and even if we did we would need to prove that $y-x=y+(-x)$


text:
Q: Proof of injections
Let $f: X\to Y$ be a surjection and $g: Y\to Z$ be such that $g \circ f$ is an injection. Prove that both $f$ and $g$ are injections.

My attempt:
Since $f$ is surjective then there exists $ x, x'\in X$ such that $(x,y)\in f$ and $(x',y')\in f$, but since $g\circ f$ is an injection then $(x,z)\in g\circ f$ and $(x',z)\in g\circ f$ which implies that $x=x'$ ... but now I am stuck completing the proof.

A: For any functions $f: X \rightarrow Y$, $g: Y \rightarrow Z$, $g \circ f$ is an injection implies that $f$ is an injection. In your case $f$ is also surjective, hence bijective. Then, writing $g = (g \circ f) \circ f^{-1}$ what can you conclude?

A: Suppose $f(x)=f(y)$. Then $g(f(x))=g(f(y))$ so $x=y$. Hence $f$ is an injection.
Suppose $g(x)=g(y)$. Then there exist $x_0,y_0\in X$ such that $f(x_0)=x$ and $f(y_0)=y$. It follows that $g(f(x_0))=g(f(y_0))$ so $x_0=y_0$. But now $x=y$ so $g$ is an injection.

A: You are on the right track.
Suppose $g(y_1)=g(y_2)$ and by surjectivity of $f$, find $x_1,x_2\in X$ with $f(x_1)=y_1$ and $f(x_2)=y_2$.  Then we have $g\circ f(x_1)=g\circ f(x_2)$ which implies that $x_1=x_2$, which in turn implies that $y_1=y_2$ so that $g$ is injective.
Next, suppose $f(x_1)=f(x_2)$.  Apply $g$ and use the injectivity of $g\circ f$ to conclude that $f$ is injective.


text:
Q: Type script get max array I have an array with one column n_fnc and I would like to find the max value .
I tried with this but I don"t get anything.
 let first = this.fncs.map(item => item.n_fnc);
   console.log("First",first);
    x= Math.max(...first);

[
fnc service
getlastid(response,fncs:Fnc[]):void{
      let fnc:Fnc;
      response.forEach(element => {

        fnc =new Fnc();
        fnc.n_fnc=element.n_fnc;
        fncs.push(fnc);

    });

Fnc component.ts
this.fncs=[];
this.fncservice.obs.subscribe((response)=>this.fncservice.getlastid(response,this.fncs));
     console.log("A",this.fncs);
    var max= Math.max.apply(Math, this.fncs.map((m) => m.n_fnc));
    console.log("Max",max);

A: You can use apply function to do that -

var fncs = [{
 n_fnc: 1
},{
 n_fnc: 499
},{
 n_fnc: 99
},{
 n_fnc: 10
}];

var max = Math.max.apply(Math, fncs.map((m) => m.n_fnc));
console.log(max);

The code block in fnc.component.ts should be like -
this.fncs=[];
this.fncservice.obs.subscribe((response)=> {
    this.fncservice.getlastid(response,this.fncs);
    console.log("A",this.fncs);
    var max= Math.max.apply(Math, this.fncs.map((m) => m.n_fnc));
    console.log("Max",max);
});

A: You can use apply function to do that -

let fncs = [{
 n_fnc: 1
},{
 n_fnc: 499
},{
 n_fnc: 99
},{
 n_fnc: 10
}];

let mytemp = fncs.sort((a, b) =>  { return b.n_fnc > a.n_fnc ? 1 : -1; });

console.log(mytemp[0]);


text:
Q: graphing a function with pgfplots x-intercept is not showing I have a function $f(x)=\sqrt{{1-2e^{-x^2}}}$ I wish to plot.
The problem I am encountering is that the function has a vertical tangent at $\sqrt{\ln{2}}$ which is also an x-intercept.
The graph stops short of intersecting the x-axis.
Here is my effort thus far.
\documentclass[english]{article}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}
\begin{axis}[xmin=-2.5,xmax=2.5,ymin=-1.5,ymax=1.5,
  xlabel=$x$,
  ylabel=$y$,
  xtick=\empty,
  ytick=\empty,
  xticklabels={,,},
  yticklabels={,,},
  x label style={yshift=-6ex,xshift=2ex},
  y label style={yshift=1ex,xshift=-5ex},
 axis lines=middle,
 axis line style={->}
  ]

\addplot[ultra thick,smooth,blue,samples=400,domain={(ln(2))^0.5:2}] {(1-2*e^(-x^2))^0.5};

\end{axis}
\end{tikzpicture}
\end{document}

Here is the output:

A: You can select this one point and make it zero like this:
\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmin=-2.5, xmax=2.5,
ymin=-1.5, ymax=1.5,
xlabel=$x$,
ylabel=$y$,
ticks=none,
x label style={yshift=-6ex, xshift=2ex},
y label style={yshift=1ex, xshift=-5ex},
axis lines=middle,
axis line style={->}
]
\addplot[
ultra thick, smooth, blue,
samples=50,
domain=(ln(2))^0.5:2,
y filter/.expression={x==(ln(2))^0.5?0:y},
] {(1-2*e^(-x^2))^0.5};
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Populate in node js i'm new to Node.js and i'm trying to use populate(), but it doesn't work for me.
I want to populate user with forms
This is the model

const UserSchema = new Schema({
    firstName: {
        type: 'string',
        required: ' Firstname is Required'
    },
    lastName: {
        type: 'string',
        required: ' lastName is Required'
    },
    email: {
        type: 'string',
        required: ' email is Required'
    },
    phone: {
        type: 'string',

    },
    entrprise: {
        type: 'string'
    },
    password: {
        type: 'string',
        required: ' password is Required'
    },
    forms: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Form"
    }

    ]
})

and this is the function

const getUser = async (req, res) => {
    try {
        const { userId } = req.params;
        if (!userId) return res.status(400).json({ message: "ERROR ID!" });
        const result = await User.findOne({ _id: userId })
            .populate('forms')
            .exec()
        return res.status(200).json({ message: "Success", result });
    } catch (err) {
        res.status(500).json({ message: "INTERNAL ERROR SERVER!" });
        console.log(err.message);
    }
};

but this is what i'm getting as result
"message": "Success",
"result": {
    **"forms": [],**
    "_id": "5fc917c49aca9b98b8d9b2aa",
    "firstName": "lea",
    "lastName": "bouteflika",
    "email": "inspirez@gmail.com",
    "password": "$2b$10$zJ5Du2YdfJBsz1ah6JYm7uPe1RYMwmmqmq68TxbvbwYnHVcDKNQeq",
    "phone": "+213556865069",
    "__v": 0
}

the forms are empty, does anyone have answer?

A: the code about populate is correct, you should check the id in forms field exists in From Model, because when you insert data in collection just one collection is updated
const listOfIds = await User.findById(userId );
let result = await Form.find({_id: {$in:[listOfIds.forms]}}).lean()
console.log(result)

so search list of ids in Form model, if the result is 0 so check the insert query;
and you can use finById instead of finOne
for a insert new form do like this
//1
const form = new Form({
  title
 //....
});
//2
let user = await User.findById(userId); // find the user
//3
let newForm = await form.save(); // save new form
//4
user.forms.push(newForm); // push the new form into user for populate
//5
await user.save(); //update user


text:
Q: Remove tags with Simple HTML DOM parser php code:
    $result = array();
    $html = file_get_html('http://site.com'.$_POST['link'].'');
    $content = $html->find('#details');
    foreach($content as $value) {
        $result['example'] = $value->outertext;
    }

HTML (for parser):

test

        test

test

test2

test2

I need to delete the last two elements "tr". How do I do this using html dom parser?

test2

test2

Sorry for my bad English and thank you in advance.


text:
Q: Problemas com $.get e PHP Gelera estou me batendo um pouco apra descobrir o que está acontecendo com um código que montei.
Tenho um loop que baixa arquivos .csv de um servidor especifico para o meu servidor. São 9 arquivos.
Após termino dos downloads preciso apagar as bases, realizar as inserções novamente e apagar os arquivos, parecia simples mas algumas coisas estão saindo do controle.
No inicio o arquivo "insert_delete.php" recebia os 3 loops dos 9 arquivos, porém ele se perdia e registrava logs informando duplicata de inserções e delete de arquivos. Sendo assim separei em 3 arquivos, isso parou de acontecer.
Um questão estranha é que quando executo diretamente o arquivo "insert_delete.php" tudo acontece dentro dos conformes, porém quando executo pelo script a base está ficando em branco, como se o TRUNCATE acontecesse depois do foreach.
Me parece que está passando algo e não estou vendo.
Vamos lá a bagunça que eu fiz:
Script
//Contagem dos arquivos se houver mais que 8 arquivos realiza a solicitação de inserção, se não continua contando
function cont(){
    setTimeout(function(){
        $.get("query/cont_arquivos.php", function( data ) {
            if(data < 9){
                $('.box_loading').show();
                $(".cont").html(
                    "Aguardando arquivos "+data
                );
                cont();
            }else{
                $.get("insert_delete.php", function(){});
                $.get("insert_delete1.php", function(){
                    $('.box_loading').hide();
                });
                $.get("insert_delete2.php", function(){});

                $(".cont").html(
                    "Inserindo nas bases... "
                );
            }
        });

    },1000);
}

PHP(insert delete)
<?php
include "conn.php";

$files1 = glob('nomedosarquivos*.csv'); // obten alguns arquivos da pasta

$sql = "TRUNCATE TABLE nomedatabela"; //apaga a base
$conn->query($sql);

if(count($files1)>2){
  foreach($files1 as $file){ // loop dos 3 arquivos
    if(is_file($file))
    if (($base = fopen($file, "r")) !== FALSE) {
        $count = 0;
        $ok = 0;
        $erro = 0;
        while (($data = fgetcsv($base, 0, ";")) !== FALSE) {
            $data = array_map("utf8_encode", $data);
            $count++; //contar as linhas
            if ($count == 1) { continue; } //não inserir os titulos

            if ($data[0] == "") { break; } //sai do while se este campo estiver em branco

            //validações de campos

            $sql = "INSERT into nomedatabela (campos....) VALUES (dados..)";
            if($conn->query($sql)==TRUE){
                $ok++;
                //somente conta as linhas que foram inseridas

            }else{
                //conta os erros
                $erro++;
                //executa o log informando qual erro e em qual linha aconteceu
            }
        }
        fclose ($base);
        if(unlink($file)){
            //executa o log informando que o arquivo foi deletado
        }else{
            //executa o log informando um erro ao deletar o arquivo
        }
      }
    }
  }
 ?>

A: Você ja tentou utilizar o $.get().done().always().fail()?
Pelo que eu vi, esses métodos teriam que ser chamados após o término do anterior ....
  function cont() {
    setTimeout(function () {
        $.get("query/cont_arquivos.php", function (data) {
            if (data < 9) {
                $('.box_loading').show();
                $(".cont").html(
                    "Aguardando arquivos " + data
                );
                cont();
            } else {
                $.get("insert_delete.php", function () { })
                .done(function () {
                    $.get("insert_delete1.php", function () {
                        $('.box_loading').hide();
                    }).done(function () {
                        $.get("insert_delete2.php", function () {
                        }).done(function () {
                            $(".cont").html("Inserindo nas bases... ");
                        });
                    });
                });
            }
        });
    }, 1000);
}


text:
Q: What does a la carte mean as an adjective or figuratively? From James Poulos, "Actually, The GOP Will Struggle To Capitalize On Obama's Perfect Storm Of Scandals," Forbes (May 14, 2013):

The GOP, conservatives are told, needs to endorse life templates a la carte -- supporting gay marriage here, a path to citizenship there.

I want to know what "a la carte" means as an adjective or figuratively.

A: Dictionary definitions of à la carte tend to focus on the approach that many restaurants adopt toward their offerings, in which they price menu items separately and let customers select from among multiple options for different courses (for example, appetizers, soup/salad, main course, and dessert, as well as beverage pairings) of the meal. For example, The American Heritage Dictionary of the English Language, fifth edition (2010) has this entry for the term:

à la carte adv. & adj. With a separate price for each item on the menu. {French, à la carte, by the menu}

And Merriam-Webster's Eleventh Collegiate Dictionary (2003) has this:

à la carte adv or adj {F[rench], by the bill of fare} (1816) : according to a menu or list that prices each item separately

The implicit distinction here is between à la carte, on the one hand, and prix fixe ("fixed price") on the other. The Eleventh Collegiate defines prix fixe as "a complete meal offered at a fixed price; also : the price charged." The key feature of prix fixe is that it is a take-it-or-leave-it proposition: customers buy the meal that the restaurant offers that day or they do not; the customers has no options at a more granular level.
Used figuratively,  à la carte means something like "skipping around through a series of options and choosing the ones you like." So the author quoted in the posted quotation is saying that the Republican Party in the U.S. is being urged (by "reform-minded Republicans," the article says) to select its positions on sociopolitical issues one by one, on the basis of their cultural popularity or other criteria, rather than adhering to a fixed and (supposedly) consistent program of policies based on a clear worldview.
I read the author's "à la carte" language as being hostile to an à la carte approach and as endorsing, sub silencio, a prix fixe alternative. But in doing this, the author fails to address the fact that someone—or some group of people—must do the selecting of the items that appear in a prix fixe meal, as surely as individual customers choose the elements of the meal that appears on their plates when consulting an à la carte menu. The essential difference is that the restaurant decides in the prix fixe case, while the consumer does so in the à la carte case.
What makes this particular quotation rather odd, when you think about it, is that the Republican Party is somehow both the restaurant owner and the restaurant customer, figuratively speaking. The author implies that the GOP should resist adopting an à la carte approach to the platform that it runs on—as if the party hadn't already worked through various political options à la carte in arriving at the prix fixe menu that it currently offers voters. The only way to avoid running onto the shoals of à la carteism at some point in the process, it seems to me, is by viewing the political prix fixe menu as being the product not of multiple discrete choices, but of some absolute, unconditional, uncompromising force—as being, perhaps, the result of a series of logically necessary conclusions dictated by a consistent moral compass that transcends political considerations.
The author's underlying argument seems to be that, in endorsing appropriate life templates, the GOP should refuse to consider an option's sociopolitical popularity—and its potential bearing on Republican candidates' electability—and instead be guided by a higher authority. Whether the author actually believes this argument is a matter for conjecture. I suspect that it's considerably easier to criticize the expedience of à la carte political relativism than to explicitly defend the actual mechanics behind prix fixe political absolutism.


text:
Q: Value of bootstrap dropdown do not change I am using bootstrap drop down with exactly similar in behaviour to html select drop down. But on the bootstrap website, I none of the drop downs actually change it's value in the span or input tab, when I change the drop down.
Also I am looking for the change event to occur when I change the item.
Yet I tried to map as much as possible:
I am doing the following:

        5

      <input type='hidden' value='5' class='dropdown-field spec-no-of-rows' />

5

10

20

50

100

500

1000

I have included boostrap and bootsrap-dropdown and bootsrap-select.
When I click on the box, no dopdown appears, neither any event is triggerred. what wrong I am doing.
So can I have exactly same behaviour of html select in bootstrap?

A: i had forgot to add in my javascript :
$('div[data-select=true]').dropSelect();

Now everything works smooth.


text:
Q: Drawing rectangle on picture box from another form's button I have a form with a picturebox on it, and another form with a button on it. How would I picturebox1_paint on the first form once I press the button on the other form?
Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
    e.Graphics.DrawRectangle(Pens.Blue, x.text, y.text, width.text, height.text)
End Sub

this is what I have, what would I need to alter to get it to work?

A: At Form1, add
Sub PaintImage(rectangle As Rectangle)
    ' create image in size of PictureBox1
    Dim image As New Bitmap(PictureBox1.Width, PictureBox1.Height)

    ' paint on created image
    Using gr As Graphics = Graphics.FromImage(image)
        gr.DrawRectangle(New Pen(Color.Red), rectangle)
    End Using

    ' display finished image in PictureBox1
    PictureBox1.Image = image
End Sub

and call it from the form with button:
Sub Button1_Click(sender as Object, e as EventArgs) Handles Button1.Click
    Form1.PaintImage(New Rectangle(x, y, width, height)) ' assume we already have x, y, w, h
End Sub

You can delete your Paint() event handler shown in the question. Its purpose is to repaint PictureBox1.Image if its size or visibility is changed and in most cases you can leave it as it is.


text:
Q: Sqlalchemy psycopg2 set socket options I'd like to try setting the socket options for a psycopg2 postgres database connection to do abortive connection releases. We are facing an issue similar to that described here: https://www.box.com/blog/container-networking-mystery-missing-rsts/.
There's an example of setting socket options for a MySQL connection here: https://github.com/mozilla/mozpool/blob/master/mozpool/db/pool.py, but I can't seem to access the socket with a psycopg2 connection.
Is it possible to set socket options using a psycopg2 connection?

A: You can use connection.fileno to get the file number of the socket and do whatever you want with it.


text:
Q: Limiting Join Qty If I have a couple of tables like the following
Table1
-----------------------------
Name                      Qty
-----------------------------
John                       1
Paul                       2
               ...
Ringo                      1

and
Table2
-----------------------------
Forename    Surname      Cost
-----------------------------
John        Smith        123
John        Jones        815
Paul        Smith        273
Paul        Jones        297
             ...
Ringo       Smith        755
Ringo       Jones        334

and I want to construct a query so the quantity returned from Table2 by each subset is ordered by Table2.Cost and limited by Table1.Qty, to return something like:
Results
-----------------------------
Forename    Surname      Cost
-----------------------------
John        Jones        815
Paul        Jones        297
Paul        Smith        273
Ringo       Smith        755

Is there a way to do this?

A: Try this one
SELECT T.Forename,T.Surname, T.Cost
  FROM
     (
         SELECT *,
                ROW_NUMBER() OVER ( PARTITION BY Forename ORDER BY Cost DESC )
                AS rn
           FROM Table2
      ) T
JOIN Table1 ON Table2.Foreman=Table1.Name
WHERE T.rn <=Qty;

A: SELECT Forename,
       Surname,
       Cost
  FROM
     (
         SELECT *,
                ROW_NUMBER() OVER ( PARTITION BY Forename ORDER BY Cost DESC )
                AS rn
           FROM Table2
      )
WHERE rn = 1;

A: Updated and Tested: If it's about getting the highest cost from Table 2 depending upon Qty from Table 1, then use the following:
CREATE TABLE #table1 (name NVARCHAR(100), qty INT);
CREATE TABLE #table2 (forename NVARCHAR(100), surname NVARCHAR(100), cost INT);

INSERT INTO #table1 VALUES
('John', 1),
('Paul', 2),
('Ringo', 1);

INSERT INTO #table2 VALUES
('John', 'Smith', 123),
('John', 'Jones', 815 ),
('Paul', 'Smith', 273),
('Paul', 'Jones', 297),
('Ringo', 'Smith', 755),
('Ringo', 'Jones', 334);

WITH DATA AS (
SELECT t2.forename, t2.surname, t2.cost, t1.qty,
rn = ROW_NUMBER() OVER (PARTITION BY t1.name ORDER BY t2.cost DESC)
FROM
  #table1 t1
  INNER JOIN #table2 t2 ON t1.name = t2.forename
)
SELECT d.forename, d.surname, d.cost
  FROM
DATA d
WHERE d.rn <= d.qty

A: create table #table1(name varchar(100), qty int)
create table #table2 (forename  varchar(100),  surname  varchar(100), cost int)

insert into #table1 values
('John',1),
('Paul',2),
('Ringo',1)

insert into #table2 values
('John'   ,     'Smith'      ,  123),
('John'    ,    'Jones'    ,    815 )   ,
('Paul'   ,     'Smith'    ,    273),
('Paul'   ,     'Jones'    ,    297),
('Ringo'  ,     'Smith'    ,    755),
('Ringo'  ,     'Jones'    ,    334)

select * from
#table1 t1 cross apply
    (select top (t1.qty) * from #table2 t2 where t1.name = t2.forename order by t2.cost desc) t


text:
Q: Counting "Friends" in either direction in SQL I have a model where people can "Friend" each other (Friendships).  How could I query the # of people a person is both friend towards and friended by, without counting 2-way friendships twice?
Here's an example:
1 -> 2
2 -> 1
1 -> 3
4 -> 1

I'd want that to register as #1 having 3 friends
Friendships (id, person_id, friend_id)

A: Select
  count(distinct(f.user_id + f.friend_id))
From
  Friends f
Where
  f.user_id = 1 or f.friend_id = 1

It might be more efficient to do something like this, though:
Select
  Count(*)
From (
  Select friend_id From Friends f Where f.user_id = 1
  Union
  Select user_id From Friends f where f.friend_id = 1
) as a

For getting everyone's friend count, assuming a users table too:
Select
  u.user_id,
  count(distinct f.user_id + f.friend_id)
From
  Users u
    Left Outer Join
  Friends f
    On u.user_id = f.user_id Or u.user_id = f.friend_id

Though joining using an or usually means a slow query. The other way would be:
Select
  u.user_id,
  count(distinct f.friend_id)
From
  Users u
    Left Outer Join (
      Select user_id, friend_id from Friends
      Union All
      Select friend_id, user_id from Friends
  ) f
    On u.user_id = f.user_id

You could change Union All to Union and get rid of the distinct, not sure which would be quicker.

A: Select distinct f1.id,count(f1.id)
from friendships f1
join friendships f2 on f1.person_id = f2.friend_id
Group by f1.id

A: select id, count(*)
from
  (select id, person_id as p1, friend_id as p2 from friendships
   union select id, person_id as p2, friend_id as p1 from friendships) fs
group by id

A: select person_id, sum(ct) friend_count
from (select person_id, count(*) ct from friends
      group by person_id
      UNION ALL
      select f1.friend_id, count(*) ct
      from friends f1
      left join friends f2 on f1.person_id = f2.friend_id
      where f2.person_id is null
      group by f1.friend_id) u
group by person_id


text:
Q: Eliminar extraño espacio en blanco a la derecha y scroll horizontal lo que pasa es que al diseñar una web, en el espacio derecho me aparece un raro espacio en blanco, me aparece un scroll horizontal y no encuentro el motivo.
Acá el código
https://codepen.io/cris123m/pen/dyYrKdo

A: Hay una imagen flotando y animada con la clase "anim-2". En el código no agregaste la imagen, no te puedo ayudar modificando exactamente los valores, porque no se cuál sea tu caso en específico.
El width de .anim-2 está agregado como 70%, cambialo a tu conveniencia, porque está superando el tamaño del documento por la posición absoluta.


text:
Q: Example junit5 pact message provider test I have been able to convert message consumer pact tests to junit5, but am not sure how to use the information in the junit5 provider readme to convert the corresponding message provider verification tests.  Can someone point to an example or suggest an outline of how the provider tests for message queue providers are supposed to work with the PactVerificationcontext?
I am trying to convert something like:
import au.com.dius.pact.provider.PactVerifyProvider;
import au.com.dius.pact.provider.junit.Consumer;
import au.com.dius.pact.provider.junit.PactRunner;
import au.com.dius.pact.provider.junit.Provider;
import au.com.dius.pact.provider.junit.loader.PactFolder;
import au.com.dius.pact.provider.junit.target.AmqpTarget;
import au.com.dius.pact.provider.junit.target.Target;
import au.com.dius.pact.provider.junit.target.TestTarget;

@RunWith(PactRunner.class)
@Provider("provider")
@Consumer("consumer")
@PactFolder("target/pacts")
public class MessageProviderPact {

  @TestTarget
  public final Target target = new AmqpTarget();

  private KafkaTemplate<String, MsgObject> kafkaTemplate
      = (KafkaTemplate<String, MsgObject>)Mockito.mock(KafkaTemplate.class);

  private MessageProducer messageProducer = new MessageProducer(kafkaTemplate);

  @Test
  @PactVerifyProvider("case a")
  public String verifyCaseA() throws IOException {
    // given
    ListenableFuture<SendResult<String, MsgObject>> future =
        mock(ListenableFuture.class);
    doReturn(future).when(kafkaTemplate).send(any(String.class),
        any(MsgObject.class));

    // when
    DomainObj domainObj = new DomainObj();
    String topic = "kafka_add";
    messageProducer.send(topic, domainObj);

    // then
    ArgumentCaptor<MsgObject> messageCapture = ArgumentCaptor.forClass(
        MsgObject.class);
    verify(kafkaTemplate, times(1)).send(eq(topic),
        messageCapture.capture());

    // returning the message
    return objectMapper.writeValueAsString(messageCapture.getValue());
  }
}

A: You should not use the kafka template to verify the Pact message, you might have created the test Object for unit testing in order to test the Messages you can use the same test Objects. You can find the full implementation here.

A: An example can be found in the pact-jvm project repo
The relevant code has been included below:
@Provider("AmqpProvider")
@PactFolder("src/test/resources/amqp_pacts")
public class AmqpContractTest {
  private static final Logger LOGGER = LoggerFactory.getLogger(AmqpContractTest.class);

  @TestTemplate
  @ExtendWith(PactVerificationInvocationContextProvider.class)
  void testTemplate(Pact pact, Interaction interaction, PactVerificationContext context) {
    LOGGER.info("testTemplate called: " + pact.getProvider().getName() + ", " + interaction);
    context.verifyInteraction();
  }

  @BeforeEach
  void before(PactVerificationContext context) {
    context.setTarget(new MessageTestTarget());
  }

  @State("SomeProviderState")
  public void someProviderState() {
    LOGGER.info("SomeProviderState callback");
  }

  @PactVerifyProvider("a test message")
  public String verifyMessageForOrder() {
    return "{\"testParam1\": \"value1\",\"testParam2\": \"value2\"}";
  }

}


text:
Q: Where is the Apps key on a standard Microsoft keyboard? ConEmu has a shortcut for renaming the current tab. It's Apps+R. I have never seen an Apps key on any keyboard. Where is it?

A:
In computing, the menu key or application key ≣ Menu
is a key found on Microsoft Windows-oriented computer keyboards,
introduced at the same time as the Windows logo  key. Its symbol is usually a small icon depicting
a pointer hovering above a menu, and it is typically found on the
right side of the keyboard between the right Windows logo key
 and the right Ctrl key
(or between the right Alt key and the right Ctrl
key).
While the Windows key is present on the vast majority of
keyboards intended for use with the Windows operating system, the menu
key is frequently omitted in the interest of space, particularly on
portable and laptop keyboards.
The key's primary function is to
launch a context menu with the keyboard rather than with the usual
right-mouse button. It can be used when the right-mouse button is not
present on a mouse.
Some Windows public terminals do not have a ≣ Menu key on their keyboard
to prevent users from right clicking; however, in many Windows
applications, a similar functionality can be invoked with the ⇧
Shift+F10 keyboard shortcut, or sometimes Ctrl+⇧ Shift+F10.
Some laptop computers include a menu function on the Fn key
(usually
operated by typing ⇧ Shift+Fn); however, this generally invokes
functions built into the vendor's software and is not the same as the
key described above. For example, the Logitech Illuminated Keyboard
has an FN key where the menu key is usually found.
Pressing FN together with the keyboard's print screen key
PrtScr, above Home
produces the ≣ Menu key function.
Programmers using the Windows API can intercept this key by looking
for a WM_KEYDOWN message with wParam VK_APPS (defined as 0x5D in
winuser.h). It has key code 117 (0x75).

Source: Wikipedia - Menu key

Where is the key located on the keyboard?

On most keyboards it's between the Fn and Ctrl keys.
The key in question typically looks like the following:

A: From the ConEmu documentation:

A: The "APPS" Key is also known as the "Context Menu Key". This may clarify (1) that it does what a right mouse click does, reveal the context menu for the current context and (2) that what you see depends on the context - what has the focus (active in-focus window, selected file/directory tree item, etc.) and (3) for those who sometimes DO make intentional use of the context menu function, what sort of things might be accomplished through the use of the "APPS" key. Also (4) it may suggest the oft-ignored methods for adding more to, or altering the performance of, the context menu's options for the current context.
bon appetite

A: It's another name for the Menu Key. (http://en.wikipedia.org/wiki/Menu_key)
It typically has a picture of a right-click menu on it.

A: On my Pavilion g7 it just shows the menu icon without the mouse pointer, but acts exactly like a right mouse click. And yes it is between the right Alt & Ctrl keys.


text:
Q: Using Graphics class and DrawRectangle method(-x, -y) in webforms using c# Scenario: I need to replicate the solar power plant field configuration on web page(set of rectangles for mirrors and receiver).
I need to dynamically add rectangles to webpages with given X,Y,width and height parameters using c#.net. I will receive the user input a set of coordinates for rectangles as X,Y full page graph.
Eg: (-42.34,-240.34,2.25,16.65)
(10.34,-140.34,10.25,5.65)
The coordinates I receive from user input are related to X & Y full page graph that includes negative coordinates also. But the DrawRectangle accepts the X & Y values as positive and only integer values.
My query is how should I relate the user input X & Y Coords ( -ve & +ve) on the web page and float width values to integer?
When I try to convert to Int, the rectangles are either getting overlapped or not displaying at all. The set of input values for rectangles are closer and there is difference in point values only.

A: Given the objective (and ignoring the required Graphic.DrawRectangle), Your best bet is to use SVG. The SVG format is actually a XML file that describes the image you want, so you can generate it on server side and cache it as text (either on clint or server), also the SVG uses vectorial graphics (as the name suggests*) wich allows for arbitrary resolution.
*: SVG stands for Scalable Vector Graphics.
I recommend you this tutorial at 3w.org on SVG to get you started.

Here are examples of a SVG:
Inline SVG in HTML
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>SVG test</title>
    </head>
    <body>
        <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
            <rect x="10" y="10" width="50" height="30" />
        </svg>
    </body>
</html>

SVG in img element
rectangle.svg
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <rect x="10" y="10" width="50" height="30" />
</svg>

index.htm
<!DOCTYPE html>
<html>
    <head>
        <title>SVG test</title>
    </head>
    <body>
        <img src="rectangle.svg" alt="rectangle" />
    </body>
</html>

I recommend the second option (separate file). Note that this are woking drafts, well supported working draft. So, check browser compatibility.
It may be the case that you would prefer not to output the SVG text directly, in that case, check Drawing SVG in .NET/C#? here, at StackOverflow.


text:
Q: Angular/JavaScript equivalent of a C++ smart pointer As I'm starting to learn Angular I keep coming across sentences like 'don't forget to destroy the X in ngOnDestroy', where X might be something like a Subscription
In C++ there are smart pointers (probably, I'm 15+ years out of date). Are there any equivalents in Angular/Javascript?
So here
this.numberStream = obNumberStream.subscribe(
....

You would instead have something like numberStreamPtr, you would reference the Subscription functions like numberStreamPtr().XXX, and most importantly, you wouldn't need to call unsubscribe because it would be called automatically when the component destroy was called

A: There are a number of approaches mentioned here:
https://blog.angularindepth.com/why-you-have-to-unsubscribe-from-observable-92502d5639d0
but if you use the package below then you can just place this decorator on the component for it to happen automagically
@AutoUnsubscribe

https://netbasal.com/automagically-unsubscribe-in-angular-4487e9853a88
// There is also a simple/standard pattern for Observables here
Angular/RxJs When should I unsubscribe from `Subscription`

A: No, unfortunately there's no equivalent to smart pointers in Javascript, mostly due to it being an interpreted language. Observables are different than using a plain old object as well because they are internally responsible for destroying themselves; calling unsubscribe on an Observable does not immediately destroy it, it just ends the Subscription. Anything else that is still subscribed to it will continue to receive emissions.
However, there are a couple of usage patterns that make unsubscribing a bit easier to manage:

*

*Per the Rx contract spec, a cold, finite Observable does not need to be unsubscribed. Cold means that the Observable has only one Subscriber (and is not 'hot'). Finite means the Observable emits one value and then completes. These kinds of Observables handle unsubscribing and destroy themselves one complete. The most common example of this in an Angular app is a call with the HttpClient.

*Any Observable that issues an OnError or OnComplete notification to its subscribers will also handle the unsubscribe notification, and don't need to be unsubscribed explicitly.

*Hot Observables with multiple observers and a long lifetime (like Subjects) should be unsubscribed to prevent memory leaks. However, using Angular's async pipe to unwrap emission values automatically internally handles the unsubscribe notification. It's a good idea to try and use it where possible.

*Any Observables that need manual unsubscription can be handled elegantly with either a base class or a mixin (i.e. a base class that has an array of Subscribers and automatically unsubscribes them in ngOnDestroy, with derived classes adding the subscriptions to that array).

In my experience with Angular, Observables that need manual unsubscriptions are definitely in the minority. I got kind of off topic from your original question, but hopefully this helps you with something.


text:
Q: How can I make a Standard User a Local Administrator from within PowerShell? I'm writing a small PowerShell script launched from a batch file which will change a Standard User (when logged in) to a Local Administrator. It needs to be fully automated, and I know the given machine's Admin credentials. I figured that I would begin by passing the Admin credentials, but I'm having trouble getting around the Password prompt (since it requires user action). So far I have this.
 Start-Process powershell.exe -Credential "Domain\Username" -NoNewWindow -ArgumentList "Start-Process powershell.exe -Verb runAs"
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('Windows PowerShell Credential Request')
Sleep 1
$wshell.SendKeys('SuperSecret')

Sendkeys isn't working as far as I can tell, and neither does -Password when I try to pass it as an argument. I'm not sure if I should pursue this method or if there is other logic that will let me assume a Local Administrator without being prompted to begin with. Also, this will be run on more than one machine, however the credentials are constant since they will all be on the same network.


text:
Q: Applying a function to find high density area of a distribution (coding) Background:
Recently, I came across an R function called HDIofICDF (also see below) that provides two limit-values for any distribution (a unimodal curve) such that from one limit-value to the other limit-value covers 95% highly dense area of that distribution.
The code requires that user put Inverse cdf of a distribution. For R-recognized distributions, this is achieved by "qdistribution name" e.g., qf, qchisq etc., and "," and then the arguments needed for the "qdistribution name". For example for an F distribution finding the two limit values is possible via:
HDIofICDF( qf , df1 = 10 , df2 = 90 ) OR for a Chi-Square Distribution, one can use: HDIofICDF( qchisq, df = 10)

Coding Question:
Suppose I have created my own distribution and have the Inverse cdf of this distribution. My Inverse cdf (similar to a "qdistribution name" in R) is given when I use (just as an example to show what arguments my Inverse cdf uses):
invcdf.posterior(p = .025, t = 2.81, N1 = 10, N2 = 10, rscale = 1 )
Now: given my invcdf.posterior and its arguments above, how can I use the HDIofICDF function to obtain the two limit-values for my distribution?
Here is my R codes I have:
HDIofICDF = function( ICDFname , credMass=0.95 , tol=1e-8 , ... ) {

 incredMass = 1.0 - credMass
 intervalWidth = function( lowTailPr , ICDFname , credMass , ... ) {
 ICDFname( credMass + lowTailPr , ... ) - ICDFname( lowTailPr , ... )
}
optInfo = optimize( intervalWidth , c( 0 , incredMass ) , ICDFname=ICDFname ,
                  credMass=credMass , tol=tol , ... )
 HDIlowTailPr = optInfo$minimum
 return( c( ICDFname( HDIlowTailPr , ... ) ,
         ICDFname( credMass + HDIlowTailPr , ... ) ) )
}
##########################################################################
## Example 1 of use: ##

HDIofICDF( qf , df1 = 10 , df2 = 90 ) ## This is a F distribution working OK

THIS IS HOW I TRIED TO APPLY THE HDIofICDF function TO MY OWN DISTRIBUTION:
HDIofICDF( invcdf.posterior, t = 2.81, N1 = 10 , N2 = 10, rscale = 1 ) ## Not working

The error I get is:
Error in eval(expr, envir, enclos) :
  argument "t" is missing, with no default
Called from: eval(expr, envir, enclos)

A: Notice that your HDIofICDF function has an argument tol.
Because of partial argument matching, when you call HDIofICDF(invcdf.posterior, t = 2.81, N1 = 10 , N2 = 10, rscale = 1), the t that you specified is assumed to mean tol. (You can verify this by modifying your HDIofICDF function to print tol.)  Because of this, when your invcdf.posterior is subsequently called, R complains that the t argument is missing.
Here's a toy example illustrating what is going on:
fun1 <- function(a, b) a + b
fun2 <- function(aaa, ...) fun1(...)
fun2(a = 1, b = 2)
# Error in fun1(...) : argument "a" is missing, with no default
fun2(aaa = 99, a = 1, b = 2)
# [1] 3

As suggested by the example above, to get around your problem, explicitly specify tol in your call to HDIofICDF, e.g.
HDIofICDF( invcdf.posterior, t = 2.81, N1 = 10 , N2 = 10, rscale = 1, tol = 1e-8)


text:
Q: I'm not seeing any POST requests when I run my Blazor Server App I'm running a blazor server app that has been deployed to IIS. The site has a REST web service as it's back end. The code is something like this:
<EditForm Model="@boundObject" OnValidSubmit="HandleValidSubmit">
    <td>
        <input type="checkbox" @bind="boundbject.HasCar" />
    </td>
    <button type="submit">Submit</button>
</EditForm>

@code {

    private void HandleValidSubmit(object handler)
    {
        if(boundObject.HasCar)
        {
            webService.WriteHasCar(boundObject.objectID,true)
        }
    }

}

It works just fine but looking at the network traffic in Fiddler when I submit this request, I can see the PATCH request going to the webService that the call to the web service does, but I'm not seeing a POST request for when I hit the submit button. What am I missing here? Is the Fiddler trace failing to see it or will my code not generate a POST request? And if it doesn't, how is the value of the checkbox getting to the server?

A: You can't see a Post request because no post request is made. Your form is not submitted. No traditional post request occurs though you're using a submit button.
The submit action is intercepted by Blazor and cancelled, as this is an SPA application with well-defined space boundaries. You usually do not navigate out of these boundaries, and if you do, as for instance, navigating to an external login page, your SPA does not exist any longer. When you are redirected back, it is resurrected...
Server Blazor Apps do not use the HTTP protocol, but rather SignalR. All the communications between the client-side (browser) and server-side of Server Blazor App is perform via SignalR.
Note that the initial request to your App is an HTTP get request. This is the only time HTTP is used and not SignaR


text:
Q: Retrofit JSONAPI converter needed? Is there some way to use the JSONAPI spec with Retrofit?, don't know how this will work or how to start, any help?.
I found this gist: https://gist.github.com/Gregadeaux/cbcc3781fda9d7fa6498, it uses RxJava and some other libraries.
Also, is a converter needed?.
Thank you.

A: https://github.com/jasminb/jsonapi-converter is what you're looking for
from the docs
// Create object mapper
ObjectMapper objectMapper = new ObjectMapper();

// Set serialisation/deserialisation options if needed (property naming strategy, etc...)

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://yourapi")
        .addConverterFactory(new JSONAPIConverterFactory(objectMapper, Book.class, Author.class))
        .build();

// Create service using service interface
MyBooksService booksService = retrofit.create(MyBooksService.class);

A: retrofit provide list of existed JSON converters, also you can implements Converter.Factory interface and provide your own converter. Then you can pass your class in an instance when building your adapter.
Related resources:

*

*Retrofit — Define a Custom Response Converter


text:
Q: OS X / macOS doesn't connect to NAS I have problems getting a Mac-Mini to connect to our QNAP NAS over Wifi. It once worked. As it's my wife's Mac and she doesn't care about backups or whatsoever, I don't know since when it actually doesn't work anymore.
Ping, nslookup and traceroute give no hints on network problems (ping comes back and so on). Tried telnet as well. It hangs on "Trying 192.168.1.3..." whereas telnet against other (LA)network devices gives "Unable to connect to remote host". As well tried QFinder (from QNAP) and it doesn't find the NAS.
We have three Macs at home (an iMac, the Mac-Mini and a MacBook Air, all with macOS 10.12.1). Internet and Routing is done via a Fritzbox 7490 (with FRITZ!OS 06.60). The iMac and MacBook Air have no problems connecting (via AFP or SMB) to the Shares on the NAS.
On the Mac-Mini when I CMD+K "afp://192.168.1.3/" (which is the IP of the NAS), I don't get the typical user-name-and-password dialog. There's just the small "Connecting to afp://192.168.1.3/" window which stays until the "There was a problem connecting to the server "192.168.1.3"" dialog is shown. In Finder the "Connect as..." button, shown under "Network"->"(AFP)", does nothing (But this is something I noticed on the other Macs as well).
Console shows:
11.12.16 12:13:21,778 NetAuthSysAgent[967]: AFP error -1 mapped to EIO
11.12.16 12:13:21,778 NetAuthSysAgent[967]: ERROR: AFP_GetServerInfo - connect failed 5
11.12.16 12:13:21,779 NetAuthSysAgent[967]: AFP error -1 mapped to EIO

I tried

*

*removing Wifi-connections from Mac-Mini's preferences

*restarting every hardware involved

*sudo dscacheutil -flushcache (in Terminal)

*Googleing and Duckduckgoing

Did anyone else experienced such behaviour? Does someone has ideas on what else to try, or even has a solution right away?
Thanks a lot in advance!
---- edit 2016-12-17 ----
I remembered, that I once had the same problem with the iMac, although with a slightly different network-setup. Back then I switched the iMac from manually assigned IP to DHCP - just because I was out of other options. This did the trick.
As the Mac-Mini (having the problems now) is/was configured to use DHCP,  I manually assigned an IP. Again, just because of not having any other ideas. And it woks!
I'm going to leave the question open, because it's not a real answer. The fact, that one time the problem is fixed by turning DHCP on, and the other by turning it off, confuses me.
Here some additional info on the network setup:
Router/DNS: 192.168.1.1
Mask: 255.255.255.0
DHCP IP range: 200-250
In both described occasions the manually assigned IP was before/less than 200.


text:
Q: Can I track my workout and listen to music with Apple Watch Series 2 without having to carry my iPhone? I do not have any experience with the Apple Watch, currently I am just using an iPhone. Before I buy an Apple Watch I would like to verify my question.
I know I need to pair it with an iPhone. But from what I have gathered, the new Apple Watch Series 2 is much more independent then the previous version.

*

*Tracking should be possible with the GPS module.

*Pairing a bluetooth headphone is possible.

*Playing music without iPhone is also possible.

Am I right? Or are there any limitations I have missed?

A: You are correct on all three counts.
The Workout app will work without your iPhone, at least. Third-party apps might need to be updated to be completely independent. Strava, for instance, won't start without an active iPhone connection, but Runkeeper will.
Both the first generation WATCH and Series 2 support syncing of a single playlist up to either 2GB or 250 songs.


text:
Q: iOSApp crash when shared via testflight with COSMCtrl _foregroundAppActivity incoming bundle has nil supplied UUID, finds existing error in devicelog iOSApp crash when shared via testflight with "COSMCtrl _foregroundAppActivity incoming bundle  has nil supplied UUID, finds existing " error symptomsd in devicelog App works fine if distributed via AppCenter that uses AdHoc profile.

*

*App only crashing when distributed via testflight but it works fine when shared with appcenter or in debug mode.

*App is not crashing at launch time, it crashes after one screen so I think it may not be related to app signing certificate Dev

*CPU spike is there on that event but its not that much its only 12 to 20% when checked in debug mode.

*Yes I am doning some API hit at that point and parsing response JSON.

Any clue or suggestion will be appreciated.

A: I also faced the same issue and I found that i have updated the UI in background thread. Fix of this is I Updated the UI in Main thread and issue was fixed. I hope it will help you!


text:
Q: Notation for "reference to array" type In c++, type of a reference to array is shown like int (&) [10]. As an example, when I try to compile with g++ and clang the following code
template <typename T> void foo(T&);

int main() {
    int a[] {1, 2, 3};

    foo(a);
}

I get the following error:
undefined reference to `void foo<int [3]>(int (&) [3])'

In this error text, why is the type of argument shown as int (&) [3]? Why don't we denote array reference types like references to integral types or class types, i.e. int [10] &? What is the reason for using (&)?
I know we can define a 'reference to array' variable like this:
int (&b)[3] = a;

And this definition indeed 'looks like' the type of b. But is this the only reason? Is there a problem related to the notation int [10] &?

A: It comes from how the type of pointers to arrays look like: int(*)[10]. The * is just replaced by &, like in all reference types.
The reason that pointers to arrays look like that is how it looks like in C, and C++ had no reason to change it.
int (*a)[10];
// "(*a)[10]" is an int
// The type of `a` is `int (*)[10]`, just remove the name

I don't see any technical reasons why int[10]* and int[10]& would not be possible as the name of the types for "pointer or reference to an array of 10 int", other than compatibility with C


text:
Q: Hide on body click exept item id = something How do I hide the menu except if the user clicked on element with ID = 'menubutton'?
$('body').click(function(event) {
    $('#menu').hide();
    });

A: Use the not() selector
$('body :not(#menubutton)').click(function(event) {
    $('#menu').hide();
});

http://api.jquery.com/not-selector/

A: Use the target element.
$('body').click(function(event) {
    // If the element clicked doesn't have the id "menubutton"
    if ( $(event.target).attr( 'id' ) !== 'menubutton' ) {
        $('#menu').hide();
    }
});

A: $('body').click(function(event) {
    // don't hide if the clicked element was #menubutton,
    // or any element within #menubotton
    if (!$(event.target).closest('#menubutton').length) {
        $('#menu').hide();
    }
});

A: $('body :not(div #menubutton)').click(function(event) {
   $('#menu').hide();
});

jQuery Not()
The selector for not() might need some changes for your case


text:
Q: How to calculate the loss between Q values of Target network and Policy Network in DDQN? I need some clearity about DDQN,
in understanding some background about DDQN
1 : create PolicyNetwork
2 : create TargetNetwork
3 : Copy PolicyNetwork weights to TargetNetwork
4 : create replay memory
5 : action = PolicyNetwork argmax(State)
6 : store state,reward,nextState,done to ReplayMemory
7 : R_State,R_reward,R_Action,R_NextState = ReplayMemory.sample()
8 : QValues = PolicyNetwork.predict(R_State,)
9 : QTarget = TargetNetwork.predict(R_NextState)
10 : Loss = QValue[R_action] - argmax(QTarget)

now Here is my problem :
Lets say we have 4 actions so the last layer is 4, How Can i call optimizer Fit function while it accepts 4 values while the loss is a single value? ( I feed the Fit function same R_state values as states).


text:
Q: ClassNotFoundException is driving me crazy I am trying to run this basic RMI example provided in the Java website:
https://docs.oracle.com/javase/7/docs/technotes/guides/rmi/hello/hello-world.html
And it just won't run because I think it can't find the interface. It always throws this exception:
java.lang.ClassNotFoundException: Hello
Here is the code for the interface:
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Hello extends Remote {
    String sayHello() throws RemoteException;
}

And the code for the server is
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Server implements Hello {

    public Server() {}

    public String sayHello() {
        return "Hello, world!";
    }

    public static void main(String args[]) {

        try {
            Server obj = new Server();
            Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);

            // Bind the remote object's stub in the registry
            Registry registry = LocateRegistry.getRegistry();
            registry.bind("Hello", stub);

            System.err.println("Server ready");
        } catch (Exception e) {
            System.err.println("Server exception: " + e.toString());
            e.printStackTrace();
        }
    }
}

I have added the interface to my classpath as well. My classpath contains the following entries:
 - C:\Users\mkris\Desktop\untitled\src\Hello.class

 - C:\Users\mkris\Desktop\untitled\src\Hello.java
 - C:\Users\mkris\Desktop\untitled\src

I am using the IntelliJ IDE. My src folder contains the three .java files and the corresponding .class files.
I've been trying to fix this issue for almost an entire day now and it is driving me insane. I'm very close to snapping my laptop in half.
Please help me out.
Thanks!


text:
Q: How to invoke Mongoid model inside Sidekiq worker? Is it possible to write MongoDB document via Mongoid from Sidekiq worker?

# lib/worker.rb
require 'sidekiq'
require 'model' # lib/model.rb
class AwesomeWorker
  include Sidekiq::Worker
  def perform
    RandomNumberModel.create! { random_number: Random.new.rand(1..100) }
  end
end

When I run Sidekiq it returns uninitialized constant AwesomeWorker::RandomNumberModel
What I'm doing wrong?

A: try ::RandomNumberModel.create! { random_number: Random.new.rand(1..100) }
if it fails, you did mistake in path to required file

A: Might it help of anyone :)
You have to create your worker under app > workers folder. Then every model will be easily accessible there.
# app/workers
class AwesomeWorker
  include Sidekiq::Worker
  def perform
    RandomNumberModel.create! { random_number: Random.new.rand(1..100) }
  end
end


text:
Q: ¿Como cargar elementos HTML dentro de un modal dinamicamente? Estoy implementando varias ventanas modales mediante Bootstrap. Una para cada cosa diferente.He hecho la prueba para cargar diferentes datos en una misma ventana modal.
Explico....
Tengo una para recoger usuarios favoritos,otra para usuarios seguidores y otra para usuarios a los que sigo.
He hecho la prueba para cuando presiono el botón indicado ya sea para cualquiera de esos datos que quiero,me abran el mismo modal,pero con la diferencia de que me traen datos según el botón que presiono,ya sea favoritos,seguidores y siguiendo.Todo marcha muy bien.
Esos datos los traigo de la BD a través de ajax(Jquery) y PHP.
¿Cual es el problema?
Hacer aparecer elementos HTML diferente según el link en el que hago clic.
Ejemplo:
cuando hago clic en el link Favoritos me gustaría que me saliera un textbox,pero cuando hago clic en el link Seguidores no quiero el textbox. Sabiendo que estos datos(Seguidores,Favoritos,Siguiendo)se abrirán el mismo modal.
Quizás me puedan entender.

$(document).ready(function(){
$('#multi_opt_user').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget)
  var recipient = button.data('whatever')
  var modal = $(this)
  modal.find('.modal-title').text(recipient)

});
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Seguidores

    Favoritos

             <button id="pethatlimypro" type="button" class="close" data-dismiss="modal">×</button>

                                       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

A: No se si entendi bien, pero si quieres agregar elementos HTML puedes usar append
Algo así:
$("#id_del_elemento_al_que_se_agrega").append("Código html");

A:

$(document).ready(function(){

$('#seguidores').click(function(){
         $('#pocos').html('
seguidores
')
});

$('#favoritos').click(function(){
         $('#pocos').html('
favoritos
')
});

$('#multi_opt_user').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget)
  var recipient = button.data('whatever')
  var modal = $(this)
  modal.find('.modal-title').text(recipient)

});
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Seguidores

    Favoritos

             <button id="pethatlimypro" type="button" class="close" data-dismiss="modal">×</button>

                                       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

A: aqui te dejo mi codigo funciona de maravilla. copie y pegue lo que tengo
esto va en una .php

aqui va el otro .php

    <button type="button" class="close" data-dismiss="modal">×</button>

titulo

aqui pones el codigo q quieras

    <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>


text:
Q: Print Lines Containing String: Odd Behavior I am using Python3 to try to emulate
awk '/STRING/'

I made some code that works, but it stops on the first instance instead of finding all lines that contain the specified character/string.
After I made the code, I saw these two pages, but the suggestions did not work
Print line containing "word" python
Search and get a line in Python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Made by Devyn Collier Johnson, NCLA, Linux+, LPIC-1, DCTS
def cat(openfile): #Emulates cat#
    with open(openfile) as file:
        lines = file.readlines()
        return ''.join(lines)
def GETLINEWITH(FILECONTENTS, CONTAINING):
    for item in FILECONTENTS.split('\n'):
        if CONTAINING in item:
            return item.strip()

print(GETLINEWITH(cat('./Base.xaiml'), 'terminal'))

I have a file (./Base.xaiml) that contains several instances of the word "terminal".  I am using this file and string for testing purposes.
EDIT: I also want to save the results to a variable -
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Made by Devyn Collier Johnson, NCLA, Linux+, LPIC-1, DCTS
def cat(openfile): #Emulates cat#
    with open(openfile) as file:
        lines = file.readlines()
        return ''.join(lines)
def GETLINEWITH(FILECONTENTS, CONTAINING):
    for item in FILECONTENTS.split('\n'):
        if CONTAINING in item:
            print(item.strip()) #I implemented the give suggestion

VAR = GETLINEWITH(cat('./Base.xaiml'), 'terminal'))

Results:
I tried Jon Clements suggestion:
with open('./Base.xaiml') as fin:
    matching = ('terminal' in line for line in fin)
    for line in matching:
        VAR = matching
print(VAR)

However, the output is one memory address. ''.join() and group() do not help.
Edit2:
Newest code
Issues - nonetype error and the output cannot be saved to a variable
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Made by Devyn Collier Johnson, NCLA, Linux+, LPIC-1, DCTS
def cat(openfile): #Emulates cat#
    with open(openfile) as file:
        lines = file.readlines()
        return ''.join(lines)
def GETLINEWITH(FILECONTENTS, CONTAINING):
    for item in FILECONTENTS.split('\n'):
        if CONTAINING in item:
            print(item.strip())
for line in GETLINEWITH(cat('./Base.xaiml'), 'terminal'):
    print(line)

A: Here you go, note that I am just putting together everyone elses comments explicitly for you.
#!/usr/bin/env python3

def cat(openfile):
  with open(openfile) as file:
    return file.read()

def GETLINEWITH(FILECONTENTS, CONTAINING):
  for item in FILECONTENTS.split('\n'):
    if CONTAINING in item:
      yield item.strip()

matchedlines = []

for line in GETLINEWITH(cat('./Base.xaiml'), 'terminal'):
   print(line)
   matchedlines.append(line)

print(matchedlines)

The matchedlines variable is just an example for you of one way to save the matched lines in a variable.
An alternative GETLINEWITH implementation is:
import re

def GETLINEWITH(FILECONTENTS, CONTAINING):
  for item in FILECONTENTS.split('\n'):
    m = re.search(CONTAINING, item)
    if m:
      yield m.string

Which will let you match on regular expressions.

A: Anyway - the reason it "stops" is because you're returning after a match....
def GETLINEWITH(FILECONTENTS, CONTAINING):
    for item in FILECONTENTS.split('\n'):
        if CONTAINING in item:
            return item.strip() # <---- returns as soon as something's found

Change it to a yield to make the function a generator and then loop over it:
for line in GETLINEWITH(cat('./Base.xaiml'), 'terminal'):
    print(line)

Ultimately, your function should just be:
with open('thefile') as fin:
    matching = (line for line in fin if 'something' in line)
    for line in matching:
        # do something

Or, put them all into a list:
lines = list(matching)

A: File objects are iterable, and a list comprehension can be used to filter the input.
with open('./Base.xaiml','r') as lines:
    matching_lines = [ line.rstrip('\n')
                       for line in lines
                       if line.find('terminal') != -1 ]

for line in matching_lines:
    print line         # change to print(line) for python 3.x

EDIT: or if you really want it to be a function
def matching_lines(filename, substring):
    """ Return all the lines in a file that contain a given substring. """
    with open(filename,'r') as f:
        return [s.rstrip('\n') for s in f if s.find(substring) != -1]

for s in matching_lines('./Base.xaiml', 'terminal'):
    print s


text:
Q: How does one pass the properties of a $_POST to a Function? I would like to pass the properties to a function to Update details in a database. I want all the columns that were selected in the form to be passed to a function. Frankly, I don't know what to do.
My code is the following:
if (isset($_POST["updateWineButton"])) {

    $wineID = $_POST["wineID"];
    $wineCountryID = $_POST["wineCountryID"];
    $wineSizeID = $_POST["wineSizeID"];
    $wineRatingID = $_POST["wineRatingID"];
    $wineColourID = $_POST["wineColourID"];
    $packageID = $_POST["packageID"];
    $wineCategoryID = $_POST["wineCategoryID"];
    $wineCode = $_POST["wineCode"];
    $price = $_POST["price"];
    $description = $_POST["description"];
    $wineRating = $_POST["wineRating"];
    $wineIMG = $_POST["wineIMG"];

    updateWine($updateWine);
    $status = "$description has been updated.";
}

Update Wine Function
function updateWine($wineUpdate)
{
    global $pdo;
    $statement = $pdo->prepare("UPDATE WINE SET wineID=?, wineCountryID=?, wineSizeID=?, wineRatingID, wineColourID=?,
                            packageID=?, wineCategoryID=?, wineCode=?, price=?, description=?, wineRating=?, wineIMG=?
                            WHERE wineID=?");

    $statement->execute([$wineUpdate->wineID,
        $wineUpdate->wineCountryID,
        $wineUpdate->wineSizeID,
        $wineUpdate->wineRatingID,
        $wineUpdate->wineColourID,
        $wineUpdate->packageID,
        $wineUpdate->wineCategoryID,
        $wineUpdate->wineCode,
        $wineUpdate->price,
        $wineUpdate->description,
        $wineUpdate->wineRatingID,
        $wineUpdate->wineIMG]);

    $statement->fetch();
}

A: Something like the following should work for you:
function updateWine()
{
    global $pdo;

    $keys = [
        "wineID", "wineCountryID", "wineSizeID", "wineRatingID", "wineColourID", "packageID", "wineCategoryID",
        "wineCode", "price", "description", "wineRating", "wineIMG",
    ];

    $results = [];

    foreach ($keys as $index) {
        if (isset($_POST[$index])) {
            $results[$index] = $_POST[$index];
        }
    }

    $statement = $pdo->prepare("UPDATE WINE SET " . implode('=?, ', array_keys($results)) . "=? WHERE wineID =?");

    $statement->execute(array_merge(array_values($results), [$_POST['wineID']]));

    $statement->fetch();
}

if (isset($_POST["updateWineButton"]) && isset($_POST['wineID'])) {
    updateWine();
}

Hope this helps!

A: if I understand correctly you want to do something like this,
if (isset($_POST["updateWineButton"])) {
  $result = updateWine($_POST);
  if($result){
    $status = "$description has been updated.";
  }else{
    $status = "An error occurred.";
  }
}

//your function woud then look like ...

function updateWine($postdata){
  $wineID = $postdata["wineID"];
  $wineCountryID = $postdata["wineCountryID"];
  $wineSizeID = $postdata["wineSizeID"];
  $wineRatingID = $postdata["wineRatingID"];
  $wineColourID = $postdata["wineColourID"];
  $packageID = $postdata["packageID"];
  $wineCategoryID = $postdata["wineCategoryID"];
  $wineCode = $postdata["wineCode"];
  $price = $postdata["price"];
  $description = $postdata["description"];
  $wineRating = $postdata["wineRating"];
  $wineIMG = $postdata["wineIMG"];
  //udpate your database with the above values
  //check if update is successful
  return true;
  //else if there was an error
  return false;
}


text:
Q: Convert image with high quality using imagemagick I want to remove spots from the image shown below. I have tried using Imagemagick's convert function, but the black spots are not removed. I need a cleaner image with bold date showing.

A: In Imagemagick, you can remove the spots using connected components and optionally morphology. For example the following removes 2 pixel isolated spots or less. The morphology fills in some of the dark part of the text (it removes or opens the white background). But it may make some of the characters merge (touch):
Input:

convert spots.png \
-threshold 1% -type bilevel \
-define connected-components:area-threshold=2 \
-define connected-components:mean-color=true \
-connected-components 4 \
spots_clean.png

convert spots.png \
-threshold 1% -type bilevel \
-define connected-components:area-threshold=2 \
-define connected-components:mean-color=true \
-connected-components 4 \
-morphology open diamond:1 \
spots_clean_o1.png

convert spots.png \
-threshold 1% -type bilevel \
-define connected-components:area-threshold=2 \
-define connected-components:mean-color=true \
-connected-components 4 \
-morphology open octagon:1 \
spots_clean_o2.png

A: I think there is no "easy" way to do this. But :

*

*You can iterate over all pixels of the image and check this:

*

*if the current pixel is black : check all neighbourg pixels.

*if all neightbourg pixels are white, change current pixel to white.

*A better way, but longer way, is to use an OCR, to recognize the numbers and characters. Then rebuild the image with the characters found.


text:
Q: In MYSQL, how to upload a csv file that contains a date in the format of '1/1/2020' properly into a DATE data type format (standard YYYY-MM-DD) I have a column of data, let's call it bank_date, that I receive from an external vendor as a csv file every day. As such the dates in that column show as '1/1/2020'.
I am trying to upload that raw csv file directly to SQL daily. We used to store the SQL bank_date format as text, but we have converted it to a Data data type, and now it keeps zero'ing out every time, with some sort of truncate / "datetime value incorrect" error.
I have now tested 17 different versions of utilizing STR_TO_date (mostly), CAST, and CONVERT, and feel like I'm close, but I'm not quite getting the syntax right.
Also for reference, I did find 2 other workarounds that are successful, but my boss specifically wants it uploaded and converted directly through the import process (not manipulating the raw csv data) for safety reasons. For reference:

*

*Workaround 1: Convert csv date column to the YYYY-MM-DD format and save file. The issue with this is that if you try to open that CSV file again, it auto-changes the date format back to the standard mm/dd/yyyy. If someone doesn't know to watch out for this and is re-opening the csv file to double check something, they're gonna find an error when they upload, and the problem is not easy to identify.

*Workaround 2:Create an extra dummy_date column in the table that is formatted as a text data type and upload as normal. Then copy and paste the data into the correct bank_date column using a str_to_date function as follows: UPDATE dummy_date SET bank_date = STR_TO_DATE(dummy_date, '%c/%e/%Y'); The issue with this is that it just creates extra unnecessary data that can be confused when other people may not know that 1 of the columns is not intended for querying.

Here is my current code:
USE database_name;
LOAD DATA LOCAL INFILE 'C:/Users/Shelly/Desktop/Date Import.csv'
INTO TABLE bank_table
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 ROWS
(bank_date, bank_amount)
SET bank_date = str_to_date(bank_date,'%Y-%m-%d');
The "SET" line is what I cannot work out on syntax to convert a csv's 1/5/2020' to SQL's 2020-1-5 format. Every test I've made either produces 0000-00-00 or nulls the column cells. I'm thinking maybe I need to tell SQL how to understand the csv's format in order for it to know how to convert it. Newbie here and stuck.

A: You need to specify a format for a date that is in the file, not a "required" one:
SET bank_date = str_to_date(bank_date,'%c/%e/%Y');


text:
Q: How to output Django form on the browser I'm learning to create a post and comment session with Django and I'm following a tutorial but I don't know why I'm not getting the same result as the one in the tutorial. The post aspect is working but the form for comments is not being displayed on the browser. Even after going through Django documentation and other resources online, I still don't see where I'm getting it wrong. I have the following directories and files:
start is my app directory while education is the main django directory
start/models.py
class Comment (models.Model):
    post = models.ForeignKey(Post,related_name = 'comments', on_delete = models.CASCADE)
    name = models.CharField()
    email = models.Email()
    body = models.TextField()
    createdAt = models.DateTimeField(auto_now_add=True)
    class Meta:
        ordering = ['createdAt']

start/forms.py
from django import forms
from .models import Comment

class post_comment(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['name', 'email', 'body']

start/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import post_comment

def fullPost(request, slug):
    post = Post.object.all()
    return render (request, 'start/start.html', {'post': post})
    if request.method == 'POST':
        form = post_comment(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect ('fullPost', slug=post.slug)
        else:
            form = post_comment()
        return render (request, 'start/fullPage.html', {'post': post, 'form': form})

start/templates/start/fullpost.html
•••

Comment

<form method = 'post' action = '.'>
    {% csrf_token %}
    {{ form.as_p }}
   <button> Post comment  </button>
</form>

A: The issue is with the structure of the  fullpost view
In this line:
    return render (request, 'start/start.html', {'post': post})

the function is exited without the form.
You could try:
start/views.py
...
    def fullPost(request, slug):
        post = Post.object.all()
        #return render (request, 'start/start.html', {'post': post})
        if request.method == 'POST':
            form = post_comment(request.POST)
            if form.is_valid():
                comment = form.save(commit=False)
                comment.post = post
                comment.save()
                return redirect ('fullPost', slug=post.slug)
        else:
            form = post_comment()
        return render (request, 'start/fullPage.html', {'post': post, 'form': form})
...

If form.is_valid() fails, it will fall through to the end, rendering the form with the incorrect data.
Edit
Since you are learning , the following line may be wrong

post = Post.object.all()

because objects.all() retrieves all the posts in the db. Unless you want to comment all posts, you may need to  rewrite it as follows:

post=Post.objects.get(slug=slug)

This will retrieve the post with the matching slug, assuming the slug field is unique.
https://docs.djangoproject.com/en/3.1/topics/db/queries/#retrieving-all-objects
https://docs.djangoproject.com/en/3.1/topics/db/queries/#retrieving-a-single-object-with-get


text:
Q: How to change width of underline in css I have a cell in a table like this:
Grand Total

I need to give it a line under the text "Grand Total". I used text-decoration: underline;. It worked well, but I need to change the color and thickness of the underline. I used text-decoration-color: red; to add color but it doesn't work. How can I solve this problem?

A: You cannot modify the width of underline tag. Instead go for Border-bottom approach and change it's properties as required.

.underline {
  border-bottom: 5px solid red;
}

    Grand Total

A: Use pseudo elements like :before and :after to control the length of the underline as well

td {
  position: relative;
}

td:after {
  content: '';
  position: absolute;
  width: 100%;
  display: block;
  height: 5px;
  background-color: red;
  bottom: -5px;
}

      Grand Total

A: You should give class or id to your specific line, like:
HTML:
Grand Total

CSS:
#total {
  border-bottom: 1px solid red;
  padding: 0 0 4px;
}

A: The best approach is to use the text-decoration-thickness css property. Here is the link to the documentation. A simple code sample would look something like:
text-decoration: underline solid black 2px;

The 2px here is the text-decoration-thickness or rather the width of the underline.

A: From here

td {
  color: red;
  text-decoration: underline;
}

span {
  color: black;
  text-decoration: none;
}

    Grand Total

A: use border-bottom  define color cording  like this

b {
    border-bottom: 1px solid red;
    padding: 0 0 4px;
}
Grand Total

A: If you target your 'b', you can use a background gradient which will allow you to adjust the thickness of the line and the line's vertical placement.
eg.
b {
    background-image: linear-gradient(to bottom, #fdb514 50%, transparent 50%);
    background-position: 0px 0.9em;
    background-repeat: repeat-x;
    background-size: 1px 15px;
    display: inline;
}

A: Usually I use these three CSS properties to style the underline
To set the thickness of the underline
text-decoration-thickness: 3px;
To set the color of the underline
text-decoration-color: red;
To offset the underline
text-underline-offset: 5px;

A: td {
position: relative;
}

td::after {
content: '';
position: absolute;
width: 30%;
display: block;
height: 5px;
background-color: red;
bottom: -5px;
}

To control the width, you just change the width from 100% to whatever value you wish.