PHP send mail HELP

Question: I am using this function to send an email, but this does nto work..
What's wrong?? =(
<?php

$SMTP = "mailer2.mondoweb.it";
$TO = "firstname.lastname@example.com";

function InviaMail($subject, $body, $hdrs) {
    global $SMTP, $TO;
    ini_set("SMTP", $SMTP);
    mail($TO, $subject, $body, $hdrs);
}

$subject =  "Clevery. Richiesta informazioni su: ". $_POST['offerta'] .".";

    $body = "Clevery. Richiesta informazioni su: ". $_POST['offerta'] ."

" .
            "Nome cliente: " . $_POST['nome'] . "
" .
                        "Email: " . $_POST['email'] . "
" .
            "Referente: " . $_POST['referente'] . "
" .
            "Città: " . $_POST['citta'] . "
" .
            "Provincia: " . $_POST['provincia'] . "
" .
            "Telefono: " . $_POST['telefono'] . "
" .
            "Note: " . $_POST['commento'] . "
";

    $hdrs = "Content-Type: text/html; charset=iso-8859-1\n" . "From: " .
            "\"clevery.it\" <email@example.com>";
InviaMail($subject, $body, $hdrs);
?>

Comment: your server have sendmail or something equivalent to send email ? :)
Comment: What are the error messages or at least the symptoms!
Comment: Absolutely nothing. No errors, nothing. The email is not sent out. This is driving me crazy!
Comment: What does your `mail()` call return: true or false?
Comment: The mail function does not know if the mail made it off your server, only that PHP handed the mail to the local mail server to send. If `mail()` returns true, you should check your mail log to find out what happened after that.
Comment: How do I check if it returns true or false?
Comment: @DiegoP Eep, scary question, how did you write this code without knowing how functions work? `$returnvalue = mail($TO, $subject, $body, $hdrs; echo "Return value was: $returnvalue";`
Comment: It just returns empty. I do not see any true or false
Answer:     <?php
    function InviaMail($subject, $body, $hdrs) {
        global $SMTP, $TO;
        ini_set("SMTP", $SMTP);
        if(mail($TO, $subject, $body, $hdrs)===true){
            return true;
        }else{
            return false;
        }
    }

   echo (InviaMail($subject, $body, $hdrs)===true)?'Mail was sent.':'Error Sending mail.'
    ?>

Answer: SMTP used Port 25 to send mails which is blocked by most of the ISP's to check if it is the problem with your code or your ISP try doing this.
echo mail($to, $subject, $body, $hdrs) ? 'Mail Sent Successfully' : 'There was an error sending mail';

Try the above code.

PHP send mail HELP


Remove the special characters (like %20) from URL

Question: Is it possible to replace the URL encoded characters for space,?,etc. with the exact character ? Because one of the content in my site takes the following URL and it doesn't looks so nice!

https://expatchoice.asia/eat-drink/restaurants-casual/ana-intercontinental-tokyo%E3%80%80ana%E3%82%A4%E3%83%B3%E3%82%BF%E3%83%BC%E3%82%B3%E3%83%B3%E3%83%81%E3%83%8D%E3%83%B3%E3%82%BF%E3%83%AB%E3%83%9B%E3%83%86%E3%83%AB%E6%9D%B1%E4%BA%AC
Answer: Please take a look at transliteration module. Together with pathauto you could get better urls. But i don't know how well this works with chinese characters.
Comment: Is this only for the file names and not the node titles?
Comment: It's for URLs. But you can get it to work with pathauto. So it depends on how you create the aliases for your nodes.


Logging into multiple Linux servers using ssh

Question: I have a local windows machine, where I connect to a local linux box through putty, and I will have to login to multiple linux servers using ssh, through sudo.
I was wondering if there was a windows .bat script, that would help me in getting this done.
I normally login to server as follows:
#ssh firstname.lastname@example.com -v -p2345
#sudo su -

And I was not able to find any links from ServerFault, to get this automated. Not sure if had overlooked or missed some .. :-)
Please let me know if there is anybody who would have done this , and if so how (would appreciate if someone could provide me with the .bat script).
Cheers
Answer: If there's something you need to do on every system you log into, you could configure and distribute a .bashrc that would automate your login tasks.
That said, don't automate sudo-ing to root. You're applying godlike powers to yourself; you should at least be typing a password to remind you to be careful. It's a best practice, and in our shop a policy, that you never sudo su to root; everything you need to do should be handled through individual sudo commands. That way you only access privilege when you need it; and all your privileged actions are logged, courtesy of sudo, improving security and occasionally answering the question "What the hell happened on this system?"
Comment: As stated above, I will have only the following info, because this is NOT my server.Hostname, IP address, username and password. I do have a .bat script that opens my putty connecting to my local linux box, as follows : "start C:putty -ssh email@example.com 22 -pw xxxpassxxx". So , basically I would like to have some thing like the above mentioned .bat script created in on my Windows PC.
Comment: Well, at the risk of sounding trite, you could just make a batch file which contains a line like you've described for each system you want to log into. You won't be able to script the sudo command, though; once you're into an interactive shell, you can't pass additional commands.
Answer: Do you want to run the same groups of operations repetitively?  You might want to check out Fabric, which is a cool Python library to go the extra distance and iteratively run crap on computers after SSH'ing into them.  Otherwise, if you just want to pull up a ton of prompts with ssh logins, I would suggest the following.

Setup SSH keys (I assume this is accessible to you).  This is the easiest tutorial I know that explains this with PuTTY.
Set up a batch file like so.  You can use the PuTTY and cut out the middle man if you are cool with that. (WARNING: this is just a rough guess; I do not have a Windows computer in front of me, but have done things like this in the past.)
SET PAGEANT=C:\path\to\pageant.exe
SET PUTTY=C:\path\to\putty.exe
SET PUTTYPRIVKEY=C:\path\to\priv\key.ppk
SET USER=someuser
SET RPORT=2345
SET HOSTS=126.96.36.199 188.8.131.52 22.214.171.124 host1.example.com host2.example.com
REM # Activate the private key, this assumes you password-protected it wisely.
"%PAGEANT%" "%PUTTYPRIVKEY%"
FOR %%H in (%HOSTS%) do (
ECHO.
ECHO Attempting to SSH to host %%H . . .
ECHO.
START "%PUTTY%" -ssh %%H:%RPORT% -2 -l %USER% -i "%PUTTYPRIVKEY%"
)

Also a possibility is the -m parameter of PuTTY, which according to the docs, runs a script against the remote host once authenticated.  With the right keys and agent forwarding (-a or -A; ask if you don't know), this might get you down to a button click or too.
Comment: As stated above, I will have only the following info, because this is NOT my server.Hostname, IP address, username and password. I do have a .bat script that opens my putty connecting to my local linux box, as follows : "start C:putty -ssh firstname.lastname@example.com 22 -pw xxxpassxxx". So , basically I would like to have some thing like the above mentioned .bat script created in on my Windows PC.
Comment: Sorry, my bad. Was kind of loopy apparently; I try to re-read the question after finishing my answer. Apparently, not all the time. So, have you copied the script? Put it into a file, then change the variables with the paths to putty (or do you use a different `ssh` binary? I am confused.)
Answer: This isn't exactly what you're asking for, but gnu screen is incredibly useful for managing multiple servers: http://www.gnu.org/software/screen/
To start or reattach to a screen session when you ssh somewhere you can do this:
ssh user@host screen -RD

Or run "screen -RD" after you connect. Do whatever you need to do, then instead of logging out you "detach" (Ctr-a d) from the screen session, or just close the terminal window. Next time you ssh in with screen, you'll be right back where you left off.
Some more info on screen, which admittedly can be a little confusing to get started with:

http://aperiodic.net/screen/start


How to get the MaxLength from a Fluent API mapping specification in runtime?

Question: I need to retrieve the maxlength value specified for a field using Fluent API and Entity Framework 5 Code First.
I have seen a couple of examples using MetadataWorkspace but it doesn't work when you use Fluent API.
For instance, I tried this code but the value for MaxLenght is always null:
ObjectContext.MetadataWorkspace.GetItem<GlobalItem>(typeof(TEntity).FullName, DataSpace.OSpace).MetadataProperties[field].TypeUsage.Facets["MaxLength"].Value

Inside the Fluent API configuration file I have the following code for the necessary properties:
Property(t => t.Name).HasMaxLength(50);

I know the mapping is working because if I try to save the object with more than 50 characters in that field it fails.
I just need guidance for getting the maxlenght value but to give some perspective the goal is:

Create new Foo object
Get the maxlength value defined for Bar property using Fluent API.
Apply certain rules based on the maxlength to the string to be assigned to Bar.
Save.

Thanks in advance.
Comment: You want us to write it for you???
Comment: That wont be necessary, I just need guidance on what library can I use to get the maxlength value, the code is already done except for that part. I just edited the question to make it clear. Thanks.
Comment: `but it doesn't work when you use Fluent API.`  what doesnt work ?
Comment: @philsoady, I edited the question to clarify it. Thanks.
Comment: are you sure the facet was declared ? Show matching api config
Comment: http://stackoverflow.com/a/9580743/1347784
Comment: @philsoady, I updated the question. From what i see in other posts that works ok if you use annotations but not fluent api to specify the maxlength validation.
Answer: You should use the storage model. Check docu on the Enum DataSpace
Use The EntityType items.
  [TestMethod]
    public void EFToolsTest() {

        var context = new BosMasterDbContext("MYDBCONTEXT");
        ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
        MetadataWorkspace workspace = objContext.MetadataWorkspace;

        var xyz = workspace.GetItems<EntityType>(DataSpace.SSpace);
        foreach (var ET in xyz) {
            foreach (var sp in ET.Properties) {
                Debug.WriteLine(sp.Name + ":" + sp.MaxLength);

                }
            }
        }

Comment: I may have a different version (using EF 5.0) but I have to use (sp.TypeUsage.Facets.Contains("MaxLength") ? sp.TypeUsage.Facets["MaxLength"].Value : string.Empty) to get the MaxLength. The compiler won't accept "sp.MaxLength".
Comment: This answer has is problematic with the future of entity framework dropping the object context.


Calculating time difference by groups

Question: I have a question about calculating the time difference for different sources and targets.
Table1:

Source      Target     Time                   TimeDif(wrong) (right)
188.8.131.52     220.127.116.11    2012-01-03 21:50:40    3               3
18.104.22.168     18.104.22.168    2014-01-03 21:50:43    5               5
18.104.22.168     220.127.116.11    2014-01-03 21:50:48    3               NULL
22.214.171.124     220.127.116.11    2014-01-03 21:50:51    3               4
184.108.40.206     184.108.40.206    2014-01-03 21:50:55    4               4
188.8.131.52     220.127.116.11    2014-01-03 21:50:59    4               NULL
....        ....       ......

Right now I calculate the time difference with:
diffTime <- difftime(time[1:(length(time)-1)] , time[2:length(time)]) * -1

The problem is that the time difference by calculating this method are not correct. That means the method calculate the whole column and does not make any decision between different sources and targets. I'm not sure if this problem can be fixed by the package (sqldf) to query and to group the data together. The query should also implement the method, but I think that is not possible. So would be nice if you have any solutions.
Comment: Can you first tell us what you are trying to compute here?
Comment: Here's the problem: Assuming you are trying to compute the lead for each target/source group, MySQL does not support analytic functions.  So you might do better with a different approach.
Comment: I try to compute the time difference of the access from source to target. So it is not possible with MySQL :-/
Answer: Supposing you want to do stuff in R, you need a grouping function. With for example group_by from dplyr you can do that:
library(dplyr)
dat %>%
  group_by(Source, Target) %>%
  mutate(tdif = lead(Time) - Time)

the result:
   Source  Target                Time          tdif
   <fctr>  <fctr>              <dttm>        <time>
1 220.127.116.11 184.108.40.206 2012-01-03 21:50:40 63158403 secs
2 18.104.22.168 22.214.171.124 2014-01-03 21:50:43        5 secs
3 126.96.36.199 188.8.131.52 2014-01-03 21:50:48       NA secs
4 126.96.36.199 22.214.171.124 2014-01-03 21:50:51        4 secs
5 22.214.171.124 220.127.116.11 2014-01-03 21:50:55        4 secs
6 184.108.40.206 22.214.171.124 2014-01-03 21:50:59       NA secs

Note that the first tdiff value is much larger than what you stated in the intended output. This is richt and due to the fact that the date of the first timestamp is from 2012, while the other timestamps are from 2014.
Comment: Thanks buddy, i tried it on my dataset and it works 100%. Thank you very much! I have to learn more about the package (dplyr)! :)

Calculating time difference by groups


P-value Granger Causality test

Question: Is a p value more than 0.05 but less than 0.1 still significant to detect Granger Causality?
It should be, but very often I see people just stop at the 5% significance
EDIt__ And is correct to say that a 10% significance is a WEAKER causality?
Answer: The p-value threshold of 0.05 is somewhat arbitrary, so you could argue that 0.1 is already significance. It might cause you some raised eyebrows through, mostly because 0.05 is such a widely used threshold.
In practice, a p-value lower than 0.1 but above 0.05 is considered a strong hint towards the alternative hypothesis (causality in this case), but not yet statistically significant.
The way the p-values are presented and how conclusions are drawn based on it is a rather broad discussion and I don't think it matters much which test was used.
Comment: By the looks of it, the Granger causality test adds a term causal term to the linear prediction model and compares that to a similar linear model without that term. This comparison of Residual Sum of Squares is done by an F-test, which takes a value near 1 if there is no causality, and deviates from 1 if there is a difference in RSS. This value is then translated to a p-value using the F-distribution. The 'strength' of the causality is expressed in the F-value. If it is close to 1, it's weak, if it is high, the causality has a big effect.
Comment: I see. Based on this, being a pvalue of <0.1 just a "strong hit"  and not statisticaly significant, we can safely say that, in this case, it represents a weaker causality. Correct?
Comment: The p-value in itself says little about the measure of causality, or how strong or weak it is. This is expressed by the test-statistic. The p-value respresents the probability of the data happening in the way you found, conditional to the null-hypothesis, so the probability of finding the causality you found, if there was no causality present in the data. So no, you can't say that the causality is weak if the p-value is low. You can be really sure of a weak causality, leaving you with a low p-value.
Comment: Then what are the real life implications of saying that one causality is found at 1% level and the other one at 10%?
Comment: It shows how certain you are of the causality that you found. Very crudely, you could say that at 1%, the chance that the causality that you found was actually not there, is 1%, in contrast to 10%.
Comment: Thanks Jarko for you time :) If I might ask you just one last thing, you mentioned that I could establish the strenght of the causality (or I guess any other hypotheses) looking at the test-statistic. Isn't this value "incorporated" in my p value already? Could you just give me more details?

P-value Granger Causality test


Populate treeview with user created tables, and their columns

Question: I am learning C# and .NET on my own. I am trying to learn how to use GetSchema.
What I am trying to do is this:
Open MS Access database and populate treeview control with database schema. I want to populate parent nodes with user created table names, and their child nodes will contain column names.
I have tried to adapt the code example I linked to above but have failed.
Here is the code:
using (OleDbConnection OleDBConnection = new OleDbConnection())
{
    OleDBConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
        "Data Source=" + databaseLocation + ";Persist Security Info=False;";

    try
    {
        OleDBConnection.Open();
        // get database schema
        DataTable dataTable = OleDBConnection.GetSchema("Tables");
        // clear the treeview
        TreeView.Nodes.Clear();
        // here I tried to populate the treeview but have failed
        foreach (System.Data.DataRow row in dataTable.Rows)
        {
            // add parent node -> table name
            TreeView.Nodes.Add(row["TABLE_NAME"].ToString());
            // now add children -> all table columns
            foreach(DataColumn column in dataTable.Columns)
            {
                TreeView.Nodes.Add(column.ColumnName);
            }
        }
        // all done, close the connection
        OleDBConnection.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        Application.Exit();
    }
}

The result I get, when testing on Northwind database, is the following:
- Customers
    - TABLE_CATALOG
    - TABLE_SCHEMA
    - TABLE_NAME
    - TABLE_TYPE
    - TABLE_GUID
    - DESCRIPTION
    - TABLE_PROPID
    - DATE_CREATED
    - DATE_MODIFIED
- Employees
    - TABLE_CATALOG
    - TABLE_SCHEMA
    - TABLE_NAME
    - TABLE_TYPE
    - TABLE_GUID
    - DESCRIPTION
    - TABLE_PROPID
    - DATE_CREATED
    - DATE_MODIFIED
...

The problem with the above result is that it also includes non-user created tables as parent nodes, and I do not get column names from those tables ( instead, I get TABLE_CATALOG and so on for every table).
QUESTION:
How can I load user created tables as parent nodes, and add child nodes that hold those tables column names?
Again, I apologize if the solution is trivial, but bare in mind that this was my first attempt since I am just beginning with C# and .NET
Answer: There are two problems in your code.

The GetSchema returns only the table details of the database. That
information does not contain column details. To filter out system
tables you have to use the other overload of GetSchema(). You can
specify the table type filter criteria. "TABLE" in the restrictions
refers user created tables. Other values are "SYSTEM TABLE, ACCESS
TABLE, TABLE".
The columns should be added as a child node of the parent tree node.

suggestion: Use the debug visualizers to identify what data is available in a table.
Sample Code,
using (OleDbConnection OleDBConnection = new OleDbConnection())
{
    OleDBConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
        "Data Source=" + databaseLocation + ";Persist Security Info=False;";

    try
    {
        OleDBConnection.Open();

        string[] restrictions2 = new string[] { null, null, null, "TABLE" };
        System.Data.DataTable DataTable2 = OleDBConnection.GetSchema("Tables", restrictions2);

        // clear the treeview
        treeView1.Nodes.Clear();
        // here I tried to populate the treeview but have failed
        foreach (System.Data.DataRow row in DataTable2.Rows)
        {
            // add parent node -> table name
            var parent = treeView1.Nodes.Add(row["TABLE_NAME"].ToString());
            // now add children -> all table columns

            string[] restrictions1 = new string[] { null, null, (string)row["TABLE_NAME"], null };
            System.Data.DataTable DataTable1 = OleDBConnection.GetSchema("Columns", restrictions1);

            foreach (DataRow row1 in DataTable1.Rows)
            {
                parent.Nodes.Add((string)row1["COLUMN_NAME"]);
            }
        }
        // all done, close the connection
        OleDBConnection.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        Application.Exit();
    }
}

Answer: This ought to do what you want.  You might want to take the time to examine the data in the table and column DataTables.  They aren't exactly as you might expect to see.
    public static TreeView PopulateTreeViewWithSchema(System.Data.OleDb.OleDbConnection conn, TreeView tree)
    {
        if (tree == null)
            tree = new TreeView();

        // get database schema
        DataTable tableTable = conn.GetSchema("Tables");
        DataTable columnsTable = conn.GetSchema("Columns");

        // clear the treeview
        tree.Nodes.Clear();
        // here I tried to populate the treeview but have failed
        foreach (System.Data.DataRow row in tableTable.Rows)
        {
            // add parent node -> table name
            string tableName = row["TABLE_NAME"].ToString();
            if (!tableName.StartsWith("MSys"))
            {
                TreeNode node = new TreeNode(tableName);
                tree.Nodes.Add(node);
                // now add children -> all table columns
                foreach (System.Data.DataRow columnRow in columnsTable.Rows)
                {
                    if (columnRow["TABLE_NAME"].ToString().Equals(tableName))
                    {
                        node.Nodes.Add(columnRow["COLUMN_NAME"].ToString());
                    }
                }
            }
        }
        return tree;
    }


How to analyse data from the same group where some people have opted out and data is anonymous?

Question: I have a peculiar situation, I am conducting research and had a group of students participate in it. I had them scored on (property) $X$ and say $n_1$ people participated.
After an intervention, I measured the same property $X$ but this time $n_2$ (where $n_2 < n_1$) people participated.
Now the catch is that the experiment is so designed that the forms are filled in anonymously and there is no way to compare the scores of the same individual.
So now I am left with the group mean and I want to run some tests on these.
I want to know -- which tests are most suitable for this kind of data?
Please explain the rationale as well or give hints /links so that I am convinced.
Answer: You have implicitly paired samples (before and after intervention) but because of anonymity, the pairing is lost.
As a result, if you want to test for a treatment effect, you're left with an independent samples two-sample test (you don't actually have complete independence because of the pairing effect, but it shouldn't matter in this case).
The most common procedures for that would be a two-sample $t$ test or a Mann-Whitney-Wilcoxon test.
At the end you say "now I am left with the group mean" -- I hope you have more information than just the group mean, or there will be nothing you can feasibly do. If you have the original scores, you should be fine to do either procedure, or if you have the means, standard deviations and sample sizes you would be able to at least do the t-test.
Both tests make some assumptions, but the main difference in the assumptions (if you're testing means) is that the t-test makes the additional assumption of normality; if your two samples are not too strongly non-normal about their own group means, this won't really matter very much, but you would want to make some assessment of the suitability of that assumption. If you're specifically testing mean-shift alternatives, you should check that the shapes and spreads are similar even if you use Wilcoxon-Mann-Whitney (it can be used without that assumption but the alternative doesn't have a location-shift interpretation any more).
Comment: Yes, I have the sample size ,standard deviation and means available pre and post intervention. But I am not sure whether the data that I have is normally distributed. Also the sample size is small i.e. less than 25.
Comment: Do you have the individual data or only those summary statistics?
Comment: Yes, I have individual data but anonymous data.
Comment: Then if you do a t-test, I'd suggest doing a Q-Q plot of the residuals (observations - group mean), and looking at the relative standard deviations, or perhaps some direct display of the raw data by group, like dotplots or stripcharts. In fact I'd do something like this no matter which procedure I considered. Is your alternative of interest specifically in a mean-shift or is some more general kind of difference of interest here?
Comment: Have you looked at any displays of your data?
Comment: Yes I had looked up the qqnorm plot in R and it doesn't shift too much from the normality i think. Thanks for the help . I will have to admit that I am new to statistics and sorry to say that I don't understand mean-shift as of yet. I will look up these terms and post my queries if any. Thanks again.
Comment: on 'mean shift'. Consider two different possibilities for treatment effect. (i) the treatment on average adds 3 to every 'pre' value.  (ii) the treatment on average doubles every 'pre' value. ... the first is a 'mean shift' (more generally a location-shift), while the second is a scale shift.
Comment: When you say you looked up the qqnorm plot in R - if you plotted only the raw data from both groups (i.e. without allowing for the potential difference in means) that plot could be misleading. If you looked at deviations from the group mean (or plotted them separately) that would be okay.


Overriding third-party module code

Question: I am using Composer to download third-party modules to my Drupal 8 repository.
I have a requirement that involves all of the functionality that module gives but there are unfortunately 2 lines of code that I need to remove in a PHP file in the module_name/src/Helper folder.
The lines I've commented out are to stop the request to open a jQuery UI dialog box.
I'm curious as to what you guys think. It is a requirement from the client that I have this functionality in place.
Here is the code snippet taken from the Ajax Add To Cart Module:
namespace Drupal\ajax_add_to_cart\Helper;

use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\ajax_add_to_cart\Ajax\ReloadCommand;
use Drupal\block\Entity\Block;
use Drupal\Core\Ajax\ReplaceCommand;

/**
 * Class AjaxCartHelper.
 *
 * @package Drupal\modules\ajax_add_to_cart
 */
class AjaxCartHelper {

  /**
   * Ajax add to cart response.
   *
   * @param string $form_id
   *   Form id.
   * @param object $response
   *   Response object to store information.
   *
   * @return object
   *   Return response object.
   */
  public function ajaxAddToCartAjaxResponse($form_id, $response) {
    // Adding modal window.
    $options = [
      'width' => 250,
      'height' => 300,
    ];
    $settings = [
      $form_id => [
        'title' => t('Successful Added'),
        'message' => t('Cart Updated Successfully'),
      ],
    ];
    $title = $settings[$form_id]['title'];
    $message = $_SESSION['messages']['status'][0]->__toString();
    if (!empty($this->cartBlock)) {
      // ****LINE TO REMOVE****
      $response->addCommand(new OpenModalDialogCommand($title, $message, $options));
      // **********************
    }
    else {
      $customblock = $this->container->get('plugin.manager.block')->createInstance('commerce_cart', []);
      $render = $customblock->build();
      // ****LINE TO REMOVE****
      $response->addCommand(new OpenModalDialogCommand($title, $render, $options));
      // **********************
    }
    $response->addCommand(new ReplaceCommand('.block-commerce-cart', $this->cartBlock));
    $response->addCommand(new ReloadCommand());
    unset($_SESSION['messages']);
    return $response;
      }
}

I've added the comment - / ****LINE TO REMOVE**** to the lines that need to be removed
My ideas are:

Duplicate the whole module so that it's custom and use that as the solution (even though module updates won't affect the custom module and i'll have to update it each time)
Comment the two lines out and then update the third-party module

Is there any other methods I'm missing? I've seen the libraries override but thats for the purposes of theming purposes- JS and CSS, I just wondered if theres anything out there in the drupal community fro overriding the PHP that modules provide?
It must be a common requirement by Drupal Devs.
Comment: Without seeing the code of that file, it's hard to answer. It could be a class implementing a service, a event handler, or something else. Depending on what that class is, the answer changes, even in the case the class name is exposed from a hook.
Comment: @kiamlaluno i'll add the exact module & code snippets to the question. Thanks
Comment: @kiamlaluno i've updated the question
Answer: I think the best method would be to use the cweagan patch manager package with composer and a local patch file.  This would allow the module to be updated normally with composer and the patch applied. If the code changes too much for the patch, it will fail and you can update the patch.
Just require cweagans/composer-patches and then modify your composer.json to include the patch.
Also, this is a good way to add patches from Drupal.org or github issues.  If your fix is something that should be generally available, sumbit an issue with the patch.  Then set up your composer patch section to use the URL to the patch in the issue.  For d.o. patches, this makes it easy to find the issue related to the patch since it issue number is in the url.

Overriding third-party module code


Finding conditions for vectors in linear transformations

Question: I'm trying to anwser this.

Given the linear transformation $T(x,y)=(5x+4y,-3x-2y)$, Could it be possible to find a non-zero vector $v$ such that $T(v)=nv?$ for some $n\neq1,2$

My thinking: No, such vector $v$ does not exist. Because,
Let $v=(x,y)$,  then $T(v)=T(x,y)=(5x+4y,-3x-2y)$. Now let's assume $T(v)=nv$
in search for a vector satisfying the equation. $T(v)=nv$
$\Rightarrow$ $(5x+4y,-3x-2y)=(nx,ny)$ which gives the system of equations
$$
\left\{
\begin{array}{c}
5x+4y=nx \\
-3x-2y=ny \\
\end{array}
\right.
$$
Then by leaving alone $y$ from the first equation and making a substitution the second one it results in (Note the $x$ "gets eliminated") this equation $n^2-3n+2=0$. Which it's only satisfied for $n=1$ and $n=2$. Is this a strong argument to prove that it doesn't exist such $n\neq1,2$?
Thanks!
Answer: Hint:
Your transformation is represented by the matrix:
$$
\begin{bmatrix}
5&4\\-3&-2
\end{bmatrix}
$$
and the eigenvalues of this matrix are $\lambda_1=1$ and $\lambda_2=2$.
This is another version of your argument ( that is correct). Can you see why?


Are there any distributions other than Cauchy for which the arithmetic mean of a sample follows the same distribution?

Question: If $X$ follows a Cauchy distribution then $Y = \bar{X} = \frac{1}{n} \sum_{i=1}^n X_i$ also follows exactly the same distribution as $X$; see this thread.

Does this property have a name?
Are there any other distributions for which this is true?

EDIT
Another way of asking this question:
let $X$ be a random variable with probability density $f(x)$.
let $Y=\frac 1 n\sum_{i=1} ^n X_i$, where $X_i$ denotes the ith observation of $X$.
$Y$ itself can be considered as a random variable, without conditioning on any specific values of $X$.
If $X$ follows a Cauchy distribution, then the probability density function of $Y$ is $f(x)$
Are there any other kinds of (non trivial*) probability density functions for $f(x)$ that result in $Y$ having a probability density function of $f(x)$?
*The only trivial example I can think of is a Dirac delta. i.e. not a random variable.
Comment: Thank you; that clears most of it up.  However, there are different answers depending on whether you *fix* $n$ or if you want this result to hold for *all* $n.$  If it's the latter, the condition on the cf or cgf is severe and leads to a ready solution.  If it's the former, then potentially there are additional solutions.
Comment: I was thinking for all $n$ but if anyone wants to provide an analysis on a fixed $n$ also, that would be welcome.
Comment: Your title makes little sense, because the "expected value of a sample" is a *number.*  Do you mean the *arithmetic mean* of the sample instead?  The question is also vague: by "distribution" do you mean a specific distribution or do you mean--as is suggested by the term "Cauchy"--a *family* of distributions?  That's not some minor subtlety: the answer completely changes depending on what you mean.  Please edit your post to clarify it.
Comment: @whuber, I added a second part to the question which hopefully tightens down the range of possible interpretations.
Answer: This is not really an answer, but at least it does not seem to be easy to create such an example from a stable distribution. We would need to produce a r.v. whose characteristic function is the same as that of its average.
In general, for an iid draw, the c.f. of the average is
$$
\phi_{\bar{X}_n}(t)=[\phi_X(t/n)]^n
$$
with $\phi_X$ the c.f. of a single r.v. For stable distributions with location parameter zero, we have
$$
\phi_X(t)=\exp\{-|ct|^\alpha(1-i\beta \text{sgn}(t)\Phi)\},
$$
where
$$
\Phi=\begin{cases}\tan\left(\frac{\pi\alpha}{2}\right)&\alpha\neq1\\-\frac{2}{\pi}\log|t|&\alpha=1\end{cases}
$$
The Cauchy distribution corresponds to $\alpha=1$, $\beta=0$, so that $\phi_{\bar{X}_n}(t)=\phi_X(t)$ indeed for any scale parameter $c>0$.
In general,
$$
\phi_{\bar{X}_n}(t)=\exp\left\{-n\left|c\frac{t}{n}\right|^\alpha\left(1-i\beta \text{sgn}\left(\frac{t}{n}\right)\Phi\right)\right\},
$$
To get $\phi_{\bar{X}_n}(t)=\phi_X(t)$, $\alpha=1$ seems called for, so
\begin{eqnarray*}
\phi_{\bar{X}_n}(t)&=&\exp\left\{-n\left|c\frac{t}{n}\right|\left(1-i\beta \text{sgn}\left(\frac{t}{n}\right)\left(-\frac{2}{\pi}\log\left|\frac{t}{n}\right|\right)\right)\right\}\\
&=&\exp\left\{-\left|ct\right|\left(1-i\beta \text{sgn}\left(t\right)\left(-\frac{2}{\pi}\log\left|\frac{t}{n}\right|\right)\right)\right\},
\end{eqnarray*}
but
$$
\log\left|\frac{t}{n}\right|\neq\log\left|t\right|
$$
Comment: You don't need to invoke the theory of stable distributions.  Letting $\psi=\log \phi$ be the cgf, your equation is $$\psi(t/n) = \psi(t)/n$$ for $n=1,2,3,\ldots.$ Since $\psi$ is an even continuous function and zero at the origin, this immediately implies that the germ of $\psi$ at the origin is $-|ct|.$
Comment: Should this be the accepted answer? Besides $\alpha = 1$  the only way I can see to solve this is with $\alpha = 0$, which (I think) is the Dirac delta.
Comment: That is my impression from these results, but I am pretty sure that there are people more knowledgeable around here w.r.t. stable distributions.
Comment: So is it fair to say that based on your analysis, Cauchy is the only solution for a = 1?
Answer: Normal distribution and shifted Poisson are examples. The shifted Poisson is $s=x-\lambda$, where $\lambda$ is Poisson intensity. There's a whole family of distribution such that the linear combination (not just the sample mean) of variables follows the same distribution, it's called stable distribution.
Comment: Note that the question is not about the result being stable (same distribution up to location and scale parameters), it is about being exactly the same distribution with same location and scale. The analysis in the accepted answer strongly suggests the only possible solutions are Cauchy and the Dirac delta.
Comment: The Poisson cannot possibly be a solution, because the support of the mean of a sample of $n$ is the set of non-negative rational numbers of the form $i/n,$ $i\in\mathbb Z,$ many of which are not in the support of the Poisson distribution.


Replicating Background Behavior From Brawl Stars

Question: So an interesting problem/question, but I've been trying to replicate this background effect here (brawl stars), with the icons filling the background and moving in chosen direction with a specific speed off the screen.
I've been able to initialize the background tiles/icons to immediately show up when the view is loaded, however I am having trouble timing new tiles/icons to come in at the right time, and at the right speed to look the same. I also don't know if this is the best approach and this just represents my feeble attempt at messing around and trying to replicate this behavior.
Any advice or ideas welcome.
func initializeBackgroundTiles()
{
    let itemsPerRow = 4

    let itemHeight = self.frame.width / 7
    let widthBetween = (itemHeight * 2) / 5
    let columnHeight = widthBetween * 4

    for column in 0...10 {

        for row in 0...5 {

            let columnPosition = (columnHeight * CGFloat(column))

            let xCalc = CGFloat(
                -(itemHeight + widthBetween) // one row to the left as well
                + (itemHeight * Double(row) + (widthBetween * Double(row))))

            let yCalc = (((self.frame.height - itemHeight) - columnPosition * 2) +
                         ((row % 2 == 1 ? columnHeight : 0)))

            let tileSubview = CustomImageView(frame: CGRect(
                x: xCalc,
                y: yCalc,
                width: itemHeight,
                height: itemHeight))

            tileSubview.image = UIImage(named: "lightBand")!.withTintColor(.white)
            tileSubview.alpha = 0.04
            ContentView.addSubview(tileSubview)

            UIView.animate(withDuration: 30, delay: 0, options: [.curveLinear]) {

                let newX = ((itemHeight * Double(row)) + (widthBetween * Double(row))) + widthBetween * 3
                let newY = 0 - ((itemHeight + (row % 2 == 0 ? columnHeight : 0)) + columnPosition * 2)

                tileSubview.frame = CGRect(
                    x: newX,
                    y: newY,
                    width: itemHeight,
                    height: itemHeight
                )
            } completion: { completed in
                tileSubview.removeFromSuperview()
            }
        }
    }
}

func addBackgroundTilesTimer()
{
    Timer.scheduledTimer(timeInterval: 6, target: self, selector: #selector(continueBackgroundTiles), userInfo: nil, repeats: true)
}

@objc func continueBackgroundTiles()
{
    // spawn a vertical and horizontal row every x seconds
    let itemHeight = self.frame.width / 7
    let widthBetween = (itemHeight * 2) / 5
    let columnHeight = widthBetween * 4

        for row in 0...7 {

            let columnPosition = (columnHeight * CGFloat(1))

            let xCalc = CGFloat(
                -((itemHeight + widthBetween) * 2) // two buffer rows to the left as well
                + (itemHeight * Double(row) + (widthBetween * Double(row))))

            let yCalc = (((self.frame.height - itemHeight) - columnPosition * 2) +
                         ((row % 2 == 1 ? columnHeight : 0)))

            let tileSubview = CustomImageView(frame: CGRect(
                x: xCalc,
                y: yCalc,
                width: itemHeight,
                height: itemHeight))

            tileSubview.image = UIImage(named: "lightBand")!.withTintColor(.white)
            tileSubview.alpha = 0.04
            self.ContentView.addSubview(tileSubview)

            UIView.animate(withDuration: 30, delay: 0, options: [.curveLinear]) {

                let newX = ((itemHeight * Double(row)) + (widthBetween * Double(row))) + widthBetween * 3
                let newY = 0 - ((itemHeight + (row % 2 == 0 ? columnHeight : 0)) + columnPosition * 2)

                tileSubview.frame = CGRect(
                    x: newX,
                    y: newY,
                    width: itemHeight,
                    height: itemHeight
                )
            } completion: { completed in
                tileSubview.removeFromSuperview()
            }
        }
    }

Comment: Could you please share gif with the current behavior?
Comment: It's the same as the brawl stars one to start, but the new ones just come in at the wrong speed from the bottom and its all wonky. I'm just trying to brainstorm a better solution than the makeshift one I'm using right now, or a way that I should approach this.
Comment: Got it, I will upload the code tomorrow when I will get to my laptop
Answer: I'm not sure if you still need this but here is the answer. Don't forget to initialize it with the rect of view controllers view. If you want to rotate it like in brawl stars then just add transform which rotates TiledBackgroundView.
class TiledBackgroundView: UIView {

    private var timer: Timer?

    private let vCount = 10
    private let hCount = 5
    private let timeScale = 10

    private var itemHeight: CGFloat {
        frame.height / CGFloat(vCount)
    }

    private var itemWidth: CGFloat {
        frame.width / CGFloat(hCount)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        initializeBackgroundTiles()
        addBackgroundTilesTimer()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func initializeBackgroundTiles() {
        for column in 0..<hCount {
            for row in 0..<vCount {
                addTile(
                    column: column,
                    row: row
                )
            }
        }
    }

    func addBackgroundTilesTimer() {
        timer = Timer.scheduledTimer(timeInterval: Double(timeScale), target: self, selector: #selector(continueBackgroundTiles), userInfo: nil, repeats: true)
    }

    @objc func continueBackgroundTiles() {
        for column in 0..<hCount {
            addTile(
                column: column,
                row: vCount
            )
        }
    }

    func addTile(
        column: Int,
        row: Int
    ) {
        let x = itemWidth * CGFloat(column)
        let y = itemHeight * CGFloat(row)

        let tileSubview = UIImageView(
            frame: CGRect(
                x: x,
                y: y,
                width: itemWidth,
                height: itemHeight
            )
        )
        tileSubview.contentMode = .center

        tileSubview.image = UIImage(named: "<your_image>")!.withTintColor(.white)
        addSubview(tileSubview)

        let duration = CGFloat(timeScale) * (CGFloat(row) + 1)

        UIView.animate(withDuration: duration, delay: 0, options: [.curveLinear]) {
            tileSubview.frame.origin = .init(x: x, y: -self.itemHeight)
        } completion: { completed in
            tileSubview.removeFromSuperview()
        }
    }

}


Induction: Every triangulation of an n-sided polygon has n − 2 triangles

Question: I am having trouble understanding a certain proof.
Claim: Every triangulation of an $n$-sided polygon has $n-2$ triangles.
Base Case ($n=3$): Trivial.
We let $P$ be a polygon with $n$ edges. A diagonal is drawn between two vertices of $P$, splitting $P$ up into two smaller polygons $a$ and $b$. Polygon $a$ has $k+1$ edges ($k$ edges of $P$ plus the diagonal), where $k$ is between $2$ and $n-2$. Then, polygon $b$ has $n-k+1$ edges ($n-k$ edges of $P$ plus the diagonal). If we apply the induction hypothesis to polygon $a$, then polygon $a$ can be broken up into $k-1$ triangles. Likewise, by applying the induction hypothesis to polygon $b$, polygon $b$ can be broken up into $n-k-1$ triangles. Putting polygons $a$ and $b$ together, we get $n-2$ triangles.
$(k-1)+(n-k-1) = n-2$ triangles.
I think my confusion arises when considering that we didn't use the induction hypothesis for $n+1$ sides. Instead, we used the induction hypothesis separately on two sub polygons of $P$.
Here's the proof I'm referencing: https://www.cise.ufl.edu/~ungor/courses/fall08/polytri.pdf
Answer: This is strong induction.
Let $\Phi(n)$ be the statement that all triangulations of $n$-gons have $n-2$ triangles.
Instead of the "weak" induction step $$\Phi(n)\implies \Phi(n+1),$$ we use
$$\tag1 (\forall k\le n\colon \Phi(k))\implies \Phi(n+1).$$
The principles are equivalent:
If we define $\Psi(n)\equiv \forall k\le n\colon \Phi(n)$, then we imemdiately get $\Psi(n)\implies \Psi(n+1)$ from $(1)$.

Remark: An overlooked and somewhat tricky part is hidden in your bold "A diagonal is drawn ...". It is a not fully trivial (but true) fact that every (not necessarily convex) polygon has a diagonal.
Comment: The link in the question leads not only to the proof that the OP is asking about but also (on the next page) to a lemma saying that every polygon has a diagonal.
Comment: But ISTM that the proof is at best incomplete, partly because there is no definition of what a "diagonal" is - at least in the two pages that I looked at.


HINT on 127: "Command not found" fail2ban

Question: I have a problem with Fail2ban. In the log I have this:
2021-12-05 00:49:23,968 fail2ban.utils          [979765]: ERROR   7f9a6df8cdf0 -- stderr: '/bin/sh: 1: iptables: not found'
2021-12-05 00:49:23,968 fail2ban.utils          [979765]: ERROR   7f9a6df8cdf0 -- stderr: '/bin/sh: 2: iptables: not found'
2021-12-05 00:49:23,968 fail2ban.utils          [979765]: ERROR   7f9a6df8cdf0 -- stderr: '/bin/sh: 3: iptables: not found'
2021-12-05 00:49:23,968 fail2ban.utils          [979765]: ERROR   7f9a6df8cdf0 -- returned 127
2021-12-05 00:49:23,969 fail2ban.utils          [979765]: INFO    HINT on 127: "Command not found".  Make sure that all commands in 'iptables -w -N f2b-nginx-badbots\niptables -w -A f2b-nginx-badbots -j RETURN\niptables -w -I INPUT -p tcp -j f2b-nginx-badbots' are in the PATH of fail2ban-server process (grep -a PATH= /proc/`pidof -x fail2ban-server`/environ). You may want to start "fail2ban-server -f" separately, initiate it with "fail2ban-client reload" in another shell session and observe if additional informative error messages appear in the terminals.
2021-12-05 00:49:23,969 fail2ban.actions        [979765]: ERROR   Failed to execute ban jail 'nginx-badbots' action 'iptables-allports' info 'ActionInfo({'ip': '22.214.171.124', 'family': 'inet4', 'fid': <function Actions.ActionInfo.<lambda> at 0x7f9a6f56eca0>, 'raw-ticket': <function Actions.ActionInfo.<lambda> at 0x7f9a6f56f3a0>})': Error starting action Jail('nginx-badbots')/iptables-allports: 'Script error'
2021-12-05 00:49:23,969 fail2ban.actions        [979765]: NOTICE  [nginx-badbots] Restore Ban 18.104.22.168
2021-12-05 00:49:23,976 fail2ban.utils          [979765]: ERROR   7f9a6df8cdf0 -- exec: iptables -w -N f2b-nginx-badbots

Can someone enlighten me?
thanks in advance
Comment: '/bin/sh: 2: iptables: not found'
seems you do not have iptables installed
Comment: Hello,

That was it, thank you for your help.
Answer: In the loglines you posted you can see the error " /bin/sh: 2: iptables: not found'"
A command not found message usually means that either the command is not installed, or (less often) that the command is not within the PATH environment variable.
Try to install the package which includes the required command, in your case this would be the iptables command, which is the same name for the package.
An installation command like sudo apt install iptables should provide you with the required command for the fail2ban functionality on debian.
Answer: For anyone that already has iptables installed, this is what I did:
I'm on Ubuntu 18.04, using fail2ban v0.9.4
I went into /etc/fail2ban/action.d/iptables-common.conf and edited the last line in the file:
# Option:  iptables
# Notes.:  Actual command to be executed, including common to all calls options
# Values:  STRING
#iptables = iptables <lockingopt> <--- Commented this
iptables = /sbin/iptables <lockingopt> <--- Changed to this

I gave it the binary path to iptables and it's working now.


React.js: Avoid updates of currently edited input

Question:
Demo: jsfiddle
/**
 * @jsx React.DOM
 */
var NumberField = React.createClass({
    render: function() {
        return <input type="number" value={this.props.value} onInput={this.onInput}/>;
    },
    onInput: function(e) {
        if (!this.props.onValueChange) {
            return;
        }
        var value = parseInt(e.target.value, 10);
        return this.props.onValueChange(value);
    }
});

var TempConverter = React.createClass({
    getInitialState: function() {
        return {c: 0};
    },
    render: function() {
        var c = this.state.c;
        return

            <NumberField onValueChange={this.onChangeC} value={c}/> C

            <NumberField onValueChange={this.onChangeF} value={c2f(c)}/> F

;
    },
    onChangeC: function(c) {
        this.setState({c: c});
    },
    onChangeF: function(f) {
        this.setState({c: f2c(f)});
    }
});

function c2f(c) {
    return 1.8 * c + 32;
}
function f2c(f) {
    return 0.5555555555555 * (f - 32);
}

When I change the °F value by one, it gets converted to Celsius and then back to Fahrenheit, resulting in rounding errors.
Is there any way to avoid updates on the currently modified element?

Backbone.js has the exact same problem.
Answer: You ask,

Is there any way to avoid updates on the currently modified element?

In general, not really. This is actually a feature of React: your UI is guaranteed to always be in sync with your underlying data! Of course, by overriding shouldComponentUpdate and doing some manual work you can prevent the fields from changing, but it's intentional that the path of least resistance leads you to an always-accurate UI.
It sounds like you want to be able to show either an exact °C temperature or an exact °F temperature, so the best approach here seems to be to store that as well. Otherwise, you're feigning more precision than you actually have. I've modified your code so that it operates in one of two modes: Celsius mode or Fahrenheit mode:
var TempConverter = React.createClass({
    getInitialState: function() {
        return {type: "c", val: 0};
    },
    render: function() {
        var c, f;
        if (this.state.type === "c") {
            c = this.state.val;
            f = c2f(c);
        } else {
            f = this.state.val;
            c = f2c(f);
        }

Tracking the value this way allows you to store and display the exact temperature the user entered and be confident that you're not losing any precision.
Live demo here: jsfiddle
(You could also round the temperature before displaying, of course, but your response to your Backbone.js question indicates that's not your preferred solution.)


I am getting context value undefined in the child component using contextType in an expo app

Question: I am trying to use context api in my app, the way i am trying to use is https://reactjs.org/docs/context.html#classcontexttype
here's a snack that I need to fix https://snack.expo.io/@mohmdalfaha/contexttype-example the context value is always undefined??
Comment: I have fixed this by just removing {} from {AppContext}
Answer: There is error in your import in child component. As you are exporting AppContext as default you can't import in {}. You can import constant in {}.
Here's a snack for that https://snack.expo.io/ByQkOVgXS


Guidance regarding probability

Question: Does anyone know any good problems collection for elementary probability to be used along with Stirzaker ?
I currently have Fifty Challenging Problems in Probability by Mosteller, but that is not sufficient practice.
Any help is greatly appreciated.
Answer: I also have the Mosteller collection, but some of those problems are more about clever tricks than actually practicing solving probability problems.
This one is like a collection for job interviews.
https://www.math.ucdavis.edu/~gravner/MAT135A/resources/chpr.pdf
Pretty easy yet instructive exercises.
Probability Through Problems by Marek Capinski
I used this to help me through a class.
One Thousand Exercises in Probability

Guidance regarding probability


How best to represent a web app's usage?

Question: I've been gathering data for the usage of a web app.
For each day at the same hour and over several months I have:

(A) total number of members
number of online members and its % to (A)
number of members who connected during the day and its % to (A)
number of new members
number of forum members
number of new forum members
number of chat participants

Plus the periods where it was on sale (there's one time fee to access it).
What can I show with those data and how best to represent it graphically ?
(I'll be using Apple Numbers.)
Answer: Well, it mostly depends on the intended usage of the data. Often, data of this form is intended to show the influence or reach of an application. For this, most businesses will report some form of the average unique users during some time period, like "500 unique visitors each month", or facebook's "active daily users". For an application with a key activity, like uploading photos, you might also report something related to that activity, like "5 new photos uploaded every second." Would your data allow that? For displaying it graphically, a simple line our bar chart showing how the influence (y) grows over time (x) is usually sufficient.
If you can tell us more about what you hope to use the data for, others may have better ideas than mine.
Comment: I can find out the % of members who completed a task but only at present time, not over a period - so this is not concerned by my question. I want the data to show everyone (team and members) how we're doing (is it successful or not, if not where is the problem) and the relations between data. Basic question: which data am I supposed to put together in the same graph ?


A question on the Riemann zeta function

Question: Question: Consider a $L$-shaped path $L_\epsilon:\frac{1}{2}+\epsilon\to \frac{1}{2}+\epsilon+i\ (H+\epsilon)\to \frac{1}{2}+i\ (H+\epsilon)$ where $H>0$ is fixed and $\epsilon>0$ is arbitrarily small. If the Riemann zeta function, $\zeta(s)$ is non zero on $L_\epsilon$ then prove that $$\int_{L_\epsilon} \frac{d}{ds}\log[(s-1)\zeta(s)]\ ds = \log\left[\left(-\frac{1}{2}+i(H+\epsilon)\right)\zeta\left(\frac{1}{2}+i(H+\epsilon)\right)\right]-\log\left(\left(\epsilon-\frac{1}{2}\right)\zeta\left(\frac{1}{2}+\epsilon\right)\right)$$
My Try: Since the function $f(s)=(s-1)\zeta(s)$ is entire and  $f(s)$ has no zeros on $L_\epsilon$ so we can for each point $s'\in L_\epsilon$ find a small neighbourhood $U(s')$ so that $f(s)\neq 0$ $\forall s\in U(s')$. Hence we can find an open set $U=\bigcup\limits_{s'\in L_\epsilon} U(s') $, so that $L_\epsilon\subset U$ and $f(s)\neq 0$ for every $s\in U$.
But Fundamental Theorem of Calculus would not work due to singularities involved and the logarithm of the zeta function must be defined carefully.
Comment: (+1) Thank you for taking the feedback and improving your question.
You found an open simply connected region $U$ on which $(s-1)\zeta(s)$ is non-zero, therefore you can find a holomorphic branch of $\log$ on $U$ and exactly use the fundamental theorem of calculus.
Comment: Why the downvote? Because it is a research level question?
Comment: No, probably because you offer no motivation, no context, no work of your own and sort of just demand an answer. Please read this short page: https://math.stackexchange.com/help/how-to-ask

(I didn't vote on your question either way btw)
Comment: @Arkady I have added my work. Please see and answer
Comment: @Arkady Thank you. Please write an answer as to how can I find a holomorphic branch of $\log$. I will accept your answer.
Comment: @Arkady We need to carefully define the logarithm of the zeta function. How do we do that?
Comment: I'm not sure I understand your question. The existence of a branch of log for any holomorphic function not vanishing on a simply connected open set is a result in complex analysis.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/137034/discussion-between-arkady-and-ava).
Answer: If $f$ is a holomorphic function on a simply connected region $U$ and $f(z) \neq 0$ for all $z\in U$, there exists a holomorphic function $g$ such that $\exp \circ g = f$. This is a standard result in complex analysis. See the reference cited here.
You have constructured the simply connected region $U$ on which $f(s) = (s-1)\zeta(s)$ is non-vanishing and holomorphic so just apply this result. Then you can use the fundamental theorem of calculus to conclude.
Comment: But how do we define the logarithm of the zeta function?
Comment: Have you checked the link? It has a recipe there.
Comment: Yes I checked it. But you have not used the properties of zeta function. My professor is not convinced with the application of FTC here.

A question on the Riemann zeta function


Configuring an alternate jail in fail2ban for manual use

Question: I have a fail2ban instance that works well.
But I also like to occasionally examine the logs manually and try to ID system probes that are working around my standard f2b definitions.
What I'm looking for is how I can define a jail that will last an extended period of time that I can manually use in a command like this:
fail2ban-client set $JAIL banip $IP

Can someone give me the syntax to specify a custom jail in the config file that isn't really triggered from log files (or it could be a standard jail that has some condition that might not make it actually trigger), that I can use in a manual statement?  What I want to do is have a much longer ban time for manual bannings that I identify personally while looking through logs.
Answer: Here's how I did this..
I added this to jail.local:
[manban]
enabled  = true
filter   = manban
action   = iptables[name=HTTP, port="80,443,110,995,25,465,143,585,993,587,21,22", protocol=tcp]
logpath  = /var/log/manban.log
maxretry = 1
# 1 month
bantime  = 2592000
findtime = 3600

Then I added the file /etc/fail2ban/filter.d/manban.conf:
[Definition]
failregex = ^\[\w{1,3}.\w{1,3}.\d{1,2}.\d{1,2}:\d{1,2}:\d{1,2} \d{1,4}. \[error] \[client.<HOST>].File does not exist:.{1,40}roundcube.{1,200}
ignoreregex =

I copied the filter protocol of another filter but point it to a file that doesn't exist, then I created a dummy file:
touch /var/log/manban.log

then run the command:
fail2ban-client reload

Now to manually ban an IP address for one month, type:
fail2ban-client set manban banip <IP>

This did the trick.
There are clients now that "learn" your fail2ban bantime, and will automatically adjust their system probes to not get banned.  But when you look at the logs, it's obvious these are system probes.  You can mess up their systems by creating extraordinary long ban times.  You could also write a script that could dump IPs matching a certain criteria to your special ban log and have fail2ban ban them for an extended period of time.
Answer: Why not use an empty filter?  Here's my /etc/fail2ban/filter.d/manual.conf
[Definition]
failregex=
ignoreregex=

And then /etc/fail2ban/jail.d/manual.conf
[manual]
enabled = true
port = http,https
action = iptables-multiport[name=manual, port="http,https", protocol=tcp]
bantime = 9999999999999999

And then after a quick fail2ban-client reloadI can simply
fail2ban-client set manual banip <IP>


Vmware Tools potentially locking files/folders on Windows Server

Question: I have a Windows 2008 R2 X64 server running on Vmware ESXi.  Originally it was running on Hyper-V, but I have since converted the VHD to a VMDK and migrated to ESXi.  I also installed VMware Tools.  This server is our TeamCity continuous integration server, performing nightly builds of software packages that my company develops.  Since the move, occasionally certain files that the build process should delete fail to delete due to "The file is in use by another process".  We are trying to delete the files using the CMD del command.  Sometimes it works, others not.  I fired up process monitor with the path of the directory where failures occur as the PATH filter (PATH contains C:\work ).  I see a LOT of vmtoolsd.exe Createfile, FileSystemControl, and CloseFile operations occurring in quick succession, repeatedly.  Has anyone heard of Vmware tools causing filesystem locks on Windows guests?
I have not been able to capture it with procmon when it actually happens yet, but I plan to try.
Also, due to running out of space, this directory C:\work, was recreated  by renaming it to C:\work-old, adding a second virtual disk E:\, and mounting the disk to the directory C:\work , then copying the contents of C:\work-old to the newly mounted C:\work.  I see Vmware Tools is constantly performing FSCTL_Get_Reparse_Point on C:\work.
UPDATE:
I disabled the VMware tools service last night and it still happened.  I believe the C:\work directory, which is a share that is actually the E: drive mounted as a directory to C:\work is being accessed by 2 remote hosts simultaneously and perhaps this is causing a lock on the directory by the first host.  This did not used to happen before I mounted the E: to the work directory,, Are there any known issues with file locking and volumes mounted as directories?
Comment: 1. Instead of "redirecting" C:\work why not expand the VMDK and extend the C: volume in Windows? 2. Do you have the Shared Folders component of VMware Tools installed? If so, try removing it. 3. Are you running any type of backup during the hours that the locks occur, such as a VM level backup?
Comment: If you select a custom install of VMware Tools and expand the VMCI Driver node you'll find the Shared Folders component. It used to be installed by default when selecting a default install of VMware tools. If it is installed then my guess is that may be causing your issue. I've seen it cause a variety of file system issues in Windows VM's.
Comment: Shared folders does not exist under ESXi to my knowledge, I think that is only for the Workstation/Desktop version.  I had Crashplan installed for backups and removed it completely due to this issue, but it still happens.
Answer: It turns out that the problem was not caused by VMware Tools.  It is more likely that the windows Application Experience service caused this issue, but I am not positive.  I ultimately resolved the issue by adding a virtual disk and creating a new share, then pointing the build to look to this share.  If the build step leaves an open handle for this share, it wont affect the subsequent step which does not refer to that share again (previously everything was done from the same share, so if there was an open handle, file operations would fail).


Run D6 and D7 instance on same domain?

Question: Client wants to have their D6 and D7 site run under the same domain. They're not ready to upgrade. Each has a similar theme so linking to the D6 site will 'look' seamless. How can this be done?
Answer: Put the D7 site under the root web directory. You should be able to go the site and see the D7 site. Then, put the D6 site under the root web directory in a new directory called 'd6' or whatever you want. Then, in the settings for the D6 site, put the root path as webdirectory/d6.
Then you can reference the d6 site from the d7 by directing users to the link "something.com/d6/someNode"
Otherwise, you really can't have both running under the same web root. It has to choose one or the other.

Run D6 and D7 instance on same domain?


Centre image horizontally inside li where image wider than li

Question: What options (if any) do I have to centre the image within the li tag? What I have is an oversized image deliberately placed into a smaller sized li. What I am trying to achieve is the image centred within the li tag ... ie so that the cropped overflow would be shared on both the left and right, not just the right. The code below is a reduced version of what I am working with.
HTML

CSS
li{
  overflow:hidden;
  width: 250px;
}
img {
  border: 3px solid pink;
}

The codepen is here http://codepen.io/anon/pen/ebCEi. Note: I wont be able to use background images.
Comment: What is your desired result?
Comment: To get the image centred within the li tag ... ie so that the cropped overflow would be shared on both the left and right, not just the right - will update my question
Answer: li {
    overflow:hidden;
    width: 250px;
    position:relative;
    height:106px;
}
img {
    border: 3px solid pink;
    position:absolute;
    left:-75px;
}

jsFiddle example
You'll notice the left and right border on the image isn't visible because it extends beyond the viewport of the list item.
Answer: Use text-align:
li {
   overflow:hidden;
   text-align: center; /* <-------  */
   width: 250px;
}

If that doesn't work try this:
img {
    border: 3px solid pink;
    margin: 0 auto; /* <-------  */
}

Answer: Try this:
HTML

CSS
li{
  overflow:hidden;
  text-align:center;
  width: 250px;
}
img {
  border: 3px solid pink;
  margin:0 auto;
}

Comment: Ummm, that's because your image is wider than the list item.
Comment: So you want the `li` centered -- not the image. Good luck.
Comment: image centred within li if possible. If it's not possible it would be helpful to see from the specs why not, thanks
Comment: @BhushanFirake yes I know, but that's deliberate too
Comment: Done, sorry I thought it was obvious as it's in the code `overflow:hidden;
  width: 250px;`
Comment: Changed the title too, that probably didn't help.


how to send an array from php to javascript

Question: function Perfil(){

    var metodo = "Perfil";
    $.ajax({
        url: url_header,
        type: 'POST',
        data: {Metodo:metodo, id:idUser},
        success: function(data) {
            alert(data);
        },
        error: function(data){
            alert(data);
        }
    });
}

PHP file:
public function Perfil(){
    try {
    $id = $_POST["id"];
    $result=mysql_query("SELECT tipo FROM pessoa WHERE id=".$id." ");
    $row = mysql_fetch_assoc($result);
    if($row['tipo']=="PJ"){
        $result=mysql_query("SELECT CNPJ, ValorMin, ValorMax, PossuiReserva, Descricao, foto_profile, Premium, Wifi, Id_evento_nao_premium FROM PJ WHERE ID_Pessoa= ".$id." ");
    $response  = array();
    while($row = mysql_fetch_assoc($result)){
        $response[] = $row;
            }
        echo json_encode($response);
     }
     catch (Exception $e) {
        echo 'O sistema retornou um erro:
';
    echo ''.$e->getMessage()."";
     }

 }
}

When he enters the javascript success function it shows the following date:
[{"CNPJ":"07677711000144","ValorMin":"120","ValorMax":"500","PossuiReserva":"1","Descricao":null,"foto_profile":"","Premium":"0","Wifi":"0","Id_evento_nao_premium":"0"}]
But I knew not how it works with this information in javascript.
I've tried
data[0];    data["CNPJ"];

but nothing helped, help ..
Comment: Have you tried `data[0]["CNPJ"]`?
Comment: try to $_POST["id"]; as $_REQUEST["id"]; and add an 'exit' after  echo json_encode($response); and as you are getting a number of rows you need to get the data as an array in success function. Mean use a for loop
Answer: You need to ensure that it returns a json object, instead of a string (default). You can do so by adding the dataType variable. Then the returned data is an object..
function Perfil(){

    var metodo = "Perfil";
    $.ajax({
        url: url_header,
        type: 'POST',
        dataType: "json",
        data: {Metodo:metodo, id:idUser},
        success: function(data) {
            alert(data[0].CNPJ);
        },
        error: function(data){
            alert(data);
        }
    });
}

edit: You can also shorthand this:
$.getJSON(url_header, {Metodo:metodo, id:idUser}, function(data) { alert(data[0].CNPJ); });

Comment: I got so **var v = $.parseJSON(data.toString());
            alert(v[0].CNPJ);**
Comment: returned in undefined alert
Comment: fixed answer, sorry, tested on jsFiddle as well to ensure the JSON is handled right: http://jsfiddle.net/WpnDs/
Comment: Tried what? This solution works and I sent a jsFiddle link proving the concept in a test. ajax function returns string by default. once dataType is set to json you can treat it as json.
Comment: yee that works too, i also edited and added a shorthand method to do it. thank you :)


i want subsonic read database password from a variable instead of app.config

Question: I have successfully implemented SUBSONIC DAL in my desktop application. it was superb experience. but subsonic reads database password from app.config file. as app.config deploy with application on client side, therefore its a big security threat.
It would be helpful if i can read database password from a variable instead of app.config.
Thanks in advance,
Regards.
Answer: The easiest and best way to protect connection string data is to encrypt the connection string section of the app.config
Read here http://msdn.microsoft.com/en-us/library/system.configuration.rsaprotectedconfigurationprovider.aspx
Answer: Dataservice.setdefaultconnectionstring() resolve my problem
Answer: The short answer to this is probably not going to happen because it would mean that either you need to add all the source files to your current project and change the way subsonic loads the connection string.
If you are worried about passwords being deployed to the client then it might be a better idea to use integrated security which works brilliantly.
Also you did not specify which version you are using , since modifying v3 is a little easier in my opinion


VPS CPU usage very high

Question: I just switched my hosting to a VPS. I will admit that server admin is something I am very very new at. Anyhow, I am getting repeated emails about my server load exceeding 100% so i clearly need to get something configured differently.
Here is my #top:
http://support.schaffner-publications.com/images/top.jpg
My VPS configuration is:

os- CENTOS 6.5 i686 ram- 756 MB bram- 1024 MB cpu - (2) x Xeon E5645
  24x Core software - PHP, MySQL, Apache, FFmpeg, Lame, Libogg,
  Libvorbis, FLVtool2, Mplayer, Mencoder, AMR, kernel - 2.6.32+

I have about 15 Joomla sites all with caching turned on. Most are low traffic, although I have 1 site that gets about 10,000 pageviews per day, and one that gets about 200 pageviews per day.
How to get my load down?
Traffic stats:
<code>Unknown robot (identified by 'bot*')    941,891+589 260.70 GB   12 Jul 2014 - 20:12
MSNBot  45,500+319  3.06 GB 12 Jul 2014 - 20:11
Googlebot   33,529+60   2.82 GB 12 Jul 2014 - 20:12
Unknown robot (identified by 'crawl')   11,713+65   752.50 MB   12 Jul 2014 - 20:09
Unknown robot (identified by 'robot')   10,278+24   487.78 MB   12 Jul 2014 - 19:52
Unknown robot (identified by 'spider')  6,966+13    431.20 MB   12 Jul 2014 - 20:11
Yahoo Slurp 3,986+7 261.62 MB   12 Jul 2014 - 20:10
Unknown robot (identified by '*bot')    3,691+23    246.48 MB   12 Jul 2014 - 17:54
Unknown robot (identified by empty user agent string)   1,196   68.15 MB    12 Jul 2014 - 19:54
Unknown robot (identified by hit on 'robots.txt')   0+291   245.82 KB   12 Jul 2014 - 20:09
MSNBot-media    55+68   4.03 MB 12 Jul 2014 - 19:15
Alexa (IA Archiver) 29  1.94 MB 11 Jul 2014 - 13:04
Netcraft    1   92.55 KB    10 Jul 2014 - 11:46
</code>
Comment: Your web traffic exceeds the capacity of your VPS to handle it. And...was that...Windows XP?!?
Comment: CENTOS 6.5, with this being a traffic thing what should i do. My awstats says my traffic from my busiest site is added to my original post
Comment: lol yes it was windows XP. im on my old netbook today that i havent gotten around to updating to 7
Comment: you have 1 zombie there, but i bet php is hanging on mysql.
Answer: Top says it all. You are using 83% user, which is from tendesig. top -c will give more information on what is being run as well. It may be you need a larger server. You can try checking PHP error logs to see if there is anything amiss with the account. You can also check the MySQL process list to check for any long running queries. This would be "show processlist;" in MySQL.
Really, you need more cores and check that the scripts ran are optimized. There are at least 10 PHP processes competing for CPU time which is reflected in the 16 load average (average of processes waiting for CPU time). A 16 LA is not good, you want to aim for having that around 1-2 at highest.
Answer: Joomla tends to be quite heavy on CPU. However, you can use the various cache modes to considerably improve that situation. Give a look here.

VPS CPU usage very high


How can I configure the User Protect module to avoid editing/deleting users with "edit users" permissions?

Question: I am working in Drupal 6. I have created a role "admin users" with permissions for edit and delete users but I need that this role "admin users" cannot edit/delete the user admin. I have installed the User Protect module but I cannot to configure it correctly for the role "admin users" can not modify it.
Answer: I had to do it one day and I did like that. But in my case the permission is edit user 1. The code simply remove the user from the list. Feel free to change as you want.
<?php
function mymodule_menu_alter(&$items) {
  $items['admin/user/permissions']['access callback'] = 'mymodule_user_access';
}

function mymodule_user_access($string, $account = NULL, $reset = FALSE) {
  if ($string == 'administer permissions' && user_access('edit user 1')) {
    return TRUE;
  } else {
    return FALSE;
  }
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'mymodule_user_profile_form_validate';
}

function mymodule_user_profile_form_validate(&$form, &$form_state) {
  $account = $form_state['values']['_account'];
  if(!user_access('edit user 1') && $account->uid == 1) {
    form_set_error('category', t('You does not have right to edit this user.'));
  }
}

function mymodule_perm() {
  return array(
    'edit user 1',
  );
}

function mymodule_theme() {
  return array(
    'mymodule_user_admin_account' => array(
      'arguments' => array('form' => NULL),
    ),
  );
}

function mymodule_theme_registry_alter(&$theme_registry) {
  unset($theme_registry['user_admin_account']['file']);
  $theme_registry['user_admin_account']['function'] = 'theme_mymodule_user_admin_account';
  $theme_registry['user_admin_account']['include files'] = array();
  $theme_registry['user_admin_account']['theme path'] = drupal_get_path('module', 'mymodule');
  $theme_registry['user_admin_account']['theme paths'][] = drupal_get_path('module', 'mymodule');
}

function theme_mymodule_user_admin_account($form) {
  // Overview table:
  $header = array(
    theme('table_select_header_cell'),
    array('data' => t('Username'), 'field' => 'u.name'),
    array('data' => t('Status'), 'field' => 'u.status'),
    t('Roles'),
    array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
    array('data' => t('Last access'), 'field' => 'u.access'),
    t('Operations')
  );

  $output = drupal_render($form['options']);
  if (isset($form['name']) && is_array($form['name'])) {
    foreach (element_children($form['name']) as $key) {
      if(!user_access('edit user 1') && $key == 1) {
        unset($form['accounts'][$key]);
        unset($form['name'][$key]);
        unset($form['status'][$key]);
        unset($form['roles'][$key]);
        unset($form['member_for'][$key]);
        unset($form['last_access'][$key]);
        unset($form['operations'][$key]);
      }

      $rows[] = array(
        drupal_render($form['accounts'][$key]),
        drupal_render($form['name'][$key]),
        drupal_render($form['status'][$key]),
        drupal_render($form['roles'][$key]),
        drupal_render($form['member_for'][$key]),
        drupal_render($form['last_access'][$key]),
        drupal_render($form['operations'][$key]),
      );
    }
  }
  else {
    $rows[] = array(array('data' => t('No users available.'), 'colspan' => '7'));
  }

  $output .= theme('table', $header, $rows);
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}


Using pairwise comparison on gls object with heterogeneity of variances?

Question: I'm comparing total yield from fields under 5 different treatments. As you can see, the variance differed between the treatments (diagnostics from lm() fit):

So I fitted the model with nlme::gls() and a variance structure depending on the treatment:
vs <- varIdent(form= ~1|Treatment)
ls1 <- gls(Yield ~ Treatment, weights=vs, data=prod, method="ML")

When doing an anova on this model and one without 'Treatment', the effect of treatment on yield proved to be significant (p<0.05). So I wanted to see which treatments differed from each other and found the package emmeans (used to be lsmeans) which can work with gls objects.
When I run emmeans(ls1) I get the desired output and at the bottom it says "P value adjustment: tukey method for comparing a family of 5 estimates"
I learned that one of the assumptions of Tukey's test is homoscedasticity, which is not the case here (that's why I used gls() to begin with).
So I cannot use the results of emmeans()?
What other options do I have?
This analyses is for a paper, can I just describe the results I've plotted without any post hoc tests and thus without reporting p-values?
I've read several times that post hoc tests and reporting p-values are overrated, but then how do I report? "Figure x clearly show that treatment A differs from treatment B"? Does that suffice?
EDIT:
I checked the assumptions again with the gls() modelfit and these are the standardized residuals vs the fitted values now:

I assume I can use Tukey's test then?
Comment: If your new model shows not signs of heteroskedasticity anymore (based on the image it doesn't) then you are golden and Tukey is a-OK.
Comment: Does your model still have problems with heteroskedasticity after modeling variance?
Comment: Oh no it doesn't, I didn't check that... the residuals vs. fitted values plot looks good now. I've added the new diagnostic plot in the question.
I assume using Tukey is okay then?
Comment: You can use `adjust = "mvt"` and the multivariate t distribution will be used. I doubt the adjusted p values will be much different from the Tukey ones though.
Answer: You may use the glht() function in the multcomp package if you run the following code before:
model.matrix.gls <- function(object, ...) {
    model.matrix(terms(object), data = getData(object), ...)
}
model.frame.gls <- function(object, ...) {
    model.frame(formula(object), data = getData(object), ...)
}
terms.gls <- function(object, ...) {
    terms(model.frame(object), ...)
}

phAnova<-glht(ls1, linfct=mcp(Treatment="Tukey"))
summary(phAnova)

Look at this link, down the page:
http://rstudio-pubs-static.s3.amazonaws.com/13472_0daab9a778f24d3dbf38d808952455ce.html.


Como fazer download de um arquivo de release do GitHub usando WebClient em .NET 3.5?

Question: Depois de minha pergunta de Criar arquivos Zip e descompactar usando .NET 3.5 eu estou com um problema. É que antes eu conseguia fazer o download de meu arquivo numa release do GitHub, só que depois não funcionava mais.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.IO.Compression;
using System.Reflection;

namespace IEIPInstaller
{
    public partial class Main : Form
    {
        private string temp = Path.Combine(Path.GetTempPath(), "IEIPInst");
        private string localProg = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

        public Main()
        {
            if (Directory.Exists(temp))
            {
                if(File.Exists(temp + "\\IEIPv0.2-alpha-Windows.zip"))
                {
                    File.Delete(temp + "\\IEIPv0.2-alpha-Windows.zip");
                }
                Directory.Delete(temp);
            }
            if(File.Exists(localProg + "\\IEIPv0.2-alpha-Windows.zip"))
            {
                MessageBox.Show("Installer cannot be initialized because you have IEIP with this program.", "IEIPInst", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(0);
            }
            else
            {
                InitializeComponent();
                Directory.CreateDirectory(temp);
            }
        }

        private void btnNo_Click(object sender, EventArgs e)
        {
            Directory.Delete(temp, true);
            Application.Exit();
        }

        private void btnYes_Click(object sender, EventArgs e)
        {
            btnYes.Enabled = false;
            btnNo.Enabled = false;
            lblWant.Text = "";
            Complete.Text = "Status: Connecting...";
            startDownload();
        }

        private void startDownload()
        {
                WebClient client = new WebClient();

                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                client.DownloadFileAsync(new Uri("https://github.com/JPPlaysGamer/IndustriesExes.Inc/releases/download/ieip-pre2/IEIPv0.2-alpha-Windows.zip"), temp + "\\IEIPv0.2-alpha-Windows.zip");

        }
        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.BeginInvoke((MethodInvoker)delegate {
                double bytesIn = double.Parse(e.BytesReceived.ToString());
                double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
                double percentage = bytesIn / totalBytes * 100;
                Mbs.Text = (bytesIn / 1024 / 1024).ToString("F2") + " / " + (totalBytes / 1024/ 1024).ToString("F2") + " Mb";
                Complete.Text = "Status: Downloading...";
                IEIPProgress.Value = int.Parse(Math.Truncate(percentage).ToString());
                this.Text = "IEIP Installer - " + IEIPProgress.Value + "%";

            });
        }
        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            this.BeginInvoke((MethodInvoker)delegate {
                if(File.Exists(temp + "\\IEIPv0.2-alpha-Windows.zip"))
                {
                    File.Move(temp + "\\IEIPv0.2-alpha-Windows.zip",  localProg + "\\IEIPv0.2-alpha-Windows.zip");
                }

                Complete.Text = "Status: Completed";

                btnNo.Text = "Exit";
                btnNo.Enabled = true;

            });
        }

    }
}

Esse é o código de antes e esse é a URL do arquivo:
WebClient client = new WebClient();

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri("https://github.com/JPPlaysGamer/IndustriesExes.Inc/releases/download/ieip-pre2/IEIPv0.2-alpha-Windows.zip"), temp + "\\IEIPv0.2-alpha-Windows.zip");

Eu troquei DownloadFileAsync para DownloadFile como a função Async tem thread separada da main e recebo esta exceção:
System.Net.WebException: A conexão subjacente estava fechada: Erro inesperado em um envio. ---> System.IO.IOException: EOF inesperado ou 0 bytes recebidos do fluxo de transporte.
Eu fiz tudo certo mas agora não funciona mais. Alguém poderia me explicar sobre isso?
Answer: Eu descobri o problema, como eu uso o .NET 3.5, não há suporte a TLS e já que mudei para a versão 4.5 funcionou.
Pode ser também que o GitHub talvez usasse conexão TLS e não ter funcionado. Existe uma versão do .NET 3.5 que tem suporte a TLS e vi que funcionou. Pode funcionar também com ServicePointManager.SecurityProtocol adicionando SSl3, TLS, TLS11, TLS12 e TLS13 mas no .NET 3.5 não tem TLS11, TLS12 e TLS13.


Getting Monit Web Interface and CLI to work on Ubuntu server

Question: I have a hard time getting monit to work on my Ubuntu 18.04.4.
I've installed monit via sudo apt install monit, then I've enabled httpd like this:
set httpd port 2812 and
    use address localhost
    allow localhost
    allow admin:monit

This is basically the default configuration of monit. Then I restarted monit via sudo systemctl restart monit.
If I take a look at its log file at /var/log/monit.log, I can see that the monit web server should be running:
Starting Monit 5.25.1 daemon with http interface at [localhost]:2812

On the server, I have ufw running, output of sudo ufw status verbose:
root@v22017062828950292:~# sudo ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
2812/tcp                   ALLOW IN    Anywhere
22/tcp                     ALLOW IN    Anywhere
8080/tcp                   ALLOW IN    Anywhere
127.0.0.1 2812/tcp         ALLOW IN    127.0.0.1
127.0.0.1 80/tcp           ALLOW IN    127.0.0.1
2812/tcp (v6)              ALLOW IN    Anywhere (v6)
22/tcp (v6)                ALLOW IN    Anywhere (v6)
8080/tcp (v6)              ALLOW IN    Anywhere (v6)

However, if I execute monit status, I get:
Monit: the monit HTTP interface is not enabled, please add the 'set httpd' statement and use the 'allow' option to allow monit to connect.

I've tried binding monit to 0.0.0.0 like this:
set httpd port 2812 and
    use address 0.0.0.0
    allow 0.0.0.0/0.0.0.0
    allow admin:monit

Then I can connect via browser and the IP of my server to the Web Interface, but monit status still outputs, that the http interface is not enabled.
I'm currently running out of ideas, since with the last configuration I can clearly reach the web interface from my browser but not via the command line interface.
I also tried disabled ufw with sudo ufw disable, resulting in the same problem, that the CLI can not connect to the web interface.
Do you have any more idea, what could be wrong?
Answer: What happens of you do sudo monit status? Where did you put your configuration at?
The monit client must be able to read the configuration to run the status command. It needs to know the port and username/password to connect.  If you properly secured your config with the password, it would only be readable by root.
Comment: Same message for `sudo monit status`. The configuration file is the default location at `/etc/monit/monitrc`. Also, monit is using that configuration file, as stated above, because I can make it work browser access, but not CLI access. So the config is readable.


Prove that $\sigma_2 = U \sigma_2 U^\top$ for all $U\in\operatorname{SU}(2)$

Question: Let $\sigma_1,\sigma_2,\sigma_3$ be the Pauli matrices. Prove that $U\sigma_2 U^\top=\sigma_2$ for all $U\in\operatorname{SU}(2)$.
I can prove that $U\sigma_2 U^\top= \pm \sigma_2$ using the fact that $U\sigma_2 U^\top$ is skew-symmetric and that the determinant is $1$, but I can't differentiate between $+1,-1$.
Answer: Let $u,v\in\Bbb C$ such that $|u|^2+|v|^2=1$. Then $$U\sigma_2U^\top=\begin{pmatrix}u&v\\-\bar v&\bar u\end{pmatrix}\begin{pmatrix}0&-i\\i&0\end{pmatrix}\begin{pmatrix}u&-\bar v\\v&\bar u\end{pmatrix}=\begin{pmatrix}i(-uv+uv)&-i(u\bar u+v\bar v)\\i(u\bar u+v\bar v)&i(\bar u\bar v-\bar u\bar v)\end{pmatrix}=\sigma_2.$$


Magento: Get Image Gallery in list.phtml

Question: How can I grab the image gallery into the category page in Magento, for a loaded product?
this->getImageGallery($_product)

, won't work..
Answer: $product = Mage::getModel('catalog/product')->load($_product->getId());

foreach ($product->getMediaGalleryImages() as $image) {
    echo var_export($image->getUrl());
}

Comment: this solution adds a significant load to the page is list is long.
Comment: Just one side note. The `getMediaGalleryImages()` method returns only the enabled images.
Comment: Is it possible to get url of resized image using above code ?
Comment: @Anand you do
Comment: Because it loads each full product item, it does add about 500ms to our TTFB for the catalog pages (64gb ram 3.9ghz 8core server) any other ideas?
Comment: @RickyOdinMatthews i want to call only two images of the product on mouseover and onmouseout. what should i do?
Answer: Here's another method which doesn't require loading the entire product object.
<?php $media_gallery = $_product->getMediaGallery(); ?>
<?php foreach ($media_gallery['images'] as $_image):?>
    <img src="<?php echo $this->helper('catalog/image')->init($_product, 'image', $_image['file'])->resize(135); ?>" alt="<?php echo $this->escapeHtml($_image['label']) ?>" />
<?php endforeach; ?>

Comment: To get this to work on list.phtml, I had to add the code; `$_product->getResource()->getAttribute('media_gallery')->getBackend()->afterLoad($_product);`


Pegar informações de um "Object"

Question: Estou usando uma API para pegar alguns dados de filmes, porém eu queria pegar somente as informações "name" dos gêneros, que são "Ação, Aventura, Comédia, Fantasia".
Porém o numero de gêneros nem sempre é o mesmo, as vezes são 2, 3..
genres: [
    {id: 28, name: "Ação"},
    {id: 12, name: "Aventura"},
    {id: 35, name: "Comédia"},
    {id: 14, name: "Fantasia"}
]

Estou usando o seguinte código:
$.getJSON('https://api.themoviedb.org/3/movie/166426?api_key=MINHA-API&language=pt-BR').then(function(response) {
                    console.log(response.genres);

Ao usar desse modo, o console retorna 4 Object e dentro deles informações id e name
(4) [Object, Object, Object, Object]

Se eu usar
console.log(response.genres[3].name);

Ele me retorna o gênero do objeto 3, que é "Fantasia", mas se eu procurar um filme que possua 2 gêneros por exemplo, ele já da erro.
Answer: Basta utilizar o método map do array e retornar apenas o atributo name:
let names = genres.map(genre => genre.name);

Veja o exemplo:

const genres = [
    {id: 28, name: "Ação"},
    {id: 12, name: "Aventura"},
    {id: 35, name: "Comédia"},
    {id: 14, name: "Fantasia"}
];

let names = genres.map(genre => genre.name);

console.log(names);
Comment: Bom, com esse código ele sempre me retorna esses 4 gêneros.
Tbm há outros gêneros que podem ocorrer, não só esses 4
Comment: Sim, porque eu coloquei apenas 4 no exemplo. Você precisa adaptar para o seu problema, colocando `response.genres.map(genre => genre.name)`
Comment: Funcionou perfeitamente, obrigado mesmo.
Comment: @YuriFrança você pode marcar a resposta como aceita utilizando o botão **✓** logo abaixo da pontuação da resposta, no lado esquerdo da mesma.

Pegar informações de um "Object"


Create Windows application from an existing RDLC file

Question: I have created a few reports that run on report server.
There was an evaluation period 180 days for report server and our company decided not to buy a license.
Is it possible
to utilize the RDLC files and create from them a few windows applications (winforms)?
If so, could you shortly describe the steps?
Comment: I'm inclined to say "no you can't" as you still need the reporting services back end to render the reports regardless of how or where you call them from!
Comment: You can build your report using ReportViewer Class & Data Objects as datasource. Then get the data and render it using .NET application.
Answer: There exists a ReportViewer control that can display rdlc reports from a server or local machine in a WinForms application. If that is a possible option you can work with, try looking into it. Here is some documentation from Microsoft on Using WinForms ReportViewer Control.
There is a dedicated segment in the article above that talks about Viewing reports in local processing mode


From two dates and frequency get daterange list

Question: I have two dates:
'1990-01-01'
'2020-02-18'
I would want to convert them in a date range list of as maximum, 25 years:
[ ['1990-01-01', '2015-01-01'], ['2015-01-01', '2020-02-18'] ]

Or as maximun, 5 years:
[ ['1990-01-01', 1995-01-01'], [1995-01-01', '2000-01-01'], ['2000-01-01', '2005-01-01'], ['2005-01-01', '2010-01-01'], ['2010-01-01', '2015-01-01'], ['2015-01-01', '2020-01-01'], ['2020-01-01', '2020-02-18'] ]

I tried with pandas.interval_range with no success.
Answer: Looks like you need pd.date_range.
Ex:
data = pd.date_range('1990-01-01', '2020-02-18',freq="5YS")
print(data)

Output:
DatetimeIndex(['1990-01-01', '1995-01-01', '2000-01-01', '2005-01-01',
               '2010-01-01', '2015-01-01', '2020-01-01'],
              dtype='datetime64[ns]', freq='5AS-JAN')

Comment: Maybe just adding `list(zip(dti[:-1], dti[1:]))` should do it
Comment: OP seems to want intervals though
Comment: That is what I tried. But i am not getting the final interval ( ['2020-01-01', '2020-02-18'] )
Comment: @Alfonso_MA. Add an additional check and append `end`: ex: `if '2020-02-18' not in data:
    data = data.append(pd.DatetimeIndex(['2020-02-18']))`
Answer: Perhaps dateutil.rrule fits your needs. You can define a rule to generate all the datetimes you need, for example:
dstart=datetime.datetime(2001,1,1)
for a in rrule(YEARLY, dtstart=dstart, interval=5, count=5):
    print(a)

Grouping datetimes in pairs is left as an exercise to the reader ;-)
Answer: You can use pd.date_range. Since the spacing between the generated dates must be of 5 years, you'll have to add the end date yourself, then create the intervals from the generated dates:
start = '1990-01-01'
end = '2020-02-18'

s = pd.date_range(start, end, freq='5YS').append(pd.DatetimeIndex([end]))

print(s)
DatetimeIndex(['1990-01-01', '1995-01-01', '2000-01-01', '2005-01-01',
               '2010-01-01', '2015-01-01', '2020-01-01', '2020-02-18'],
          dtype='datetime64[ns]', freq=None)

Then use zip to create the interval:
list(zip(s[:-1], s[1:]))

[(Timestamp('1990-01-01 00:00:00'), Timestamp('1995-01-01 00:00:00')),
 (Timestamp('1995-01-01 00:00:00'), Timestamp('2000-01-01 00:00:00')),
 (Timestamp('2000-01-01 00:00:00'), Timestamp('2005-01-01 00:00:00')),
 (Timestamp('2005-01-01 00:00:00'), Timestamp('2010-01-01 00:00:00')),
 (Timestamp('2010-01-01 00:00:00'), Timestamp('2015-01-01 00:00:00')),
 (Timestamp('2015-01-01 00:00:00'), Timestamp('2020-01-01 00:00:00')),
 (Timestamp('2020-01-01 00:00:00'), Timestamp('2020-02-18 00:00:00'))]


Degrees of freedom in emmeans package

Question: This is my first time uploading, so please bear with me.
I am currently trying to do a post-hoc test with three interaction term (time X support X NFC).
We did a follow-up on participants' well-being for four time points (Time1 ~ Time 4), and assessed their support and their NFC once in Time 1.
My model is a mixed model (used lme function) with time as a random slope, and participants' ID as a random intercept. The dependent variable is well-being. I ran an emmeans as below:

The question I have is that post-hoc analysis shows df that are either 1825 or 3005. However, between time points, participants were lost (N = time 1: 1833 > time 2: 1191 > time 3: 984 > time 4: 842; total observations are N = 4850) and I can't really understand why the degrees of freedom are same over all the time conditions.
I have been struggling to understand this output for days and would highly appreciate if someone explain this to me. Thanks in advance!
Comment: The df are higher when you compare two times with the other factors the same, because that is a within-subject comparison. But with so many df, there is really no difference between 1825 df and 3005 df, or 1000 df for that matter. So understanding the df is not something to worry about here.
Comment: The df are the same because your model (not shown) evidently pools the variance estimates together. I imagine you have ONE estimate of residual SD and ONE estimate of subject SD. Do `VarCorr(model5)` to see those estimates. BTW, are you really sure you want to compare all combinations of those three factors?
Comment: Thank you for the comments:) I really appreciate it!

My model is:

AFFECT~1+PO+SES+age+sex+support*NFC*(time+I(time^2)+I(time^3)), random=~(time+I(time^2)+I(time^3))|ID

NFC is the moderator, and support*time is how supporting someone led to different affective well-being at each time points. Therefore, I am trying to look into three-way interaction of NFC*support*time.
Comment: Like what you said, I am also a bit worried about comparing all combinations of the three factors (and whether it is a good approach when cubic term is included as a random slope)....But my advisor asked me to at least look into it. If there is a better approach, please do tell me! I would appreciate any input on this matter:)
Answer: Based on a comment as well as the OP, I gather that two of the three predictors involved in the interaction of interest are continuous covariates. One of them, NFC, appears only as a linear term, and the other, time, is modeled using a cubic polynomial.
If you had three actual factors, there are contexts in which testing pairwise comparisons among all factor-level combinations, though even then, I think most people would do only selected such comparisons, e.g., simple comparisons of one factor for each combinations of the other two. Otherwise, you lose a huge amount of power in multiplicity adjustments for the scads of possible comparisons, many of which you probably don't really care about.
But with polynomial trends in the model, I would never involve them in pairwise comparisons. Also, anything more than two levels of NFC is superfluous because a comparison of any two different values is a test of its linear trend. So one suggestion I would make is to test a suitable set of interaction contrasts. For example
emm1 = emmeans(model5, ~ NFC * support * time,
    at = list(time = 1:4, NFC = c(-1,1)),
    type = "response", lmer.df = "satterthwaite")
emm1  # list the estimates

contrast(emm1, interaction = c("pairwise", "pairwise", "poly"))

This would give you tests of interactions of pairwise comparisons of the first two factors with linear, quadratic, and cubic contrasts of the time trend.
There are other approaches, for example, using emtrends() to estimate the polynomial trends for time, and then conducting pairwise comparisons of those. See vignette("interactions", "emmeans") for more discussion and examples.
Comment: I also suggest supplementing this with some visual interpretations of the model, e.g., `plot(emm1)` or `emmip(emm1, support ~ time | NFC)` In these plots, it might be helpful to include more `NFC` values so you can visualize the different possibilities as it changes.
Comment: Thank you so much for explaining the alternatives! It helped me immensely to get a clear picture of my model. Thanks again for addressing my questions.

Degrees of freedom in emmeans package