how to filter table ( table data is populated from JSON file) by using jQuery?

Question: I have a table which has some user details. I have populated those data from JSON. At the bottom of the table , i have a text field which is provided for users who can type some information to filter the table.
For example,
Consider a table contains 10 rows. the first 6 rows contains developer details and the last 4 rows contains tester details. If a user type developer in the text box , then the table should display the rows, which contain information about the developer. how can i achieve this by using jQuery ?
I don't want to post my wrong code here. so please don't ask me to post some code.
Answer: You can use the filter() jquery function to filter through the rows until you find the ones which  matches what you write in a text box and filter after you click a button.
Example:
HTML:

Member	Stuff

Developer	1

Developer	2

Developer	3

Tester	4

Tester	5

<input type="text" id="filter" />
<input type="button" id="btnFilter" value="Filter" />

Javascript:
$(document).ready(function() {
    $("#btnFilter").click(function() {
        $("#myTable tbody tr").show();
        if($("#filter").val.length > 0) {
            $("#myTable tbody tr").filter(function(index, elm) {
                return $(elm).html().toUpperCase().indexOf($("#filter").val().toUpperCase()) < 0;
            }).hide();
        }
    });
});

Working fiddle: http://jsfiddle.net/tKqw9/1/
EDIT: Added toUpperCase() to the text compare part so it compares case insensitive.
Also added a compare to the whole
 element content so it can search over any cell value in the row.
Comment: Nice solution. One suggestion: make the text comparison case-insensitive so the user could type in either "Developer" or "developer" and still get valid results.
Comment: @JasonTowne Thanks. I updated the answer to search case insensitive and search over the whole `` content
Comment: @RobertoLinares can you explain index, elm in function?? and why you have used .toUpperCase() for two times ?
Comment: i have populated the data of table from json file. I tried your suggestion but its not working..
Comment: @arjun the `index` and `elm` parameters are default parameters that you can use in jquery looping functions like $.each(), $.map and $.filter() where `index` is the current element's index in the array and `elm` is a reference to the current element being used in this loop iteration. Also, I used `toUpperCase()` twice to be able to make a case insensitive comparison. The first use is to uppercase the HTML element content and the second use is to uppercase the textbox value.
Comment: @arjun consider also that in my code, I bind HTML elements to the jQuery functions and events via its ID attributes. Can you check you are binding the correct elements? You could post some of your HTML so I could update my answer referencing your elements.
Comment: Such a beautiful solution.
Answer: You may want to consider a plugin like Datatables. It has built in filter functionality similar to what you're looking for.
http://www.datatables.net/
If you don't want to or can't use a plugin there are other options out there.
Comment: Can i make it without using any plugins and just by using pure jquery ??
Comment: @arjun Absolutely. Check out my edit with a link to a similar question that was already asked and answered. The reason I recommended Datatables is because it included the filter feature you requested out of the box and includes other handy features like pagination and column sorting. If you don't need that other stuff then by all means write your own filter function.


Get bootstrap-datetimepicker to appear on field and on icon, without duplicating

Question: I am trying to get bootstrap-datetimepicker to work the way I want it to. Normally the datetime selector only pops up when clicked on the icon. But I want it to pop up when clicked on the field and on the icon.

      <input class="form-control" type="text" name="leaving_time" id="leaving_time">

I found out that if I added the same class (datepicker) on the input field the popup will appear when clicked on the field, which is what I want.
The problem however is that if I click on the field first and then the icon the date picker that popped up when clicked on the field does not disappear. Which means there ends up being two date pickers on the screen.
However if I click on the glphyicon first and then the field it works properly. As in, when the field is clicked the date picker on time disappears and the on field appears. How do I make it so that the same thing happens if the field is clicked first and then the icon.

      <input class="form-control datepicked" type="text" name="leaving_time" id="leaving_time">

Here is the javascript codes that calls datetimepicker:
$(document).on('ready page:change', function() {

$('.datepicker').datetimepicker({
   format: 'MMM Do YYYY',
   pickTime: false,
   collapse: true
});
});

Answer: You can simply focus the input when clicking on the input group addon span.

$('.datepicker').each(function(k, v) {
  var $input = $(v).find('.make-datepicker');
  $input.datetimepicker({
    format: 'MMM Do YYYY',
    collapse: true
  });
  $(v).find('span.input-group-addon').click(function(e) {
    $input.focus();
  });
});

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/v4.0.0/build/css/bootstrap-datetimepicker.css" rel="stylesheet" />

  <input class="form-control make-datepicker" type="text" name="leaving_time" id="leaving_time">

Comment: Works beautifully, thank you. Is there away to refactor the code if I have multiple pickers, ex: date picker and a timepicker?
Comment: yes, you can simply change the parent div (`.datepicker`) classes or change the class being used (ie use `.datetime`).
Answer: Late answer but I've found a better solution for anyone need.

    <input type="text" id="testdate" name="testdate" class="form-control" value="">


Is exam expired or not using laravel controller

Question: I have two dates one is exam_start_date_time and exam_end_Date_time.When i click on "start Exam"it goes to laravel function and checks if current datetime is passed end datetime it need to show "exam expired" else it start the exam.
<code>$t1 = \Carbon\Carbon::parse($questionData->exam_end_date_time);
$t2 = \Carbon\Carbon::parse($questionData->exam_start_date_time);
if (\Carbon\Carbon::now()->gte($t1)){
    return redirect()->back()->with('error', 'Exam Expired !!');
}
</code>
but here i get exam expired even the exam enddatetime remains time to close .
Answer: Try this
<code>$t1 = \Carbon\Carbon::parse($questionData->exam_end_date_time);
$now = \Carbon\Carbon::now();

if($t1 < $now)
{
    return redirect()->back()->with('error', 'Exam Expired !!');
}
</code>
Comment: show me your `$questionData->exam_end_date_time` value ? format ?
Comment: its not working, still time remains and shows exam is expired
Answer: maybe you are looking for this....
i think it will work for you
<code>$endTime = \Carbon\Carbon::parse($questionData->exam_end_date_time);
    $startTime = \Carbon\Carbon::parse($questionData->exam_start_date_time);
         if (\Carbon\Carbon::now()->between($endTime,$startTime)){
               return redirect()->back()->with('error', 'Exam Expired !!');
         }else{
            $left = Carbon::now()->diffInMinutes($endTime ,false);
            $left = Carbon::now()->diffInDays($endTime ,false);
            $left = Carbon::now()->diffInHours($endTime ,false);
            return redirect()->back()->with('info', $left.'Time Left !!');
         }
</code>
Comment: if exam is on 22/09/2020 and start time is 12.00 pm and end time is 1.00 pm. and current time is 12.42pm then exam have time. its not finished. then the exam is not expired
Comment: what do you want ? which variable are you using ? min,hours,days ?
Comment: min is using beacuse i have a timer here.
Comment: use `$left.' Minute Time Left !!'
Comment: check local time configuration
Comment: @SindhuDiya go config folder and set your time  'timezone' => 'Asia/Dhaka', or your country ... i think it will help you
Comment: if press start of exam  before actual startdate of exam ,how should i test that condition
Comment: it will be like this... `if(\Carbon\Carbon::now() < $startTime){}` ...
Comment: @SindhuDiya where are you ? are your problem did  not  solve yet ?


How does R calculate prediction intervals in the forecast package?

Question: I have a large dataset with different factors that I want to forecast to the future. These forecasts I will then later on use as inputs for a Monte Carlo simulation. My idea would be to use arima forecasting on the different variables. Subsequently, I would use the resulting prediction interval as inputs for the Monte Carlo simulation.
Using R, (I think) I get what I want by using the following.
First, I set some parameters FC_years <- 4 FC_boundaries <- 68 # This would be 1 sd
Next, the forecasting is done by: fit <- auto.arima(POP) forecast <- data.frame(forecast(fit,FC_years,level=FC_boundaries))
What is now very important for me in order to use these results for a MC simulation, is to know how R calculates the prediction interval (I have been searching for quite a while now, but I can't get a clear answer), and how this interval is distributed (I assume it is normal, but again, I can't get a clear answer).
Just as an example, the following dataset could be used:
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 68235 72498 76700 80326 83195 85447 87276 89004 90858 92894 94995 97015 98742 100031 100830 101219 101344 101418 101597 101932 102384 102911

Can anybody give me any hints?
Answer: Unless you are using the forecast function's bootstrap = TRUE option the forecast package's ARIMA intervals are calculated by passing an ARIMA object to predict(). The intervals assume that residuals are normally distributed . If you look at the R documentation for predict.Arima() you will see that it uses KalmanForecast() to produce them.
See the following link for a good description of how to calculate a prediction interval for an ARIMA model manually:
https://onlinecourses.science.psu.edu/stat510/node/66
The code is available on Rob Hyndman's github page here:
https://github.com/robjhyndman/forecast/blob/master/R/arima.R
An exception to the resulting prediction intervals being normal around the point estimate is if you have set lambda (are using a Box-Cox transformation) in which case they will not be normal after the back-transformation.
Answer: https://www.otexts.org/fpp/2/7 Goes into some further detail.
95% prediction interval is $y^t \pm 1.96 \sigma$
and
80% prediction interval is $y^t \pm 1.28 \sigma$
Where $y^t$ is a forecast value and $\sigma$ "is an estimate of the standard deviation of the forecast distribution".


Table data and horizontal rule spacing

Question: Here is the fiddle .
How can I assign the Horizontal rule to the top ? Means it should touch/overlap the table border.
Thanks.
Answer: http://jsfiddle.net/haWd5/2/
hr TAG SHOULD MARGIN:0 ;  PADDING : 0
Answer: That's you want http://jsfiddle.net/haWd5/1/ ?. Write like this:
hr{
    margin:0;
    padding:0;
}
td{vertical-align:top;}

Table data and horizontal rule spacing


Erro em Slider HTML

Question: Olá! Tenho um slider em HTML e estou implantando PHP para torná-lo gerenciável, todavia, ao colocar o PHP, o slider parou de funcionar. Acredito que seja um erro na parte a seguir do código:
                echo '
';
            echo '
';
            echo '
';
            echo '
';

Acredito que a concatenação esteja errada. O que fazer?
Answer: O problema aí é uma mistura de aspas na parte HTML mesmo.
Uma maneira mais simples é fechar o PHP para cair no modo HTML puro, assim você pode usar aspas duplas e simples para separar os parâmetros em HTML dos objetos em JS:
<?php
   // ... resto do codigo ...
?>

<?php
   // ... resto do codigo ...
?>

Outra é usar HEREDOC, se quiser futuramente usar variáveis do PHP sem precisar de echo:
echo <<<HTML

HTML;

Mais detalhes sobre HEREDOC aqui:

Para que serve <<< EOH no PHP?

Erro em Slider HTML


Should I disable all UI modules once the site is in production?

Question: Just wondering if I should I disable all UI modules once the site is in production?
e.g.: Context UI
Most of them are not required for any other module.
Answer: This is probably considered best practice in terms of performance because on every call each module is loaded into memory and executed.
However you may find it annoying to have to constantly re-enable the modules, particularly with views or rules.
Comment: I agree. I guess the question is how much the performance is improved by disabling these module... to hang this in the balance.
Comment: To get around having to constantly disable and re-enable modules, use the feature in the admin menu module that allows you to specify which modules to disable with one click. See http://drupal.org/node/944810#comment-3646430 for more info.


Is this an acceptable definition for REST API endpoints?

Question: I am looking for a REST API design that I can use to manage entities and relations.
An important point is that the REST API can also be used for imports. There is also the special feature that a foreign key can be specified for entities. If an entity with this foreign key already exists, it should be updated, otherwise it should be created.
I wanted to avoid additional URL's like /bulk or /import if possible. So I guess I bent the pure REST rules a bit.
Here is my definition so far. Is this still acceptable or do the experts here get a cold shiver?
Entities

HTTP verbs
Plural URL
Singular URL

GET
/entities - retrieves collections of Entities resources. It is possible to use Request-Parameter or filters with a HTTP-Body like {"filter":{...}}
/entities/{id} retrieves single Entity resource

POST
/entities - creates or update a single Entity resource.
-

PUT
/entities - create or update collections of Entity resources. Use HTTP-Body [{...}.{...}]
/entities/{id} - update single Entity resource

PATCH
/entities - patch collection of Entity resources, see JSON Patch
/entities/{id} - patch single Entity resource, see JSON Patch

DELETE
/entities - delete Entity resources. It is possible to use Request-Parameter or filters with a HTTP-Body like {"filter":{...}}. Without filter all Entities will be deleted
/entities/{id} - delete single Entity resource

Relations

HTTP verbs
Plural URL
Singular URL

GET
/entities/{id}/relations - retrieves collections of Entities relations. It is possible to use Request-Parameter or filters with a HTTP-Body like {"filter":{...}}
/entities/{id}/relations/{id} retrieves single Entity relation

POST
/entities/{id}/relations - add a collection of Entity relations to the relations. Use HTTP-Body [{relation_id},{relation_id}]
-

PUT
/entities/{id}/relations - replace collection of Entity relations
-

PATCH
/entities/{id}/relations - patch collection of Entity relations, see JSON Patch
-

DELETE
/entities/{id}/relations - delete Entity relations. It is possible to use Request-Parameter or filters with a HTTP-Body like {"filter":{...}}. Without filter all Entity relations will be deleted
/entities/{id}/relations/{relation_id} - delete single Entity relations

States

HTTP verbs
Plural URL
Singular URL

POST
/entities/activate - activate Entity resources. It is possible to use Request-Parameter or filters with a HTTP-Body like {"filter":{...}}
/entities/{id}/activate - activate single Entity resource

POST
/entities/deactivate - deactivate Entity resources. It is possible to use Request-Parameter or filters with a HTTP-Body like {"filter":{...}}
/entities/{id}/deactivate - deactivate single Entity resource

The status to be set can be named arbitrarily. For example also like /entities/{id}/star and /entities/{id}/unstar.  Enumerations are also possible. Like e.g. /entities/{id}/speed/slow, /entities/{id}/speed/medium, /entities/{id}/speed/hight.
Answer:
Is this still acceptable or do the experts here get a cold shiver?

Not acceptable - the description above suggests that you are trying to create specialized versions of HTTP methods to do what you want, rather than relying on the common standardized definitions that we all share.
My guess is that you haven't quite internalized the idea that your resource model and your data model are different things.
GET/PUT/POST/DELETE message semantics apply to the resource model.

I wanted to avoid additional URL's like /bulk or /import if possible.

You can, technically, do that, but you may be making your life harder without realizing any real benefit.
It normally takes the form of HTTP POST combined with distinct payloads for each of the different kinds of actions, and handler implementations that analyze the payload to understand the work to be done.
For example, on the HTML web, our only out-of-the-box option for unsafe transfer of information to the server is a POST form, so if we want to achieve different effects on the same resource, we include in the body of the request metadata so that the server can understand our intent.
Comment: One reason for this was to avoid that each relation has to be set by a separate request.
If I understand this correctly, the right way would be to define own URL's for these cases which then use `POST`?


Using constant versus changing random seeds for cross validation hyperparam optimisation

Question: If I understand things correctly, in a nested cross validation the inner cross validation is for optimising over the search space of hyperparams, and the outer loop is validating the accuracy the optimal hyperparams determined by the inner loop. i.e.

outer cross validation

hyperparameter search

inner cross validation

We then have the choice of either reusing the same inner cross validation splits (i.e. the same random seed) or we can randomise (i.e. change the random seed) for each inner cross validation of every hyperparam vector candidate we investigate.
On the one hand, I can see that by keeping the seed the same we are only changing one variable (namely the chosen vector of hyperparam candidates), which makes the hyperparam optimisation easier. i.e. if both the hyperparams and data are changing, optimisation is having to optimise over more free variables.
On the other hand, if we randomise the folds for each hyperparam vector candidate there is less chance we will find a local minima / maxima due to the chance of an "unlucky" single choice of inner cross validation split producing a model that is optimal for that single split, but not for other possible splits.
How does the choice of randomise versus not randomise for the inner cross validation affect the hyperparameter vector search optimisation?
I suspect that the answer is very dependent on the size of the hyperparam search space (i.e. the difficulty of optimising the hyperparams) versus the distribution of the data (i.e. the probability of choosing a really "bad" split and wrongly concluding we've found the best vector of hyperparams).
Answer: If you search for a zillion hyperparameter combinations, you will start to overfit whatever you're testing those against.
Therefore, I'd be tempted to take one single train/validate split, do your hyperparameter search on that. And then, and only then, evaluate it against some other split or fold or test/validation data set.
Using random splits for each set of parameters sounds like something to avoid because:

as you say, for some hyperparameter options, you'll 'get lucky', jsut because of the train/validate split giving a randomly high score
you're basically overfitting to every possible train/validate split of your data, leaving you no novel splits to validate against
Comment: The outer cross validation should prevent overfitting. There is no leakage from the inner hyperparameter optimisation into the outer cross validation.

As the inner cross validations are independently randomised and therefore independent of the candidate hyperparameters the randomisation would then generate (random, possibly biased) noise in the hyperparameter optimisation. I'm guessing this noise probably doesn't greatly affect the optimisation, as it is likely the vast majority of inner cross validation splits are representative of the entire training data set for a large enough data set.
Comment: You're running hyperparameter optimization for each of the outer splits right? That means you are trying a bunch of hyperparameters against a whole bunch of splits. As far as "for a large enough data set", such a thing is rare in practice ;-)  If you have infinite data, you are in a good position :-)  Otherwise, generally speaking, one increases the capacity of one's model to match the amount of data available, and the overfitting problem comes back.
Comment: (If I'm misunderstanding your two loops, perhaps you can add some additional detail in the question about how you are running the two loops, exactly what hyperparameters you are trying, and where etc?)
Comment: I've edited the question to show the ordering of the three nested loops.
Comment: Can I clarify your second bullet point:  "every possible train/validate split of your data" as referring to the outer cross validation and not the inner, then? I had assumed you were talking about the inner cross validation. If so, what you're implying is that the hyperparameter search may end up spending more time searching the inner (randomised) cross validation space than the hyperparameter space, i.e. the choice of inner cross validation split may become more important than the choice of hyperparameters for *every* outer split.


Finding Standard Deviation

Question: I am having trouble finding the standard deviation of a list, and not quite sure what I am doing wrong. Code is below any help would be appreciated.
n = len(combTimeArray)

numbers = []

mean = sum(combTimeArray)/len(combTimeArray)

numbers.append(int(combTimeArray)

for n in range(len(numbers) - 1)
        if numbers[n] > mean
                numbers.append((numbers[n] - average)**2)
        if numbers[n] < mean
                numbers.append((mean - numbers[n])**2)
        SD = (sum(numbers)/len(numbers))**(1/2.0)
        print SD

Comment: Is this a homework? If not, use `numpy.std`.
Comment: `average` on said line 73 is never defined. I think you mean `mean`
Comment: @MartijnPieters However it must be noted that the OP accepted the suggested edit http://stackoverflow.com/review/suggested-edits/3603438
Comment: And what error are you actually getting? please post the traceback
Comment: @KDawG: Ah, interesting. If the OP feels that that edit better reflects the actual code used, then that's always better.
Comment: @KDawG: however, with no actual problem description here (no input or expected output, errors or wrong output is shown), it is still entirely possible that the colons are a major problem the OP was facing. :-P
Comment: output errors are:

 File "test.py", line 73
    numbers.append((numbers[n] - average)**2)
Comment: What part would
import numpy
SD = numpy.std(combTimeArray)
replace?
Answer: import numpy
SD = numpy.std(combTimeArray)

Comment: what part would

import numpy
SD = numpy.std(combTimeArray)

replace?
Comment: The only thing missing is the assignment of combTimeArray, which is also missing from your question. This code will then put the standard deviation in SD.
Answer: it is hard to understand your code :p At first you can replace the for loop with a for-each loop -> this makes your code much easier to read and remove the ugly numbers[] statement.
Here is my example code (if you don't want to use numpy or smth. similar)
from math import sqrt,pow
numbers = [2,4,4,4,5,5,7,9]

def standardDeviation(l):
   mean = sum(l)/len(l)
   differencelist = []
   for elem in l:
      differencelist.append(pow(elem-mean,2))
return sqrt(sum(differencelist)/len(differencelist))

Answer: It's been a while since I had to do standard deviation so you should double-check the math part yourself (and everyone is correct to tell you to do numpy unless you have to do this out for homework or some other reason) but some notes:

Python has an absolute value function
You can do a for n in numbers rather than accessing each number through an index--much simpler and cleaner.
It looks like your numbers array first stores all the values, and then you're adding on the difference of each number from the mean to the same list.  Either make a second list or look into the map function if you want to be extra-fancy.

Finding Standard Deviation


What is the "endpoint" in flask's .add_url_rule()?

Question: Consider the following code
import flask

class API:
    def hello(self):
        return flask.Response('hello', 200)

api = API()
app = flask.Flask(__name__)
app.add_url_rule('/', 'hello', api.hello)
app.run()

It returns "hello" upon a GET call to /.
The documentation for add_url_rule states that

[add_url_rule] works exactly like the route() decorator.

It requires however at least three parameters. The first and third one are understandable and mimic @route(). What is the second one (hello in my case)?
The documentation further states that this is

endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint

What does this mean? Why isn't the URL (/) and the method to call (api.hello) sufficient? What is the role of the "endpoint"? How is it exactly used?
Answer: It's the name for the route; the one you'd use in the url_for() function for example. The endpoint name is the registration key for views, a symbolic name by which you can reference the route from other parts of your application.
@route() takes the same parameter; the default is the name of the decorated function. This is documented both in the add_url_rule() documentation as well as the documentation for @route():

endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint.

(bold italic emphasis mine).
Note that the example in the documentation tried to show the same:

Basically this example:
@app.route('/')
def index():
    pass

Is equivalent to the following:
def index():
    pass
app.add_url_rule('/', 'index', index)

Note that the second argument 'index' matches the function name.
Comment: Yes, this is what I read in the documentation, I am trying to understand how this is useful vs. just the URL and the called method. You mentioned `url_for` - I am reading the doc for it (and try to understand the rationale in "Three good reasons for it"). Thanks for the pointer.
Comment: @WoJ: because a short symbolic name trumps a url path that could have patterns in it. The symbolic name is less likely to change as your requirements change.
Comment: @MartijnPieters the Flask just updated arguments for `add_url_rule`.
since this is marked as accepted, should you update the answer? to avoid confusing for next viewer, like me
Answer: import flask

app = flask.Flask(__name__)

class API:
    def __init__(self):
        app.add_url_rule("/", view_func=self.hello)

    def hello(self):
        return flask.Response("hello", 200)

if __name__ == "__main__":
    API()
    app.run()

Try this. If you want to run flask pass the variable to class and inside class run the application.


How do I answer apt installation questions non-interactively?

Question: Some packages ask configuration questions when installed with apt-get. That makes life awkward when I want to install something non-interactively.
How do I find out what questions a package will ask, and provide answers automatically?
(Context: I'm installing things using configuration management tools. But this probably applies in a wider range of cases.)
Answer: According to the apt-get man page, you can provide a config file for the package.

-c, --config-file
Configuration File. Specify a configuration file to use. The program will read the default configuration file and then
  this configuration file. See apt.conf(5) for syntax information.

Also note the -y option for automatically answering yes.

-y, --yes, --assume-yes
Automatic yes to prompts. Assume "yes" as answer to all prompts and
  run non-interactively. If an undesirable situation, such as changing a
  held package or removing an essential package, occurs then apt-get
  will abort.

According to this thread on the ubuntu forum, you can discover the questions or pre/post scripts in the DEBIAN folder of the deb archive, modify the scripts and repackage the deb. However, another remark is that sometimes an ncurses gui is used which makes things difficult. In short, there does not seem to exist an easy solution..


Adicionar variável expect

Question: Gostaria de criar um shell script que conecta na controladora CISCO para inserir os macAddres dos clientes, usando expect,  na verdade necessito criar um script para automatizar o processo.
Variaveis
mac_desejado ,descricao
comando controladora
<code>config macfilter add mac_desejado 0 management "descrição"

#!/usr/bin/expect -f
spawn ssh -l andre 220.127.116.11
expect "password: "
send "PASSWORD\r"
expect "ls\r"
send "exit\r"
</code>
Answer: <code>~#!/usr/bin/expect
set timeout 20
set ip [lindex $argv 0]
set mac [lindex $argv 1]
set desc [lindex $argv 2]

spawn telnet $ip

expect "User:"
send "user\r"

expect "Password:"
send "password\r"

expect ">"
send "config macfilter add $mac 0 management \"$desc\"\r"
expect ">"
send "save config\r"
expect "n)"
send "y\r"
expect ">"
send "exit\r"
</code>
Comment: Andre não use o campo de Resposta para fazer uma "edição da sua pergunta". Copie o código e edite a sua pergunta original!
Comment: Olá, eu encerrei a pergunta, pesquisei e fiz mais alguns testes e deu certo!

Adicionar variável expect


S is a system of representatives left cosets -> S^-1 system of representatives right cosets

Question: Let G be a group and let H is a subgroup of G. Prove the following:
If S is a system of representatives for the left cosets of H in G, then $S^{-1}=\{s^{-1}:s \in S\}$ is a system of representatives for the right cosets of H in G
How I tried to prove it:
s belongs to S -> $s=a*h_{1}$ for some $h_{1}$ belongs to H and for an unique a belongs to G.
$s=a*h_{1} -> h_{1}^{-1}*a^{-1}=s^{-1}$
a is unique -> a^-1 is unique, total amount of different a^-1=total amount of different a's=$[G:H]$(=number of left and right cosets). Thus proven that each s^-1 belongs to an unique right coset of G (since $h^{-1}_{1}\in H$ and $a^{-1} \in G$)
Is my proof ok? And if not, what can I improve about it? Thanks in advance
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Answer: Disregarding any of the mathematical content, usually we write proofs in $\LaTeX$ (or mathtype, in this case) and do not overuse mathematical symbols like $\forall$, $\exists$, $\Rightarrow$. This means that we write in full sentences and try to explain what we're doing with words. In your case, although the first part of your proof is logically correct, it is hard to digest for a reader. You could improve it by cleaning up some of the parts:

If $s \in S$, then we may write $s = ah_1$ for some $h_1 \in H$ and an unique $a \in G$. Taking the inverse of this equation gives us $h_1^{-1}a^{-1} = s^{-1}$.

And this applies to your entire proof.
In the next part, though, your logic is not clear. The number of unique $a$'s is not equal to $[G:H]$. If $s = ah_1$, then $sh_1^{-1} = a$. So $a$ is uniquely determined by our choice of $h_1 \in H$, and therefore we actually have $|H|$ choices for $a$. At this point, your proof breaks down.
Hint? To prove this, I would prove that $gH \mapsto Hg^{-1}$ is a well-defined bijection between between the left and right cosets of $H$ in $G$.
Comment: To make an example: Suppose $G = \mathbb Z$ and $H = 2\mathbb Z$. Following your argument, let $s = 1$ be the representative of $1\mathbb Z$. Then $1 = a + h_1$ for some $h_1 \in 2 \mathbb Z$ and an unique value of $a$. How many possible values of $a$ are there? Well, there's clearly more than than $[G:H] = 2$. Just take $h_1 = 0, 2, 4$. Then $a$ is (uniquely) $1, -1, -3$.
Comment: But by saying that, you would say that there are |H| different left cosets in G, per defintion the amount of elements in #S=|H|. But we also know per defintion that the system of representatives contains exactly one element from each left coset of G, so #S=[G:H]. Where am I going wrong here?
Comment: The number of choices for $a$ does not coincide with the number of cosets. My argument above shows this. I am not saying that there are $|H|$ different cosets of $G$. I am saying that there are $|H|$ different choices for $a$, and this is unrelated to the number of cosets of $H$ in $G$.
Comment: Well, do you agree when I say that when we let a belong to the integers, the amount of aH that is contained in G is [G:H]?
Comment: The number of $aH$ in $G$ is not equal to the number of distinct values of $a$, *under the restriction that $s = ah_1$.* (And to be clear, if there are no restrictions, then the number of distinct choices of $a$ would just be $|G|$.)
Comment: Really? Do you have a counter-example for that? Because by thm for every left coset aH and bH we have aH=bH v aH intersect bH is empty, so logically speaking it would be reasonable to think that for all the different left-cosets aH in G for some a belongs to G all the different values in total of a would be equal to [G:H] or am I missing some sort of definition of something?
Comment: You're talking about different things. Sure, there are $[G:H]$ different cosets of $H$ in $G$ and every coset is of the form $aH$ for some $a \in G$. Notice how there is no restriction on $a$. We're just saying *any* $a \in G$. The point is that once we add a restriction, like $s = ah_1$, the situation is different.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/106548/discussion-between-twstud-and-cxx).


Erro de permissões ao tentar enviar um arquivo com PHP

Question:

    <form action="" method="post" enctype="multipart/form-data">
        Selecione : <input name="arquivo" type="file">
        <input type="submit" value="Enviar">
    </form>

    <?php
    //Salva a foto com nome aleatório dentro da pasta
    $pasta = 'pasta-upload';

    $arq = $pasta . '/' . uniqid(rand(), true);

    $image = false;

    if (!chmod($pasta, 0755)) {
        echo 'Erro ao mudar as permissões';
    } else if (isset($_FILES['arquivo']['tmp_name'])) {
        if ($_FILES['arquivo']['error'] !== UPLOAD_ERR_OK) {
            echo 'Erro no upload';
        } else {
            $tmp = $_FILES['arquivo']['tmp_name'];

            $image = getimagesize($tmp);

            $ext = str_replace(array('image/', 'x-'), '', $image['mime']);

            $arq .= '.' . $ext;

            if (!$image) {
                echo 'Formato invalido';
            } else if (!move_uploaded_file($tmp, $arq)) {
                echo 'Erro ao mover o arquivo';
            } else {
                echo '';
            }
        }
    }
    ?>

Devolve o seguinte

Warning: chmod(): Operation not permitted in /Applications/XAMPP/xamppfiles/htdocs/tm/index.php on line 16
  Erro ao mudar as permissões.

Já tentei ir ao terminal e executar o comandos
sudo chmod 777 /Applications/XAMPP/xamppfiles/htdocs/tm/pasta-upload
cd /Applications/XAMPP/xamppfiles/htdocs/tm/
sudo chmod 755 /Applications/XAMPP/xamppfiles/htdocs/tm/pasta-upload

Estou a usar o XAMPP.
Comment: O erro persiste porque, mesmo que tenha alterado as permissões do diretório, você está tentando alterar novamente no código (e é o código que não tem permissões de fazer esta alteração). Tente substituir a parte do código `if (!chmod($pasta, 0755))` por `if (!is_writable($pasta))`.
Comment: funcionou obrigado
Answer: Para referências, o código em questão foi desenvolvido nesta pergunta.
O que acontece é que no código, mais precisamente na linha !chmod($pasta, 0755), você está tentando alterar as permissões do diretório definido $pasta, de forma a garantir que o mesmo possa ser gravado. O erro é gerado porque o PHP não possui permissões necessárias para fazer esta alteração. Por isso foi necessário que você executasse este comando manualmente:
sudo chmod 755 /Applications/XAMPP/xamppfiles/htdocs/tm/pasta-upload

Feito isso, você já definiu a permissão de escrita no diretório, então no código você não precisa fazê-lo novamente, mas o que precisa é garantir que o diretório possua esta permissão e isso é feito com a função is_writable. Desta forma, seu código ficaria:
...

if (!is_writable($pasta)) {
    echo 'O diretório não possui permissão de escrita.';
} else if (isset($_FILES['arquivo']['tmp_name'])) {
    if ($_FILES['arquivo']['error'] !== UPLOAD_ERR_OK) {
        echo 'Erro no upload';
    } else {
        $tmp = $_FILES['arquivo']['tmp_name'];

        $image = getimagesize($tmp);

        $ext = str_replace(array('image/', 'x-'), '', $image['mime']);

        $arq .= '.' . $ext;

        if (!$image) {
            echo 'Formato invalido';
        } else if (!move_uploaded_file($tmp, $arq)) {
            echo 'Erro ao mover o arquivo';
        } else {
            echo '';
        }
    }
}

...

Desta forma, o envio do arquivo somente ocorre quando o diretório possui as permissões necessárias.
Comment: Então o PHP não possui permissão porque porque o usuário proprietário não é o mesmo, se eu não me engano o usuário seria o `www-data`, eu ia comentar isto na resposta, mas eu estava para testar primeiro no Mac do trabalho.


Can I update $LATEST lambda version to point at an old function version

Question: I have a lambda function that I need to roll back and use a previous version.
The lambda is triggered by an S3 event, where S3 invokes the function ARN without any version or alias qualifier, therefore only uses the $LATEST
Due to IAM constraints in the organization, I'm unable to alter the s3 events to point to a specific Lambda version or alias.
Is there an easy way to update $LATEST to point to a previous version of the function?
Answer: I don't think you can "out of the box". What you can do is one of the following:

Open the Lambda version you want to restore, copy the code and then paste it in the Lambda console. You can now save the "new" code and it will behave like the "old" version

Or

If you are using Git (which I hope you do) you can revert the function repository to an old commit, restoring the project to the version you desire (if you know roughly what is the related commit before publishing)
Comment: The first option was the best for my situation, since I need to walk a client through the steps, and simpler is better :). I ended up having them navigate to the function version, selection 'Actions' then 'Export function'. Created a zip that they uploaded as the $LATESTS.  Thanks!
Comment: Right, totally forgot you can export functions as zip! Glad it worked ;)


Somar hora à uma data e hora com PHP

Question: Bom dia.
Fiz uma vasta pesquisa antes de perguntar, e não achei a resposta.
$row['data_saida'] = "2019-06-20";
$row['hora_saida'] = "08:35:02";

Essas duas strings vem do banco de dados, retornando a data e a hora separada (como mostrado acima), mas, gostaria de gerar uma previsão com base em outra string, que retorna do banco de dados. Ou seja:
$row['data_saida'] = "2019-06-20";
$row['hora_saida'] = "08:35:02";
$row['tempo_viagem'] = "02:30:02";

Gostaria de somar 02:30:02 com 2019-06-20 08:35:02, para obter a previsão de chegada.
Answer: Você pode efetuar essa operação com a classe Datetime em conjunto com o DateInterval
$row['data_saida'] = "2019-06-20";
$row['hora_saida'] = "08:35:02";
$row['tempo_viagem'] = "02:30:02";

$saida = sprintf('%s %s', $row['data_saida'], $row['hora_saida']);

$data  = new DateTime($saida);
$data->add(new DateInterval("P0000-00-00T{$row['tempo_viagem']}"));

$chegada = $data->format('Y-m-d H:i:s');

// Chegada com data pt-BR
//$chegada = $data->format('d/m/Y H:i:s');

echo $chegada;

Veja este fiddle (Clique no botão RUN F9)
Comment: Obrigado! Ajudou muito. :D
Answer: Você deve usar strtotime() com a string da data e hora seguido do intervalo que se quer adicionar. Ou seja, para adicionar hora, minuto e segundo teria que seguir a data e hora com '+X hours +Y minutes +Z seconds'. Para fazer isso pode-se manipular a string de duração que vem do banco como no exemplo abaixo:
$data = '2019-06-20';
$hora = '08:35:02';
$duracao = '02:30:02';

$data_hora= $data.' '.$hora ;
$duracao = vsprintf(" +%d hours +%d minutes +%d seconds", explode(':', $duracao));

print date('Y-m-d H:i:s',strtotime($data_hora.$duracao));

Veja funcionando:
http://sandbox.onlinephpfunctions.com/code/6207ff0ca1897f5c1443be549c923548020e22a6
Comment: Perfeito meu nobre. Obrigado! :D

Somar hora à uma data e hora com PHP


Heroku with rails 4 app fails to install gems via Bundler

Question: I have seen a lot of questions along these same lines but I have tried bundle updating and committing the updated Gemfile.lock with no success. Here is the output when I try to push to my heroku git repo:
-----> Ruby app detected
-----> Compiling Ruby/Rails
-----> Using Ruby version: ruby-1.9.3-jruby-1.7.4
-----> Installing JVM: openjdk7-latest
-----> Installing dependencies using Bundler version 1.3.2
       Ruby version change detected. Clearing bundler cache.
       Old: jruby 1.7.4 (1.9.3p392) 2013-07-24 fffffff on OpenJDK 64-Bit Server VM 1.7.0_25-b30 [linux-amd64]
       New: jruby 1.7.4 (1.9.3p392) 2013-07-24 fffffff on OpenJDK 64-Bit Server VM 1.7.0_45-b31 [linux-amd64]
       Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin --deployment
       Picked up JAVA_TOOL_OPTIONS: -Djava.rmi.server.useCodebaseOnly=true
       You are trying to install in deployment mode after changing
       your Gemfile. Run `bundle install` elsewhere and add the
       updated Gemfile.lock to version control.
       You have added to the Gemfile:
       * source: git://github.com/gregbell/active_admin.git (at master)
       You have deleted from the Gemfile:
       * source: https://github.com/gregbell/active_admin.git (at master)
       You have changed in the Gemfile:
       * activeadmin from `git://github.com/gregbell/active_admin.git (at master)` to
       `no specified source`
       Bundler Output: Picked up JAVA_TOOL_OPTIONS: -Djava.rmi.server.useCodebaseOnly=true
       You are trying to install in deployment mode after changing
       your Gemfile. Run `bundle install` elsewhere and add the
       updated Gemfile.lock to version control.

       You have added to the Gemfile:
       * source: git://github.com/gregbell/active_admin.git (at master)

       You have deleted from the Gemfile:
       * source: https://github.com/gregbell/active_admin.git (at master)

       You have changed in the Gemfile:
       * activeadmin from `git://github.com/gregbell/active_admin.git (at master)` to
       `no specified source`
 !
 !     Failed to install gems via Bundler.
 !

 !     Push rejected, failed to compile Ruby app

Does anyone have any insight into why this might be failing? The lines showing a change in active_admin haven't been updated since a long time ago and pushes have been made to heroku since then.
Also in regards to You are trying to install in deployment mode after changing your Gemfile I have run bundle install and added my Gemfile.lock and pushed multiple times. A view of running git status in my project:
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
# .ruby-version
# app/assets/stylesheets/_base.scss
# app/assets/stylesheets/_colors.scss
# app/assets/stylesheets/_footer.scss
# app/assets/stylesheets/_forms.scss
# app/assets/stylesheets/_header.scss
# app/assets/stylesheets/_icons.scss
# app/assets/stylesheets/_k.scss
# app/assets/stylesheets/_k_mixins.scss
# app/assets/stylesheets/_k_ratings.scss
# app/assets/stylesheets/_project_windows.scss
# app/assets/stylesheets/_reset.scss
# app/assets/stylesheets/application.scss
# app/assets/stylesheets/ie_fixes.scss
# app/assets/stylesheets/mixins.scss
nothing added to commit but untracked files present (use "git add" to track)

and my .gitignore:
# See http://help.github.com/ignore-files/ for more about ignoring files.
#
# If you find yourself ignoring temporary files generated by your text editor
# or operating system, you probably want to add a global ignore instead:
#   git config --global core.excludesfile '~/.gitignore_global'

# Ignore bundler config.
/.bundle

# Ignore the default SQLite database.
/db/*.sqlite3
/db/*.sqlite3-journal

# Ignore all logfiles and tempfiles.
/log/*.log
/tmp

# Ignore database config file
database.yml

*.iml
.rvmrc
.idea

Comment: I've also tried creating a new heroku app to deploy on and it still fails with the same error.
Answer: If you're using a prerelease version of Bundler 1.4 when you run bundle on your local machine, you are running into an issue where the URLs for github gems changed from using the git protocol to https: https://github.com/bundler/bundler/issues/2600
To solve this, you should either update to a more-recent pre-release of Bundler 1.4 locally (by running gem install --pre bundler or remove the Bundler 1.4 prerelease and use 1.3.x.
Comment: ahh good catch, the problem I had with bundler 1.3.x was running into stack level too deep errors trying to bundle install
Answer: This problem is bacause you commit bad (old) Gemfile.lock to heroku server.
You need to update Gemfile.lock on heroku after adding/removing gems.
Do following steps:

save HEROKU_APP_NAME of existing heroku app ( HEROKU_APP_NAME.herokuapp.com )
remove heroku application from https://dashboard.heroku.com/apps and create new one
rename new heroku app to old HEROKU_APP_NAME
remove Gemfile.lock from your git repo
remove Gemfile.lock form your local project and form .gitignore (if it exist there)
run bundle install
commit changes to git repo ( new created Gemfile.lock )
run git push heroku master


is this formula provable in predicate logic? ⊢ (∀x)(∀y)(f(x1) = y1 → ((∀z)g(z) = f(x1) ≡ (∀z)g(z) = y1))

Question: "Can you prove ⊢ (∀x)(∀y)(f(x1) = y1 → ((∀z)g(z) = f(x1) ≡ (∀z)g(z) = y1)) in predicate logic? explain."
I'm saying no, but I'm not sure why. Is it because it's not a tautology? and how would Godel's incompleteness theorems come to play here?
Please help, thanks.
Comment: I think Godel's theorems are about formal systems representing basic arithmetic. Not the system of predicate logic.
Comment: oh okay, so how would we know if this is or isn't provable?
Comment: What are x1 and y1 in the statement? The quantifiers are over x, y and z so it seems odd.
Comment: Godel's completeness theorem states that all valid first order formulas are provable. Godel's incompleteness theorems say there are undecidable statements in any system powerful enough to represent arithmetic, and you can do that in first order predicate logic. This statement isn't powerful enough for it to apply however. Only monadic functions and an equality predicate suggest it's decidable.
Comment: @coffeemath http://math.yorku.ca/~brettler/1090_w14/FinalNatasha1090.pdf

the question comes from page 4 question 3c on that link. I'm not sure why the professor wrote x1 and y1 instead of just x and y
Comment: It is easily provable with *Natural Deduction* rules for *identity* : (=symm) : $s=t⊢t=s$ and (=trans) : $s=t,t=r⊢s=r$.
Answer: In first order logic, there are validities in addition to tautologies. These statements are statements that are true in every possible interpretation, and just not being a tautology isn't enough to tell you if it's a valid statement or not. Gödel's incompleteness theorems suggest that for every system that's powerful enough to represent arithmetic, there are statements that are undecidable... that is the truth value might be true in a particular model but not be a theorem of the formal system, but that doesn't say that validity is undecidable directly.
Church's theorem does however. That's the answer to the Entscheidungsproblem, the question on whether there's an algorithm to decide the validity of a first order statement. Church answered this in the negative for statements that are sufficiently complex.
I can't say for sure in your particular statement, since the statement looks a bit ambiguous, with quantifiers not matching any variables, and syntactic identity symbol being used where I think biconditional is meant. However if I take your statement to be this one in prenex normal form:
$\forall$x$\forall$y$\forall$z$\forall$u : ((f(x) = y) $\implies$ (g(z) = f(x)) $\iff$ (g(u) = y))
Then we can say some things about it. First, it is decidable since the only dyadic predicate is equality. This means we can determine whether it's a valid statement though several ways. We can negate the statement and use resolution. If we come up with the empty clause, it's a contradiction and hence it's unsatisfiable. The negation of an unsatisfiable statement is a valid statement. If you run out of rules, you've saturated the search and proven it satisfiable.
But satisfiable doesn't mean valid. A formula can be satisfiable and it's negation can be satisfiable as well, and what that means is there are models for each instance. This opens another way to find out if the statement is provable or not: finite model generation. I think that since the statement has only equality and monadic functions that if there's a model of it the model is finite so we can generate interpretations of the statement to see if it applies. If there's a finite model for the statement and the negation of the statement, the statement is unprovable also.
You can prove, through saturation of resolution or finite model generation that the statement isn't logically valid. It is satisfiable though.
Comment: thank you for your answer. heres the link to the question http://math.yorku.ca/~brettler/1090_w14/FinalNatasha1090.pdf, it is question 3c on the 4th page, so you can see I have not miscommunicated the question.

i guess resolution would be the way to go, don't know why I didn't think of that. But again, thank you. I will try using resolution and see if I can come up with a proof for this formula


Onto Function and Range/Codomain

Question: Does the range have to equal the whole codomain for a function to be onto, or is it simply that the columns of $A$ span $\mathbb R^m$?
Answer: By definition, a function is onto (or surjective) if and only if its range equals its codomain.
If the function is a linear mapping from $\mathbb R^n$ to $\mathbb R^m$ which is represented by a matrix $A\in \mathbb R^{m\times n}$, this is the case if and only if the columns of $A$ span $\mathbb R^m$.

Onto Function and Range/Codomain


How to explain Bayesian's summary?

Question: I ran Bayesian logistic regression as below.
n=1000
set.seed(1)
df <- data.frame(smoke = sample(c(0,1), n, TRUE),
                   cancer = sample(c(0, 1), n, TRUE),  #y
                   diabetes = sample(c(0, 1), n, TRUE),
                   depression = sample(c(0, 1), n, TRUE),
                   weight = sample(40:75, n, TRUE))
str(df)
df$smoke <- as.factor(df$smoke)
df$cancer <- as.factor(df$cancer)
df$diabetes <- as.factor(df$diabetes)
df$depression <- as.factor(df$depression)

fit_rstanarm <- stan_glm(cancer ~ .,data = df,family = binomial(link="logit"))
summary(fit_rstanarm)

There are no convergence issues, and the mean in Estimates shows the same values as the Estimate in Coefficients when I ran logistic regression. Does this mean I can say depression is an important factor to cause cancer? I only need to find which x variables are important to y, but I do not completely understand how to explain this result.
Answer:
Does this mean I can say depression is an important factor to cause cancer?

For different reasons: no!
First: you could derive that depression and cancer have something to do with each other but you can not tell whether one of these is the cause and the other the result or whether both depend on an unnamed third cause. Depression has an estimator and the 10% to 90% credible interval does not include zero.
Second: the coefficient of depression is negative. So more depression goes along with less cancer!
Third: you will need to define what you consider "important" before calling something important. It looks like a depression reduces the risk of cancer by about .2 on the log odds scale. Is that important in your eyes?
Fourth: You know how the data was constructed as depression = sample(c(0, 1), n, TRUE) so its all random! You can learn to be more cautios with statements. After all, you looked at 80% credible intervals and you looked at 5 of those. For a more critical view consult
plot(fit_rstanarm)
summary(fit_rstanarm, probs = c( .025, .05, .5, .95, .975))

How to explain Bayesian's summary?


Resampling within a survey to account for missing data

Question: Suppose I have survey responses that look like this:
<code>N=60000, Population
n=1000, Total sample
n=800, Users of Company X
n=200, Randomly chosen from 800 and asked about their Future Use of Company X
n=100, Planning to use Company X less in the future
</code>
The reason that only 200 of 800 users were asked about future use was due to them being asked about other companies as well. The survey would be far too long if they were asked about their future use of all companies that they use.
My goal is to understand the flow of future use. For example, of those individuals who are using Company X less in the future, which other companies are they planning on using more. However, with a sample of 100, there are not enough responses to other companies from the same users to other companies to get a usable proportion.
Can I, with some level of accuracy, infer the flow of business from a more robust sample of users of Company X?
Update: I think, what I may be referring to is called bootstrapping.
Comment: Please stop changing the title, you are obfuscating my purpose. Perhaps that suggests that this is a poorly defined problem. I'll update it again.
Answer: Your question is above my pay grade, as it were, but I can suggest a first look at the R survey package, which might implement some of the routines that you'd use to answer your questions.
Comment: This package has methods built in for part of what I was looking for
Answer:
Standard formulas for standard errors of a proportion would be suitable. With regards to your question about which companies the "n=100 sample" plan to use in the future, these standard errors would be based on n = 100. If this yields standard errors that are too large for your liking, then you need to increase your sample size.
In some cases you might be able to increase your effective sample size by engaging in more targeted sampling of the subset of the population that interests you (i.e., with company X, but planning to use company X less in the future).
Comment: @Brandon I still don't quite see how it is a special case. In survey research, we define a population, and attempt to sample from that population. In some cases the population is adults in a given country, in other cases it is people who use company X, in other cases it is people who use company Y, and in other cases it is people who use Company X, but are considering switching. In all these cases there are pragmatic challenges of actually getting a sample that is representative of the target population, and that is sufficiently large to draw relevant inferences.
Comment: I can't go back to the population at this point (we have a lockout time and our population is well known to us) so I must make the best use of the sample that I have. In my previous statement, I made an error. I'm looking for a statistical method for sampling my sample of users of company X to be able to converge upon which companies they are planning on doing more business with in the future.
Comment: Thanks Jeremy, I'll keep that in mind. Although, I don't think this is exactly what I'm looking for (the question about error was more of an aside to my primary question)
Comment: @Brandon. Okay. It seems that your sample size for given questions is being reduced because of (a) random sampling within a random sample and (b) a certain question is only applicable to a subset of your sample. However, I don't see how this would change the process of deriving standard errors. You have a final sample size for that question, and that's that. Perhaps, I'm not understanding what you mean by a "more robust sample of users".
Comment: Essentially, I'd like a statistical method for sampling the population of users of Company X, to be able to say which other companies they are planning on doing more business with in the future. aka, Who's eating who's lunch.


Apache redirects to localhost

Question: I set up WAMP 3.1.9 on my laptop and want to access the website from LAN using my phone. Apache version is 2.4.39, I replaced the default virtualhost settings in the httpd-vhosts.conf file with the following:
<VirtualHost *:80>
  ServerName localhost
  DocumentRoot "${INSTALL_DIR}/www"
  <Directory "${INSTALL_DIR}/www/">
    AllowOverride All
    Require all granted
  </Directory>
</VirtualHost>

I am using windows 10 and added httpd.exe to the firewall exceptions.
The problem is that, when I access my laptops LAN ip (192.168.2.8) from my phone, I get a "could not establish connection" error. When I look at the sites adress, it says 'localhost' instead of the LAN ip, so I'm suspecting that Apache redirects the request to localhost, but I cannot find the setting which does this nor am I able to find this online.

I solved it by reinstalling WAMP

I am now using using version 3.2.0.
Edited httpd-vhosts.conf and changed the line Require local to Require all granted.
Restarted all services
Cleared history of my phone
Attempted to reach the site from my phone, resulted in a connection time out but no redirect.
Added httpd.exe as an exception to windows firewall. This is done by: start > type: Windows Defender Firewall > Allow app or feature ... > change settings > allow another app.. > browse > C:\wamp64\bin\apache\apache2.4.41\bin\httpd.exe > add > ok
cleared history of phone again.
Successfully reached the site on my laptop.
Answer: See the documentation:

The ServerName directive sets the request scheme, hostname and port
  that the server uses to identify itself.
ServerName is used (possibly in conjunction with ServerAlias) to
  uniquely identify a virtual host, when using name-based virtual hosts.
Additionally, this is used when creating self-referential redirection
  URLs when UseCanonicalName is set to a non-default value.

Since you said the ServerName was localhost, Apache redirects to localhost when it generates a redirect.
If you want the canonical name to be 192.168.2.8 then use that.
Comment: I thought about that, but in all the online discussions about this topic `ServerName localhost` and `ServerAlias localhost` are used. Which is why I did not think of it as the cause of the problem. Anyway, I have done a reinstall of WAMP and it is currently working with localhost as servername.Based on your comment I have changed serverAlias to the laptops IP to prevent possible future issues.

I am still wondering why my post is being downvoted though

Apache redirects to localhost


row-fluid vs row in twitter bootstrap

Question: I have a container-fluid container element, and have been using row as opposed to row-fluid, admittedly out of ignorance. Now I am trying to replace the row class with row-fluid class, but have run into some questions.  First, I looked at how the row-fluid width is defined in the .less, and it's completely hieroglyphic to me, so would anyone care to explain?  More importantly, when I replace row with row-fluid, the height of the element collapses to 0 requiring me to include the .clearfix class in order for the row-fluid element to grow to contain its children columns. Why is this necessary, i.e. what is being floated and why when I replace row with row-fluid?
Comment: Bootstrap v3's `.row` = Bootstrap v2's `.row-fluid`
Answer: It depends on what elements you want to know the width of. The row-fluid class itself has a width of 100%. The spans (or columns) have a relative width, set up in such a way that it combines to 100.
On the floating: all columns get floated, this is what makes it fluid. The only height related thing that a row-fluid does is setting min-height: 30px. This makes it by definition strange that anything would collapse to a height of 0.
I'd suspect the styling you've done on top of your old grid is what causes your main problems.
Comment: it seems strange that i got away with using row-fluid, since i just checked the .css file and it's not defined even though the layout is working, so i guess it just interprets row-fluid as row or something? anyways, thanks for your input, and my question is solved on account of row-fluid not existing. thank you!
Comment: I'm a little new here. But since the heart of the issue lies in the fact that row-fluid doesn't exist in BS3, should I still retag?
Comment: @Derek So you are talking about Bootstrap 3 then? If that's the case, retag the question to `twitter-bootstrap-3` please.
Answer: This is what twitter bootstrap says:

Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding.

Well, that is about container not rows, but if that explanation is not enough for you, then  this is the short explanation which should make things clear for you.
NOTE: If its version 2, then row-fluid itself is being float: left which would need to be cleared as you say.
This is because Fluid grids utilize nesting differently: each nested level of columns should add up to 12 columns. This is because the fluid grid uses percentages, not pixels, for setting widths.
Hope this helps :)
Comment: Bootstrap 3 doesn't have a `row-fluid` class, so I suspect he is asking about Bootstrap 2.
Comment: @gpgekko Yes it would be for version 2 but I found the explanation for the `clearfix` thing in docs of version 3, so I just linked that in answer as well :)
Answer: Bootstrap 2.x to 3.0 class change
Bootstrap 2.x-->.row-fluid and Bootstrap 3.0 -->.row

row-fluid vs row in twitter bootstrap


create a cmd file with a loop (wget recursive download)

Question: What i have done :
wget -e robots=off --mirror -np --no-check-certificate https://awebsite.com/.../page1.html

my cmd code :
for i in {1..400}
do
    wget -e robots=off --mirror -np --no-check-certificate "http://website.com/.../page$i.html"
pause

Edit: I use windows. I mixed up
Thank you in advance
Edit 2 :
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /L %%G IN (1,1,3) DO (
    set num=%%G
    wget -e robots=off --mirror -np --no-check-certificate "https://website.com/.../page!num!.html"
)
ENDLOCAL
pause

But it download page1 .html and page2 .html and page3 .html (always a space... :/)
Comment: Add your own code to your question. You are expected to show at least the amount of research you have put into solving this question yourself.
Comment: Ok, but my cmd closes itself and i can't find the downloaded files
Comment: `@echo off` is not a valid Bash command, nor is `pause` a standard Unix command. You seem to be mixing Bash and Windows CMD syntax.
Comment: Is the goal to produce a  cmd.exe .bat file script or a bash script? Are you asking that someone convert the bash command into a cmd command?
Comment: Is it possible to make a loop in cmd ? I want to create a .cmd But I don't know much about it (just few python tips or how to use visualWget)
Comment: Of course, loops are possible in `cmd`. The syntax is different though. Read the output of `for /?` and/or visit [SS64](https://ss64.com/nt/)
Comment: Thanks. Please look at edit n°2
Comment: Well, you explicitly tell it to add a space: `set num=%%G`. Better use the preferred syntax `set "num=%%G"` to avoid unwanted (and invisible and therefore hard to spot) trailing spaces.
Answer: It works !!!
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /L %%G IN (1,1,3) DO (
    set "num=%%G"
    wget -e robots=off --mirror -np --no-check-certificate "https://website.com/.../page!num!.html"
)
ENDLOCAL
pause
Comment: btw: if that's all you want to do, you don't need the `num` variable and so also no delayed expansion. Inside the loop, you can use `%%G` directly: `wget -e robots=off --mirror -np --no-check-certificate https://website.com/.../page%%G.html"


Python module importing itself with leading underscore but there is no corresponding .py file

Question: In the PyBluez source code I've noticed a couple things I haven't seen before. This file named widcomm.py starts with the following:
from .btcommon import *
import socket
import struct
import threading
import os
import _widcomm

In the previous directory, there is no _widcomm.py or another widcomm.py. I've read that modules with a leading underscore might be "private" or accelerated, but I can't find anything about a module seemingly importing itself with an underscore.
A few lines under that you get this interesting function:
def dbg (*args):
    return
    sys.stdout.write (*args)
    sys.stdout.write ("\n")

Am I correct in thinking the code under return has no way of ever being executed? As far as I can tell this function serves no purpose.
What exactly is going on here?
Comment: Yes, the code below `return` won't be executed. However, this has nothing to do with the `_widcomm` import.
Comment: It may be a C extension module. When writing C extensions, its common to have a .py file for stuff that doesn't need C level code that imports the stuff that does need C. As for `return`, its just a quick and dirty way of doing debug - you are meant to comment out the `return` to enable it.
Answer: Regarding the obscure return statement.
You can push the blame-button on the github you linked and there you'll see following comment for the return:

suppress debugging messages

Below that return there are said debugging-messages printing the arguments to stdout. So the return is there to not execute those messages that where there before the return. Like you guessed and @mkrieger1 commented those statements will never be executed as long the return is in place.
Answer: According to the setup file of this Python package,
ext_modules.append(Extension('bluetooth._widcomm',
        include_dirs=["%s\\Inc" % WC_BASE],
        define_macros=[('_BTWLIB', None)],
        library_dirs=["%s\\Release" % WC_BASE],
        libraries=["WidcommSdklib", "ws2_32", "version", "user32",
                   "Advapi32", "Winspool", "ole32", "oleaut32"],
        sources=["widcomm\\_widcomm.cpp",
                 "widcomm\\inquirer.cpp",
                 "widcomm\\rfcommport.cpp",
                 "widcomm\\rfcommif.cpp",
                 "widcomm\\l2capconn.cpp",
                 "widcomm\\l2capif.cpp",
                 "widcomm\\sdpservice.cpp",
                 "widcomm\\util.cpp"]))

the _widcomm import refers to an extension module which is built from the _widcomm.cpp and related C++ source files.


Prove that these two series are equal

Question: I am doing a course in Reliability. There is a system of n parallel identical components, each of which has a failure probability $$exp(-\lambda t)$$. As is the case with parallel systems, the system works if at least one component works OR, the system fails if all the components fail. Therefore, R(t) be the probability that the system works.
$$\therefore R(t) = 1 - (1 - e^{-\lambda t} )^n   - (1) $$. i.e, probability that no components fail.
Also, $$R(t)= \sum_{x=1}^n {^nC_x}(e^{-\lambda t})^x(1-e^{-\lambda t})^{n-x} - (2)$$
Now, it is easy to see that (1) and (2) are same. Now, we are to calculate the integral $$\int_0^\infty R(t)dt$$ (which is actually called the mean life time of the system).
Now from (1)
$$\int_0^\infty R(t)dt = \int_0^\infty (1 - (1 - e^{-\lambda t} )^n )dt
= \int_0^\infty \sum_{x=1}^n {^nC_x}\times(-1)^{i+1}\times e^{-x \lambda t} (Binomial Expansion) =
 \frac{1}{\lambda} \sum_{x=1}^n {^nC_x \frac{(-1)^{x+1}}{x}}  -(a) $$
Also, from (2)
$$ \int_0^\infty R(t)dt= \int_0^\infty \sum_{x=1}^n {^nC_x}(e^{-\lambda t})^x(1-e^{-\lambda t})^{n-x} dt
 = \frac{1}{\lambda} \int_0^1 \sum_{x=1}^n {^nC_x}v^{x-1}(1-v)^{n-x}dv$$ (taking  transformation) $$v = e^{-\lambda t}$$. Thus it becomes, $$\frac{1}{\lambda} \int_0^1 \sum_{x=1}^n{(^nC_x)}v^{x-1}(1-v)^{\bigl(n-(x-1)\bigr)-1}dv = \frac{1}{\lambda} \sum_{x=1}^n {(^nC_x)}\frac{\Gamma(x)\Gamma(n-x+1)}{\Gamma(n+1)} = \frac{1}{\lambda} \sum_{x=1}^n \frac{1}{x} - (b) $$
Now, (a) and (b) are derived from same expression, so they are same. You can also check by taking any arbitrary integer value of n.
But what is bothering me it is not directly obvious that expressions (a) and (b) are same. Can anyone give any direct proof that series (a) and series (b) are same, i.e $$\sum_{x=1}^n \frac{1}{x} = \sum_{x=1}^n {^nC_x \frac{(-1)^{x+1}}{x}} $$ ?
Comment: Have you tried using induction?
Comment: @Integrand I tried but it does not help. If I assume that the statement is true for n = m. Then if I try to prove it for n = m+1, the LHS is ok, but in the series in RHS causes trouble, as all the $$^mC_x$$ terms change to $$^{(m+1)}C_x.$$
Answer: Alternatively, consider the generating function of the RHS:
\begin{align}
\sum_{n=1}^\infty \sum_{k=1}^n \frac{(-1)^{k+1}}{k}\binom{n}{k} z^n
&=-\sum_{k=1}^\infty \frac{(-z)^k}{k} \sum_{n=k}^\infty \binom{n}{k} z^{n-k} \\
&=-\sum_{k=1}^\infty \frac{(-z)^k}{k} \cdot\frac{1}{(1-z)^{k+1}} \\
&=-\frac{1}{1-z}\sum_{k=1}^\infty \frac{1}{k}\left(\frac{-z}{1-z}\right)^k \\
&=\frac{1}{1-z} \log\left(1-\frac{-z}{1-z}\right) \\
&=\frac{1}{1-z} \log\left(\frac{1}{1-z}\right) \\
&=-\frac{\log(1-z)}{1-z},
\end{align}
which is known to be the generating function of the harmonic numbers $H_n$,
so
$$\sum_{k=1}^n \frac{(-1)^{k+1}}{k}\binom{n}{k}=H_n.$$

Prove that these two series are equal


Utilizar comando cls de .bat em Linguagem Java

Question: Estou com um código para iniciar uma sessão no Putty, com o IP referente a um equipamento de cada cidade.
Dentro do código em java, eu faço o uso de comandos .bat, como por exemplo o uso do comando |CLIP e o start putty.
Porém, como tenho um Menu dentro de um WHILE, esse menu acaba poluindo a tela cada vez que o while se repete.
Portanto, pensei em apensar usar código:
Runtime.getRuntime().exec("cmd /c cls");

Porém, não funciona, não limpa a tela, porém não dá erro. É como se o código ignorasse a linha do cls.
Alguém saberia informar como deve ser feito esse clear na tela?
Esse código vai ser usado pelo setor de redes da empresa, então eu realmente preciso entregar uma coisa mais "limpa" para usarem.
while(menu == 1){

    System.out.println("-----------------------------");
    System.out.println("Teófilo Otoni OLT 6 ---> teo6");
    System.out.println("Teófilo Otoni OLT 7 ---> teo7");
    System.out.println("Caravelas -------------> car");
    System.out.println("Cidade Nobre ----------> cid");
    System.out.println("Manhuaçu --------------> man");
    System.out.println("Santana do Paraíso ----> par");
    System.out.println("-----------------------------");

    System.out.println("");
    System.out.println("OLT [APENAS OS 3 PRIMEIROS DÍGITOS]: ");
    olt = entrada.next();

    if(!"teo6".equals(olt) && !"teo7".equals(olt)  && !"car".equals(olt) && !"cid".equals(olt)  && !"man".equals(olt) && !"par".equals(olt) && !"san".equals(olt) ){
        System.out.println("##### OLT INVÁLIDA #####\n\n");

    }else{
        Runtime.getRuntime().exec("cmd /c cls");
        Runtime.getRuntime().exec("cmd /c echo "+sn+"| clip");
        System.out.println("S/N: ");
        sn = entrada.next();
    }

Answer: Esta resposta do SOen explica porque sua abordagem não funciona, mas basicamente Runtime.exec redireciona a saída padrão para um pipe que pode ser lido pelo processo Java. Como a saída foi redirecionada, esta não é aplicada ao console, e por isso ele não limpa a tela do mesmo.
A mesma resposta dá a solução: invocar o comando com um ProcessBuilder e conectar a saída do comando com a saída do processo Java, usando inheritIO (método disponível a partir do JDK 7):
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();

Assim, quando o programa for iniciado em um console pela linha de comando, a tela será limpa.
Comment: Cara, funcionou perfeitamente!!!
Muito obrigado! Estava atrás da solução há algum tempo.
Obrigado mesmo.


php string comparison error parsing an ini file

Question: I have a simple ini file:
[section_one]
test = abc

[section_two]
yada = blah
#and_so=on

I wrote a parser function to update it b/c my comment char is '#' instead of ';' -- so parse_ini_file() complains. But here's my quick & dirty solution:
<?php
function edit_ini_file ($fName, $fKey, $fVal) {
  print"
Search: $fKey = $fVal
";
  // declarations
  $_comntChar='#';
  $_headrChar='[';
  $keyMatch=FALSE;
  $iniArray = array(); // new array in memory
  $dataOut = ''; // datastream for output file
  // temp cursor vars for looping & reporting
  $verbose = 1;
  $curSec = ''; // current section
  $curKey = ''; // current key
  $curVal = ''; // current value
  $curLine=-1;  // current line Number
  if (isset($fName)) {
    if (!is_file($fName)) return FALSE;
    $lines = file($fName);
    //read file as array of lines
    foreach ($lines as $line) {
        $curLine+=1;
        if ($verbose) print '
['.$curLine.'][IN:] '.$line;
      //parse for k/v pairs, comments & section headings
      if (   (strpos($line,$_headrChar)==1) // assume heading
          || (strpos($line,$_comntChar)==1) // assume comment
          || (!strpos($line,'=')) // also skip invalid k/v pairs
         ){
            array_push($iniArray, $lines[$curLine] ); //stuff the entire line into array.
            if ($verbose) print " - no k/v";
       } else { // assume valid k/v pair
        //split k/v pairs & parse for match
        $pair = explode('=', $line);
        $curKey = trim($pair[0]);
        $curVal = trim($pair[1]);
        if ($verbose) print "[KV]: k=$curKey:v=$curVal";
        if (trim($curKey) === trim($fkey)) { // <=== THE BUGGER: never returns true:
          $keyMatch=TRUE;
          print ("MATCH: Replacing value in for key=$curKey in Section $curSec at line $curLine
");
          array_push ($iniArray, array($curKey => $fVal ));
         } else {
         array_push ($iniArray, array($curKey => $curVal ));
        } //end-matcher
       } //end-parser
     } //end foreach
    if (!$keyMatch) { //append new data to end
      print "
Key not Found. Appending!
";
      array_push ($iniArray, array($fKey => $fVal) );
     }
  //reformat nested array as one long string for a single bulk-write to disk.
  foreach($iniArray as $curSect => $val) {
    if (is_array($val)) {
        foreach($val as $curKey => $curVal)
             $dataOut .= "$curKey = $curVal\n";
    } else { $dataOut .= "$val"; }
  }
  print "dataout:
" .$dataOut. "
";
  //put file & pass return val
  return (file_put_contents($filename, $dataOut)) ? TRUE : FALSE;
 }//if isset
}//end-func

Basically I'm just exploding a text file line-by-line stuffing a new array and dumping it back to the disk
MY BUG: for some reason my comparison trying strcmp() or "==" or "===" never seems to work...
if (trim($curKey) === trim($fkey)) { doSomething.. }

That little BUGGER is driving me nuts b/c I know it's gotta be something stupid.
ANy point in the right direction would be appreciated...
Comment: You do know about [`parse_ini_file()`](http://php.net/manual/en/function.parse-ini-file.php), right?
Answer: Is it $fKey or $fkey?
Make a decision!
;)


POST XLSX file to IIS site using DropZone

Question: I am trying to use DropZone (www.dropzonejs.com/) to post an xlsx file to read on the client side. This works in my test environment using ember server. However, once I brought it across to IIS8, I am getting a 405 Method Not Allowed error.
DropZone makes a POST request with the file.
I tried adding the POST verb to the StaticFile Handler Mapping but it does not seem to affect it. I was wondering if it could be to do with the Origin not having a trailing slash, while the Referer does.
The StaticFile Handler Mapping in IIS for the Site has a Path of * and Verbs is set to "All Verbs", Access is "Read", Mapping is "File or Folder"
This is what I can see using Chrome Developer Tools:
POST http://<my site URL>/#  405 Method Not Allowed 28ms
General
Remote Address:<my server ip>:80
Request URL:http://<my site url>/
Request Method:POST
Status Code:405 Method Not Allowed

Resonse Headers
Access-Control-Allow-Headers:Accept, Content-Type, Origin
Access-Control-Allow-Methods:GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Allow:GET, HEAD, OPTIONS, TRACE
Cache-Control:private
Content-Length:5291
Content-Type:text/html; charset=utf-8
Date:Thu, 10 Sep 2015 23:20:03 GMT
Server:Microsoft-IIS/8.0
X-Powered-By:ASP.NET

Request Headers
Accept:application/json
Accept-Encoding:gzip, deflate
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Content-Length:252016
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryJMRgHAltxqUm8aBL
Host:labeleditorclient
Origin:http://<my site URL>
Referer:http://<my site URL>/
User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
X-Requested-With:XMLHttpRequest

Request Payload
------WebKitFormBoundaryJMRgHAltxqUm8aBL
Content-Disposition: form-data; name="file"; filename="1.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

------WebKitFormBoundaryJMRgHAltxqUm8aBL--

Answer: I found out what the issue was. The default page was index.html.
There was no handler for html that handled POST.
So I followed the instructions here to add a handler for html http://sysadmin.circularvale.com/server-config/enabling-post-requests-to-static-eg-html-pages-using-iis-7/
After that, it worked.


Obtain a formula for $\frac{dy_1}{dx}$ if $y_1$, $y_2$ are defined implicitly by:

Question: $G_1(x, y_1(x), y_2(x)) = 0$
$G_2(x, y_1(x), y_2(x)) = 0$
Since $G_1$ and $G_2$ are composite functions I can use the chain rule and split them up into partial derivatives. The derivative of both functions should be $0$ since they are both horizontal lines. I'm not sure what to do after that. Maybe just substitution?
Comment: Are you told they are horizontal lines or asserting it?  There is nothing here to support that.  The derivative with respect to what?  Let $G=y-x^2$  We don't have any derivatives that are identically zero.
Comment: You are right. It shouldn't have to be horizontal. It was just a shot in the dark.
Answer: Assuming $G,y_1,y_2$ are nice enough to satisfy hypotheses of the implicit function theorem,
$$
\partial_xG_1 = \partial_1 G_1 + \partial_2G_1 \partial_xy_1 + \partial_3 G_1 \partial_x y_2 = 0
$$
and
$$
\partial_xG_2 = \partial_1 G_2 + \partial_2G_2 \partial_xy_1 + \partial_3 G_2 \partial_x y_2 =0.
$$
This is a two-by-two linear system for $\partial_x y_1$ and $\partial_x y_2$ which (I put in Mathematica) solved
$$
\partial_xy_1 = -\frac{\partial_1G_2 \partial_3 G_1 - \partial_1 G_1 \partial_3 G_2}{\partial_2G_2 \partial_3 G_1 - \partial_2 G_1 \partial_3 G_2}.
$$
Comment: That looks right. I wish I knew a way to solve the system. It gets pretty bad algebraically. Does anyone know any other way?
Comment: Don't get lost in the notation. You have something of the form $ax + by = z_1$ and $cx + dy = z_2$. The solution is two lines of linear algebra which I can't be bothered to type.
Comment: I understand. Thanks a bunch.


Interpreting Non-Significant Moderated Regression for Multiple Interactions and a Surprisingly Significant Main Effect

Question: I was wondering if someone could explain this to me.
I've carried out a hierarchical regression, entering 9 independent variables at Step 1 (Block 1), and 8 interaction terms at Step 2 (Block 2). The 8 interaction terms relate to X1 interacting with each of the other Xs. X1 is dummy coded, X2 and onwards are centred.
I'm confused by the results. Model 1 is significant, but Model 2 isn't. From what I understand, this means none of the interactions are significant enough to interpret in Model 2, and so I should focus on Model 1. Please correct me if I'm wrong.
Surprisingly, Model 1 shows 2 out of 9 Xs are significant, when really only 1 should be (i.e. X1, the dummy coded experimental conditions). Purely out of interest, I used a simple regression to check X2 (the surprisingly significant main effect) against my dependent variable, and it came back F(1, 162) = .174, p = .677, with an R2 of .001. The "significant" independent variable in Model 1 isn't significant outside of the Model. Is there any reason why an IV would be significant when grouped with other IVs but not on its own?
Can anyone explain where I go from here, now that Model 2 is non-significant. Theoretically, at least one of the interactions 'could' have moderated the relationship, though the literature's murky on it. I'm considering using Hayes' Process to check each interaction separately, but using Bonferroni to correct for the repeated tests will reduce my alpha considerably.
Answer: The concept of significance is quite subtle, particularly when more than one test is run. If you estimate more parameters, this means that under null hypothesis there will be more variation in the estimators. This means that the threshold for significance is higher (because more deviation from null values will happen by random variation even if the H0 is true). For this reason it can occasionally happen that a model with more parameters (model 2 with the interactions) is not significant at the same time when a model that has fewer of the same parameters (your model 1) is significant.
This is admittedly hard to interpret, but I'd suspect that model 1 was only marginally significant and model 2 maybe marginally insignificant. Overall this seems to be a borderline situation with some weak indication that main effects play a role overall, but no conclusive evidence. You need to keep in mind that fixed significance thresholds such as $\alpha=0.05$ are largely arbitrary, and p=0.03 is really not that different from p=0.07, despite one being "significant" at 5%-level whereas the other one is not.
"Surprisingly, Model 1 shows 2 out of 9 Xs are significant, when really only 1 should be (i.e. X1, the dummy coded experimental conditions)." I'm not sure what you mean by "only 1 should be" - how can you be sure that the second one truly is a null effect? Even if it is, testing at 5%-level makes the probability 5% that a true null effect will come out significant, and if you test lots of effects (like, e.g., 9 main effects and 8 interactions), these things happen ultimately with pretty large probability (this is why the Bonferroni correction exists, see below).
" Is there any reason why an IV would be significant when grouped with other IVs but not on its own?" When tested together with other independent variables, the procedure takes dependency among independent variables into account. For example the situation could be that X2 and X3 both have positive influence on Y but X2 is negatively correlated with X3. If you then build a model without X3, you may not see the influence of X2 because it is countered by the influence of X3, which is not in the model. If you put both of them in the model, the test will be adjusted for the correlation. (X3 may still be insignificant, particularly with a not so big sample size, because there is no guarantee that every influential variable will be significant.)
"Can anyone explain where I go from here, now that Model 2 is non-significant." I don't think you can construct a positive statement for any interaction out of this. So you've got to say "no evidence for any interaction existent". Regarding the main effects, as I said, you could say "weak indication".
"I'm considering using Hayes' Process to check each interaction separately, but using Bonferroni to correct for the repeated tests will reduce my alpha considerably." ...and Bonferroni is right about that.


How to keep ng-model value even when running validations?

Question: The topic was heavily discussed in this post
However, there was never addressed any solution as to a general solution to make sure that the ng-model values are not wiped when the validation fails. For me, I find that when it fails, the model has values shown as 'unknown', however this causes the 'key' to be lost so when I do set a valid value, it is not tied to the same instance.
If it makes a difference, I am using the $validators pipeline within a custom attribute for validations.
Answer: im not quite sure i get your question but doesnt your problem get resolved with
<code><input type="number" ng-model="xxx" ng-model-options="{ allowInvalid: true }">
</code>
that way youre telling to the model to keep invalid values inserted in the model in this example that could be text in the number input


Can there be a walk between a tree and it's subgraph formed by removing an edge from the tree?

Question: Say T is a tree and e is an edge in T. H is a subgraph of T obtained by removing edge e in T. Can there be a walk in H that connects to T?
Edit: I've been trying to work it out, and what I have is that there cannot be walk that connects the two, since graph T is made of both graphs connected by e, and by removing edge e, subgraph H is formed, so both subgraph H and a walk connecting them can't exist.
Is this right? Is there a better way to say this if so?
Comment: What do you mean by "a walk in $H$ that connects to $T$"?
Comment: @austin so say the the two vertices for the edge _e_ are _v_ and _w_. Since _H_ is formed by removing that edge, one of the vertices has to be in T, and one has to be in _H_. So can there be a walk from _v_ to _w_?
Comment: As you have defined it, $H$ is a subgraph of $T$, so the vertices $v$ and $w$ belong to both $H$ and $T$. To answer your more specific question, there cannot be a walk from $v$ to $w$ using only edges of $H$; one characterization of trees is that there is a unique $xy$ path for any vertices $x$ and $y$.
Answer: One characterization of trees is that there is a unique $xy$-path between any two vertices $x$ and $y$. In your example, the edge $vw$ is the unique $vw$-path in $T$. Having removed the edge $vw$, there is now no other $vw$-path. That is to say, $v$ and $w$ belong to separate connected components. (This leads us to a second characterization of trees. They are minimally connected, meaning that the removal of any edge disconnects the tree.) Thus, a slightly stronger claim could be made: Let $x$ be any vertex in the connected component containing $v$ and $y$ be any vertex in the connected component containing $w$. There is no $xy$-path in $H$.
Comment: I see! For some reason I was thinking that by removing an edge in T that the graph would somehow split into 2 trees; but _v_ _w_ could be any edge in _T_, so _H_ wouldn't even be a tree, but a disconnected simple graph.
Comment: @user316577 Your intuition is correct; $H$ is the disjoint union of two trees. The vertex $v$ belongs to one tree and $w$ to the other, so there is no hope of walking from $v$ to $w$.


Start pgAdmin4 in different browser Ubuntu 18

Question: Can't find where to change the default startup browser on Ubuntu.  When I start pgAdmin4 the default browser opens, but I would like to start a different browser (eg: Firefox). In windows you can right click the service, but I'm stuck finding the way to change this on Unbuntu.
Comment: I've already reply to same question please check https://stackoverflow.com/questions/51637530/pgadmin-4-v3-1-how-can-i-use-another-browser-win-7/51719736#51719736
Comment: Well you did for Windows as far as I understand, when starting pgAdmin4 in Ubuntu there is no such a thing as the "tray icon".
Comment: @MurtuzaZ there is a tray option I never noticed before in the top bar, next to the date and other settings. Feeling rather stupid I've never noticed it before. If you change your suggestion to an answer I can mark it as answered.
Answer: With the latest version of pgAdmin4, developers have added copy URL option on right click on tray icon, Download the latest version then right click on pgAdmin4 tray icon which will give you option to Copy URL, once you click that option then open your desired browser and paste the URL and hit Enter.
And you are good to go :)
Also, there is an option to run the custom browser command also.
In new chrome versions you can run pgAdmin 4 as "native" desktop app. While the pgAdmin v4 web server is running, right click the icon in the Windows System Tray and select Configure... In the Browser Command input add the following:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app=%URL%
Note: Above path can change for you in Ubuntu.

If you want to run in chrome browser window, configure command like this:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" %URL%
Note: Above path can change for you in Ubuntu.
Hope this helps.
Comment: The question was regarding Ubuntu, not Windows.
Comment: I may be blind but where is this tray icon?
Comment: This is not an answer as it is for a different OS.
Answer: It is kind of a trick. It is quite fast to change the default browser in ubuntu, then run pg admin and change the default browser back. Did not found how to do it like in windows.


Deleting keys from redis using node js

Question: I am trying to delete keys in redis using the below code but for some reason, its not deleting the keys in redis but consoling works perfect. Can someone please help what am I missing here
import { RedisClient } from 'redis';

let rediClient: RedisClient = redis.createClient(redisPort, redisHostName, {
    auth_pass: authPass,
    no_ready_check: true,
    prefix: KEY_PREFIX,
    retry_strategy: redisRetryStrategy,
    tls: { servername: hostName },
  });

let cursor = '0';

const scan = (pattern: string, callback: () => void) => {
  redisClient.scan(
    cursor,
    'MATCH',
    pattern,
    'COUNT',
    '1000',
    async (err, reply) => {
      console.log(err);
      if (err) {
        throw err;
      }
      cursor = reply[0];
      const keys = reply[1];
      console.log(keys);
      console.log(keys.length);
      console.log(keys[1]);
      if (keys) {
        await redisClient.del(keys[1], (deleteErr, deleteSuccess) => {
          console.log(`err ==> ${deleteErr}`);
          console.log(deleteSuccess);
        });
        console.log(` key 0 is : ${keys[0]}`);
        redisClient.del(keys[0]);
        // keys.forEach((key) => {
        //   redisClient.del(key, (deleteErr, deleteSuccess) => {
        //     console.log(`err ==> ${deleteErr}`);
        //     console.log(deleteSuccess);
        //   });
        // });
      }

      if (cursor !== '0') {
        console.log(cursor);
        return scan(pattern, callback);
      }

      return callback();
    }
  );
};

export const deleteResetPin = (pattern: string) => {
  scan(pattern, () => {
    console.log('Scan Complete');
  });
};

Requirement: I want to delete all keys matching the pattern using node js
Answer: With the commented part (starting at keys.forEach) running the scan function will delete all the keys that matches the pattern, but there's a couple of thinks to fix/improve here:

the callback (and therefore also the log) will be called before the keys are deleted.
if scan reply with an error the error will be uncaught and the process will exit.
you're mixing callbacks and promises.
you can delete a bunch of keys at once.

Here is a "promised" version of the function:
const { promisify } = require('util'),
  client = require('redis').createClient(),
  scanAsync = promisify(client.scan).bind(client),
  delAsync = promisify(client.del).bind(client);

async function scanAndDelete(pattern: string): Promise<void> {
  let cursor = '0';
  do {
    const reply = await scanAsync(cursor, 'MATCH', pattern, 'COUNT', '1000');
    cursor = reply[0];

    await delAsync(reply[1]);
  } while (cursor !== '0')
}

Answer: For Node Redis >= 4
const redisClient = require('redis').createClient(),

async function scanAndDelete(pattern) {
  let cursor = '0';
  // delete any paths with query string matches
  const reply = await redisClient.scan(cursor, { MATCH: pattern, COUNT: 1000 });
  for (key of reply.keys) {
    cursor = reply.cursor;

    await redisClient.del(key);
  }
}

Comment: You should also iterate over the cursor, otherwise you'll stop after 1000 entries (= `COUNT`)

Deleting keys from redis using node js


How to export a menu and blocks?

Question: I created a Superfish menu in a test installation of Drupal (8.5.4) and want to import it into another install (8.5.5).  How can I do this?
Is the navigation data stored in menu_link, menu_link_content, and menu_tree?  I tried importing these tables into my new install, but when I try to "Place Block" in Block Layout - I don't see the old menu showing up as a Superfish block.
I also tried using the Menu Export module. But was unable to find the "Menu Export Configuration" page that they show in the image.
The new install is migrated from Drupal 7. So it lacks a config table.  Where is the config installed?  I think I need to copy the menu which is stored in a blob in the config table, but I don't know where to put it.
Note: The main question is "How can I export the menu"? To which the answer appears to be "Not possible." I'm still confused though as the menu information has to be stored somewhere. The other sub-questions are trying to get at pieces of the puzzle.
Comment: Ufff, that are many questions. Please try to narrow down your problem to one specific question. Otherwise this question simply is too broad to be answered in this site's Q&A style as it requires a lot of back-and-forth communication we can't and don't want to handle here.
Comment: Links are content I believe and not exportable out of the box. Menus themselves are exportable.
Comment: The main question is "How can I export the menu"?  To which the answer appears to be "Not possible."  I'm still confused though as the menu information has to be stored somewhere.

The other sub-questions are trying to get at pieces of the puzzle.
Answer: Both menu link items and custom block content are treated as content within Drupal core. That's to say, they aren't covered by the configuration management system.
In instances where it make sense to have menu link items or custom block content stored in the configuration system, there are modules out there to assist with this:

Fixed block content: Provides a way of having permanent custom content blocks without broken instances if the block does not exist.
Config menu link: A drop-in replacement for core's Custom Menu Links module.

There many other options to store menu/block data into the config system so it's worth your time to explore other options to find the one that best matches your scenario (especially since Superfish seems to be a part of it).
Comment: Drupal core won't let you (without trying to copy DB tables) The above example modules use the config management system to import/export.
Comment: If the menu items are content, how can I export and import them?
Comment: I'm up for copying the tables.
Comment: Here is something I found - https://github.com/calbasi/migrate_menu - Not sure about the state of the solution though.

How to export a menu and blocks?


Latest added data in a particular contenty-type on custom page

Question: I am a newbie in Drupal,I have content-type "News" where the user adds news related to product. I want to show the latest 3 added news on content-type "Home-Page" (Home-Page is not front page).

What would be the standard way to get the desired output?

**I am using Drupal7
Answer: There are many, many ways to accomplish this but here is one of the simplest ways I can think of.
I'm going to use the Drupal Views module to do this.  The intent of this is not to cover all things Drupal, rather it's to give you a crash course in creating a block using Views to accomplish what you're looking to do.
First, install and enable Views.  There are several tutorials out there that show you how to do this.  Nodeone has an awesome video introduction to Drupal Views.  (Personally this is one of my favorite Drupal resources. :)
Now that Views is installed and enabled, go to Structure, then 'Views' (In D7 this will be at http://www.example.com/admin/structure/views.)

Next create a new view (Add New View.)

Next, configure your View settings.  The example settings below will create a new block that contains the three most recent News items that link to the full version of each article article.  Views is capable of far more, but for the sake of simplicity I'll stick to creating a simple block.

Now go back to "Structure" and this time go to "Blocks."

My theme will be different from yours, but what you need to do is find the view you created, choose a location on your theme where you would like it to be displayed and then click save.  In this example I'm moving the block to the top of the navigation bar on the right hand side of my theme.

Once saved you should see similar output on your site as in the image below.  Note that this has my theme applied and your block will look different.

Lastly, to control which pages this block will be displayed on you can use the Blocks visibility settings.  How do I show blocks only on certain pages? is a great resource.

There are likely a million other ways to accomplish this, but this was the quickest I could think of using my nifty Greenshot app.
Comment: thks for this clear description. i also think this is the best solution.
Answer: Check out the Views module. This allows you to make pages (or blocks or many other things) which can get data from your drupal installation. Very powerfull.
In your case, you use a view to get the top 3 items from the content type "News" sorted by date posted.