c# search an array of objects for a specific int value, then return all the data of that object

Question: So i've created a class that holds strings, ints, and floats.
then i declared an array in main of those types and read in objects of that type into it
now i need to search that array for a specific value, and if that value matches, then return the whole object
how would i go about doing this?
really stumped
public class cdClass
{
    private static string artist = null;
    private static string genre = null;
    private static string cdTitle = null;
    private static float mSRP;
    private static int stock;
    private static int upc = 0;

    //Following functions are public member methods
    public void read_cd(string artist, string genre, string cdTitle, float mSRP, int stock, int upc)
    {
        //cdClass cd = null ;
        System.Console.WriteLine("Enter Artist Name: ");
        artist = Console.ReadLine();

        System.Console.WriteLine("Enter CD Title: ");
        cdTitle = Console.ReadLine();

        System.Console.WriteLine("Enter Genre Type: ");
        genre = Console.ReadLine();

        System.Console.WriteLine("Enter Manufacturers Suggested Retal Price: ");
        mSRP = float.Parse(Console.ReadLine());

        System.Console.WriteLine("Enter UPC Number: ");
        upc = int.Parse(Console.ReadLine());

        System.Console.WriteLine("Enter Stock: ");
        stock = int.Parse(Console.ReadLine());

        //return cd;
    }

    public  int get_upc()
    {
        return upc;
    }

MAIN:
//Follwoing cod will initialize an array of Cd's
cdClass[] cdArray = new cdClass[20];

float taxRate = 0;
do
{
    int i = 0;
    cdClass current_cd = new cdClass();
    current_cd.read_cd(artist, genre, cdTitle, mSRP, stock, upc);
    cdArray[i] = current_cd;
    i++;

} while (businesslogic.question() != 'Y');

buyer = inputfunctions.buyer();
int UPC = inputfunctions.get_upc();

for (int i = 0; i < 20; i++)
{
    if (cdArray[i].get_upc() == UPC)

Answer: You could use a simple LINQ extension method to search for the object.
var foundItem = myArray.SingleOrDefault(item => item.intProperty == someValue);

Here is some MSDN information regarding LINQ to get you more familiar.
EDIT for the code posted.
I first want to say it looks like you are bringing across some paradigms from a different language, like java with your getter method instead of using .NET style properties, something you might want to look into.  But I have made a code example more tailored to your specific case..
You can replace the block
for (int i = 0; i < 20; i++)
{
    if (cdArray[i].get_upc() == UPC)

With
cdClass foundCD = cdArray.SingleOrDefault(cd => cd.get_upc() == UPC);

Or using the Array.Find() method as suggested by BrokenGlass..
cdClass foundCD = Array.Find(cdArray, delegate(cdClass cd) { return cd.get_upc() == UPC); });

Answer: Array.Find() is an alternative to LINQ in this special case, especially if you are restricted to an older .NET version:
var fooItem = Array.Find(myArray, item => item.fooProperty == "bar");

Comment: Just FYI if you are restricted to a version of .NET that cannot use LINQ it is highly unlikely you would use the lambda expression syntax for the predicate of `Array.Find()`... `Object found = Array.Find(myArray, delegate(MyType o) { return o.Foo == someValue; });`
Answer: Use LINQ like:
public class Car
{
    public int ID { get; set; }
    public int CarName { get; set; }
}

class Program
{
    public IEnumerable<Car> GetCars
    {
        get { return MyDb.Cars; }
    }

    static void Main(string[] args)
    {
        Car myCar = GetCars.FirstOrDefault(x => x.ID == 5);
        Console.WriteLine("ID: {0} | CarName {1}", myCar.ID, myCar.CarName);
    }
}

http://msdn.microsoft.com/en-us/library/bb397926.aspx will provide you with the necessary information to get you started with LINQ.
Answer: class TheThing {
    public int T1;
    public float T2;
}

List<TheThing> list = new List<TheThing>();

// Populate list...

var instance = (from thing in list
               where thing.T1 == 4
               select thing).SingleOrDefault();

This assumes you'll only have one match where T1 == 4, if you're going to have more than one then do something like this:
var instances = from thing in list
                where thing.T1 == 4
                select thing;

Answer: For those that are still "stuck" in .Net 2...
My class array structure...
public class EmployerContactDetailsClass
{
    public string wsStudentID { get; set;}
    public string wsOrgID { get; set;}
    public string wsContactID { get; set;}
    public string wsContactName { get; set;}
    public string wsContactEmail { get; set;}
    public string wsEmployerEmail { get; set;}
    public bool wsUserChoiceVerifier { get; set;}
}

I want to find a specific element in this class based on a passed index value using wsStudentID == 'somevalue'.
First create a list array
List<EmployerContactDetailsClass> OrgList = new List<EmployerContactDetailsClass>();

Next create a single node element
EmployerContactDetailsClass OrgElem = new EmployerContactDetailsClass();

Build your list from some data source (my case a Reader object)
                        OrgElem.wsOrgID = reader["OrganisationID"].ToString();  //Org ID from database
                        OrgElem.wsContactID = reader["ContactID"].ToString();   //Contact ID from employer database
                        OrgElem.wsUserChoiceVerifier = (bool)reader["UserChoiceVerify"];  //boolean by default
                        if (reader["ContactGivenName"].ToString() != string.Empty && OrgElem.wsUserChoiceVerifier)
                            OrgElem.wsContactName = reader["ContactGivenName"].ToString() + " " + reader["ContactFamilyName"].ToString();
                        else
                            OrgElem.wsContactName = "TO WHOM IT MAY CONCERN";
                        OrgElem.wsContactEmail = reader["ContactEmail"].ToString();   //"email@example.com";
                        OrgElem.wsEmployerEmail = reader["OrganisationEmail"].ToString();    //"firstname.lastname@example.com";

                        //now add the elements into the array class
                        OrgList.Add(OrgElem);

Convert the List<> into an Array[]
EmployerContactDetailsClass[] OrgListArray = (EmployerContactDetailsClass[])OrgList.ToArray();

Find a given StudentID in the array using a Delegate.
String wsStudentID = 'FIND007'; //with respect to Roger Moore RIP
EmployerContactDetailsClass OrgElemFound = Array.Find(OrgListArray, ByStudentID(wsStudentID));

And the Predicate method somewhere else on your code...
//predicate method to return true or f if studentID matches the array list (used to pass into SendEmail)
private Predicate<EmployerContactDetailsClass> ByStudentID(string wsStudentID)
{
    return delegate(EmployerContactDetailsClass OrgElem)
    {
        return OrgElem.wsStudentID == wsStudentID;
    };
}

Cheers!


Vim EasyMotion search matches

Question: Vim EasyMotion has search character using:
<Leader>fc

which highlights all occurrences of character from which i can choose.
Is there an equivalent motion for search matches like
<Leader>fadd

which hightlights all occurrences of phrase "add" from which i can choose?
Answer: <leader>f{char} brings you to character, not a search pattern. (now default <leader><leader>f )
The way I am using this plugin is, I am watching the position (char or word) I want to go to, type <leader><leader>f or w..., type the highlighted letter to move my cursor to the right position. So I don't have a requirement of going to a certain pattern using easymotion.
however what you want is possible. you could search add first, by / or ?, then type <leader><leader>n or <leader><leader>N all adds are with a prefix, which you could choose.
(if your easymotion mapping is with single <leader>, change the double leaders to single)
read
:h easymotion

2.1  Default mappings

for detail

Vim EasyMotion search matches


Got undefined variable when using it in the component but it is defined in the template

Question: Got undefined variable when using it in the component but it is defined in the template
Im noobie :p
when i try to get this.authService.queue_start in console i get undefined

public queue_start: string;
constructor(private http: Http, private authService: AuthService, private router: Router) {
const token = localStorage.getItem('token');
if(token){
        this.http.get('api/v1/user?token='+ token)
          .subscribe(
              response => {
                  this.authService.dataa = response;
                  this.authService.queue_start = this.authService.dataa.json().queue_start;
                  },
              error => console.log(error),
          );
    }

if(this.authService.queue_start == "1"){
     console.log(this.authService.queue_start,"queue_start = 1");
   }else {
  console.log(this.authService.queue_start);
   }
}
Comment: would you mind specifying which variable is undefined
Comment: this.authService.queue_start
Comment: after this line `this.authService.dataa = response;`, try `console.log(this.authService.dataa.json());` to see what the response looks like
Comment: I get {id: 27, username: "hASVAN", email: "email@example.com", Points: "999", queue_start: "1"}
Comment: Ah I see, the problem is because `http.get` returns an observable, therefore your code run in async. I've put an answer.
Answer: The problem is http.get return an observable, therefore your code will run in async.. These line here:
if(this.authService.queue_start == "1"){
   console.log(this.authService.queue_start,"queue_start = 1");
}else {
   console.log(this.authService.queue_start);
}

will get executed before this.http.get('api/v1/user?token='+ token) gives the result.
In order to solve this, you have to made this.http.get('api/v1/user?token='+ token) into a new method which return a promise.
getData(token): Promise<any> {
    return new Promise(resolve => {
        this.http.get('api/v1/user?token='+ token)
            .subscribe(
                response => {
                    resolve(response.json().queue_start);
                },
                error => console.log(error));
    });
}

To call this async method in the constructor would be like this:
if(token){
    this.getData(token).then(queueStart => console.log(queueStart));
}

Now you should be able to see that queueStart would have the result that you want.
This is what your class now looks like:
public queue_start: string;

constructor(private http: Http, private authService: AuthService, private router: Router) {
    const token = localStorage.getItem('token');
    if(token){
        this.getData(token).then(queueStart => console.log(queueStart));
    }
}

getData(token): Promise<any> {
    //....
}

---------------UPDATE------------------
To use the result you get, you would use it like this:
if(token){
    this.getData(token).then(queueStart => {
        this.authService.queue_start = queueStart;
        if(this.authService.queue_start == "1"){
            console.log(this.authService.queue_start,"queue_start = 1");
        }else {
            console.log(this.authService.queue_start);
        }
    });
}

Comment: thx for your time man i hope you get all the happiness you deserve
Comment: sorry im new in angular where do i need to add  getData: Promise {
  return new Promise(resolve => {this.http.get('api/v1/user?token='+ token)
    .subscribe(
        response => {
            resolve(response.json().queue_start);
        },
        error => console.log(error));
});
Comment: put it in the class as its method, let me update the answer @hasvan
Comment: thx man but when  i add    this.getData(token).subscribe(queueStart => console.log(queueStart)); I get this error ERROR in /var/www/battle/src/app/app.component.ts (31,33): Property 'subscribe' does not exist on type 'Promise'.
Comment: @hasvan yep that's also my typo, my bad, change `subscribe` to `then`
Comment: its working were do i need to add please this.authService.dataa = response;
                  this.router.navigateByUrl('play');
                  this.authService.isLoggedIn = true;
                  console.log(this.authService.dataa.json().id);
                  this.authService.avatar = this.authService.dataa.json().avatar;
                  this.authService.queue_start = this.authService.dataa.json().queue_start;
                  this.authService.Points = this.authService.dataa.json().Points;
                  this.authService.username = this.authService.dataa.json().username;
Comment: @hasvan I assume those are statements which need to be called after you get your response. Therefore put those inside the `then`, just like the `console.log(queueStart)`.. But because you have multiple statements, don't forget the `{ }` mark... So it would be like this `then(queueStart => { /*your multiple statement goes here*/ });`
Comment: can you please show me how to add getData to the if and show me how to make this as the answer and thx you if(this.authService.queue_start == "1"){
   console.log(this.authService.queue_start,"queue_start = 1");
}else {
   console.log(this.authService.queue_start);
}


How to conditionally execute jQuery validate plugin

Question: I have a form (similar to shown below) which is being validated by jQuery validate plugin -
JQuery Form Validation
$("#form").validate({
    debug: true,
    rules: {
        Field1: {
            required: true,
            field1condition: true
        },
        Field2: {
            required: true,
            field2condition: true
        }
    }
    ,
    submitHandler: function (form) {
        submit(form)
    }
});

I need this entire form to be validated ONLY if certain button (let's say id="clickme") has been clicked earlier. But in any case, the form should be submitted (so if the button was clicked then validate and submit else don't run validate and only submit). I can use depends: for each field but it seems like a cumbersome task as I have a lot of conditions for every field. Is there any  simpler way to achieve this functionality?
Thanks in advance.
Answer:
(so if the button was clicked then validate and submit else don't run validate and only submit)  Is there any simpler way to achieve this functionality?

YES.
Use class="cancel" on the submit button.
<input type="submit" class="cancel" ....

OR
<button type="submit" class="cancel" ....

Using class="cancel", this button will submit the form as per the plugin's submitHandler and bypass the form validation entirely.  Without class="cancel", this button would trigger validation and only submit when the form is fully validated.
I suppose you could dynamically add/remove this cancel class on a single form submit button based on some other action, function or button.

BTW:
Your submitHandler is probably superfluous...
submitHandler: function (form) {
    submit(form)
}

I only say "probably" because I'm not sure if you have another function named submit() or if you're simply improperly using jQuery .submit().
However, this is more like what the plugin is doing by default...
submitHandler: function (form) {
    $(form).submit(); // <- default form action
}

If that's the case, then you do not even need the submitHandler option, since that is already the default behavior of the plugin.  Simply remove the submitHandler.
Comment: Exactly what I was looking for. This works for me nicely. Thanks a lot! And yes, I have a submit() function available.
Answer: Declare a global variable _validate
   $(document).ready(function(){

    var _validate = false;

    //You need to initialize validate before.
    $("#form").validate({
        debug: true,
        rules: {
            Field1: {
                required: true,
                field1condition: true
            },
            Field2: {
                required: true,
                field2condition: true
            }
        }
        ,
        submitHandler: function (form) {
            submit(form)
        }
    });

    $("#clickme").click(function(){
        _validate = true;
    });

    $("#submit_button_click_id").click(function(e){
    e.preventDefault();
    if(_validate) $("#form").validate();
    else $("#form").submit();
    });
 });

Comment: That's cumbersome and it will not work.  The `.validate()` method is only use for *initializing* the plugin and will do nothing when called within your conditional handler.


Evaluating $\lim_{x\to 0}{\frac{\sin^2x}{2x^2}}$ without L'Hospital

Question: I have been trying to evaluate
$$\lim_{x\to 0}{\frac{\sin^2x}{2x^2}}$$
Finally, I used the L'Hospital's Theorem and I got the answer $1/2$, but I wonder if there is a way to solve this without this.
I also tried using Squeeze Theorem, but my boundaries were approaching different numbers.
Comment: If you know that $\sin x / x \to 1$, this is one line.
Comment: Unfortunately, I don't know this. Should I have known it?
Comment: Well, since $\lim_{x \to 0} \frac{\sin x}{x}$ is the definition of the derivative of $\sin$ at $0$, yes.
Comment: http://math.stackexchange.com/questions/75130/how-to-prove-that-lim-limits-x-to0-frac-sin-xx-1
Comment: There is an answer providing the most elementary method. Make sure you upvote it if useful.
Answer: Hint:
$\sin^\prime = \cos$, so that $\sin^\prime(0) = \cos 0 = 1.$ Can you make this quantity appear?
In more detail: (place your mouse over the gray area to reveal its contents)

You can write$$\frac{\sin^2 x}{x^2} = \left(\frac{\sin x}{x}\right)^2 = \left(\frac{\sin x-\sin 0}{x-0}\right)^2 \xrightarrow[x\to 0]{} \left(\sin^\prime(0)\right)^2 = 1$$using continuity of the function $t\mapsto t^2$.
Comment: This is circular reasoning, because the proof of $\sin' x=\cos x$ usually uses the fact that $\lim_{x\to 0}\frac{\sin x}{x}=1$.
Comment: In [this question](http://math.stackexchange.com/questions/75130/how-to-prove-that-lim-limits-x-to0-frac-sin-xx-1) there are some proofs of why $\lim_{x\to 0}\frac{\sin x}{x}=1$.
Comment: Depends on the proof. Yours, maybe -- some use the fact that $\sin x = \mathrm{Im}(e^{ix})$ and differentiate the complex function; some use the series representation; some use other techniques (e.g., based on $\cos^2 + \sin^2 =1$)... Whether something is "legitimate" or not is really a matter of background.
Comment: @ClementC. i think limit is a more low level concept, so it should'nt be proven using derivatives. please correct me if you think i am wrong
Comment: It may be - that's for the OP to judge... here is a simple method, only requiring knowledge of derivative of sine (which I would deem basic in almost all context not specifying "from first principles"). Whether it is allowed in the context of the OP's question is up to him/her.
Answer: Hint: If you want to use the Squeeze Theorem, you can proceed geometrically and observe that for $x\neq 0$ \begin{align}\frac12|\sin x| \le \frac12|x|\le \frac12|\tan x| &\implies 1\le \frac{|x|}{|\sin x|}\le \frac{1}{|\cos x|}\\ &\implies |\cos x|\le \frac{|\sin x|}{|x|}\le 1\\&\implies\cos^2x\le \frac{\sin^2 x}{x^2}\le1\end{align}
Comment: This geometric interpretation pre-supposes that you have chosen a scale for the angle that already satisfies this inequality resp. has the limit as 1. Remember, geometrically the angle is an equivalence class of ordered pairs of intersecting lines.
Answer: $\displaystyle\lim_{x\to 0}\frac{\sin^2x}{2x^2}=\frac{1}{2}\lim_{x\to 0}\Bigg(\frac{\sin x}{x}\Bigg)^2=\frac{1}{2}$


How to visualize Dirichlet distribution (with more than 3 targets)?

Question: I want to plot a Dirichlet distribution $\operatorname{Dir}(\alpha), \alpha=[\alpha_1, \alpha_2, \ldots,\alpha_n]$. However, when I google it, almost all of the results consider 3 targets ($n=3$), and the distribution can be visualized by a triangle (e.g. Dirichlet distribution from Wikipedia).
What if I have 4 ($n=4$) or 5 ($n=5$) targets? Will the visualization be rectangle or pentagon?
To obtain some toy data, we can do
<code>from scipy.stats import dirichlet
import numpy as np

n_samples = 100
alpha = np.array([0.4, 5, 15, 3, 2])
toy_data = dirichlet.rvs(alpha, size=n_samples) #shape (100, 5)
</code>
Answer: A Dirichlet distribution is a distribution over a simplex.
A simplex is a lower-dimensional ($n-1)$ subspace of an $n$-dimensional space. With two targets, the simplex is a line. With three targets, it's a triangle. In four, it's a tetrahedron (not a square)…and so on.
The reason you don't see 4-target examples is because it's hard to display probability density on the 3D structure. The reason you don't see 5-target or higher is that we're bad at visualizing 4D spaces. Our visual system (and indeed, our entire grip on reality) is centered on 3D space. Trying to visualize more than that is the challenge of Abbott's famous book Flatland.
Comment: I've always wanted to write some code for visualizing 4-element compositional data/distributions in a tetrahedon, even though it would be more cool than useful ... I wonder if there's an analog of pairs plots for higher-order compositional data ... ??
Comment: Thanks for your explanation. It makes sense to me. If I have n=5, do you think it is reasonable to use the vertex figure (which is a pentagon) of 4-simplex to visualize the Dirichlet distribution? Or do you have any idea for visualizing 4-simplex? Thanks!
Comment: @GuanjieHuang, if you can provide an example dataset, people could play with it, & we could see what people might come up with.  Personally, I'm dying to see Ben's visualization...
Comment: @gung-ReinstateMonica Thanks! I also pretty want to see Ben's plot. BTW, I add some toy data to my question. So, each toy data will be 5D. Please feel free to let me know if you have any thought about it! Thanks


Getting firebase storage image 403

Question: I'm using Next.js and am struggling to get firebase storage images to render on screen as they keep coming back as 403 errors.
I upload an image to storage when adding a document to firestore with a url nested in it then use that url to get the image
This is my Next Image tag with recipe.main_image.url == https://storage.googleapis.com/example.com/recipes/0O3Oycow4lJvyhDbwN0j/main_image/190524-classic-american-cheeseburger-ew-207p.png
And recipe.main_image.name == the name of the photo in firebase storage.
<Image
  alt={recipe.main_image.name}
  src={recipe.main_image.url}
  width={650}
  height={650}
/>

The alt tag comes back as the right thing (image name in firebase storage) so I know the image is getting sent back but for some reason I'm unauthorised I've tried multiple fixes including changing firebase rules to
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

AND
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

But neither change the outcome I've also set my next config up so I'm getting firebase storage
  images: {
    domains: ['images.ctfassets.net', 'storage.googleapis.com'],
  },

Comment: Do you intend to serve the image to the public?
Answer: If the images will be served to the public, then i would suggest to grant public access to the image. Cloud Storage for Firebase is backed by Google Cloud Storage. You can make individual objects publicly readable or make the bucket publicly readable.
or better yet, generate signed URLs, this way you can grant limited time access to an object. If you're working with Javascript then you may take a look at this sample code on how to generate a signed URL.
/**
 * TODO(developer): Uncomment the following lines before running the sample.
 * Note: when creating a signed URL, unless running in a GCP environment,
 * a service account must be used for authorization.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The full path of your file inside the GCS bucket, e.g. 'yourFile.jpg' or 'folder1/folder2/yourFile.jpg'
// const fileName = 'your-file-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function generateV4ReadSignedUrl() {
  // These options will allow temporary read access to the file
  const options = {
    version: 'v4',
    action: 'read',
    expires: Date.now() + 15 * 60 * 1000, // 15 minutes
  };

  // Get a v4 signed URL for reading the file
  const [url] = await storage
    .bucket(bucketName)
    .file(fileName)
    .getSignedUrl(options);

  console.log('Generated GET signed URL:');
  console.log(url);
  console.log('You can use this URL with any user agent, for example:');
  console.log(`curl '${url}'`);
}

generateV4ReadSignedUrl().catch(console.error);

You may visit this documentation for more information.

Getting firebase storage image 403


How to determine whether a set of propositions is consistent?

Question: Definition of consistency is: A set of formulas ⊆ WFF is consistent iff there is no A ∈ WFF such that Σ ⊢ A and Σ ⊢ (¬A).
Say you have a set of propositions statements (i.e. $A \lor B \rightarrow C$, etc.) and let's call this "Set1".
I know that to prove that set is inconsistent, you find an "A" such that Set1 ⊢ A and Set1 ⊢ (¬A).
But what are the steps to prove that the set is consistent?
Answer: The most useful technique for proving $\Sigma$ consistent is to provide a model for it -- that is, an interpretation of the primitive symbols in it that makes every formula in $\Sigma$ true. If the logic is sound, it cannot conclude something false from true, so whenever $\Sigma\vdash A$, then $A$ will also be true in that model. Since $A$ and $\neg A$ cannot both be true in the same interpretation, this means that $\Sigma$ is consistent.
If the logic is complete then every consistent $\Sigma$ will have a model. Usual propositional logic and first-order logic are both complete.
In the case of propositional logic, an interpretation is simply a table that shows which propositional letters we take to be true and which ones we take to be false. If $\Sigma$ contains finitely many different propositional letters, we can in principle try all interpretations until we find one that is a model.
The situation is less nice for first-order logic. It is still true that every consistent $\Sigma$ has a model, but the model may need to contain infinitely many elements for the quantifiers to range over, and is not necessarily easy to describe. Even if we have a description for a model, proving that it is actually a model can be very difficult -- in some sense it can be exactly as difficult as proving the $\Sigma$ is consistent.
And due to Gödel's incompleteness theorems, we know that are first-order theories that are consistent but cannot be proved to be consistent (from any given meta-system we wish to conduct this proof in).
Answer: If you are working with propositional logic (I assume it from the text of your answer) and $Set_1$ is a finite set of formulas (like your : $A \lor B \rightarrow C$), you can use the Method of analytic tableaux :

the semantic tableau (or truth tree) is it is a decision procedure for sentential and related logics.

In case $Set_1$ is consistent, it gives you a model of it (because $Set_1$ is consistent iff it is satisfiable).


A second-hand guitar pitch sounds weird

Question: I got a guitar from my friend's son. The high E string is weird because fret no. 12 and 13 and 14 have the same pitch: F#! Furthermore, other strings have a similar problem. On the B string, fret no. 13 and 14 have the same pitch: C#. On the G string, fret no. 13 and 14 have the same pitch G#!
Is this a special guitar or is it broken?
Comment: This question would be much clearer with more information - basically what sort and model of guitar is a good starter point.
Comment: Thank you all! It looks like an acoustic guitar. Every string has a problem at fret 13, having the same pitch like fret 14. The high E string has problem at fret 12,13 and 14, having the same pitch #F. I have to agree with you that the neck must be warped although I cannot see the differences of the space between each fret and the string. And I believe it is not worth it to have it fixed. Thank you for your answer!
Answer: It appears that the top string has a problem on fret 14. The fretwire is too high. Or - fretwires 12 and 13 are too low. Either way, the string is sounding from 14 when pressed at 12, 13 and 14. Second string has the same problem. The third string is odd, in that with the same problem, the note heard should be A!
It might be salvagable by raising the bridge, thus moving the strings higher from the fretboard - it could be as simple as that. As long as the bridge/saddle is adjustable.
It could be that the neck is warped. It could be that the frets around that area need sorting. Neither of which are jobs for the inexperienced.
It will make a difference depending on which type of guitar it is - acoustic, classical, elactric, solid or semi. Since you ask the question, it's fair to assume you are inexperienced, and this problem isn't one to gain experience sorting.Time to find a luthier!
Comment: A professional luthier could certainly fix the problem better than an amateur would be likely to.  On the other hand, it's possible that the guitar isn't worth that much *but* there might be some personal satisfaction in taking something that was otherwise a piece of junk and rescuing it to make it usable.
Answer: Warped neck, hallmark of cheap guitars CNC-milled from wood of unsuitable quality.  If the guitar was one of those supermarket deals for about the price of a proper string set, it's probably not fixable.
For more expensive instruments, a truss rod justification may do the trick.
Answer: I agree with Tim, that the 14th fret is sticking out (or above) the fretboard more than the 2 frets closer to the head. In which case you need to find a "luthier" (an instrument repair expert). A test you can do yourself is press a string down at about the 15th or 16th and hold the same string down at fret 3 and look at the gap between the string and each fret from the side view while holding the string down. You should be able to see the differences in the space between the frets in question. A point that will help later as you gain experience, is this is a test I and other people who work on their own gear uses to see if the neck is bowed too much or too little. Ideally, you want just a slight gap between the string and fret at frets 5 and 6. That gap keeps the string from buzzing while playing. If not clearing right you need to have the neck adjusted.
Answer: The problem may not be too serious.  The solution could be as simple as a truss rod adjustment. Hopefully a proper set up by a trained guitar technician may be all you need.
From what you have described my best guess without looking at the guitar is that it has a back bow in the neck. If the 14th fret is where the neck joins the body, that is even more likely the case.  The less likely possibility is a high 14th fret as Tim suggested.
The good news is, if your guitar has a truss rod, a back bow is not necessarily a sign of damage to the neck. If the guitar is a steel string guitar, it should have an adjustable truss rod (unless it is a really cheap guitar). The truss rod is designed to put counter tension on the neck to compensate for the tension exerted by the strings.  If the truss rod is too tight for the gauge strings installed, it will overcompensate resulting in a back bow.  This can be easily corrected with proper adjustment of the truss rod with the proper tool. To correct a back bow in the neck, you would loosen the truss rod. Don't try this yourself if you are not experienced as you can break the truss rod or strip the nut if you are not careful.
If your guitar has an adjustable truss rod, it will be accessed for adjustment either through the soundhole or by removing a small plate on the headstock between the tuning pegs.  I say this not to suggest you try adjusting yourself, but to aid in verifying the existence of a truss rod on your guitar.
A trained or experienced guitar tech or luthier can inspect the guitar and let you know if it's worth performing a full setup.  In a complete set up of an acoustic guitar, the truss rod may be adjusted, as well as the saddle height (the bar that the strings pass over at the bridge behind the soundhole).  The adjustments will be made after a new set of strings are installed per recommendations of the expert and based on your preference for string type. Most guitars will allow for some flexibility in string selection without major modifications to the guitar.
Good luck.

A second-hand guitar pitch sounds weird


Como criar um processo interminável?

Question: Pergunta simples, como eu faço para o meu processo do aplicativo ser "imparável" pelo sistema? Quero que quando um usuário tenta fechar o aplicativo apareça a mensagem "Acesso negado", e quando força a finalização da o erro no kernel CRITICAL_PROCESS_DIED. Isso é o que acontece com o processo wininit.exe pelo CMD:
C:\> taskkill /im wininit.exe
ERRO: o processo "wininit.exe" com PID 532 não pôde ser finalizado.
Razão: Acesso negado.

Nem sequer o processo WinInit é exibido no gerenciador de tarefas. Tem como programaticamente fazer o aplicativo poder fechar sem problemas e outra hora ser interminável?
Answer: Achei essa classe em outra pergunta do SO:
Public Class CriticalProcessInformationProcessor
    <DllImport("ntdll.dll", SetLastError:=True)>
    Private Shared Function NtSetInformationProcess(hProcess As IntPtr, processInformationClass As Integer, ByRef processInformation As Integer, processInformationLength As Integer) As Integer
    End Function
    Public Shared Sub EnableCriticalProcess()
        Dim isCritical As Integer = 1
        ' we want this to be a Critical Process
        Dim BreakOnTermination As Integer = &H1D
        ' value for BreakOnTermination (flag)
        Process.EnterDebugMode()
        'acquire Debug Privileges
        ' setting the BreakOnTermination = 1 for the current process
        NtSetInformationProcess(Process.GetCurrentProcess().Handle, BreakOnTermination, isCritical, 4)
    End Sub
    Public Shared Sub DisableCriticalProcess()
        Dim isCritical As Integer = 0
        ' we want this to be a Critical Process
        Dim BreakOnTermination As Integer = &H1D
        ' value for BreakOnTermination (flag)
        Process.EnterDebugMode()
        'acquire Debug Privileges
        ' setting the BreakOnTermination = 1 for the current process
        NtSetInformationProcess(Process.GetCurrentProcess().Handle, BreakOnTermination, isCritical, 4)
    End Sub
End Class

Como criar um processo interminável?


Why is a 0-1 loss function intractable?

Question: In Ian Goodfellow's Deep Learning book, it is written that

Sometimes, the loss function we actually care about (say, classification error) is not one that can be optimized efficiently. For example, exactly minimizing expected 0-1 loss is typically intractable (exponential in the input dimension), even for a linear classifier. In such situations, one typically optimizes
  a surrogate loss function instead, which acts as a proxy but has advantages.

Why is 0-1 loss intractable, or how is it exponential in the input dimensions?
Answer: The 0-1 loss function is non-convex and discontinuous, so (sub)gradient methods cannot be applied. For binary classification with a linear separator, this loss function can be formulated as finding the $\beta$ that minimizes the average value of the indicator function $\mathbf{1}(y_{i}\beta\mathbf{x}_{i} \leq 0)$ over all $i$ samples. This is exponential in the inputs, as since there are two possible values for each pair, there are $2^{n}$ possible configurations to check for $n$ total sample points. This is known to be NP-hard. Knowing the current value of your loss function doesn't provide any clue as to how you should possibly modify your current solution to improve, as you could derive if gradient methods for convex or continuous functions were available.
Comment: ^^ or evolutionary/swarm-based intelligence methods maybe?
Comment: Very good point - in practice random search or exhaustive search are the only methods which could be used to find the minimum of such a loss function, right?
Comment: Before jumping from random search towards complex evolutionary/swarm algorithms, I'd check out the cross-entropy method (CEM).
Comment: @samrairshad Yes, in fact 0-1 loss is not that uncommon to see in evolutionary methods.
Answer: The classification error is in fact sometimes tractable. It can be
optimized efficiently - though not exactly - using the Nelder-Mead
method, as shown in this article:
https://www.computer.org/csdl/trans/tp/1994/04/i0420-abs.html
"Dimension reduction is the process of transforming multidimensional
vectors into a low-dimensional space. In pattern recognition, it is
often desired that this task be performed without significant loss of
classification information. The Bayes error is an ideal criterion for
this purpose; however, it is known to be notoriously difficult for
mathematical treatment. Consequently, suboptimal criteria have been
used in practice. We propose an alternative criterion, based on the
estimate of the Bayes error, that is hopefully closer to the optimal
criterion than the criteria currently in use. An algorithm for linear
dimension reduction, based on this criterion, is conceived and
implemented. Experiments demonstrate its superior performance in
comparison with conventional algorithms."
The Bayes error mentioned here is basically the 0-1 loss.
This work was done in the context of linear dimension reduction. I
don't know how effective it would be for training deep learning
networks. But the point is, and the answer to the question: 0-1 loss
is not universally intractable. It can be optimized relatively well
for at least some types of models.

Why is a 0-1 loss function intractable?


Limitations on regex in nginx?

Question: I had a rewrite rule on Apache for /year/month/date links in a form that specifically defined 4 digits, then 2 digits, then 2 digits, that looked like this:
^([0-9]{4})/([0-9]{2})/([0-9]{2})/$

On nginx this regex causes an error that says the whole line is not terminated by a ; sign, until i remove the {} brackets and leave the regex like this:
^/([0-9]+)/([0-9]+)/([0-9]+)/$

Is this limitation intentional on nginx's part or some mistake on my part?
The whole line from Apache:
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/$ index.php?page=date&year=$1&month=$2&day=$3

The whole (working) line from nginx:
rewrite ^/([0-9]+)/([0-9]+)/([0-9]+)/$ /index.php?page=date&year=$1&month=$2&day=$3;

Answer:
If a regular expression includes the "}" or ";" characters, the whole expressions should be enclosed in single or double quotes.

http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

Limitations on regex in nginx?


What is the term for the dual of the Principle of Vacuous Truth?

Question: The Principle of Vacuous Truth might be defined by the tautology: $A \implies (\neg A \implies B)$.
Q: What is term for the principle defined by the tautology: $A \implies (B\implies A)$?
Comment: The second one is a sort of Weakening.
Comment: Your title and your body are asking two different things, or one uncertain thing and one more answerable thing.
Comment: The first one is Explosion (aka Ex falso).
Comment: 2) can be seen as Weakening (From $P$ to $P \lor Q$ .. but in conditional form), Simplification (from $P \land Q$ to $P$ ... but again, in conditional form), or Strengthening the Antecedent (We effectively change the antecedent for $A$ from $\top$ to $B$). In Existential Graphs it would correspond to Insertion. How about calling it Conditionalization?
Answer: I have seen the first one called Duns Scotus Law
I asked about the second one myself
Answer: In the speech Die Grundlagen der Mathematik, delivered in 1927 and published the following year, David Hilbert calls it "Zufügen einer Voraussetzung", which is translated as "introduction of an assumption" in From Frege to Gödel: A Source Book in Mathematical Logic 1879-1931 edited by Jean van Heijenoort.
Comment: Aah, rolls off the tongue so easily! :P


Overriding the abstract methods in the subclass

Question: I've two classes, Class Test2 has 2 abstract methods and 1 non-abstract method.
Class Test3 calls Cat() of Test2 and implements two Test2 abstract methods.
My question is if I don't add any body to the abstract methods in Test3, have I overridden the methods?  I have not implemented the Dog() and Bird(), then why does Test3 compile and run?
Thanks
<code>abstract public class Test2
{
      abstract public void Dog();
      abstract public void Bird();

       public static void Cat()
       {
           System.out.println("Meow");
       }
}

public class Test3 extends Test2
{
    @Test
    public void Play()
    {
        Cat();
    }

    @Override
    public void Dog() {
        // TODO Auto-generated method stub

    }

    @Override
    public void Bird() {
        // TODO Auto-generated method stub

    }
}
</code>
Answer: Your abstract methods are void and thus return nothing, the compiler expects the method to return nothing and by adding the curly braces you have defined the body; the body is just empty.
This is similar to when you implement an interface, the only thing the compiler cares about is that you have fulfilled the contract.


Como criar componentes dinâmicos em React Native?

Question: Preciso criar um componente para avaliação, onde é possível avaliar algo com 0-5 estrelas clicando nos ícones das estrelas.
Mas da maneira que faço, estou excedendo a quantidade de this.setState() aninhados, o que gera erro pois pode causar um loop infinito.
Código do Componente:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { Container } from './styles';

class StarsToRate extends Component {
  constructor(props) {
    super(props)
    const {
      size,
    } = this.props;
    this.state = {
      rating: 0,
      iconSize: size,
    }
  }

  render() {
    const { rating, iconSize } = this.state;
    return (
      <Container>
        {[1, 2, 3, 4, 5].map((element) => {
          if (element <= rating) {
            return <Icon name="star" size={iconSize} color="#EBC600" onPress={this.setState({ rating: element })} />;
          }
          return <Icon name="star-border" size={iconSize} color="#EBC600" onPress={this.setState({ rating: element })} />;
        })}
      </Container>
    );
  }
}

StarsToRate.defaultProps = {
  size: 24,
};

StarsToRate.propTypes = {
  size: PropTypes.number,
};

export default StarsToRate;

Erro exibido:
Comment: O problema não é que tu tá chamando o `setState` sempre? Tenta alterar o `onPress` para: `onPress={element => this.setState({rating: element})}`
Comment: `element` utilizado na _arrow function_  já está declarado no escopo superior, ao utilizar dessa maneira acusa-se um erro. Tentei contornar chamando uma outra função `touchStar(data) {
    this.setState({ rating: data });
  }`, mas volto ao erro de setState's aninhados.
Answer: O problema é que você está chamando a função logo que você cria o componente. Tente substituir nos componentes o:
onPress={this.setState({ rating: element })}

por:
onPress={() => this.setState({ rating: element })}

Exemplo funcional com botões
Comment: Funcionou muito bem, obrigado!


Lagrange Multipler KKT condition

Question: I am looking at SVM, and reviewing Lagrange multiplier. Let's say with the constraint function $$g(x,y) = x^2 + y^2 -1 > 0, $$ I am maximizing $$f(x,y) = x + y -1 .$$ Intuitively, since the constraint function does not provide a finite constrained region, there is no solution, and $f(x,y)$ can infinitely increase.
However, if I just plainly proceed with Lagrange multiplier calculation,
$$L(x,\lambda) = (x + y -1) +\lambda(x^2 + y^2 -1)$$
I get the solution:
$$y,x = -\sqrt{2}/2, \lambda = 1/\sqrt{2}$$
And this still satisfies KKT conditions although the solution is wrong.
$$g(x) => 0 , \lambda =>      0, \lambda g(x) = 0.$$
I expected that I would have some result that conflicted KKT conditions, but nothing was violated.
Does this mean that Lagrange multiplier under KKT conditions can produce a solution that cannot be solved, without giving any indication of intractability?
If functions are complicated, what's the systematic way to confirm that the optimization with inequality constraint functions is solvable using Lagrange multiplier?
Answer: A key concept with optimization in general and the KKT conditions in particular is distinguishing:

necessary conditions for an optimum
sufficient conditions for an optimum

In its most basic form, the KKT conditions are necessary conditions for an optimum. If an optimum exists and certain regularity conditions are satisfied, the optimum must satisfy the KKT conditions.
Consider an even simpler case:
\begin{equation}
 \begin{array}{*2{>{\displaystyle}r}}
 \mbox{maximize (over $x$)} & x^2 \\
 \end{array}
\end{equation}
The KKT condition is $2x = 0$. Every optimum satisfies these conditions, but there is no optimum!
For the KKT conditions to be sufficient conditions, more is required! For example, if the optimization problem is convex and Slater's condition is satisfied, then the KKT conditions are also sufficient conditions for an optimum (and every point that satisfies the KKT conditions is an optimum).
For example,
\begin{equation}
 \begin{array}{*2{>{\displaystyle}r}}
 \mbox{minimize (over $x$)} & x^2 \\
 \end{array}
\end{equation}
is a convex, unconstrained problem hence the KKT conditions are sufficient conditions hence the condition $2x = 0$ implies $x=0$ is a solution.
Answering your direct question:

If functions are complicated, what's the systematic way to confirm
  that the optimization with inequality constraint functions is solvable
  using Lagrange multiplier?

Unfortunately, there's a bit of nuance to the answer here. There are many different conditions for the optimization problem that imply that the KKT conditions are either necessary or sufficient for an optimum.
One of the most useful categories of problems where the KKT conditions are sufficient conditions for an optimum are when the optimization problem is convex and Slater's condition holds. Checkout Stanford Prof. Boyd's course on convex optimization, but the basic idea is that a convex optimization problem can be written as:
\begin{equation}
 \begin{array}{*2{>{\displaystyle}r}}
 \mbox{minimize (over $\mathbf{x}$)} & f(\mathbf{x}) \\
 \mbox{subject to} & \forall_j g_j(\mathbf{x}) \leq 0 \\
    & A\mathbf{x} = \mathbf{b}
 \end{array}
\end{equation}
where $\mathbf{x}$ is a vector, objective function $f$ is convex in $\mathbf{x}$, constraints $g_j$ are convex in $\mathbf{x}$, and equality constraints are affine. Slater's condition is that there exists a point in relative interior of the feasible set (eg. you don't have constraints like $x^2 \leq 0$ which are only satisfied by a single point).
In the case of a convex problem where Slater's condition is satisfied, the optimal pair $(\mathbf{x}, \boldsymbol{\lambda})$ is a saddle point of the Lagrangian.
Another useful regularity condition for the KKT conditions to be necessary is the LICQ constraint qualification. The KKT Wikipedia page has a whole list of possible regularity conditions. The mathematics of optimization is a big, broad topic! Anyway, this will hopefully get you going in the right direction! As you're going along, be sure to distinguish:

Conditions on your optimization problem that imply the KKT conditions are necessary for an optimum.
Conditions on your optimization problem that imply the KKT conditions are sufficient for an optimum.
Comment: As you stated, now I feel that I seriously need to look into the area of optimization.

Lagrange Multipler KKT condition


how to replace NA with the values from another column

Question: I would like to replace NA in the following data frame with values from the variable a.
df.NA <- data.frame(
  a = c("value1", "value2", "value3", "value4", "value5"),
  b = c(NA, 6, 7, NA,8),
  c = c(9, NA, NA, 10, 11),
  d = c(NA,NA,NA, 12, 13)
)

The final data frame should look like this
df.noNA <- data.frame(
  a = c("value1", "value2", "value3", "value4", "value5"),
  b = c("value1", 6, 7, "value4",8),
  c = c(9, "value2", "value3", 10, 11),
  d = c("value1","value2","value3", 12, 13)
)

Is there an easy way to achieve this?
Thanks!
Answer: You can use mutate to apply an ifelse across every column.
library(dplyr)

df.NA %>%
   mutate(across(everything(), ~ ifelse(is.na(.x), a, .x)))
#>        a      b      c      d
#> 1 value1 value1      9 value1
#> 2 value2      6 value2 value2
#> 3 value3      7 value3 value3
#> 4 value4 value4     10     12
#> 5 value5      8     11     13

Answer: Another possible solution:
library(dplyr)

df.NA %>%
  mutate(across(-a, ~ coalesce(.x, a)))

#>   a b  c  d
#> 1 1 1  9  1
#> 2 2 6  2  2
#> 3 3 7  3  3
#> 4 4 4 10 12
#> 5 5 8 11 13

Answer: in Base R:
ids <- is.na(df.NA)

replace(df.NA, ids, df.NA[which(ids, TRUE)[,1],'a'])
      a      b      c      d
1 value1 value1      9 value1
2 value2      6 value2 value2
3 value3      7 value3 value3
4 value4 value4     10     12
5 value5      8     11     13

Answer: You also can do in Base R a simple for loop:
for (i in 2:ncol(df.NA)) {
    df.NA[i][is.na(df.NA[i])] <- df.NA[1][is.na(df.NA[i])]
    }


Percentage Of Different Scales That Are Exactly Alike?

Question: Was playing with iOS app "Piano Companion" and apparently I'm really quite amazingly consistent.

I added two favorite scales that I found in the app and they are exactly the same; namely:

D#/Eflat Yu

and

D#/Eflat Dorian

Which got me thinking:

What Percentage Of Different Scales Are Exactly Alike?
Comment: The thing is, there isn't an exhaustive list of scales (you can even create new ones yourself). Also, many existing scales don't have established names. That makes it impossible to answer this question in its current state.
Comment: If you're interested in this kind of thing, you should try reading up on music theory. Start by googling the "circle of fifths", and looking into what differentiates different types of scales (major vs minor is a good starting point). It'll help you learn why this is the wrong question to ask, and in fact makes very little sense to an experienced musician.
Comment: I don't see, how a percentage would help in anyway. A percentage is  only meaningful, if you define from which set. I for one never encountered something like Yu nor does wikipedia deliver any hits beyond chinese *instruments*.
Comment: @guidot just curiosity, what's the likelyhood two scales would be exactly the same, that's all...
Answer: All of them. Here's the simple reason why. We use different systems to name, describe, and label scales. Let's just look at the C major scale to start.
The C major scale can also be referred to as the C Ionian mode when thinking in modal contexts, but there are more ways to describe the scale then just that. You can describe a scale by pattern i.e. the C major scales has the pattern WWHWWWH starting on C. Yet another way to describe it is by its pitch class sets which for the C major scale would be {0, 2, 4, 5, 7, 9, 11}.
As other's have pointed out, not every singe scale has an official name, but you can describe every scale based on it's pattern or pitch class set so just by default there are two different systems to identify a scale.
Answer: Probably more than you want to know:
Johnson, Timothy (2003), Foundations of Diatonic Theory: A Mathematically Based Approach to Music Fundamentals, Key College Publishing. ISBN 1-930190-80-8.
:)


less css not rendering (for a split second) on page load

Question: I'm using less css in my stylesheets. I'm also in localhost via xampp.
I'm having an issue with my stylesheet not rendering (for a split second) on page load.
The page loads quickly without the styles, then loads just a split second later with the styles applied.
Has anyone had any similar issues using less?
header.php
  <!DOCTYPE html>

      <title>Feed</title>
      <meta charset="utf-8">
      <meta name=viewport content="width=device-width, initial-scale=1">

      <link rel="stylesheet" href="https://firstname.lastname@example.com/font/bootstrap-icons.css" />
      <link rel="preconnect" href="https://fonts.googleapis.com" />
      <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
      <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;500;600;700&display=swap" rel="stylesheet" />
      <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;300;400;500;700&display=swap" rel="stylesheet" />
      <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500;700&display=swap" rel="stylesheet" />
      <link rel="stylesheet" href="https://cdn.materialdesignicons.com/4.8.95/css/materialdesignicons.min.css" />
      <link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />
      <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/froala-design-blocks/2.0.1/css/froala_blocks.min.css" />
      <link rel="stylesheet/less" href="styles.less" />

index.php
<?php
    require 'navbar/navbar.php';
    require 'header.php';
?>

styles.less
@import 'whitetheme.variables.less';

/* styles are here */

whitetheme.variables.less
    @dark-font-color: rgba(0,0,0, .9);
    @medium-font-color: rgba(0,0,0, .8);
    @light-font-color: rgba(0,0,0, .7);
    @secondary-background: #fff;
    @primary-gray: #f0f2f5;
    @primary-box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
    @primary-blue: #4c8bf5;

Answer:
less css not rendering (for a split second) on page load

LESS is not CSS.
Browsers do not natively support using LESS files (*.less) as stylesheets.
LESS is a system that generates CSS stylesheet files for you.

LESS is intended to be used as part of a build process (which you'd automate with npm run, or Gulp, or WebPack, or Rollup, or whatever the JavaScript ecosystem thinks is cool this month).

You are using an external third-party script to convert LESS to CSS in the browser, which is the cause of the delay.

Specifically, here's your problem:

<link rel="stylesheet/less" href="styles.less" />

You're using a LESS processor script that runs in the browser to convert your .less file into a CSS stylesheet that browsers can natively understand - this process happens asynchronously and independently of the browser loading the page.
This is what's happening (in chronological order, as your browser loads the page):

The browser loads your / page (that's the HTML output of your index.php script).
The browser loads styles.less asynchronously.

However, browsers will load rel="stylesheet" resources synchronously and block the page render, however.

The browser loads less.min.js synchronously (as you aren't using the defer or async attributes) and it then runs and processes your LESS and converts it to CSS.

The less.min.js file will wait until less.min.js is loaded, however.

And it's during that wait-for-less.min.js-file period that the browser renders your page (fast, isn't it?) without the CSS styles that it doesn't have yet.

The best fix is to run the LESS-to-CSS conversion step as part of a project build process. I suggest you read-up on npm and the rest in order to do this properly.

Something like this:
Compiling less with webpack

Install Webpack and LESS:

https://www.npmjs.com/package/less-loader
https://webpack.js.org/guides/getting-started/

cd your-project
npm init -y
npm install webpack webpack-cli --save-dev
npm install less less-loader --save-dev

Configure Webpack + LESS:
webpack.config.js:
module.exports = {
  module: {
    rules: [
      {
        test: /\.less$/i,
        loader: [
          // compiles Less to CSS
          "style-loader",
          "css-loader",
          "less-loader",
        ],
      },
    ],
  },
};

Run npx webpack

Edit your HTML:

Remove the


Confusion regarding OAUTH2 and custom identity provider

Question: I'm working on an ASP.NET Web API, and now I'd like to implement the oauth2 protocol for the authorization to the api endpoints.
The identity provider, the authorization server and the resource (the api), will all be handled by our software. I do not need to implement Google, MS og Facebook login.
The reason for me to choose oauth, is that I'd like to use the same identity provider for futere services my company might develop.
Every sample code and tutorial I've found on the internet so far, seems to concentrete on using external identity providers, like Google, and not so much on self developed solutions. Also, they seem to include web pages for entering credentials, which is not what I'd like to do. The client library should take an apikey and use this to get the necessary token for accessing the resource api.
Is this even possible? Or have I totally misunderstood the intended use of oauth?
I hope my case is made clear, so please, if anyone can point me in the right direction to a code sample, tutorial or similar.
Answer: There is no concept of apikey in oauth. Rather, you have different flows where the client credential flow is the one you should be interested in. The flow consists in sending only the client_id and client_secret from the client application to the token endpoint of the identity provider and thus claiming the token without any user interaction.
http://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified
(Aaron has this flow documented as "Application Access")
If you decide to go with DotnetOpenAuth, the flow is possible to implement for the identity provider, the resource server and the client application. First, download their examples, try to learn as much as possible and then come back with specific questions.


Coluna fixa de um JTable em um JScrollPane

Question: Como faço para deixar uma coluna de um JTable fixa (sem scroll) dentro de um JScrollPane?
Quero deixar a primeira coluna de uma tabela fixa, a barra de rolagem só irá rolar da segunda coluna em diante, a primeira deve sempre ficar visível.
Até consegui fazer porém tenho que dividir a tabela em duas...
Comment: Não sei se isso é de fato possível. Me parece que a sua solução de dividir a tabela em duas é a melhor.
Comment: @Victor Pelo jeito não dá pra escapar de criar duas `JTable`, mas parece ser possível usar **um único `TableModel`** e fazer cada tabela (cabeçalho e "resto") usar só uma parte desse modelo.
Answer: O que você está procurando é uma row header (cabeçalho de linha - compare com column header, usado quando você quer uma linha fixa no topo). Há uma pergunta similar no StackOverflow em inglês, mas as respostas não contém muitas informações, somente dois links.
Dei uma olhada rápida nos dois, e ambos separam a JTable em duas... Entretanto, o primeiro link permite usar um único TableModel para ambas as tabelas - que é o que realmente importa, certo?
Veja o link para a solução completa. Exemplo de uso (simplificado):
TableModel data = new DefaultTableModel(0,10); // Substitua com seu TableModel particular

// Criando o modelo de coluna para a tabela "normal" (coluna 1 em diante)
TableColumnModel columns = new DefaultTableColumnModel();
for (int count = data.getColumnCount(), i = 1; i < count; i++)
{
    TableColumn c = new TableColumn(i);
    c.setHeaderValue(data.getColumnName(i));
    columns.addColumn(c);
}

// Criando o modelo de coluna para o cabeçalho (coluna 0; se quiser pode fixar mais colunas)
TableColumnModel headerColumns = new DefaultTableColumnModel();
TableColumn h = new TableColumn(0);
h.setHeaderValue(data.getColumnName(0));
headerColumns.add(h);

// Criando as tabelas
JTable table = new JTable(data, columns);
JTable rowHeader = new JTable(data, headerColumns);

// RowHeaderRendered é uma classe externa, que pode ser baixada no link acima
rowHeader.setDefaultRenderer(Object.class, new RowHeaderRenderer());

JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setRowHeaderView(rowHeader);

Comment: foi mais ou menos isso que eu fiz, na verdade especializei um JScrollPane, vou postar a minha solução para quem quiser ver. Talvez quando tiver mais tempo eu tente de outra maneira
Answer: Minha solução até então:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class JFixedColScrollPane extends JScrollPane {

  private JTable fixedTable;
  private JTable mainTable;

  public JFixedColScrollPane( JTable fxTable, JTable mnTable ) throws Exception {
    super( mnTable );
    this.fixedTable = fxTable;
    this.mainTable = mnTable;

    fixedTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
    mainTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );

    setRowHeaderView( fixedTable );

    ListSelectionListener listSelectionListener = new ListSelectionListener() {
      public void valueChanged( ListSelectionEvent e ) {
        JTable tabelaSelecionada = (e.getSource() == fixedTable.getSelectionModel()) ? fixedTable : mainTable;
        JTable tabelaASelecionar = (tabelaSelecionada == fixedTable) ? mainTable : fixedTable;
        tabelaASelecionar.getSelectionModel().removeListSelectionListener( this );
        tabelaASelecionar.clearSelection();
        int linha = tabelaSelecionada.getSelectedRow();
        if ( linha >= 0 ) {
          tabelaASelecionar.getSelectionModel().addSelectionInterval( linha, linha );
          if ( tabelaSelecionada == fixedTable ) {
            Rectangle rectangle = tabelaASelecionar.getCellRect( linha, 0, false );
            rectangle.width = tabelaASelecionar.getWidth();
            tabelaASelecionar.scrollRectToVisible( rectangle );
          }
        }
        tabelaASelecionar.getSelectionModel().addListSelectionListener( this );
      }
    };

    this.fixedTable.getSelectionModel().addListSelectionListener( listSelectionListener );
    this.mainTable.getSelectionModel().addListSelectionListener( listSelectionListener );

    final JTableHeader fixedTableHeader = this.fixedTable.getTableHeader();
    setCorner( ScrollPaneConstants.UPPER_LEFT_CORNER, fixedTableHeader );

    fixedTable.addComponentListener( new ComponentAdapter() {
      @Override
      public void componentResized( ComponentEvent e ) {
        fixedTable.setPreferredScrollableViewportSize( new Dimension( fixedTable.getColumnModel().getTotalColumnWidth(), 50 ) );
      }
    } );
  }

  public JTable getFixedTable() throws Exception {
    return fixedTable;
  }

  public JTable getMainTable() throws Exception {
    return mainTable;
  }
}

para utilizar:
new JFixedColScrollPane( tabelaFixa, tabelaMovel );


How to set all the backgrounds transparent so that the home screen could be seen?

Question: I was thinking about this problem for several days:
How to set all the backgrounds to transparent in an app so that the iOS desktop and icons could be seen? Is there any method which could help to meet the demand? (I still don't have the authority to sample image.)
I have tried some methods. I regard the whole iOS system as a big app. When we open an app on the desktop, it becomes an upper "view controller" which would cover on the desktop.
With this thought, I set the instance variable-Window, in AppDelegate class, and root view controller's background color to be clear. However, there is still a black background!.
Anyone could help? Maybe you yet haven't met this problem, but please think for seconds and provide me for some ideas.
Thanks in advance!
Answer: no, its not possible to do that. If you try to set the clear color for all the view components including UIWindow you will get black color as you are getting.
Comment: Yes, this method is impossible. But what about any other ways?
Comment: there are no other ways to achieve that why its impossible,
Comment: Is this really still true in iOS 7? I definitely saw a mockup of an app where this nowadays typical left-sided settings slide-in view was translucent and you could see the blurred home screen. Can't find any way to achieve this though. So maybe it was really just a mockup?
Comment: Actually, if you look at iOS 7's weather app, it is possible there.
Comment: Yes, and you can also see the wallpaper in Reminders, Passbook, and some other places. It's only impossible in the sense that there's no public API.
Answer: This is a solution that you can see in the vidios of the WWDC. You have to do a Gaussian Blur, so the first thing you have to do is to add a new .m and .h file with the code i'm writing here, then you have to make and screen shoot, use the desired effect and add it to your view, then your UITable UIView or what ever has to be transparent, you can play with applyBlurWithRadius, to archive the desired effect, this call works with any UIImage.
At the end the blured image will be the background and the rest of the controls above has to be transparent.
For this to work you have to add the next libraries:
Acelerate.framework,UIKit.framework,CoreGraphics.framework
I hope you like it.
Happy coding.
    //Screen capture.
    UIGraphicsBeginImageContext(self.view.bounds.size);

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(c, 0, 0);
    [self.view.layer renderInContext:c];

    UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
    viewImage = [viewImage applyLightEffect];

    UIGraphicsEndImageContext();

    //.h FILE
    #import <UIKit/UIKit.h>

    @interface UIImage (ImageEffects)

   - (UIImage *)applyLightEffect;
   - (UIImage *)applyExtraLightEffect;
   - (UIImage *)applyDarkEffect;
   - (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor;

   - (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage;

   @end

    //.m FILE
    #import "cGaussianEffect.h"
    #import <Accelerate/Accelerate.h>
    #import <float.h>

     @implementation UIImage (ImageEffects)

    - (UIImage *)applyLightEffect
    {
        UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3];
        return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
    }

    - (UIImage *)applyExtraLightEffect
    {
        UIColor *tintColor = [UIColor colorWithWhite:0.97 alpha:0.82];
        return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
    }

    - (UIImage *)applyDarkEffect
    {
        UIColor *tintColor = [UIColor colorWithWhite:0.11 alpha:0.73];
        return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
    }

    - (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor
    {
        const CGFloat EffectColorAlpha = 0.6;
        UIColor *effectColor = tintColor;
        int componentCount = CGColorGetNumberOfComponents(tintColor.CGColor);
        if (componentCount == 2) {
            CGFloat b;
            if ([tintColor getWhite:&b alpha:NULL]) {
                effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha];
            }
        }
        else {
            CGFloat r, g, b;
            if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) {
                effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha];
            }
        }
        return [self applyBlurWithRadius:10 tintColor:effectColor saturationDeltaFactor:-1.0 maskImage:nil];
    }

    - (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage
    {
        if (self.size.width < 1 || self.size.height < 1) {
            NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
            return nil;
        }
        if (!self.CGImage) {
            NSLog (@"*** error: image must be backed by a CGImage: %@", self);
            return nil;
        }
        if (maskImage && !maskImage.CGImage) {
            NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage);
            return nil;
        }

        CGRect imageRect = { CGPointZero, self.size };
        UIImage *effectImage = self;

        BOOL hasBlur = blurRadius > __FLT_EPSILON__;
        BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
        if (hasBlur || hasSaturationChange) {
            UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
            CGContextRef effectInContext = UIGraphicsGetCurrentContext();
            CGContextScaleCTM(effectInContext, 1.0, -1.0);
            CGContextTranslateCTM(effectInContext, 0, -self.size.height);
            CGContextDrawImage(effectInContext, imageRect, self.CGImage);

            vImage_Buffer effectInBuffer;
            effectInBuffer.data     = CGBitmapContextGetData(effectInContext);
            effectInBuffer.width    = CGBitmapContextGetWidth(effectInContext);
            effectInBuffer.height   = CGBitmapContextGetHeight(effectInContext);
            effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);

            UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
            CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
            vImage_Buffer effectOutBuffer;
            effectOutBuffer.data     = CGBitmapContextGetData(effectOutContext);
            effectOutBuffer.width    = CGBitmapContextGetWidth(effectOutContext);
            effectOutBuffer.height   = CGBitmapContextGetHeight(effectOutContext);
            effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);

            if (hasBlur) {
                CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
                NSUInteger radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
                if (radius % 2 != 1) {
                    radius += 1;
                }
                vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
                vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
                vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
            }
            BOOL effectImageBuffersAreSwapped = NO;
            if (hasSaturationChange) {
                CGFloat s = saturationDeltaFactor;
                CGFloat floatingPointSaturationMatrix[] = {
                    0.0722 + 0.9278 * s,  0.0722 - 0.0722 * s,  0.0722 - 0.0722 * s,  0,
                    0.7152 - 0.7152 * s,  0.7152 + 0.2848 * s,  0.7152 - 0.7152 * s,  0,
                    0.2126 - 0.2126 * s,  0.2126 - 0.2126 * s,  0.2126 + 0.7873 * s,  0,
                                  0,                    0,                    0,  1,
                };
                const int32_t divisor = 256;
                NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]);
                int16_t saturationMatrix[matrixSize];
                for (NSUInteger i = 0; i < matrixSize; ++i) {
                    saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor);
                }
                if (hasBlur) {
                    vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
                    effectImageBuffersAreSwapped = YES;
                }
                else {
                    vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
                }
            }
            if (!effectImageBuffersAreSwapped)
                effectImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

            if (effectImageBuffersAreSwapped)
                effectImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }

        UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef outputContext = UIGraphicsGetCurrentContext();
        CGContextScaleCTM(outputContext, 1.0, -1.0);
        CGContextTranslateCTM(outputContext, 0, -self.size.height);

        CGContextDrawImage(outputContext, imageRect, self.CGImage);

        if (hasBlur) {
            CGContextSaveGState(outputContext);
            if (maskImage) {
                CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
            }
            CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
            CGContextRestoreGState(outputContext);
        }

        if (tintColor) {
            CGContextSaveGState(outputContext);
            CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
            CGContextFillRect(outputContext, imageRect);
            CGContextRestoreGState(outputContext);
        }

        UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return outputImage;
    }

Comment: You should link and credit the original code rather than a version that has the Apple licensing removed.
Comment: This blur will only help you if you can get the image of the home screen. As explained in Parser's answer, there is no way to do this right now.
Comment: i think applyBlurWithRadius:30.0 is the apple standar


What test is appropriate for my data?

Question: I have three types of food (Fish, Beef, Pasta) and for each food I have the average of the pH level. For each food and pH level, I have three repeated measures showing the amount of aluminum. I want to check whether the amount of aluminum in food depends on the pH of food by adjusting for the effect of the type of food.
<code>Type of food               Fish        Beef        Pasta
pH level                   6.1         7.8         4.8

Amount of Aluminum         12.2        13.1        9.8
                           11.4        12          10.3
                           12.6        12.5        10
</code>
Comment: Standard spelling is pH not PH.  You can't test averages alone; you need the original data for a test. This looks like analysis of variance or more generally a generalised linear model. I'd expect aluminum (aluminium) content to be skewed, so watch out.
Comment: If these are the only data you have, then you cannot achieve your objective since the type of food and pH levels are *confounded*: although there is an apparent difference in mean amounts of aluminum, you have no basis to attribute those differences to the pH or the type of food; all you can conclude is that the differences are significant.
Comment: Oh thank you. I corrected it. This is the data they have given me. I'm not even sure a parametric test would work out.
Comment: I don't see why not.  Sometimes data are in turn averages of other data, but you then have a very small sample size. Nevertheless (e.g.) the values for pasta are consistently lower than all others, so there is some pattern in the data. I know nothing about the food chemistry; subject-matter specialists may be able to advise further.
Comment: If the intent was to adjust the relationship for food type, I'm reminded of Fisher's quote (*to consult the statistician after an experiment is finished is often merely to ask him to conduct a post mortem examination. He can perhaps say what the experiment died of*) - in this case, confounding ... If the experiment is to be repeated, statistical advice will allow for more of information to be had from a similar level of effort (including basic advice such as having a design where the pH isn't identical within each food type and not averaging the data before analyzing it)
Answer: Answered in comment:

If these are the only data you have, then you cannot achieve your
objective since the type of food and pH levels are confounded:
although there is an apparent difference in mean amounts of aluminum,
you have no basis to attribute those differences to the pH or the type
of food; all you can conclude is that the differences are significant.

– whuber

What test is appropriate for my data?


in concrete terms, what does the mean of a sample actually tell you about the population?

Question: Suppose you take a sample of size 3 with values 0, 0 and 1.  (3 is the minimum size to make the sample asymmetrical and make the question non-trivial.)  Ever since my first stats class, I've been vaguely confused because I didn't understand: why is it useful to calculate the mean of this sample, 1/3?
At first I naively thought that if this meant that if you assumed the background population had some standard deviation (e.g. 1), that 1/3 would be the value of the population mean that would maximize the probability of getting the observed outcome.  (Of course I mean the probability of getting the observed outcome within some arbitrarily small delta, since the probability of any specific outcome is zero.)  i.e. for my sample and assuming standard deviation 1, the value k that maximizes the value of f(k)*f(k)*f(1-k) where f is the standard normal distribution.  But presumably that's not exactly 1/3, is it?  (By the way, is there a technical term for this "observed outcome probability maximizer" value?)
[Edited to add: I was wrong.  I explicitly f(k)*f(k)*f(1-k) where f is the standard normal distribution, and it has a maximum at 1/3.  This is convenient, although it was far from obvious to me at the outset that this would be the case. This renders the rest of the question moot.]
But if 1/3 is not the value that maximizes the probability of the observed outcome, then what good is it?
Is it simply the case that before everyone had a computer in their pocket, calculating the "observed outcome probability maximizer" value was too hard, and calculating the mean was good enough?  And now that we all have pocket computers, we should just go with the "observed outcome probability maximizer" instead, and calculating the mean is obsolete?  If not, then what does "1/3" tell you about the background population?
Comment: 1/3 is not an MLE of the mean unless we make some assumption about the distribution of the sample. Transforming a likelihood to a probability - a posterior specifically - additionally requires a prior. In other words, the "probability" that a mean = X is a fundamentally Bayesian concept. On the other hand, the sample mean is always a consistent estimator of the population mean because of the law of large numbers: you are on your way to getting the true mean as you continue sampling.
Comment: @AdamO OK, yes you're right I should have specified a prior, like "a priori the mean follows a uniform probability distribution from -5 to 5".  However, even with a specification like that, I still don't see how "1/3" is the answer to a useful question.  When you say "the sample mean is always a consistent estimator of the population mean", this is what I meant in the title that I don't see what this means in *concrete* terms.  A "consistent estimator"?  For my three-element sample (0, 0, 1), what is the concrete question whose correct answer is "1/3"?
Comment: If you assume the population is Poisson, then with observations
Comment: The concrete question is, "What is the sum of $0$, $0$, and $1$ divided by $3?$" This could be related to a proportion, for instance, by asking about the probability of a future value being $1$ or $0$. Given the data, the "most likely" value is $1/3$.
Comment: @Dave I mean what is the concrete question about the population, where the correct answer is 1/3?  I am assuming the population is normally distributed.  (I am not assuming that the variable can only be 0 or 1.  It turns out that if the value can only be 0 or 1, and you observe 0,0,1, then 1/3 actually IS the value that maximizes the likelihood of that observation, although I didn't think this was obvious and I had to differentiate p(1-p)(1-p) to figure it out.  But I did not think 1/3 would be the value that would maximize the likelihood of this outcome for a normal distribution.)
Comment: If you're a frequentist and assume the population is normal, then data $0.2, .0.3, 1.1$ might lead you to guess the population mean is in the t interval $(-0.901,\,  1.835).$
Comment: The correct answer might not be $1/3$, but statistics is all about using available information (data) to make good guesses about the unknown (population parameter). There is a strong argument that $1/3$ is the best guess of the mean of the (normal) distribution from which you drew your three values. // I think the differentiation you did showed that $1/3$ *is* the maximum likelihood estimate of you assume a Bernoulli distribution, which is correct.
Comment: What are the chances of drawing three consecutive **integers** from a normal population?
Comment: Well, I'll be damned, I explicitly calculated f(k)*f(k)*f(1-k) where f is the standard normal distribution, and it turns out it has a maximum at 1/3, i.e. 1/3 is the value that maximizes the likelihood of getting 0, 0, 1.  But I wouldn't have believed it if I hadn't calculated it explicitly.  It seems far from obvious to me.  I wonder if there's an intuitive proof.
Comment: That sounds like a good new question to post! If you show your work (written in $\LaTeX$, not just photograph your handwritten derivation), I think you will get a good answer about how what you're doing is maximum likelihood estimation.
Comment: @Dave thanks! Although, I assume everyone here knows how to show that f(k)*f(k)*f(1-k) (where f is the standard normal distribution) has a max at k=1/3 - you can do it with hs calc (I just hadn't tried it).  I'm just interested in whether there's an intuitive proof that the sample mean is also the MLE for the population mean.  It also works for binomial distribution (if you get 14 black and 5 white, p=14/19 is the MLE).  The conclusion can't be too general, because (I saw on some other SE questions) there are distributions where the sample mean is NOT the MLE for the population mean.
Answer:
1/3 would the value of the population mean that would maximize the probability of getting the observed outcome

This is a more profound statement than you might realize, as it alludes to maximum likelihood estimation, a common estimation method in statistics. Being a little loose, there is a technical sense in which the calculated $\bar x$ is the most likely value of the population parameter in order for you to obtain the data you obtained (and it isn't always true, but it's true under nice-enough conditions, such as normality). That sounds good, right? And that's why statisticians like maximum likelihood estimation.
To address your final paragraph, you're onto something by saying that finding the "probability maximizer" (likelihood estimator) is a good approach, perhaps better than the sample mean, but the sample mean often is exactly that likelihood maximizer by being the maximum likelihood estimate!
Getting away from maximum likelihood estimation in particular, "estimating a population parameter" means "guessing the correct value of the population parameter". There are ways of guessing that we know have desirable properties ("good" estimates of the unknown value). Since, the usual sample mean $\bar X$ has a number of desirable properties, we often like $\bar x$ as our estimate of $\mu$.
Comment: I don't quite understand what you are saying in the first paragraph - "the calculated x¯ is the most likely value of the population parameter in order for you to obtain the data you obtained".  Are you saying that (assuming normal distribution with standard deviation 1 and unknown mean), that 1/3 *actually is* the value for the population mean that would maximize the probability of getting the observed data (0, 0, 1)?  I assumed that was not the case; it's far from obvious.
Comment: In statistical terminology, "probability" and "likelihood" do not have the same meaning.
Comment: thanks right, so modify my comment to insert at the beginning "Assume that the pdf of the population mean is uniform from -5 to 5."  Now would it be correct to say "probability"?  And, am I correct in assuming that 1/3 is not the value that would maximize the probability of seeing the observed data (assuming population distribution is normal)?
Comment: Now you're putting a prior distribution on the population value and should use some Bayesian method. I haven't run through the math, but maybe you have and have gotten $1/3$ to be the MAP (maximum a posteriori) estimate.


Can a classifier be used to improve its own training data?

Question: Introduction:
Consider a classification problem of $\mathbb{R}^n$ into $\mathbb{R}^2$. Let $\mathcal{U}$ be a set of instances whose class is unknown, but can be discovered paying a cost $\gamma$ for each instance.
Goal:
To create a Machine-Learning classifier capable of predicting the class of a new instance from $\mathcal{U}$ with an $\alpha$% accuracy (AUC, or any other metric), minimizing the total cost, which is given by $\gamma$ times the number of instances for which the class has to be discovered.
Solution:
The solution is to subselect instances from $\mathcal{U}$, discover their classes and collect them into a training dataset $\mathcal{T}$.
Problem:
The cost is $C = \gamma \times |\mathcal{T}|$. How to optimize $C$?
Consider the following scenarios:

instances are randomly selected from $\mathcal{U}$, discovered, and collected into a training dataset. The process stops when the predictor achieves a threshold goodness.

instances are randomly selected from $\mathcal{U}$, the predictor is executed on them obtaining the predicted classes. Then, instances of the more present class in $\mathcal{T}$ are ruled out, while only the others's class is discovered, paying $\beta$ for each one of them. This way, the presence of both classes in $\mathcal{T}$ will be evened by the own predictor, which will in theory lead to a better performance.

Questions:
What do you think about scenario 2)? Is it reasonable? Am I missing something? I've been searching on the internet but didn't find anything similar to my problem. Do you know any similar study?
Answer:
Usually it is a bad idea to reinvent the wheel, so if you need this to solve an applied problem, it would be wise to find already existing solution. It's not exactly the same, but you may be interested in learning more about concepts such as active learning, or human-in-the-loop in machine learning if you consider non-automated solutions as well.
The problem of actively sampling the data is often treated as multi-armed bandit problem in discrete case, or Bayesian optimization (Frazier, 2018) in general, with methods such as Gaussian processes for continuous cases. TL;DR those algorithms learn the distribution of the data and can help you to make a decision what kind of data is most promising to sample. Such approaches were used in clinical trials (Giovagnoli, 2021, Takahashi and Suzuki, 2010 for some reviews) and other scenarios.
If I understand correctly, in your second scenario you want to discard the data. Why would you do that? Throwing out valid data is almost never a good idea, especially if it is expensive to obtain. If you're sampling randomly this should not be a problem. Having unbalanced data is often not a problem. If it is, you can always use an algorithm less susceptible to it, use survey weights to adjust for it, etc.
Comment: Active Learning is the wheel I was trying to reinvent. A quick search on the web solved all the questions I was struggling with. Many thanks!


Tearing with VSYNC in full screen mode only (windowed mode works fine) on Windows 10 / DirectX

Question: I think that my DirectX 11 application worked fine on the previous system (I'm about 70% sure). But now, in Windows 10 (laptop) I have tearing issue in full screen mode only (the windowed mode works without any tearing).
The scene is quite "heavy" (it's supposed to be performance tested for my application). When DirectX renders "heavier" parts, it went down to about 50fps for a short time (my measurements may be a bit inaccurate) and then went back to 60-61fps. What is strange is, I do not not see tearing in the "heavier" parts (about 50fps).
I've heard that it can be somehow related to DWM which provides its own synchronization for windowed applications (that's why my program works fine in windowed mode?).
What can I do about it?
The swap chain:
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 1;
sd.BufferDesc.Width = width;
sd.BufferDesc.Height = height;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = numerator;
sd.BufferDesc.RefreshRate.Denominator = denominator;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = *hwnd;
sd.SampleDesc.Count = sampleCount; //1 (and 0 for quality) to turn off multisampling
sd.SampleDesc.Quality = maxQualityLevel;
sd.Windowed = fullScreen ? FALSE : TRUE;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; //allow full-screen switchin

// Set the scan line ordering and scaling to unspecified.
sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
// Discard the back buffer contents after presenting.
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

Where numerator and denominator are calculated based on this tutorial:
...
numerator = displayModeList[i].RefreshRate.Numerator;
denominator = displayModeList[i].RefreshRate.Denominator;

Which returns two very high values that gives about 60 when divided by each other (would I get the same effect by just setting them to 60 and 1?):

I also render with:
if(VSYNC){
    swapChain->Present(1, 0); //lock to screen refresh rate
}else{
    swapChain->Present(0, 0); //present as fast as possible
}

Did I miss something? Or did I do something wrong?
Comment: I think you're confusing the DXGI with the D3DX helper methods. As Chuck Walbourn said, you're already using DXGI, because its the meta api for all graphic relevant api's in windows like Direct3D, Direct2D, DirectWrite etc.
Comment: Did you try to zero out the numerator and denominator? The DXGI will  then calculate proper values automatically. (https://msdn.microsoft.com/en-us/library/windows/desktop/ee417025(v=vs.85).aspx) The link also covers, why 60/1 shouldn't be hardcoded (can lead to problems on some systems).
Comment: @Gnietschow I am almost sure I don't use DXGI (as far as I know I use just DirectX 11 in my c++ application, without DXGI which is optional "wrapper" for some tasks, but maybe I'm wrong). Anyway, thank you for the link. I know now why not to hardcode 60/1, but why my approach of calculating it does cause problems? I prefer **not** to start using DXGI just to get numerator/denominator values (complexity etc.).
Comment: DXGI is the API that handles the swapchain and device enumeration for Windows Vista+ and is used explicitly with Direct3D 10, 11, and 12. You should read the article.
Comment: @Gnietschow Indeed, you're right. And setting things to 0/0 do the job - can you make an answer from your comment? Anyway, why my method of getting those values (the one that has been taken from the tutorial) fails me?
Comment: Unfortunately I have no idea. I also tried to get the refresh rate of the adapter, but it didn't worked properly until I used the automatic 0/0. Maybe someone else can enlighten us :)
Comment: Syncing to an arbitrary framerate of a display device ("Vsync") is a **basic** function of computer graphics that must be *easily* supported and enforceable by all APIs and frameworks on all platforms using any language for development, and should also be the default. We have not evolved, and this is madness. All this is to say I sympathize while also wondering how we got to this point.
Comment: Vsync was understood in the 1960s, used in the 1970s, in 1981 we took a wrong turn and non CG people made graphics cards, in the 90s analog displays still held on and there was a return until DVI and beyond where this apparently isn't understood as a basic function again. This ends my historical review, I promise.
Answer: My comment as an answer:

Did you try to zero out the numerator and denominator? The DXGI will then calculate proper values automatically. (doc) The link also covers, why 60/1 shouldn't be hardcoded (can lead to problems on some systems).


php include path errors: Same code works on Ubuntu default Apache and php conf, but not on CentOS

Question: So the same code works on my Ubuntu server but when I upload it to my dedicated hosting server running CentOS it seems to add an extra prefix of .:/usr/share/pear:/usr/share/php:
I tried setting includepath to different things but it just doesn't work. The file is in a directory called language in the same folder as the file that is including it and I'm using:
include dirname(__FILE__).DIRECTORY_SEPARATOR."language".DIRECTORY_SEPARATOR."storage.inc";
include dirname(__FILE__)."/language/language.php";
include "language/language.php";

and a lot of other combinations but I can't get it to find the file. I keep receiving the error message:
Fatal error: require_once() [function.require]: Failed opening required '/home/neo/public_html/migration/include/class/core/storage.inc' (include_path='.:/usr/share/pear:/usr/share/php:/home/neo/public_html/migration') in /home/neo/public_html/migration/include/class/core/class_lang.inc on line 153

Comment: Something else is wrong here. The extra include paths aren't causing this, because the include path is not used when you specific an absolute path to include, as you do now.
Answer: Whenever I have something bizarrely not working on CentOS, the first thing to check is selinux. It's a security system on by default, and it stops programs accessing files anywhere they haven't been given explicit permissions.
You can either look in
/var/log/secure or maybe /var/log/audit/audit.log

for deny messages, or you can test by turning selinux off temporarily with
echo 0 >/selinux/enforce

then testing - but turn it back on later with
echo 1 >/selinux/enforce

and work out how to adjust it to let it work properly.


Find area of 3D triangle with vertexes $A(1,0,0),\>B(0,2,0),\>C(0,0,\frac23)$

Question: I have a question that asks me to calculate the area of triangle ABC in 3D space,

The equation for plan is $2x+y+3z = 2$, and the plan intersects each axes and we have $A(1,0,0);B(0,2,0);C(0,0,2/3)$ as its intersection points. Please calculate the area of the triangle ABC.

I have no idea what should I do in order to obtain this result!
Thanks
Comment: Have you heard of the cross product? If so, take the magnitude of the cross product of a couple of the sides (gives you area of parallelogram) and divide it by two.
Comment: The area of the triangle is half the magnitude of the cross product of $\vec{AC}$ and $\vec{AB}$.
Comment: Oh okay! Yes, but I was not thinking that the area of a triangle is half of the area of a parallelogram. So that means no matter what area of triangle I want to calcualte, I can always do it by thinking this way?
Comment: Use cress product of vectors represented by two adjacent sides of triangle. Cross product gives the area f parallelogram and half of it will be area of triangle
Answer: Finding length of each of the three sides $AB,BC,CA$ and using Area formula is straightforward:
$$ c^2=1^+2^2=45/9;$$
$$ a^2=2^2+\left(\frac23\right)^2={40}/{9};$$ $$b^2=1^2+\left(\frac23\right)^2=13/9;$$
Apply  formula of Brahmagupta/Heron
$$ 2s= (a+b+c); Area=\sqrt{s(s-a)(s-b)(s-c)} $$
Simplifying $$ Area= \dfrac{\sqrt{14}}{3}$$
Another way is to find (one half of) cross product any two of vectors $AB,BC,CA$ and evaluate $(3 \,\times ,3)$ area matrix.
Yet another way to find matrix is evaluating (one half of the) matrix:
$$ \left( (1,x1,y1),(1,x2,y2),(1,x3,y3) \right)$$
This method can be also used later if desired to find Volume in 3-space of enclosing tetrahedron by $(4\times 4)$ matrix with a different constant coefficient($=\dfrac16$) in front.
Comment: Should be (s-b) in the Heron formula I believe
Comment: Thanks, corrected it.
Answer: You can find the length of each side of the triangle by distance formula.  Then Heron's formula will give you the area.
Comment: Okay. Sure, I will use this as a method to verify my answer! Thanks a lot
Answer: The side vectors $AB = (-1,2,0)$ and $AC = (-1,0,2/3)$, between which their angle is given by
$$\cos \theta = \frac{AB\cdot AC}{|AB||AC|}$$
Thus, the area is
$$\frac12 |AB||AC|\sin\theta = \frac12 \sqrt{|AB|^2|AC|^2-(AB\cdot AC)^2}=\frac12 \sqrt{5\cdot \frac{13}9-1}=\frac{\sqrt{14}}3$$
Comment: Okay thanks! This will work for sure as it is the equivalent for the cross product
Answer: We can simply use De Gua's Theorem: $$A=\sqrt{\left(\frac{1\times2}{2}\right)^2+\left(\frac{2\times\frac{2}{3}}{2}\right)^2+\left(\frac{\frac{2}{3}\times1}{2}\right)^2}=\boxed{\frac{\sqrt{14}}{3}}.$$
Answer: Observe that the origin and the three vertices of the triangle form a tetrahedron. Its volume is equal to $\frac16\lvert A\times B\cdot C\rvert$. The triple product in this expression is equal to the determinant of the matrix $\begin{bmatrix}A&B&C\end{bmatrix}$, but this matrix is diagonal, so it's simply the product of the three intercepts.
On the other hand, the volume is also equal to $\frac13A_0h$, where $A_0$ is the triangle area that you're trying to find, and $h$ is the height of the tetrahedron. In this case this height is the distance of the origin to the plane. Use the point-plane distance formula, which I'm sure you know already, to find $h$, and solve for $A_0$.