How to handle  inside a button in wordpress

Question: I am using wordpress for this project. How can I handle the  tag which is getting displayed inside a button?
Here is how I am using it
 <button class="red-btn btn-effect reply" type="button">
        <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
    </button>

and its output is shown as
<button class="red-btn btn-effect reply">
        Reply        </button>

Html5 does not support  tags inside a button. How to handle this?
Comment: Is there any reason for using a button? `` with proper styling should be enough. Take the class attribute values on the `` element and add to the `` and you should be fine then remove the button.
Answer: That is because a button is not a link.
Remove the button and your output should actually be something like this instead:
Reply

Add in the neccessary classes for the link, you may need to make adjustments to the CSS for the a element.


Fetch html content after page is fully loaded using curl

Question: I am having a bit of problem here. When i load the page it takes at least 10sec to display the complete result. When i use the curl it only displays the html content of the page on runtime. I want the curl to wait at least 10 sec to fetch the complete result. This is my code,
<?php

$cookie = tmpfile();
$userAgent = 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31' ;

$ch = curl_init('http://filippo.io/Heartbleed/#www.example.com:433');

$options = array(
    CURLOPT_CONNECTTIMEOUT => 20 ,
    CURLOPT_USERAGENT => $userAgent,
    CURLOPT_AUTOREFERER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_COOKIEFILE => $cookie,
    CURLOPT_COOKIEJAR => $cookie ,
    CURLOPT_SSL_VERIFYPEER => 0 ,
    CURLOPT_SSL_VERIFYHOST => 0
);

curl_setopt_array($ch, $options);
$kl = curl_exec($ch);
curl_close($ch);
echo $kl;
?>

Kindly tell me where i m making mistake & what can i remove or add to make the script working. Thanks
Comment: I suppose you are referring to the code that is loaded after the page is open. If so, you cannot get that code with curl, since it's ajax url. You would need to find the ajax url in chrome console, and then fetch it instead of the main page.
Answer: I'm not sure where you got the 10 seconds from.  On my mid-range Linux laptop the page took about 3 seconds to load in Firefox.  However what you are confusing is the time it takes for the HTML page to load vs. the time it takes for all additional/dynamic content to load.
When you hit the URL, you get a very small static HTML page along with some javascript, css, images, etc.  The delay you see is the time it takes for the javascript to execute AJAX requests, as well as for images to load competely.
If you use curl, you are only getting the static HTML - and nothing else along with it.  No delay will help you get the full information, unless you are planning on implementing the full javascript engine and HTML parser and then load all the other resources, executing javascript code as necessary.
I strongly advise you to rethink your approach.
Answer: Add this to your $options array: CURLOPT_TIMEOUT => 10 where 10 is the number of seconds you want it to wait before timing out.
http://altafphp.blogspot.com/2012/12/difference-between-curloptconnecttimeou.html
Answer: I also had the same problem.
But CURLOPT_CONNECTTIMEOUT is the value which means if the curl cannot connect to file in this time, it would give up.
And CURLOPT_TIMEOUT is the value which means if the curl cannot crawl this file in this period after connect, it will give up.
So there is no value to set the curl function crawl after specific second.
You could use JavaScript code to load this file into the window and crawl them.
Or you could use the Python web driver


Fetch collection on basis of array item gives "FAILED_PRECONDITION: The query requires an index"

Question: I am trying to fetch all questions which has "maths" tag, but instead of success it moves to failedListener.
db.collection("questionCollection")
                .orderBy("questionID", Query.Direction.DESCENDING)
                .whereArrayContains("tags","maths")
                .limit(3)
                .get()
                .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        if (queryDocumentSnapshots.isEmpty()) {
                            Log.d(TAG, "onSuccess: LIST EMPTY");
                            return;
                        } else {
                            // Convert the whole Query Snapshot to a list
                            // of objects directly! No need to fetch each
                            // document.
                            questionList = queryDocumentSnapshots.toObjects(QuestionBO.class);

                            if (questionList != null && questionList.size() > 0)
                                mAdapter.updateQuestions(questionList);
                        }
                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                e.printStackTrace();
                Toast.makeText(mContext,"Failed",Toast.LENGTH_LONG).show();
            }
        });

Exception
FAILED_PRECONDITION: The query requires an index. You can create it here: https://console.firebase.google.com/project/testingproject-384af/database/firestore/indexes?create_index=EhJxd

Comment: So I guess exception already answers your question, no?
Comment: so what is the exception printed?
Comment: What is the exception that you get?
Comment: We're going to need more info on the issue. What kind of exception are you getting?
Comment: I have updated the exception. The query requires an indexes
Answer: Just click the link given to you in that error message.  It will take you to  the console and ask you to create the index that will satisfy the query you're trying to perform.


How to compare cpp and python outputs?

Question: I am trying to reproduce some functionality from Python in C++. It is an involved numerical method with a bunch of subfunctions.
Is there a nice way to compare the values of the Python functions with the C++ functions that I am writing and that should mirror them?
Could someone paste some code or give a mini tutorial?
Or some pointers or references?
Many thanks!
Artabalt
Comment: Write the output to two files, and then compare the files.
Comment: elaborate with an example for better grasp
Comment: What values? Do you mean something like unit tests? But since you tagged the question with "benchmarking" maybe you mean something else?
Comment: I mean for instance numpy.linalg.norm will give a certain output, and i want to make sure that it has close enough value to the norm function that I would write in cpp.
I suppose comparing the files would work, and since it is easier to read / parse files in python, have my cpp unit testing framework write data to some files, and then I could write a python script to run through it.
Was just wondering if there was not an "easier way" of doing this?
Answer: Testing.
Write tests for the functionality on Python (unless they already exist; Python code is usually tested).
Port the tests to C++. Then make your C++ functions pass the tests. Ideally, make the tests a target on your makefile and run them whenever you can.

Edit:
You can test randomly, if it's a good idea or not, might depend on your particular case.
The rule of thumb is to use a couple of each border case (you can use code coverage to see if there's a case that you're missing).
As an example, at my work I use an integration test that requires a lot of components. We simulate a betting process (all the process excluding user interface), at a given point in time, with a hardcoded server response, and we simulate the hardware printer with a redirection to a bmp.
Now, you can't test everything. I can't test every valid combination of numbers (6 numbers from 0 to 36?), in every possible order. Neither can I test every invalid combination (infinite?). You test a couple. The meaningful ones.
So we give it always the same numbers. The test is that it has to produce always the same bmp (has to render fonts the same, has to have the same texts, the same betting date, etc.).
Now, depending on your code and your application is the level of automation that generating this tests can have.
I don't know your particular case, but I would start creating a little program (the simpler, the better) that uses your library. One implementation in Python, one implementation in C++. If you were testing a string library, for example, you do a small program that deletes a letter inside a string, adds up a text, erases every other letter, etc.
Then you automate for a couple of test cases:
<code>cat largetext.txt | ./my_python_program > output.pyhthon_program.txt
cat largetext.txt | ./my_cpp_program > output.cpp_program.txt
diff output.pyhthon_program.txt output.cpp_program.txt || echo "ERROR"
</code>
The ideal case is that everytime you compile, the tests get run (this can be done if the code is simple; if not, you can do testing at the end of the day, as an example).
This doesn't grant the programs are the same (you can't test every possible input). But gives you some confidence. If you see something is not right, you first add it to your test, then make it fail, then fix it until it passess.
Regards.
Comment: I was thinking that another idea would be to write a provider module in ZMQ, two zmq modules, one in python the other in cpp, and then another module that eats the outputs and compares them. But your approach is much simpler to implement, the drawback is that one has to define all the test cases in both C++ and Python once more.
Comment: Dear Mirko, that is certainly an option, but I was thinking of a more "randomized testing", for instance by generating random vectors or matrices (many) and looking whether the output was nearly the same in all instances.

How to compare cpp and python outputs?


How can I insert NULL data into MySQL database with Python?

Question: I'm getting a weird error when inserting some data from a Python script to MySQL. It's basically related to a variable being blank that I am inserting.  I take it that MySQL does not like blank variables but is there something else I can change it to so it works with my insert statement?
I can successfully use an IF statement to turn it to 0 if its blank but this may mess up some of the data analytics I plan to do in MySQL later.  Is there a way to convert it to NULL or something so MySQL accepts it but doesn't add anything?
Comment: Does the column you're attempting to insert this NULL value into allow for NULLs? If not, what exactly is the error?
Comment: yes it does allow for null.  I see if I don't insert anything, it says the column is null the problem is my sql statements are constructed already.  Basically I'm pulling a bunch of prices from a file, and sometimes the price is blank, it means no price is avail.  I still want the details inserted but not the price.
Comment: my first idea was to turn them all to zero, but it'll mess me up later on when I do some analytics and find free products shifting the average price of the products, etc..
Comment: What EXACTLY is the "weird error" that you are getting? What does "blank" mean? Do `print repr(socalled_blank_value)` and show us the answer. What is the SQL type of the corresponding column?
Comment: sorry about that John.  The error is "Data truncated for column 'price' at row 1 [SQLCode: 1265], [SQLState: 01000]" when I print the value of the variable its totally blank..i don't think there's a space in even because if i put "if variable == "":"  that actually matches the value of this variable.
Comment: @Lostsoul: **What does "blank" mean? Do print repr(socalled_blank_value) and show us the answer. What is the SQL type of the corresponding column?**
Comment: Don't use zero, use a NULL and query on NOT NULL when doing you analytics.
Answer: When using mysqldb and cursor.execute(), pass the value None, not "NULL":
value = None
cursor.execute("INSERT INTO table (`column1`) VALUES (%s)", (value,))

Found the answer here
Comment: For me this inserted None as a string and not NULL in the db
Comment: it is an empty string in my case
Comment: @velociraptor11 it's because it needs a tuple. In python, if a tuple has only one elements, you must still use the comma (element,) or else the parenthesis will be evaluated as usual. (Element) becomes element once parenthesis are evaluated
Comment: Wow, for some reason the comma next to the variable value like `(value,)`  is important. I've been getting an error when trying to insert the same line of code except without the comma.
Comment: What if we don't use the %s notation? I usually use the "blah blah" + var + "blah blah" notation.
Comment: what if column1 is a number?
Comment: I get the error `cannot concatenate 'str' and 'tuple' objects` if I use it.
Comment: beware that sure you are passing two parameters to execute. you ate not formatting string yourself. this worked for me with python 3.5.
Comment: It doesn't matter what datatype I've set for that column? you can still insert None to float column?
Answer: Quick note about using parameters in SQL statements with Python.  See the RealPython article on this topic - Preventing SQL Injection Attacks With Python.  Here's another good article from TowardsDataScience.com - A Simple Approach To Templated SQL Queries In Python.  These helped me with same None/NULL issue.
Also, I found that if I put "NULL" (without quotes) directly into the INSERT query in VALUES, it was interpreted appropriately in the SQL Server DB.  The translation problem only exists if needing to conditionally add NULL or a value via string interpolation.
Examples:
cursor.execute("SELECT admin FROM users WHERE username = %s'", (username, ));

cursor.execute("SELECT admin FROM users WHERE username = %(username)s", {'username': username});

UPDATE: This StackOverflow discussion is more in line with what I'm trying to do and may help someone else.
Example:
import pypyodbc
myData = [
    (1, 'foo'),
    (2, None),
    (3, 'bar'),
]
connStr = """
DSN=myDb_SQLEXPRESS;
"""
cnxn = pypyodbc.connect(connStr)
crsr = cnxn.cursor()
sql = """
INSERT INTO myTable VALUES (?, ?)
"""
for dataRow in myData:
    print(dataRow)
    crsr.execute(sql, dataRow)
cnxn.commit()
crsr.close()
cnxn.close()

Answer: if the col1 is char, col2 is int, a trick could be:
insert into table (col1, col2) values (%s, %s) % ("'{}'".format(val1) if val1 else "NULL", val2 if val2 else "NULL");

you do not need to add '  ' to %s, it could be processed before pass value to sql.
this method works when execute sql with session of sqlalchemy, for example  session.execute(text(sql))
ps: sql is not tested yet
Answer: I had faced this same issue to make numeric and dates fields null.
we can make varchar fields null using 'NULL' as string in python but its a wrong method.
Solution for this is to use PyMySql library and importing NULL keyword
it will set NULL to any datatype field.
Answer: In addition to the other answers, the mycursor.execute() line must be joined with a , like so:
mycursor.execute(queryString, tupleOfValues)
Joining the arguments with a % for string formatting (mycursor.execute(queryString % tupleOfValues)) will turn the None into a string, and it will be evaluated by MySQL as a column title, resulting in *** mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'None' in 'field list'.
Answer: Based on above answers I wrote a wrapper function for my use case, you can try and change the function according to your need.
def sanitizeData(value):
    if value in ('', None):
        return "NULL"

    # This case handles the case where value already has ' in it (ex: O'Brien). This is how SQL skils single quotes
    if type(value) is str:
        return "'{}'".format(value.replace("'", "''"))

    return value

Now call the sql query like so,
"INSERT INTO %s (Name, Email) VALUES (%s, %s)"%(table_name, sanitizeData(actual_name), sanitizeData(actual_email))

Answer: Why not set the variable equal to some string like 'no price' and then filter this out later when you want to do math on the numbers?
filter(lambda x: x != 'no price',list_of_data_from_database)

Answer: Do a quick check for blank, and if it is, set it equal to NULL:
if(!variable_to_insert)
    variable_to_insert = "NULL"

...then make sure that the inserted variable is not in quotes for the insert statement, like:
insert = "INSERT INTO table (var) VALUES (%s)" % (variable_to_insert)
...

not like:
insert = "INSERT INTO table (var) VALUES ('%s')" % (variable_to_insert)
...

Comment: This is really bad. You should be using parameters in your sql statements. Not using parameters leaves you open to sql injection attacks.
Comment: @phaxian You shouldn't be inserting like this.  You should be passing a string with parameters, and then a list of parameter values as a tuple.
Comment: Thanks for the message, I thought of that but won't that just insert a variable with the text "NULL" in it? or is the text NULL a special character when inserting into databases?
Comment: @Lostsoul: So perhaps you should show us the relevant part of your script.
Comment: NULL is a special character when inserting into sql (without quotes).  If you use the second insert, it would insert the string "NULL", bu the first will have a statement like: INSERT INTO table (var) VALUES (NULL) which will put a special NULL in for the value.


How To Properly Compress UIImages At Runtime

Question: I need to load 4 images for simultaneous editing. When I load them from the users library, the memory exceeds 500mb and crashes.
Here is a log from a raw allocations dump before I did any compression attempts:
Code:
var pickedImage = UIImage(data: imageData)

Instrument:

I have read several posts on compressing UIImages. I have tried reducing the UIImage:
New Code:
var pickedImage = UIImage(data: imageData, scale:0.1)

Instrument:

Reducing the scale of the UIImage had NO EFFECT?! Very odd.
So now I tried creating a JPEG compression based on the full UIImage
New code:
var pickedImage = UIImage(data: imageData)
var compressedData:NSData = UIImageJPEGRepresentation(pickedImage,0)
var compressedImage:UIImage = UIImage(data: compressedData)!//this is now used to display

Instrument:

Now, I suspect because I am converting the image its still being loaded. And since this is all occuring inside a callback from PHImageManager, I need a way to create a compressed UIImage from the NSData, but the setting the scale to 0.1 did NOTHING.
So any suggestions as to how I can compress this UIImage right from the NSData would be life saving!!!
Thanks
Comment: Yea that way is old school but thank you (its overkill). I did figure out another solution which I can post tomorrow.
Comment: have you try using [link](https://github.com/AliSoftware/UIImage-Resize) ?
Answer: I ended up hard coding a size reduction before processing the image. Here is the code:
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize:CGSizeMake(CGFloat(asset.pixelWidth), CGFloat(asset.pixelHeight)), contentMode: .AspectFill, options: options)
{
  result, info in
  var minRatio:CGFloat = 1
  //Reduce file size so take 1/2 UIScreen.mainScreen().bounds.width/2 || CGFloat(asset.pixelHeight) > UIScreen.mainScreen().bounds.height/2)
  {
    minRatio = min((UIScreen.mainScreen().bounds.width/2)/(CGFloat(asset.pixelWidth)), ((UIScreen.mainScreen().bounds.height/2)/CGFloat(asset.pixelHeight)))
  }

  var size:CGSize = CGSizeMake((CGFloat(asset.pixelWidth)*minRatio),(CGFloat(asset.pixelHeight)*minRatio))
  UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
  result.drawInRect(CGRectMake(0, 0, size.width, size.height))
  var final = UIGraphicsGetImageFromCurrentImageContext()
  var image = iImage(uiimage: final)
}

Comment: i have the same problem in objective-C. This is my question link==>http://stackoverflow.com/questions/36034703/how-to-handle-multiple-images-with-large-size . Please help me to solve the problem.
Answer: The reason you're having crashes and seeing such high memory usage is that you are missing the call to UIGraphicsEndImageContext(); -- so you are leaking memory like crazy.
For every call to UIGraphicsBeginImageContextWithOptions, make sure you have a call to UIGraphicsEndImageContext (after UIGraphicsGetImage*).
Also, you should wrap in @autorelease (I'm presuming you're using ARC), otherwise you'll still have out-of-memory crashes if you are rapidly processing images.
Do it like this:
@autorelease {
  UIGraphicsBeginImageContextWithOptions(...);
  ..
  something = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
}


How far off-center can the center be?

Question: So sometimes a team can run a play with an unbalanced line. I was wondering "how unbalanced". Can the center be all the way to one side? Can the center be several yards away from his teammates?
I don't care if it is advisable to do this or not. I'm strictly asking if it is allowed in NFL rules.
Answer: There are no rules associated with players' distance from the center.  If there was a rule on it, it would be in the rule book.  There are just really three stipulations:

7 total players on the line of scrimmage in bounds within the back hip of the center
the center must hike the ball between his legs
the ball is set by the referee between the hashes based on the last play (so at most your furthest lineman can be is 2/3 of the field).

I will say that at my high school in the mid 90s we only ran unbalanced and had a future NFL RB go for over 300 yards a game at over a 10 clip.  There is a huge tactical advantage if a defense doesn't rotate correctly or over rotates later in the game.  And just the fact that most defenses don't normally see this.
In fact every once in a while we ran the swinging gate.  This is a very very very effective play when practiced properly especially just using some basic spread principles (RPO).  If you have a dominant player at a skill position - WR, RB, or QB you can really isolate that player in a 1 on 1 match or make the team double that player at the beginning.
The swinging gate is so effective that most pee-wee to high school rules have stipulations to either outlaw it or make it less effective.  An example is some/most organizations at that level consider the center ineligible and these kinds of formations are why high school rules are so stringent on player numbers for pass catching eligibility.  The actual rules of football allow the center to be eligible if he is at the end of the line of scrimmage.
About 15 years ago I was coaching a 7th grade boys team.  They were not very good but had 3-4 good players.  We had the fastest kid play WR - the lone - player on one side of the center (because the league made me do that).  I had a good QB that could run and a bruiser at RB.  Then I put my fastest lineman at center.
What does a team do?  You have to have a man on my WR.  You also have to have a free safety playing the middle - or we just run a post.
But here is the kicker.  You have to have 3 players minimum - 2 lineman/1 LB or more likely a lineman/2 LBs play against my C/QB/RB.  They better be really really good players.  Because my center will block the closest LB, my QB will read the DL, chances are the DL is so slow he's not even a factor.  Then either I have a one on one for at least 5 yards or I could possibly have a 2-1 if QB beats DL.
So within 5 plays the other coach puts 2 DL (one split wide) and 2 LBs.  Remember there is a CB and FS there too.  So now we have 6 players shading my QB/RB/C/WR.  So then my QB just throws it to the other side and my team is playing 7 on 5.  And my QB can throw it to the other RB and that RB can pass it too.  Since most coaches know their 5 players are screwed they have them rush hard... Flip it to the end and a TD.  The play was banned after the first year we ran it.  Probably average 15 yards a play vs 2 on other plays.
Answer: I can't find anything in the current rules that restrict the positions of the offensive line players with respect to the ball for the purposes of illegal formations.  In addition, there are no restrictions on the distance that line players can be from one another.
So although it would be tactically horrible, it appears to be legal for the rest of the line to play away from the "center" position.  If all the other linemen are on one side, the player would additionally have to report as an eligible receiver beforehand.
Comment: There are *some* restrictions on this coming from the Patriots plays in the 2015 playoffs; see e.g. [this article](http://itiswhatitis.weei.com/sports/newengland/football/patriots/2015/03/25/league-outlaws-patriots-unbalanced-line-approach-that-new-england-used-against-ravens/), although I believe they apply only if normally eligible players are reporting as ineligible.

How far off-center can the center be?


How to correct underdispersion in logistic regression

Question: I created a logistic regression model with four continuous variables and a binary outcome. I divided the residual deviance by the residual degrees of freedom, which equaled 0.63. From my understanding, underdispersion is supposed to be rare, and it essentially results in coefficients that are too conservative. This seems like less of a problem than overdispersion, which results in overconfidence. Does underdispersion need to be corrected?
Answer: Getting a residual mean deviance around 0.63 is perfectly normal for binary regression and it does not indicate underdispersion or overdispersion. For binary regression, the residual deviance is determined entirely by the size of the fitted values and not by goodness of fit. If the fitted values are mostly near zero or one, then the deviance will be small. If the fitted values are mostly near 0.5, then the deviance will be large.
There is actually no such thing as underdispersion or overdispersion for binary regression.
It is mathematically impossible for a binary variable to have a variance other than given by the binomial formula.
See for example

quasi likelihood for ungrouped binary data
What are weights in a binary glm and how to calculate them?

Overdispersion or underdispersion is only possible for binomial regression when the number of cases per binomial observation is larger than one, $n>1$.
Even then, you would not usually be concerned by a residual mean deviance of 0.63, which can easily be achieved even when the responses are truly binomial.
Here is a small example with binary data:
> y <- rbinom(1000,size=1,prob=0.005)
> fit <- glm(y~1,family=binomial())
> anova(fit)
Analysis of Deviance Table

Model: binomial, link: logit

Response: y

Terms added sequentially (first to last)

     Df Deviance Resid. Df Resid. Dev
NULL                   999     28.854
> 28/999
[1] 0.02802803

Here y has been simulated to be truly binomial, so there is no true overdispersion or underdispersion. Yet the residual mean deviance is very small, only 0.028.
The small deviance is simply a consequence of the fact that the fitted values are much less than 0.5:
> summary(fitted(fit))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  0.002   0.002   0.002   0.002   0.002   0.002

The same phenomenon exists even when the data is not binary.
For example:
> y <- rbinom(1000,size=3,prob=0.005)
> p <- y/3
> fit <- glm(p~1,family=binomial(),weights=rep(3,1000))
> anova(fit)
Analysis of Deviance Table

Model: binomial, link: logit

Response: p

Terms added sequentially (first to last)

     Df Deviance Resid. Df Resid. Dev
NULL                   999     138.29

Here the data is binomial with $n=3$, with no underdispersion, yet the residual deviance is still very much smaller than the residual degrees of freedom.
Again, this is caused by the fact that the fitted probabilities are closer to zero than to 0.5.
Using the deviance as a measure of goodness of fit is only reliable when the number of cases is large and the fitted probabilities are not too close to 0 or 1.
There is a discussion of this phenomenon in my book with Peter Dunn on generalized linear models.
We developed theoretical conditions that must be satisfied for the residual deviance to treated as a goodness of fit statistic or as a measure of over or underdispersion.
Reference
Dunn PK, Smyth GK (2018). Generalized linear models with examples in R. Springer, New York, NY.


Help with Finding ∂z/∂u and ∂z/∂v

Question: Find $∂z/∂u$ and $∂z/∂v$.
The variables are restricted to domains on which the functions are defined.
$z = \sin(x/y)$, $x = \ln u$, $y = 7v$
I solved for both ∂z/∂u and ∂z/∂v but cannot figure how to only express the answers in terms of u/v. ∂z/∂u came out to (1/y)(1/u)(cos(x/y)) and ∂z/∂v as (-x/y^2)(cos(x/y))(7).
Comment: Do you know the chain rule? What have you tried?
Comment: acraft, If you want the answer in a certain form, you should make this wish clear inside your main text, not in the comments. Also you should show the work you've done. (in the main text above)
Comment: Yes, I solved it for both ∂z/∂u and ∂z/∂v but cannot figure how to only express the answers in terms of u/v.
Comment: I'm new to StackExchange and will keep your tip in mind. ∂z/∂u came out to (1/y)(1/u)(cos(x/y)) and  ∂z/∂v as (-x/y^2)(cos(x/y))(7).  The problem is with solving for x,y so the final answers are in terms of u,v.
Answer: EDIT
Your calculation is correct.
You have an expression with $x$, $y$, $u$, and $v$. To get an expression with just $u$ and $v$, use the fact that you know what $x$ and $y$ are, i.e., substitute $\ln u$ everywhere you have $x$ and $7v$ everywhere you have $y$.
Comment: Can you explain why I need the term ∂z/∂y⋅∂y/∂u? Since z is a function of x,y; x is a function of u; y is a function of v. I have ∂z/∂u=∂z/∂x*∂x/∂u and ∂z/∂v=∂z/∂y*∂y/∂v. Did I make an error?
Comment: My apologies, you are right! I didn't follow through with the calculation. The answer is correct, and I hope the last paragraph answered your actual question then!
Comment: No worries! By any chance is it possible to solve for ∂z/∂u in terms of only u and ∂z/∂v in terms of only v?
Comment: Does my answer not make sense for how to get that?
Comment: Yes it does, but I guess my answer is still not accepted by the grading system. Thank you for your help!
Answer: All you need to do is substitute the given functions, either before or after you apply the chain rule. For example, $x = \ln u$ so you just replace all the $x$ terms in your $\frac{\partial z}{\partial u}$ and $\frac{\partial z}{\partial v}$ with $\ln u$, and similarly for $y$.
Comment: Yes, that's what I did. I ended up cos(lnu/7v)*(1/7vu) and cos(lnu/v)*(-lnu/7v^2), but I guess the grading system prefers another answer format??? Your explanation makes sense! Thank you for your time.
Comment: It might want you to rearrange things a bit - for example, to put the - sign out the front and put some parentheses around terms to avoid ambiguity (e.g. does 1/7vu mean $\frac{1}{7vu}$ or $\frac{1}{7} vu$ or something else?)

Help with Finding ∂z/∂u and ∂z/∂v


What is the difference between $E\{e^{-sx}\}$ and $E\{e^{sx}\}$ for MFG

Question: I am working in wireless communication.
When I cheek the books about MFG I found the MGF of random variable $X$ is given by  the following formula
$$
M_X(s)=E\{e^{sx}\}
$$
However when I read papers, I found the following definition
$$
M_X(s)=E\{e^{-sx}\}
$$
What is the difference between this two?.
Comment: Have you ever heard of the Laplace transform? See: https://en.wikipedia.org/wiki/Laplace_transform#Probability_theory
Comment: Both of these questions are answered in the link I provided, which apparently you did not bother to even take a cursory reading of—if $f$ is the PDF of a random variable $X$, then conventionally, the MGF of $X$ is defined as $M_X(s):=\mathbb{E}(e^{s X})$ and the Laplace transform can be written as $\mathscr{L}(f)=M_X(-s)=\mathbb{E}(e^{-sX})$.
Comment: I know the Laplace transform, But in paper they talk about MGF, since for $Y=X+Z$, where $X$ and $Z$ are independent we have $E\{e^{-sY}\}=E\{e^{-sX}\}E\{e^{-sZ}\}$. So I am confuse? Dose this properties hold in Laplace transform and what relation between  MGF and Laplace transform?
Comment: I have read the reference, thanks, So the authors In paper should say the Laplace transform not the MGF
Comment: Technically, yes. But I think probabilists will just often call it the MGF anyway because we are unpredictable :). With either version you can still recover the moments of $X$ but you have to account for the signs.
Answer: The moment generating function, or MGF, has the usual definition of:
$$MGF(s) = E\{ e^{sX} \} = \int_{-\infty}^{\infty}f(x)e^{sx}dx$$
The bilateral Laplace transform has the usual definition of:
$$ L(s) = \int_{-\infty}^{\infty}f(x)e^{-sx}dx$$
Comparing the two we can derive the following:
$$MGF(s) = L(-s) = \int_{-\infty}^{\infty}f(x)e^{sx}dx$$
Comment: The last integral should read $\int_{-\infty}^\infty f(x)e^{sx}dx$.
Comment: @LoveTooNap29 Thanks :)
Answer: If $f$ is the PDF of a random variable $X$ then, conventionally, the MGF of $X$ is defined as $M_X(s):=\mathbb{E}(e^{sX})$ and the Laplace transform of $f$ (often reworded as the Laplace transform of $X$, though technically incorrect) can be written as $\mathscr{L}[f](s)=M_X(-s)=\mathbb{E}(e^{-sX})$.
Both satisfy the lovely "independence implies multiplication" property and you can further recover the moments of $X$ from either form but you must account for the signs when using $M_X(-s)$, e.g.
$$-\frac{d}{ds} \mathbb{E}(e^{-sX})=-\mathbb{E}(-Xe^{-sX}) |_{s=0}=\mathbb{E}(X),$$
etc.


How to setup Sublime Text 3 to build script with MSYS bash?

Question: Hi i would like to know how to setup sublime text 3 build system to execute bash script threw MSYS bash.
I have try the following build system :
<code>{
    "cmd"       : ["bash", "$file"],
    "selector"  : "source.shell",
    "path"      : "C:/MinGW/msys/1.0/bin"
}
</code>
It does look to work, but it can't find gcc, i have try to add multiple path this way :
<code>    "path"      : "C:/MinGW/msys/1.0/bin:C:/MinGW/bin"
</code>
But the C: looks to break the thing.
I have also try this :
<code>    "path"      : ["C:/MinGW/msys/1.0/bin", "C:/MinGW/bin"]
</code>
But it fail also as path is waiting for a string only
<code>     "path"      :"C\:/MinGW/msys/1.0/bin:C\:/MinGW/bin"
     "path"      :"C:/MinGW/msys/1.0/bin\:C:/MinGW/bin"
     "path"      :"${C:/MinGW/msys/1.0/bin}:${C:/MinGW/bin}"
</code>
Also fail ...
<code>     "path"      : "/c/MinGW/msys/1.0/bin:/c/MinGW/bin"
     "path"      : "/MinGW/msys/1.0/bin:/MinGW/bin"
</code>
Same for those ...
Any working suggestion would be greatly appreciated.
Comment: Have you tried `"path"      : "/MinGW/msys/1.0/bin"` ?
Comment: Thanks for your answer SB87 ! yes this one work, but the pb is that it can't find gcc , so i am trying to find the way to link the 2 path MinGW\bin and msys\bin.
Comment: Try `"path"      : "/MinGW/msys/1.0/bin:/MinGW/bin"` so get rid of the `C:`
Comment: Unfortunatly it doesn't work i have edited my post to include the 2 new test that fail !
Comment: Are you getting any error message?
Comment: i just get a line `2: gcc: command not found` when i only set /msys/bin.
Comment: what is the output of `which gcc` in terminal?
Comment: got this `/mingw/bin/gcc.exe`
Comment: Ah, reading [this](http://sublimetext.info/docs/en/reference/build_systems.html) maybe you should set the `path` before you set the `cmd`? Also, have you tried `"path" : "$PATH:/MinGW/msys/1.0/bin:/MinGW/bin"`?
Comment: Thanks a lot SB87 you did help me with your mac stuff. because it give me the idea to search in install package ... and ALLELUIA got this
https://github.com/macite/sublimebashbuildsystem/blob/master/Bash.sublime-build
Comment: Well done! Syntax can be hard to figure out, sometimes a simple example clarifies it all.
Answer:
To install msys bash with sublime text 3 you just have to copy this in
  a new build system:

<code>{
    "cmd"       : ["bash", "$file"],
    "selector"  : "source.shell",

    "windows": {
        "path"  : "$path;c:\\mingw\\bin;c:\\mingw\\msys\\1.0\\bin",
        "cmd"   : ["bash", "--login", "-i", "-c", "cd \"$file_path\"; \"$file\""]
    },

    "osx": {
        "path"  : "$PATH:/usr/local/bin:/usr/X11R6/bin:/opt/X11/bin:/usr/texbin"
    }
}
</code>
thanks to macite :
https://github.com/macite/sublimebashbuildsystem/blob/master/Bash.sublime-build


scatterplot3d - change axis range

Question: I am using scatterplot3d to generate several plots, and I would like to keep the scales consistent throughout each of the plots (I am trying to show changes over time, so this is essential).  My current code is as follows (by no means elegant, as I am a beginner!):
library(scatterplot3d)
file<-read.csv("DAY2.csv")
axis1<-file$axis1
axis2<-file$axis2
axis3<-file$axis3
s3d <- scatterplot3d(axis1, axis2, axis3)
colors <- c("#9900FF", "#E69F00", "#339900", "#0000FF")
colors <- colors[as.numeric(file$treatment)]
s3d <- scatterplot3d(file[,1:3], pch = 16, color=colors, xlab =
"Axis 1", ylab = "Axis 2", zlab = "Axis 3")
legend(s3d$xyz.convert(0.4, 0.4, -0.1), col= c("#9900FF", "#E69F00",
"#339900", "#0000FF"), bg="white", lty=c(1,1), lwd=2, yjust=0,
legend = c("high perf", "low perf"), cex = 0.7)

Is it possible to specify axis ranges to keep these consistent between plots? I have checked the vignette, but there is no information in there on this.
Thanks in advance,
Jo
Answer: You can use xlim, ylim and zlim how arguments in sccaterplot3d function, example:
library(scatterplot3d)
x <- c(1, 2, 3)
y <- c(2, 2, 2)
z <- c(6, 7, 8)
max_x <- max(x)
min_x <- min(x)
max_y <- max(y)
min_y <- min(y)
max_z <- max(z)
min_z <- min(z)
s3d <- scatterplot3d(x,y,z, pch=6, angle=45, color="red",
        xlim=c(min_x,max_x),
        ylim=c(min_y,max_y),
        zlim=c(min_z,max_z))

If you modify xlim, ylim or zlim will change the axis.
Answer: Please use xlim, ylim, zlim, the x, y and z limits (min, max) of the plot.

scatterplot3d - change axis range


How to show $\operatorname{Pic}(X)=0$? Exercise $14.2$.Q Vakil's notes

Question: I'm reading Vakil's notes and I'm struggling with the exercise $14.2$.Q. I've been able to prove everything except $\operatorname{Pic}(X)=0$ with
$$
X=\operatorname{Spec}\frac{k[x,y,z]}{(xy-z^2)}.
$$
I tried to find an affine covering where all the rings are UFDs, but without results. Also I tried to compute $\operatorname{H^1}(X,\mathcal{O}_X^{\times})$ using the Cech cohomology, but also here I don't know how to set my covering.
Some (maybe usefull) facts: this ring is normal and the class group of $X$ is $\mathbb{Z}/2\mathbb{Z}$.
Thank you in advance to those who can answer or suggest something.
Answer: This is example 6.11.3 in Hartshorne. In 6.11.2 he argues that by the proof of Prop 6.11, Cartier divisors correspond to certain Weil divisors: if a Cartier divisor is given by $(U_i, f_i),$ then one associates a Weil divisor $\sum\limits_Y v_Y(f_i) [Y]$ to it. Weil divisors one gets this way are locally principal, meaning their restrictions on some open covering are principal.
Also note that by 6.15, $\operatorname{Pic}X \simeq \operatorname{CaCl}X.$
Now, the generator of $\operatorname{Cl}X \simeq \mathbb{Z}/2\mathbb{Z}
$ is given by $V(z,y)$, which is not locally principal because $p:=(z,y)$ is not locally principal in the local ring of the point $(0,0,0) =: [m]$. Indeed, $m/m^2$ is a vector space spanned by $x, y$ and $z$, and $p \otimes \frac{k[x,y,z]}{(xy-z^2)}_m$ is its subspace which contains $y$ and $z$, so $p$ can't be principal in $\frac{k[x,y,z]}{(xy-z^2)}_m$.
Comment: Thank you for your answer!
Comment: @heartless t-struct  Indeed, it had to be "CaCl".
Comment: This doesnt seem like it addresses $\operatorname{Pic}(X) = 0$; actually this is contrary to that fact since you are saying $\operatorname{Pic}(X) \cong \operatorname{Cl}(X) \cong \mathbb{Z} / 2\mathbb{Z}$


Derivatives car velocity paradox

Question: This is my first post on the Maths section of StackExchange.
I am a high school student from Greece studying for IAL Math and got a bit confused on derivatives while watching this video; specifically on minute 14:29.
The author gives an example of a car traveling on the curve $x^3$ where $x \in [0, 3]$. He then asks if the car is moving or not at $x = 0$
Let's use $x^2$ instead of $x^3$ here for simplicity.
Through the use of the derivative of $x^2$, $\frac{dy}{dx} = 2x$ we see that at $x=0$ the velocity of the car is  $\frac{dy}{dx}=2(0)=0$ which suggests that the car is not moving.
I can see, however, the point the author is making, arguing that the car is actually moving, since the derivative formula for $x^2$ is derived as such:
$
\lim\limits_{h \to 0} \frac{f(x+h)-f(x)}{h}=
\lim\limits_{h \to 0} \frac{(x+h)^2-x^2}{h}=
\lim\limits_{h \to 0} \frac{x^2+2hx+h^2-x^2}{h}=
\lim\limits_{h \to 0} \frac{2hx+h^2}{h}=
\lim\limits_{h \to 0} 2x + h =
2x
$
where in the penultimate step we can see that the derivative formula is actually $2x$ plus some very very small quantity because $h$ doesn't actually ever reach zero. So is the car actually moving with its velocity being that very very small quantity?
How can someone first argue that $h$ approaching zero can be neglected from the equation(last step) and subsequently contradict himself and argue that $h$ approaching zero should actually be included? Is it safe to assume that for $\frac{dy}{dx}=0$ an object is stationary? (In the context where $y$ is the distance travelled and $x$ is time)
Moreover, for $x=0$ the derivative formula's result is $0$ which should also be the gradient of the line tangent to the parabola at $x=0$
And indeed, the gradient of the tangent line is $y=0$ which crosses $y=x^2$ only at point $0$ and not at point $0$ plus some very very small quantity

(Desmos)
I am very confused by this and would really appreciate help. I have also tried to make my questions as clear as possible but since I do not seem to understand calculus and limits all that well I will be more than willing to provide any clarifications.
Comment: This is a central idea in calculus (might require more than a stack exchange answer), and where the logic gets a little abstract. "very small number" is a little misleading. It takes some effort to wrap your head around this, but in the limit, h isn't a number or a normal variable, and doesn't have any meaning outside of the "limit" equation.

It helps to read about the formal definition of the limit, and I'm sure there are explanations far better than this one out there, especially on the channel you linked.
Comment: There was supposed to be a greeting at the start of this post but apparently it has been filtered out. Anyways, hello everyone!
Comment: You might be interested in this youtube video by 3blue1brown, in which he discusses this apparent paradox: https://www.youtube.com/watch?v=9vKqVkMQHKk
Answer: This is the central paradox of calculus:
You are right in saying that "instantaneous velocity" does not truly exist, by the definition of velocity, that a time interval must pass.
However, in calculus, we are interested in finding this "instantaneous velocity" whereby we find the derivative at this very instant (even though in real life we cannot actually "have" such a quantity).
Regarding whether the car is stationary at that point: if t=0 is the instant right before the car moves, then it is stationary - but in a short instant later (dx) we see it is moving. Furthermore, you could argue it is beginning to move if we see that its acceleration, $\frac{d^2y}{dx^2}=2$ is more than zero hence its velocity is increasing.

How can someone first argue that h approaching zero can be neglected from the equation(last step) and subsequently contradict himself and argue that h approaching zero should actually be included?

The 2nd context where h should be approaching zero is how we find derivatives from "first principles" where we let dx be a very small (almost infinitesimal) number (ie finding velocity in a small instant denoted by $\frac{\delta y}{\delta x}$.
However, in the 1st context where we remove h approaching zero is when we find the "instantaneous velocity": using first principles, then letting it approach zero, denoted by $\lim\limits_{\delta x \to 0} \, \frac{\delta y}{\delta x} = \frac{dy}{dx}$.
Normally in calculus we "skip" the first principles using prederived formula.
Thus, the contradiction is actually the fact that there are two contexts: a small delta x vs delta x approaching zero. These are similar but still different contexts.

And indeed, the gradient of the tangent line is y=0 which crosses y=x2 only at point 0 and not at point 0 plus some very very small quantity

A "cheat" way to understand this is: what quantity would we choose when representing the gradient at 0? Furthermore, the gradient at 0 is a straight line not a variable which changes based on a quantity we choose.
Comment: Great answer! Thanks a lot. I did not realize there were two different contexts. I understand this much better now.

Derivatives car velocity paradox


CSS - background-color not working in IE11

Question: I have the following code:
.skills_column {
  padding: 50px !important;
  padding-top: 60px !important;

  &.--light {
    background-color: white;
  }
  &.--dark {
    background-color: #ced4db;
  }

  @include media-breakpoint-down(sm) {
    h1 {
      text-align: center;
    }
  }
}

There are 3 columns, a light one, and two dark ones.
All of this works in Chrome & Firefox, however, it does not work in IE11:
While the light one is white as expected, the two other columns which are supposed to be dark, are also white when viewed in IE11.
What could the problem be?
I also tried to add filter: none !important; because I read that somewhere, but that does not seem to make a difference although I might have not applied it correctly, I am not sure.
I am also using flexbox, if that should make a difference. But my problem here is with the background colors not being applied.
Comment: Sure, glad it helped. Everyday i see issues like this I feel sad for IE devs and users.
Comment: its mostly the flexbox thats affecting this. Do you have `flex` or `min-height` property on the flex items?
Comment: I only have one additional class which is applied to a child of each column, which centers an svg. But this is not directly applied to the column itself: `.content_centered {
  display: flex;
  align-items: center;
  justify-content: center;
}`  - apart from this my HTML for each column looks like this: ` ... `
Comment: hmm doesn't look harmful. Can you remove the double hyphen from the class names `--dark` & try. I have a feeling IE doesnt like this.
Comment: I'll try this. This might be it. Will report back shortly
Comment: Sorry, that took me some time. That was precisely it. I changed everything to underscores, so e.g. `_light` , and that works now. Thanks a lot. If you would want to submit this as an answer, I would pick that of course.
Answer: Can you try removing the double hyphen from your class names(--dark, --light). I have a feeling IE doesn't like BEM representations. Maybe single underscore or double underscore works.
.skills_column {
  padding: 50px !important;
  padding-top: 60px !important;

  &._light {
    background-color: white;
  }
  &._dark {
    background-color: #ced4db;
  }

  @include media-breakpoint-down(sm) {
    h1 {
      text-align: center;
    }
  }
}


Solving $\sin (100^\circ-x) \sin 20^\circ =\sin (80^\circ-x)\sin 80^\circ$

Question:
Solve for $x$ such that
$$\sin (100^\circ-x) \sin 20^\circ =\sin (80^\circ-x)\sin 80^\circ$$

First, I use the co-function formula:
$$\sin 80^\circ = \cos 10^\circ \tag{1}$$
Also,
$$\sin 20^\circ = 2\sin 10^\circ \cos 10^\circ \tag{2}$$
From these, I got
$$\sin(100^\circ-x)\cdot 2\sin 10^\circ =\sin (80^\circ-x) \tag{3}$$
I thought to use
$$2\sin a \sin b =\cos(a-b)-\cos(a+b) \tag{4}$$
but I'm stuck.
Help me please.
Comment: if you use the addition formula for the sine, you can arrive at an expression: A*sen(x)=B*cos(x), i.e. tg(x)=B/A . maybe than you can try to simplify from there...
Answer: We need to solve
$$\sin100^{\circ}\sin20^{\circ}\cos{x}-\cos100^{\circ}\sin20^{\circ}\sin{x}=\sin^280^{\circ}\cos{x}-\cos80^{\circ}\sin80^{\circ}\sin{x}$$ or since
$$\cos80^{\circ}\sin80^{\circ}-\cos100^{\circ}\sin20^{\circ}\neq0,$$
$$\tan{x}=\frac{\sin^280^{\circ}-\sin100^{\circ}\sin20^{\circ}}{\cos80^{\circ}\sin80^{\circ}-\cos100^{\circ}\sin20^{\circ}}.$$
But $$\frac{\sin^280^{\circ}-\sin100^{\circ}\sin20^{\circ}}{\cos80^{\circ}\sin80^{\circ}-\cos100^{\circ}\sin20^{\circ}}=\frac{1-\cos160^{\circ}-\cos80^{\circ}+\cos120^{\circ}}{\sin160^{\circ}-\sin120^{\circ}+\sin80^{\circ}}=$$
$$=\frac{\sin30^{\circ}+\cos20^{\circ}-\cos80^{\circ}}{\sin80^{\circ}-2\sin20^{\circ}\cos40^{\circ}}=\frac{\sin30^{\circ}+\sin50^{\circ}}{4\sin20^{\circ}\cos20^{\circ}\cos40^{\circ}-2\sin20^{\circ}\cos40^{\circ}}=$$
$$=\frac{2\sin40^{\circ}\cos10^{\circ}}{4\sin20^{\circ}\cos20^{\circ}\cos40^{\circ}-2\sin20^{\circ}\cos40^{\circ}}=\frac{4\sin20^{\circ}\cos20^{\circ}\cos10^{\circ}}{4\sin20^{\circ}\cos20^{\circ}\cos40^{\circ}-2\sin20^{\circ}\cos40^{\circ}}=$$
$$=\frac{2\cos20^{\circ}\cos10^{\circ}}{2\cos20^{\circ}\cos40^{\circ}-\cos40^{\circ}}=\frac{2\cos20^{\circ}\cos10^{\circ}}{\cos60^{\circ}+\cos20^{\circ}-\cos40^{\circ}}=\frac{2\cos20^{\circ}\cos10^{\circ}}{\sin30^{\circ}+\sin10^{\circ}}=$$
$$=\frac{2\cos20^{\circ}\cos10^{\circ}}{2\sin20^{\circ}\cos10^{\circ}}=\cot20^{\circ}=\tan70^{\circ}.$$
Id est, $$x=70^{\circ}+180^{\circ}k,$$ where $k\in\mathbb Z$.
Answer:
A geometric solution:
First draw triangle $ABC$ where $\angle BAC=20$ and $AB=AC$. Easy to find out $\angle ABC=\angle ACB=80$.
Now add point $D$ on line $AC$ such that $\angle CBD = x$, so $\angle ABD=80-x$ and $\angle BDC = 100-x$.
${sin(80-x)\over sin20}={sin(100-x)\over sin80} \implies {AD\over BD}={BC\over BD}\implies AD=BC$.
Now draw $NM$ pass through $D$ and parallel to $BC$ where $N$ is on $AB$ and $NM=AB$. Easy to see $ANM$ is congruent to $ABC$. Now $AM=AC$ and $\angle MAC=60$ so $AMC$ is equilateral. So $\angle NMC=60-20=40$. Also since $NM=AM=MC$ so $NMC$ is isosceles and $\angle MNC=70$. Note by symmetry triangles $NDC$ and $DNB$ are congruent and therefore $\angle NDB=70$. Since $ND$ and $BC$ are parallel $x=\angle DBC=\angle NDB=70$.
Answer: $$\dfrac{\sin(100^\circ-x)}{\sin(80^\circ-x)}=\dfrac{\sin80^\circ}{\sin20^\circ}$$
Use Componendo et Dividendo,
$$\dfrac{\sin(100^\circ-x)-\sin(80^\circ-x)}{\sin(100^\circ-x)+\sin(80^\circ-x)}=\dfrac{\sin80^\circ-\sin20^\circ}{\sin80^\circ+\sin20^\circ}$$
Use Prosthaphaeresis Formulas
$$\dfrac{\tan10^\circ}{\cot x}=\dfrac{\tan30^\circ}{\tan50^\circ}$$
$$\iff\tan x=\tan30^\circ\tan40^\circ\tan80^\circ$$
Now using Proving a fact: $\tan(6^{\circ}) \tan(42^{\circ})= \tan(12^{\circ})\tan(24^{\circ})$,
$$\tan20^\circ\tan(60^\circ-20^\circ)\tan(60^\circ+20^\circ)=\tan(3\cdot20^\circ)$$
$$\implies\tan x=\cot20^\circ$$
The rest should be easy.
More generally we have reached at $$\tan y\tan(60^\circ-y)\tan(60^\circ+y)\tan(90^\circ-3y)=1$$
See also :
$\cot(x+110^\circ)=\cot(x+60^\circ)\cot x\cot(x-60^\circ)$
Proving a fact: $\tan(6^{\circ}) \tan(42^{\circ})= \tan(12^{\circ})\tan(24^{\circ})$
How can I find the following product? $ \tan 20^\circ \cdot \tan 40^\circ \cdot \tan 80^\circ.$
Proving:$\tan(20^{\circ})\cdot \tan(30^{\circ}) \cdot \tan(40^{\circ})=\tan(10^{\circ})$


Calculate threshold value for Poisson distributed noise

Question: I need to calculate a threshold value to get rid of Poisson distributed noise in an image to perform a cluster analysis on the image.
The image is the representation of a signal, whose datapoints were binned into container (= single pixel of the image). For every datapoint in a container, its level is increased by one. The threshold t is used to remove pixel with intensity level < threshold t.
Poisson distribution is an assumption based on previous work on the signal.
For that I have the following equation:
$$
\sum\limits_{k=0}^t \left[P(k=t) = \frac{\lambda^ke^{-\lambda}}{k!}\right] > 0.999,
$$
$\lambda$ is known. I only need to find $t$.
My naive approach was to calculate the sum for t=1, t=2,... until sum > 0.999.
However this gives me OverflowErrors in Python.
Am I on the right path or, if not, how can I find t?
Comment: Could you give us more details? What kind of noise? For what data? Why do you need to remove it? How do you know it is Poisson distributed?
Answer: I guess, your summand is just $P(k)$, not $P(k=t)$. Assuming RHS of equal sign is correct, you normally need to use the CDF of Poisson Distribution, which has a non-trivial closed form involving Incomplete Gamma Function. So, practically, what you're doing is correct. But, you should be careful when calculating factorials and exponentials involving large numbers. You can convert your calculations as:
$$\frac{e^{-\lambda}\lambda^k}{k!}=e^{-\lambda+k\log\lambda-\sum_{m=1}^k\log m}$$
And first calculate the exponent part, i.e. $-\lambda+k\log\lambda-\sum_{m=1}^k\log m$, then exponentiate for numerical stability. Therefore, you won't need to divide a very large exponential by a very large factorial number.


jQuery Mobile select menu data-native-menu="false" selected item color

Question: I want to change jQuery Mobile select menu active item color
from blue(default) to red. For some reason I can not get my code to work.
Here is my code so far in a JSFiddle
Answer: Change the css like this:

.ui-btn.ui-btn-active {
  background-color: red !important;
}

<link href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css" rel="stylesheet" />

<select id="colormenu" data-mini="true" data-native-menu="false">
  <option value="sel1">test1</option>
  <option value="sel2">test2</option>
  <option value="sel3">test3</option>
  <option value="sel4">test4</option>
</select>


How can I restrict the respositories for specified users?

Question: I´m a newbie in linux, and I configured my subversion using a lot of tutorials on the internet.
My subversion uses webdav and I add my users using the command:
htpasswd /etc/apache2/dav_svn.passwd userb

My dav_svn.conf contains follow configuration:
<Location /svn>
    DAV svn
    SVNParentPath /svn
    AuthType Basic
    AuthName "Subversion Repository"
    AuthUserFile /etc/apache2/dav_svn.passwd
    Require valid-user
<LimitExcept GET PROPFIND OPTIONS REPORT>
</LimitExcept>
</Location>

In the directory /svn I was created some repositories like /svn/test or /svn/chat.
My Question is: How can I restrict the respositories for specified users? Because all the users have permissions in all the repositories.
Answer: add the following line below AuthuserFile
AuthzSVNAccessFile /srv/svn/conf/authz

Of cource change the path to your svn root to point to the authz file.. Then it might look like
[groups]
admin = user
devteam = user,user2,user3

[/]
@devteam = r
@admin = rw

[/some_repo]
@devteam = rw
@admin = rw

Answer: Adding onto Mike's answer from before, if you want the future capability to let users edit their own SVN access through a Trac plugin or similar, you could also give each SVN project its own Authz file. All my projects' SVN settings are held in separate files, one per project. Something like:
<Location /svn/projectname>
    DAV svn
    SVNPath /usr/local/svn/projectname
    AuthzSVNAccessFile /etc/apache2/authz/projectname
    ...
</Location>

This would be a pain to manage manually, so you'd want some sort of configuration management software on the SVN server, or your own scripts to generate the separate Locations.


Only two people on a certain page at a time?

Question: I'm not really sure how I would implement this along with a fair amount of security. I want to be able to know if someone or two people are on based on a mysql row. These two people are totally anonymous. I do have an xmpp server set up but I'm not sure how that would integrate into the mysql and I already have a separate login system for it. Server side is done with PHP
Edit: I want to ONLY allow two people on a certain page and that is it. But, if they leave the page I need to determine if they have left.
Comment: what does this mean: " I want to be able to know if someone or two people are on based on a mysql row." .. Do you want to limit ONLY TWO people on your application at a time OR do you want to know who is browsing your application at any time ?  Both can be done, one involves session, other cookies
Comment: Generally speaking, XMPP should automatically trigger an unavailable presence on behalf of the user when s/he has been "away" for an extended period of time. How long it would be depend on your session expiration settings on the server. This however may not 100% fit your purpose - Since there is ALWAYS a delay for that auto-unavailable presence to be sent (Again, the delay depends on your config.) However, using XMPP "just" for this purpose seems overkill. e.g. Have page visitors join a room, if it has 2+ users, leave automatically. You'll still run into race conditions however.
Answer: The issue is that if somebody closes their browser you have no way of being notified that they have left the page.
What you could do is have an AJAX request on the page, so that every 10-15 seconds it sends a request to the server containing a session id. Log the timestamp and the session id in a table, and you can then query the database to see what requests have been made in the last 15 seconds
Comment: I do have xmpp setup so I don't have to do polling. I was wondering if there's another way without hammering the server
Answer: You could try a solution using the OnBeforeUnload event, to notify you that a user has left the page, see best way to detect when user leaves a web page.
Comment: So what happens when the browser crashes or when the connection goes down?
Comment: @user434366: you can't do that without some form of callback (eg. ajax) telling the server every x seconds that the user's still on the page - which is fine as a solution.  I've just pointed to an alternative solution which doesn't require polling, but would need some for of session timeout (to detect that the user hasn't done anything for 5 minutes, for example).
Answer: When you say "page" you are talking about browser-side-validation, because browser should be able to tell you that the user is still on that page. If you are trying to do this then you need AJAX like waitforatrain's comment. But there are some loopholes:
1) what if browser has javascript disabled?
2) what if user is inactive after loading the page? Should the page be kept "alive" ?


How to prove this tautology using only logical equivalences?

Question: I'm having trouble with this problem.

Using logical equivalencies prove that $(p \land q)\implies (p \lor q)$ is a tautology.
Comment: A tautology is a "trivial" statement in which $A \rightarrow B$ and $B \rightarrow A$.  In your case, though, the reverse need not hold:  $(p \vee q) \rightarrow (p \wedge q)$ need not hold.
Comment: It is a tautology.  However it is not clear what "logical equivalenc[es]" you intend to use.  It would be enough to note that (for example), $(p\land q) \implies p$ and in turn $p \implies (p\lor q)$.  But these are not "logical equivalences" as I understand the phrase.
Answer: According to the equivalence $(a\rightarrow b) \Longleftrightarrow \neg a\vee b$, the De Morgan's laws, the associativity and commutativity of the logical operator $\vee$, one has
\begin{align*}
(p\wedge q) \longrightarrow (p\vee q) & \Longleftrightarrow \neg(p\wedge q)\vee(p\vee q) \Longleftrightarrow (\neg p\vee \neg q)\vee(p\vee q)\\\\
& \Longleftrightarrow (\neg p\vee p)\vee(\neg q\vee q) \Longleftrightarrow t\vee t \Longleftrightarrow t
\end{align*}
where $t$ represents a tautology.
Answer: $T$
$\Leftrightarrow T \vee T$
$\Leftrightarrow (p \vee \neg p) \vee (q \vee \neg q) \Leftrightarrow T$
We drop the parentheses because the statement is well defined...
$\Leftrightarrow p \vee \neg p \vee q \vee \neg q \Leftrightarrow T$
$\Leftrightarrow \neg p \vee \neg q \vee p \vee q \Leftrightarrow T$
$\Leftrightarrow (\neg p \vee \neg q) \vee (p \vee q) \Leftrightarrow T$
$\Leftrightarrow \neg (p \wedge q) \vee (p \vee q) \Leftrightarrow T$
$\Leftrightarrow (p \wedge q) \rightarrow (p \vee q) \Leftrightarrow T$

However, I prefer a proof via natural deduction because it is cleaner...
$1.$ $p \wedge q$ ACP
$2.$ $(p \wedge q) \vee p$ by disjunction introduction $1$
$3.$ $p \vee (p \wedge q)$ by commutative rule $2$
$4.$ $(p \vee p) \wedge (p \vee q)$ by distributive rule $3$
$5.$ $p \wedge (p \vee q)$ by idempotence $4$
$6.$ $p \vee q$ by conjunction elimination $5$
$7.$ $(p \wedge q) \rightarrow (p \vee q)$ CP $1$-$6$
Answer: A tautology is a statement that is always 'True'.
In your case you have two variables, each may take the value of either 'true' or 'false'.
You may simply plug these four cases in your expression and get 'True' in each case you try. Note that your logical expression is a composition of three operations, i.e. 'and', 'or' and 'implies'. Please, check with Wikipedia for their truth tables.
https://en.wikipedia.org/wiki/Modus_ponens
Comment: uhm, i'm trying to prove that it is a tautology without using any truth tables.
Comment: Come on... all binary operators are defined as truth functions of two variables based on the truth tables. Even De Morgan's laws or whatever. See https://en.wikipedia.org/wiki/Truth_table


On certain probability distribution

Question: I am curious about if there is a simple example illustrating that there is a probability distribution $F$ such that, if $X$ follows $F$, $\mathbb{E}[X^m]<\infty$ for all $m\geq 1$, and decays slower than exponential of any order, i.e. for any $\delta>0$, $\mathbb{E}[\exp(tX^\delta)]=\infty$ holds for all $t>0$?
Comment: what is decaying?
Answer: Take density $f(x) = c e^{-\ln^2 x} = c x^{-\ln x}$ for $x > 1$, choosing the appropriate constant $c$ to make this a probability measure (turns out $c = 2\,{\frac {{{\rm e}^{-1/4}}}{\sqrt {\pi } \left( 1+{\rm erf} \left(1/2
\right) \right) }}
$ according to Maple).  Since $x^m f(x) = c x^{m-\ln x} < c x^{-2}$ for $x$ sufficiently large. $\mathbb E[X^m] < \infty$.  But for any $t, \delta > 0$,
$$ \exp(t x^\delta) f(x) = \exp(t x^\delta - \ln^2 x) > 1$$ for $x$ sufficiently large, so $\mathbb E[\exp(t X^{\delta})] = \infty$.

On certain probability distribution


How can I print a variable in the node template?

Question: How can I print a variable in the node template?
For example, if it's a variable of content, we can print it with the following code.
<code>{{ content.field_name }}
</code>
If I have a <code>{{ counter }}</code> variable, how do I display it with Twig?
Comment: Welcome to Drupal Answers! Your question is not clear: You already know to use `{{ counter }}`, so what exactly don't you understand?
Comment: Where did `counter` come from?
Answer: If it's a variable that came from a hook_preprocess_node, you can just print it in your twig template as you wrote it in your example:
<code>{{ variable_name }}
</code>


How to fix 'TypeError: __init__() missing 1 required positional argument: 'part'' error in python

Question: The console keeps telling me this, saying there is a parameter missing.
"D:\Program Files (x86)\Python\python.exe" D:/workspace/Glossary_Builder_Python/main.py
Please input the file path
C:\Users\Administrator\Desktop\Allergies.docx
Traceback (most recent call last):
  File "D:/workspace/Glossary_Builder_Python/main.py", line 102, in <module>
    main(sys.argv)
  File "D:/workspace/Glossary_Builder_Python/main.py", line 98, in main
    extractWdFrmDocx(filepath)
  File "D:/workspace/Glossary_Builder_Python/main.py", line 18, in extractWdFrmDocx
    document = Document(file)
TypeError: __init__() missing 1 required positional argument: 'part'

I am trying to extract some highlighted(in yellow) text from a docx file, using python-docx and python 3.7.
When I go into Document func, the __init__ looks like this:
def __init__(self, element, part):
    super(Document, self).__init__(element)
    self._part = part
    self.__body = None

so here, what is 'part' for?
Below is the extracting function and main function:
def extractWdFrmDocx(filepath):
    # self.filepath = filepath
    document = Document(filepath)
    for para in document.paragraphs:
        for run in para.runs:
            if run.font.highlight_color == WD_COLOR_INDEX.YELLOW:
                keyText.append(run.text)
    print(keyText)

def main(argv):
    print("Please input the file path")
    filepath = input()
    extractWdFrmDocx(filepath)

if __name__ == "__main__":
    main(sys.argv)

Comment: Well like the error says, your Document init expects an argument, `part`, that you're not supplying; you're only passing a single argument, which is taken as the `element` argument. You need to pass both.
Comment: `so here, what is 'part' for?` - Did you write that class? If not its documentation should describe it - if not you will have to look further into the class to figure out *what it is for*.
Answer: Probably you imported Document from docx.document. You are not supposed to construct such a Document object directly. Instead a function for creating Document objects is provided as docx.Document which expects one argument, the way you are using it right now.
Therefore your code should be:
import docx

[...]

document = docx.Document(filepath)

From documentation of python-docx:

Document objects
class docx.document.Document
[...]
Not intended to be constructed directly. Use docx.Document() to open or create a document.
Comment: This can happen when you have `from docx.document import Document` instead of `from docx import Document`. The former is the actual document object you work with and the latter is the "factory" function that creates that for you by loading a specified file or loading the default built-in template file. You definitely want the latter.


Create a very basic countdown in jquery

Question: I see these countdown plugins and countdown snippits for 5 seconds. But I am looking to use jquery, with out additional plugins to crate a 30 minute timer that changes the text inside of a h2 tag to count down:

30m
 ....
29m
 //and so on.

How would this be achieved? After the countdown it should do something.
Comment: See this: [JavaScript Timing Events](http://www.w3schools.com/js/js_timing.asp)
Answer: The h2 should contain the initial minutes value, like "30". The code will look like:
$(document).ready(function() {
  setInterval(function() {
    min = parseInt($('h2').text()) - 1;
    $('h2').html(min);
    if (min == 0) {
      // Do Something
    }
  }, 60000);
});

Comment: @LorDex - no, 60,000 milliseconds is 1 minute.
Comment: ah, yes, my bad, anyway he wants to run it every 5s
Comment: interval 60000 will call this function every 60mins ;) you probably want to change it to 5000
Comment: Oh, I didn't notice that he wants to run it every 5 seconds, this runs every 1 minute. Will update the answer!
Comment: Again, no haha. He wants minutes-timer he was just mentioning the 5-second timers at first!

Create a very basic countdown in jquery


How to get an id and foreign id from multiple csv files

Question: Hi I am trying to get user id column and foreign_id column from multiple csv files.  After it loops (if (userAId.equals(userBId))) it doesn't find the match of id ... I have tried the below code before and no luck.  Any good suggestions?
public List<User> getObjectFiles(List<Map<String, String>>> csvFiles) {

  List<User> user = new ArrayList<>();
  List<Map<String, String>> userARows = csvFiles.get("userARows");
  List<Map<String, String>> userBRows = csvFiles.get("userBRows");

  List<String> userAId = new ArrayList<>();
  for (Map<String, String> userARow: userARows) {
    userAId = userARow.entry.stream()
              .filter(key->key.getKey().equals("id")
              .map(Map.Entry::getValue)
              .collect(Collectors.toList());
  }

  List<String> userBId = new ArrayList<>();
  for (Map<String, String> userBRow: userBRows) {
    userBId = userBRow.entry.stream()
              .filter(key->key.getKey().equals("foreign_id")
              .map(Map.Entry::getValue)
              .collect(Collectors.toList());
  }
  if (userAId.equals(userBId)) {
  //....more code to add for List<User> user
  }

  return user;
}

Answer: Basically its not clear what you're asking here.
Reviewing the attached code:
The content of the loop, where you stream over map is strange:
You iterate over all the entries of the map instead of using a simple "get" and in addition you always rewrite the value instead of accumulating it.
Why not just:
List<String> userAId = new ArrayList<>();
for (Map<String, String> userARow: userARows) {
    String userId = userARow.get("id");
    userAIDs.add(userId);
}

This in turn could be rewritten as a stream:
List<String> userAIds = userARows
                        .stream()
                        .map(row -> row.get("id"))
                        .collect(Collectors.asList());

The code for User B looks exactly the same, actually you could even extract that into a private method to avoid the same code duplication, but its subjective:
private List<String> calculateByFieldName(List<Map<String, String>> content, String fieldName) {
 return content.stream()
               .map(row -> row.get(fieldName))
               .collect(Collectors.asList());
}

// Then your code becomes:

public List<User> getObjectFiles(List<Map<String, String>>> csvFiles) {

  List<User> user = new ArrayList<>();
  List<Map<String, String>> userARows = csvFiles.get("userARows");
  List<Map<String, String>> userBRows = csvFiles.get("userBRows");

  List<String> userAId = calculateByFieldName(userARows, "id");
  List<String> userBId = calculateByFieldName(userBRows, "foreign_id");

  if (userAId.equals(userBId)) {
  //....more code to add for List<User> user
  }

  return user;
}

Anyways, its not clear what do you mean by "the search stops" - obviously if the lists are not equals (have the same content and order of elements) the program won't enter the "if" condition and you'll get to the last line.
Comment: Thank you @Mark Bramnik, I will try your suggestion. I meant to say that when it loops it doesnt find the ones that do match with its values. Yes it doesn't enter that if statement for those that don't match.  I will make that explanation better.  I thought through this too much with maps...


fabric-sdk-java How to implement the Network.addBlockListener method in my App.java

Question: I am new to Hyperlegder-Fabric and already manage to connect to a network through the org.hyperledger.fabric.gateway package.
This is my App.java class:

//Fabric Imports
import org.hyperledger.fabric.gateway.*;
import org.hyperledger.fabric.sdk.BlockEvent;
import org.hyperledger.fabric.sdk.ChaincodeEventListener;

//Other Imports
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;

public class App{

public static void main(String[] args) throws IOException {
        // Load an existing wallet holding identities used to access the network.
        Path walletDirectory = Paths.get("wallet");
        Wallet wallet = Wallets.newFileSystemWallet(walletDirectory);

        // Path to a common connection profile describing the network.
        Path networkConfigFile = Paths.get("connection.json");

        // Configure the gateway connection used to access the network.
        Gateway.Builder builder = Gateway.createBuilder()
                .identity(wallet, "user1")
                .networkConfig(networkConfigFile);

        // Create a gateway connection
        try (Gateway gateway = builder.connect()) {

            // Obtain a smart contract deployed on the network.
            Network network = gateway.getNetwork("mychannel");
            Contract contract = network.getContract("fabcar");

            // Submit transactions that store state to the ledger.
            byte[] createCarResult = contract.createTransaction("createCar")
                    .submit("CAR10", "VW", "Polo", "Grey", "Mary");
            System.out.println(new String(createCarResult, StandardCharsets.UTF_8));

            // Evaluate transactions that query state from the ledger.
            byte[] queryAllCarsResult = contract.evaluateTransaction("queryAllCars");
            System.out.println(new String(queryAllCarsResult, StandardCharsets.UTF_8));

        } catch (ContractException | TimeoutException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Now I need to listen for block events, so I see in the documentation that the Network package contains the addBlockListener method (https://hyperledger.github.io/fabric-gateway-java/release-2.2/org/hyperledger/fabric/gateway/Network.html)
My doubt is how i can implement this method in the above App.java file so i can get the block number, etc. I am not a java developer i am struggling a lot on this since.
Appreciate any help.
Answer: The listener you attach is an implementation of the Consumer<BlockEvent> type, where Consumer is a standard Java functional interface:
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/function/Consumer.html
To define your listener you could:

write your own listener class that implements that interface; or
define an anonymous class in-line that implements that interface; or
use a lambda expression as a short-hand for the anonymous class implementation to minimise boiler-plate code.

Using a lambda expression, your code might look like this:
network.addBlockListener(blockEvent -> {
    long blockNumber = blockEvent.getBlockNumber();
    System.out.println("Received block number " + blockNumber);
});

If you add the listener to the network before submitting your transaction, you should see the block event created when your submitted transaction is recorded on the ledger.
Comment: Thanks, that helped! I was reviewing functional interfaces and now i have a better idea of how they work. Althought i still have doubts about how to implement option 1 (write your own class that implements the interface). I edited my question to show you the problem
Comment: If you want to have one of your own classes act directly as a block event listener, you would need to declare that it implements the required interface, for example: `class MyListener implements Consumer { ... }`. In order to successfully implement this interface, it would have to include a method with the signature `public void accept(BlockEvent event)`. You could then pass an instance of MyListener as the argument to `addBlockListener()`.


Game series probability

Question: I have a few exam review questions that I don't know how to solve. Maybe someone can help me out.
Two hockey teams play a best-of-seven series (play until a team wins a total of 4 games)

Assume team A has a probability of 3/4 of beating team B.
Assume the results of the games are independent
What is the probability that all seven games will be played in the series
Answer: The series lasts $7$ games precisely if the first $6$ games are evenly split between the two teams. So we want the probability that Team A wins $3$ of the first $6$ games and loses $3$. The probability of that is
$$\binom{6}{3}\left(\frac{3}{4}\right)^3\left(\frac{1}{4}\right)^3.$$

Game series probability


Qual o tamanho máximo de um objeto em 32 e 64 bits?

Question: Especificamente o array pode ter até 4 bilhões de elementos, eu acho, e os tamanhos mais comuns de tamanho dos elementos deve ser 4, 8 ou 16 bytes.
Pergunto, qual o tamanho máximo que o objeto pode ocupar na memória? Seria 4 GB em 32 bits? É ilimitado em 64 bits?
Answer: Se por objeto você quer dizer um array, System.Array utiliza um Int32 como índice - então seu limite é definido por System.Int32.MaxValue ( 2.147.483.647, ou 0x7FFFFFFF em hexadecimal.)
O limite pré-.Net 4.5 era de 1.2GiB. Era possível forçar o limite para 2.4GiB. Hoje em dia o tamanho máximo de endereçamento é 24TiB, porém apenas em ambientes 64-bit, com a seguinte definição no arquivo .config:
<configuration>
  <runtime>
    <gcAllowVeryLargeObjects enabled="true" />
  </runtime>
</configuration>

Fontes: 1, 2.
Comment: @HarlanGomesNascimento Exato, e tem ainda o fato de que, mesmo o construtor permitindo a inicialização de um `array` com um `long`, o objeto final ainda não suporta um index do tipo `long`.
Comment: Com a opção `gcAllowVeryLargeObjects ` o índice pode usar `System.UInt32.MaxValue`, portanto pode ir além dos 2 bilhões de elementos.
Comment: Se for apenas o tamanho do array tem essa "limitação" de itens que ele possui, bem observado.
Comment: Dessa eu não sabia. Obrigado pela dica @bigown!
Answer: Depende muito da versão do .NET Framework que você for usar, versões anterior a 4.5 tinha um limite de 2 GB que poderia ser um problema para a cache em sistemas "grandes";
Com o a versão 4.5 foi introduzido a funcionalidade "gcAllowVeryLargeObjects" que permite em sistemas 64 bits usar maiores quantidades de RAM;
Acredito que o programa vai ficar limitado a quantidade de RAM que a versão do Windows consegue usar:
https://msdn.microsoft.com/pt-br/library/windows/desktop/aa366778(v=vs.85).aspx


Accessing 2D Array elements in MongoDB

Question: {
   "Name1" : "Value1",
   "Name2" : "Value2",
   "Name3" : [{
          "Elem1" : "String"
    }]
}

I want
"Elem1" : "String"
(OR)
"String"
as an output. Tried several aggregate and find functions in Mongo Shell.
Comment: please provide what all you have tried. no spoon feeding here
Answer: db.collection.find({"Name3":{$elemMatch:{"Elem1":"specificValue"}}},{"Name3.$":1})

Try this query, $ operator return the first matching document of array

Accessing 2D Array elements in MongoDB


How do you Calculate Multiple Pages to a Grand Total in LiveCycle?

Question: I am not a programmer but I have to create an expense form for traveling.  It has to be in PDF format (preferably Adobe Acrobat editable).  I created the form with Excel and exported it to Adobe but, of course, the formulas do not transfer.
I have 3 pages that are identical for calculating travel expenses with the only difference being there is one extra cell on the first page that calculates totals from each page to a grand total.  Sounds easy.  All the pages calculate individually with no problem but I cannot reference the totals from the individual pages to the first page where the grand total is.
I am using Adobe LiveCycle because it "simplifies" the programming process for people like me.  It has worked great so far but this is the only thing problem I am having and the only thing holding me from using the form.
All three pages are in the same document.  When I use FormCalc for the totals within each page, it works great:
topmostSubform.Page1.P1TotalGrand::calculate - (FormCalc, client)
$=P1MileageTotal+P1TransAirTotal+P1CarRenTotal+P1HotelTotal+P1AllowTotal+P1PhoneTotal+P1MIETotal+P1BusMealTotal+P1OtherTotal
If I go to the next page, it looks like this:
topmostSubform.Page2.P1TotalGrand::calculate - (FormCalc, client)
$=P1MileageTotal+P1TransAirTotal+P1CarRenTotal+P1HotelTotal+P1AllowTotal+P1PhoneTotal+P1MIETotal+P1BusMealTotal+P1OtherTotal
I just want to be able to add them together.  When I try, it doesn't recognize the 2nd page and I don't know why.  The form is pretty basic and I would really appreciate any help.  If you need any additional information, I'll be glad to oblige.
Answer: I believe you can do it. There should be many ways and I am a newbie too so here are two ways...

If you want grand total of 2 pages - does not matter on which page you want it, the formula should be like
topmostSubform.Page1.P1GREATTotalGrand::calculate - (FormCalc, client)
$=P1TotalGrand+P2TotalGrand

The trick is to select both by press and hold Ctrl Key, then select the field you want to select rather then type in. this should solve the problem.
If you want the total to be at page one.
Make the P2GreatTotalGrand to be a global data  and create the same data field on page one  and add this new one and one already on page one to get the grand total on page one.


smtpd_tls_auth_only exclude 127.0.0.1

Question: I configurated postfix to force uses TLS. When an external client try to send an email using this server there is not any problems. But using webmail (127.0.0.1) postfix wants TLS:
delivery temporarily suspended: TLS is required, but was not offered by host 127.0.0.1[127.0.0.1])

Which changes I need to do to master.cf?
smtp_use_tls = yes
smtp_tls_security_level = encrypt
smtpd_use_tls = yes
smtpd_tls_auth_only = yes
smtpd_tls_key_file = /etc/postfix/ssl/xxx.key
smtpd_tls_cert_file = /etc/postfix/ssl/xxx.crt
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom
smtpd_tls_session_cache_database = btree:${queue_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${queue_directory}/smtp_scache

Answer: You could:

smtp_tls_security_level = may
This will allow your server to deliver mail to hosts that don't offer TLS or hosts with bad certificates (as it would otherwise retry unencrypted).
smtpd_tls_security_level = may
This will cause your server to offer TLS encryption to clients on any listening port.
smtpd_tls_security_level = encrypt
This will cause your server to require TLS encryption from all client on any listening port.

For internet hosts it's common to do both 1 and 2, but you know your requirements better than I do.
Answer: I doubt you can do that without running a second instance of postfix with smtpd_tls_auth_only set to no and then change the webmail software to send mail to that instance instead.
You might consider reconfiguring the webmail to use TLS instead if possible or to deliver mail directly locally instead of using a TCP connection.
Comment: thanks... mhmhm... can I've an example please?
Answer: stunnel will fix this. It creates an SSL(TLS) connection to postfix:
http://www.stunnel.org/examples/
Comment: Welcome to Server Fault! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.

smtpd_tls_auth_only exclude 127.0.0.1


Does PostREST have a null-safe not-equal operator, like IS DISTINCT FROM?

Question: I'm making some simple PostgREST queries on a table with network device properties. It seems that eq and not.eq both exclude null values. I've learned that that's a "feature" of PostgreSQL, and can be worked around with the IS DISTINCT FROM operator, which treats null as a comparable value.
I can't find an equivalent (null-safe not-equals) operator in PostgREST. Is there one?
Simplified example:
# https://example.com/api?select=*&name=like.spam-*
[{
  "name":"spam-eggs",
  "type":"router",
  "sector":"cheese"
},{
  "name":"spam-ham",
  "type":"router",
  "sector":null
}]

not.eq.cheese excludes cheese and null:
# https://example.com/api?select=*&name=like.spam-*&sector=not.eq.cheese
[]

My awkward workaround is using or to include nulls:
# https://example.com/api?select=*&name=like.spam-*&or=(sector.not.eq.cheese,sector.is.null)
[{
  "name":"spam-ham",
  "type":"router",
  "sector":null
}]

Am I stuck with that workaround, or is there an operator like isdistinctfrom, neq-or-null, etc. that I've missed?
Comment: @Belayer The question is about [PostgREST operators](https://postgrest.org/en/stable/api.html#operators), OP already knows about `IS NOT DISTINCT FROM`.
Comment: Correct. PostgREST not.eq PostgreSQL. ;) I have tried, out of desperation, things like `.distinct.`, `.is.distinct.`, `.isdistinctfrom.` and gotten errors.
Answer: Current answer
Since PostgREST version 11.0.0, the isdictinct operator is translated to IS DISTINCT FROM in PostgreSQL. Using your example, the new query would be:
https://example.com/api?select=*&name=like.spam-*&sector=isdistinct.cheese

Original answer (Oct 2022)
I've checked the code and there's no implementation of IS DISTINCT FROM right now. That is, no PostgREST operator translates to it. The only reference I found is in a comment in this file, but it's for a different issue.
So, yes, right now, your workaround would be the closest you can get to the behavior you want. Creating a FUNCTION with a custom query using IS DISTINCT FROM is another alternative, although it requires more heavy lifting.
Comment: Just created [a new issue](https://github.com/PostgREST/postgrest/issues/2501) referencing this question in the github repo.
Comment: it worked! `isdistinct` added in [#2739](https://github.com/PostgREST/postgrest/pull/2739) and released in either v10.2.0 or v11.0.0 (unclear to me). Thank you! Want to update your answer or should I add a new one?
Comment: @Jacktose Yes, to confirm, it was included in [v11.0.0](https://github.com/PostgREST/postgrest/releases/tag/v11.0.0).


Is $(p-1)!+p$ a prime for every prime $p$?

Question: Is $(p-1)!+p$ a prime for every prime $p$?
It looks unlikely but I cannot get an example that will do.
Also by trying to prove it by assuming a prime factor greater than $p$ and less than $(p-1)!+p$, I am not getting anything.
Some more techniques of proof that may help or even a direct answer is appreciated.
Comment: @fleablood Yes, that is a prime generator :) Anything you can write in a list comprehension (and more) can be said to be a prime number generator. In Maths, you don't care how a function generates its output. Its a black box. If that black box is the Sieve Of Eratosthenes and F(5) is just the 5th prime the sieve spits out, it is a prime generator function. You don't care that it doesn't efficiently compute it because it is a line on a piece of paper and not a computer churning out madly.
Comment: So far as I know there is no known prime number generator.  Not being able to come up with a counter example isn't a good reason to think something is true.
Comment: @fleablood There are many prime number generators, starting with Euclid's algorithm.  What you probably mean is there are no *efficient* prime number generators.
Comment: Probably I do mean that.  How is Euclid's algorithm a prime number generator?  I suppose the simplest way to find primes would be to simply go through every number and check whether it is prime or not but that can't be said to "generate" primes can it?
Comment: @Coolwater for every prime $p$
Answer: You just didn't go far enough.  While $(p-1)! + p$ is prime for $p = 2, 3, 5, 7, $ and $11$, it is composite for $p = 13, 17, 19, 23, 29, 31, 37, 41, 43,$ and $47$.  $p = 53$ is the next prime for which it is true.
Comment: In fact, this accounts for *all* of the primes of this form for $p < 1250$. See http://oeis.org/A100858
Answer: $$12!+13=29\cdot 2503\cdot 6599$$


Cálculo com virgula em Javascript

Question: Estou refazendo um sistema de Aferição Agrícola e estou encontrando uma dificuldade para realizar alguns cálculos, inicialmente preparei os input´s para receberem somente números, em seguida formatei os mesmos para receberem uma vírgula e uma casa decimal ao receberem valores, até ai tudo funciona.
Ao tentar realizar um soma e depois a média uma das minhas função está acusando erro.
Vou tentar não complicar postando o código comentado.
Esse é o meu formulário:

      <input type="text" name="deterVal1" id="deterVal1" value="" class="form-control" onKeyPress="SomenteNumeros(this)" onKeyUp="FormataValor(this,5,event)">

      <input type="text" name="deterVal2" id="deterVal2" value="" class="form-control" onKeyPress="SomenteNumeros(this)" onKeyUp="FormataValor(this,5,event)">

      <input type="text" name="deterVal3" id="deterVal3" value="" class="form-control" onKeyPress="SomenteNumeros(this)" onKeyUp="FormataValor(this,5,event)">

      <input type="text" name="deterVal4" id="deterVal4" value="" class="form-control" onKeyPress="SomenteNumeros(this)" onKeyUp="FormataValor(this,5,event)">

      <input type="text" name="deterVal5" id="deterVal5" value="" class="form-control" onKeyPress="SomenteNumeros(this)" onKeyUp="FormataValor(this,5,event)">

      <input type="text" name="MediaFinal" id="MediaFinal" value="" class="form-control " onfocus="calMediaAfericao(this)" onKeyPress="SomenteNumeros(this)" onKeyUp="FormataValor(this,5,event)">

Função para permitir somente números:

function SomenteNumeros(input) {
 if ((event.keyCode < 48) || (event.keyCode > 57))
  event.returnValue = false;
}

Inserir a vírgula e uma casa decimal

function FormataValor(campo, tammax, teclapres) {

 var tecla = teclapres.keyCode;
 var vr = campo.value;
 vr = vr.replace("/", "");
 vr = vr.replace("/", "");
 vr = vr.replace(",", "");
 vr = vr.replace(".", "");
 vr = vr.replace(".", "");
 vr = vr.replace(".", "");
 vr = vr.replace(".", "");
 tam = vr.length;

 if (tam < tammax && tecla != 8) {
  tam = vr.length + 1;
 }

 if (tecla == 8) {
  tam = tam - 1;
 }

 if (tecla == 8 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105)) {
  if (tam <= 1) {
   campo.value = vr;
  }
  tam = tam - 1;
  if ((tam > 1) && (tam <= 5)) {
   campo.value = vr.substr(0, tam - 1) + ',' + vr.substr(tam - 1, tam);
  }

  if ((tam > 5) && (tam <= 8)) {
   campo.value = vr.substr(0, tam - 1) + ',' + vr.substr(tam - 1, tam);
  }
 }
}

Antes de fazer a soma e calcular a média chamo uma função que substitui a vírgula por ponto, essa função está acusando uma falha, o que tento fazer é isso:

function calMediaAfericao() {

 var vlrDet1 = parseInt(document.getElementById('deterVal1').value, 10);
 var vlrDet2 = parseInt(document.getElementById('deterVal2').value, 10);
 var vlrDet3 = parseInt(document.getElementById('deterVal3').value, 10);
 var vlrDet4 = parseInt(document.getElementById('deterVal4').value, 10);
 var vlrDet5 = parseInt(document.getElementById('deterVal5').value, 10);

 vlrDet1 = Number(substituiVirgula(vlrDet1));
 vlrDet2 = Number(substituiVirgula(vlrDet1));
 vlrDet3 = Number(substituiVirgula(vlrDet1));
 vlrDet4 = Number(substituiVirgula(vlrDet1));
 vlrDet5 = Number(substituiVirgula(vlrDet1));

 document.getElementById('MediaFinal').value = (vlrDet1 + vlrDet2 + vlrDet3 + vlrDet4 + vlrDet5) / 5;

}

A função substituiVirgula e a que está acusando erro, como pode ser visto aqui:

VM11866:284 Uncaught TypeError: valor.indexOf is not a function
    at substituiVirgula (eval at globalEval (jquery.min.js:2), <anonymous>:284:13)
    at calMediaAfericao (eval at globalEval (jquery.min.js:2), <anonymous>:338:20)
    at HTMLInputElement.onfocus (VM11873 iAfericaoAgricola-novo.php:1)

A função é essa:

 function substituiVirgula(valor){
  if (valor.indexOf(",") >= 0) {
   var novoValor = valor.replace(",",".");
   return novoValor;
  } else {
   return valor;
  }
 }
Comment: Talvez você queira usar uma biblioteca para formatação de números, como o [Inputmask](https://github.com/RobinHerbots/Inputmask) - isso evitaria muita dor de cabeça. Além disso A sua função de formatação tem repetições e o código para permitir somente números é facilmente burlável.
Comment: O problema é que tem algum valor que não é uma `String`. Antes da linha `if (valor.indexOf(",") >= 0) {` coloque um `valor = valor.toString();`
Comment: @adventistapr, uma dica, inserir vários trechos de código executável não ajuda a simular nada da sua dúvida, pois os trechos são executados isoladamente. Na próxima vez coloque tudo em apenas um trecho de código, como fiz na minha resposta abaixo.
Comment: Se possível aproveita a dica do @Renan e tente utilizar o Inputmask, já que eu vi que você utiliza jQuery, vai facilitar e aperfeiçoar bastante a validação dos campos.
Comment: Olá @Marco, foi na preocupação de não faltar argumentos para o bom entendimento, mas agradeço a dica.
Comment: @adventistapr Sim, eu até entendi isso, justamente por isso não editei sua pergunta, mas não é possível executar sem que nós coloquemos em local único.
Comment: Agradeço @Marco, já estou alterando nesse momento, valeu.
Answer: Foi um conjunto de pequenos erros, mas o principal é que a função calMediaAfericao() que era chamado no onfocus do último campo é quem acabava retornando o erro valor.indexOf is not a function pois você convertia os valores utilizando parseInt (que deveria ser parseFloat já que é um valor decimal) e passava pra função substituiVirgula um valor de tipo numérico, onde não existe o método indexOf.
Tenho algumas ressalvas quanto a maneira que você escolheu para chamar o método de cálculo, pois creio que um botão para isso fosse mais interessante funcionalmente, porém alterando apenas para ficar funcional para o seu objetivo, ficaria assim:

function SomenteNumeros(input) {
  if ((event.keyCode < 48) || (event.keyCode > 57))
    event.returnValue = false;
}

function FormataValor(campo, tammax, teclapres) {
  var tecla = teclapres.keyCode;
  var vr = campo.value;
  vr = vr.replace("/", "");
  vr = vr.replace("/", "");
  vr = vr.replace(",", "");
  vr = vr.replace(".", "");
  vr = vr.replace(".", "");
  vr = vr.replace(".", "");
  vr = vr.replace(".", "");
  tam = vr.length;

  if (tam < tammax && tecla != 8) {
    tam = vr.length + 1;
  }

  if (tecla == 8) {
    tam = tam - 1;
  }

  if (tecla == 8 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105)) {
    if (tam <= 1) {
      campo.value = vr;
    }
    tam = tam - 1;
    if ((tam > 1) && (tam <= 5)) {
      campo.value = vr.substr(0, tam - 1) + ',' + vr.substr(tam - 1, tam);
    }

    if ((tam > 5) && (tam <= 8)) {
      campo.value = vr.substr(0, tam - 1) + ',' + vr.substr(tam - 1, tam);
    }
  }
}

function calMediaAfericao(campo) {
  var vlrDet1 = parseFloat(substituiVirgula(document.getElementById('deterVal1').value), 10);
  var vlrDet2 = parseFloat(substituiVirgula(document.getElementById('deterVal2').value), 10);
  var vlrDet3 = parseFloat(substituiVirgula(document.getElementById('deterVal3').value), 10);
  var vlrDet4 = parseFloat(substituiVirgula(document.getElementById('deterVal4').value), 10);
  var vlrDet5 = parseFloat(substituiVirgula(document.getElementById('deterVal5').value), 10);

  campo.value = (vlrDet1 + vlrDet2 + vlrDet3 + vlrDet4 + vlrDet5) / 5;
}

function substituiVirgula(valor) {
  if (valor.indexOf(",") >= 0) {
    var novoValor = valor.replace(",", ".");
    return novoValor;
  } else {
    return valor;
  }
}

      <input type="text" name="deterVal1" id="deterVal1" value="" class="form-control" onKeyPress="SomenteNumeros(this)" onkeyup="FormataValor(this,5,event)">

      <input type="text" name="deterVal2" id="deterVal2" value="" class="form-control" onKeyPress="SomenteNumeros(this)" onkeyup="FormataValor(this,5,event)">

      <input type="text" name="deterVal3" id="deterVal3" value="" class="form-control" onKeyPress="SomenteNumeros(this)" onkeyup="FormataValor(this,5,event)">

      <input type="text" name="deterVal4" id="deterVal4" value="" class="form-control" onKeyPress="SomenteNumeros(this)" onkeyup="FormataValor(this,5,event)">

      <input type="text" name="deterVal5" id="deterVal5" value="" class="form-control" onKeyPress="SomenteNumeros(this)" onkeyup="FormataValor(this,5,event)">

      <input type="text" name="MediaFinal" id="MediaFinal" value="" class="form-control " onfocus="calMediaAfericao(this)" readonly />

Cálculo com virgula em Javascript


Get & Set Time from Date Object

Question: I am working on a pomodoro clock in Javascript.
I am a bit confused by the Date Obj. As per the below code, the idea is that the 'Session Timer' & 'Break Timer' values will be stored in a global obj so they can be retrieved &/ or updated. However, the following is confusing me:
// The following stores the current time
// which makes sense.
const meter = {
    break : new Date(),
    session : new Date()
};
// However, when I set the minutes on the Date obj
// the above break & session props are no longer
// a Date obj, instead they are number.
// So, I cant use the 'getMinutes()'
const meter = {
    break : new Date().setMinutes( 5 ), // is a number, not Date anymore!
    session : new Date().setMinutes( 10 ) // is a number, not Date anymore!
};

I could pass the break / session numbers through new Date() method to create a new date but I wonder how would I create the timer (mainly in format [hr]:[min]:[sec]). Would I have to do something as follows every second before I update the code:
let number = 1470650701308; // time in milliseconds as returned by methods (getMinutes(), getHours(), getSeconds())
let hours = 1470650701308 / ( 1000 * 60 * 60 ); // ms * sec * min
let minutes = 1470650701308 / ( 1000 * 60 ); // ms * sec
let seconds = 1470650701308 / ( 1000 ); // ms

So my question is how to go about getting the time in hours / minutes & seconds so I can update my clock every second?
Thanks
Answer: The setminutes method modifies the object and returns an int.
try this instead:
const meter = {
    break : new Date(),
    session : new Date()
};

meter.break.setMinutes(5);
meter.session.setMinutes(10);

Comment: I guess you could use `${meter.break.getHours()}:${meter.break.getMinutes()}:${meter.break.getSeconds()}`? Why do you say in your example that these methods return time in milliseconds? Only the setters do that
Comment: thanks, am aware of this (as per the code above), however, Im confused about how to output the hours / minutes / seconds for the timer on display
Comment: Ah, good catch! That solved it! Thank you, in my exploration of the values, I must have taken a wrong turn & somehow got the assumption that the return value from `get***()` methods is ms. Would you please fix & organise the answer so I can accept it for future reference.

Get & Set Time from Date Object