How to install drush on a shared hosting without SSH and without composer?

Question: I would like to install Drush on my shared hosting account in order to let a cronjob call a specific module to this installation.
I have NO SSH access and NO Composer access on this shared hosting account and will not get it neither. I can setup a crontab job and run a call.
I looked extensivly to install drush but cannot find it.
Please do not answer that I should use SSH or composer. These answers will not be helpfull :-)
Comment: Dont think there is any way. All you can do is ask your hosting provider to do it. If they say no then you'll have to move provider
Answer: Rather than using drush, consider writing a custom script you can call instead.
In Drupal 7 you can bootstrap Drupal from the command line like this:
<?php
chdir('/var/www/YOUR SITE ROOT');

// no time limit!
set_time_limit(0);

// set some server variables so Drupal doesn't freak out
$_SERVER['SCRIPT_NAME'] = '/importer.php';
$_SERVER['SCRIPT_FILENAME'] = '/importer.php';
$_SERVER['HTTP_HOST'] = 'somewhere.com';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['REQUEST_METHOD'] = 'POST';

// change to the Drupal directory
define('DRUPAL_ROOT', getcwd());

 // Drupal bootstrap throws some errors when run via command line
 //  so we tone down error reporting temporarily
error_reporting(E_ERROR | E_PARSE);

// run the initial Drupal bootstrap process
require_once('includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// act as the first user
global $user;
$user = user_load(1);
// add your custom code here

You will need to tweak this to your specific needs. Place it outside your site root for security reasons.
Answer: Upload drush.phar to your web host and then you can execute the phar file in php:
php ~/path_to_the_drush_binary/drush.phar

You'll find the drush.phar file on https://github.com/drush-ops/drush/releases, the latest drush 8 version is https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar.


Can I use a Mann-Whitney U Test with a very small sample?

Question: I want to compare differences between two independent groups (female and male) when dependent variables are continuous. However, my sample size is very small (N=6). I have done a Mann-Whitney U Test and I am not sure if the results are meaningful given the small sample.
Answer: This has been discussed at length on this site.  Briefly, the test is valid.  But no test is especially helpful because of our inability to interpret large p-values, which do not indicate "no difference".  Instead I would replace a test with a confidence interval or Bayesian credible interval.  These have interpretations regardless of sample size and regardless of whether a null hypothesis is true.
Comment: The confidence interval that is consistent with the WIlcoxon test is the Hodges-Lehmann interval whose point estimate is the median of all possible pairwise differences between the two groups.  For the mean I would use the Bayesian t-test which allows for non-normality and non-equal variance - see the inference chapter in [BBR](https://hbiostat.org/bbr).
Comment: Many thanks, Frank. Which test do you replace using a   frequentist approach for a confidence interval"?
Answer: Frank's advice is useful; I don't wish my answer to suggest any disagreement with that answer.
The Wilcoxon-Mann-Whitney test "works as it should" in small samples. There's a few things to note:

You will have the usual issues with trying to use hypothesis tests in small samples, like low power against anything but large effects (and all the consequences that come along with that). That's not specific to the test you're using -- other tests will also have the same issues because of the same small sample sizes.

A permutation test (such as the Wilcoxon-Mann-Whitney test) will not typically attain exactly the desired type I error rate, though this impact will only be particularly noticeable in quite small samples. For example, if your rejection rule is "reject if the computer tells me the p-value is $\leq$ 0.05", then you won't actually attain the 5% significance level you were aiming for, because of the discreteness of the test statistic. With the Wilcoxon-Mann-Whitney at $n_1=n_2=6$, and a two-sided alternative, that rejection rule actually leads to a 4.1% type I error rate (if the computer is using exact p-value calculations, at least), so the test conducted that way is somewhat conservative. [There's a way to mitigate this issue at least somewhat without going to randomized tests, though it may be best to avoid distracting
from the main question here by detailing it.]
Casting the rejection rule in terms of the p-value means you only get the next lower significance level to the one you were seeking. Imagine you wanted a 1% test; then the type I error rate you get goes down from there, even if there was one only just above 1% that you might perhaps have been happy to use had you only realized it was there. For example, if the available significance levels were 0.4% and 1.01%, you'll get the 0.4% level with the approach of comparing the p-value to the significance level you were originally aiming for. This problem becomes more noticeable when adjusting individual significance levels for multiple testing to control overall type I error, and considerably worse at even smaller sample sizes than yours.
It's quite possible this way to get into a situation where your actual significance level is not just "lower than you wanted", but exactly $0$. This is not merely a theoretical possibility that would not occur in practice $-$ I have seen multiple occasions where people have done just this without even realizing it. I think it's better (before seeing the data to avoid any appearance of p-hacking) to consider the available significance levels and choose the testing strategy in full knowledge of the situation one is to be faced with, rather than being surprised by it after seeing the data - or worse, to never even realize that it was not possible to reject the null with the rejection rule that was being used.
It's not difficult to identify all the available significance levels for whatever test you're using (e.g. for the specific situation you're asking about, it can be done with a single line of R code), and I can't see any good reason not to do so as a matter of course, whenever you would be faced with small sample sizes and a discrete test statistic.
Comment: I just want to add that if you don't create a rejection rule but just want to get a p-value, exact p-values are available for Wilcoxon as long as there are no ties.
Answer: For a 2-sample Wilcoxon Rank Sum test (equivalent to Mann-Whitney U test),
the smallest sample size of each of the two samples is $n_1=n_2=3$
in order for a one-sided test to give significance level 5% or less.
Even then, significance requires complete separation; that is, all
observations in one sample must be smaller than any observation in
the other (and with no tied data). Using R:
wilcox.test(c(5,6,7),c(2,3,4), alt="g")

        Wilcoxon rank sum test

data:  c(5, 6, 7) and c(2, 3, 4)
W = 9, p-value = 0.05
alternative hypothesis:
 true location shift is greater than 0

That is because ${6 \choose 3} = 20.$
1/choose(6,3)
[1] 0.05

Similarly, for a two-sided test at or below level 5%, the smallest sample sizes are $n_1 = n_2=4.$
wilcox.test(c(5,6,7,8),c(1,2,3,4))

        Wilcoxon rank sum test

data:  c(5, 6, 7, 8) and c(1, 2, 3, 4)
W = 16, p-value = 0.02857
alternative hypothesis:
 true location shift is not equal to 0

That is because $\frac{2}{{8\choose 4}} = 2/70 =  0.02857.$
2/choose(8,4)
[1] 0.02857143

Also,
wilcox.test(c(5,6,7,8),c(1,2,3))$p.val
[1] 0.05714286


Fancybox is repeating pictures

Question: i have created a gallery using fancy-box but i have a problem that when i open all items (all projects) it works properly as each item will show its own pictures (only three picture) as shown in this picture

(have only three thumbnails) but when i open a specific category (villas category) pictures for all villas will shown as this picture

(6 thumbnails included for two projects)
and if i press all project again i will have the same problem and the picture for all items will be shown  (9 thumbnails for 3 items)
so i think the problem is with the java script and here below is the html code and java script code
sorry i am new to programming and i need your help, i appreciate your efforts

  All Projects
  Villas
  Residential and Commercial
  Mixed Used

    ©Copyright Qyas Engineering Consultancy All Rights Reserved.

Answer: I would suggest you to use Isotope + fancybox combination, see this example:
http://codepen.io/fancyapps/pen/EZKYPN
Because then your code could be simplified to something like this:
// Custom click event - open fancyBox manually
$('.fancybox').on('click', function() {
  var visibleLinks = $('.fancybox:visible');

  $.fancybox.open( visibleLinks, {}, visibleLinks.index( this ) );

  return false;
});

Fancybox is repeating pictures


How to retrun variable value to the js?

Question: I want to return the value of P221_JSON_PROCESS item to the variable and then return the value to the new vis.DataSet. I tried as follows:
// P221_JSON_PROCESS contains - { id: 1, label: "Node 1" },
function returnNodes() {
var process = document.getElementById("P221_JSON_PROCESS").value;
return process;
}

var nodes = new vis.DataSet([
  returnNodes();
]);

// create an array with edges
var edges = new vis.DataSet([
]);

// create a network
var container = document.getElementById("mynetwork");
var data = {
  nodes: nodes,
  edges: edges,
};
var options = {};
var network = new vis.Network(container, data, options);

Thanks in advance!
Answer: You can use add method like
var nodes = edges.add([returnNodes()]);

or
var nodes = new vis.DataSet([,returnNodes()]);

How to retrun variable value to the js?


MATLAB fseek binary data read-in issue

Question: MATLAB 184.108.40.2064 (R2011b), UBUNTU 12.04 (precise) 64-bit
I am trying to read in a subset (not starting from the beginning) of 2D data from a binary files. I know that 1 2D dataset is 5838952 Bytes:
>>whos

DATA               5747x127                 5838952  double

I try to use fseek to skip the first 400 2D datasets:
fseek(fid,5838952*400,'bof');

and then read in the next 100 datasets:
for i = 1:100
    DATA(i,:,:) = fread(fid,[5747 127],'int16');
end

But the code continues to read in the first 100 2D datasets without skipping the first 400 as I wanted. Anyone know why? Thank!
edit:
If I do
fseek(fid,5838952*400,'bof');
position = ftell(fid)

I get:
position =

     0

Comment: Did you check the return value of `fseek`? From the documentation:  returns 0 when the operation is successful. Otherwise, it returns -1.
Comment: fseek(fid,5838952*400,'bof')                                          ans = -1. I don't know why it's unsuccessful.
Comment: I've read that "whos" returns the number of bytes each variable occupies in the workspace so perhaps that doesn't match the actual binary file! fseek(fid,10,'bof')
position = ftell(fid) returns ans=0, position=10.
Comment: Yes exactly, see my answer. Your data in file is int16 (2 bytes) but double (8 bytes) in MATLAB memory.
Answer: You are seeking off the end of the file. Run
ferror(fid)

immediately after
fseek(fid,5838952*400,'bof');

The data is int16 in the file but you are loading as double in MATLAB, so the size is four times as many bytes. You should seek to:
status = fseek(fid, 5747 * 127* 400 * 2, 'bof')

Comment: Thank you. This works great:                                                fseek(fid,5838952*400,'bof')
ferror(fid)                                                                                ans =  -1
ans = Offset is bad - after end-of-file or last character written.                 status = fseek(fid, 5747 * 127* 400 * 2, 'bof')                                                                                status = 0
ans = '   '
position = 583895200

MATLAB fseek binary data read-in issue


To create red-blue-green colormap for medical imaging?

Question: I run
imagesc(real(lena))
colormap(hsv)

where lena is a picture in 512x512 pixels.
I would like to get the special red-green-blue colormap like here discussed.
A picture processed by it:

How can you get such a colors by the command colormap?
Comment: If there aren't any predefined colour maps that you like, it's pretty easy to make your own: http://stackoverflow.com/questions/17230837/how-to-create-a-custom-colormap-programatically/17232355#17232355
Comment: @Dan just tried the colormapeditor and was very happy to find such a nice tool. Thanks for the link!
Answer: Use colormap bone to get this gray-ish blue-ish tones for your medical images.
Here's an example of this colormap taken from Mathworks:

See manual for more examples and pre-defined color maps.
Answer: Note that the paper describes a way to combine two images, it does not use a color map.
If a is the gray-scale normal MRI image, and b is the gray-scale contrast-enhanced MRI image, the paper proposes to use cat(3,a,b,a) as an RGB image, where contrast-enhancement appears as a green overlay. What that statement does is use the normal image as the red and blue channel, and the contrast-enhanced image as the green channel.


how to make an Activity scrollable even if no ScrollView is needed?

Question: I have an Activity that includes some RelativeLayouts arranged vertically in a LinearLayout. now I want the user to be able to play with the activity by scrolling it up and down, I mean suppose I have 4 RelativeLayouts in a LinearLayout in my activity and they only occupy half of the screen vertically, so there is no need for ScrollView, but I want to scroll up/down (if the user scrolled up/down) and come back to first position (like an spring!). it's not a new thing and I'm sure you all know what I say! how to do that?
Comment: there was a patent issue related to Apple's patent of bouncing list view implementation, so Google removed this feature of ScrollViews, they added blue shadow on edge instead
Comment: That springgy effect is actually a patented UI/UX pattern from apple. There some free libraries that implement similar things but I have primarily seen them applied to ListViews rather than to scrollViews. The overscroll on android is usually indicated by a gradient that shows up when you reach the end.
Comment: but ScrollView only scrolls up/down while it is needed and if you scroll up to reach to the head, then nothing happens if you scroll up more (an springy behavior doesn't happen)
Comment: interesting, but finally is it possible to do that in Android?!!! if yes, how?
Answer: Add an ontouchlistener to your scrollview that wraps your outer linear layout and have the listener handle over scroll. You will have to modify a lot of this to meet your needs but it will provide the basics of how this would work. Or you could go with the fade edge property already in listview and save a lot of time not duplicating the Apple UI.
Example Touch Listener
using System;
using System.Collections.Generic;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Views.Animations;

namespace SomeProgram
{

public class ViewFlipperSwipeDetector : ParentActivity, View.IOnTouchListener
{

    //private Activity activity;
    private ViewFlipper viewflipper;
    int MIN_DISTANCE = 100;
    private float downX, downY, upX, upY;

    public ViewFlipperSwipeDetector(ViewFlipper viewflipper)
    {
        //this.activity = activity;
        this.viewflipper = viewflipper;

    }

   private Animation inFromRightAnimation()
   {
    Animation inFromRight = new TranslateAnimation(
    Dimension.RelativeToParent, +1.0f, Dimension.RelativeToParent, 0.0f,
    Dimension.RelativeToParent, 0.0f, Dimension.RelativeToParent, 0.0f);

    inFromRight.Duration = 400;
    inFromRight.Interpolator = new AccelerateInterpolator();
    return inFromRight;
    }

    private Animation outToLeftAnimation()
    {
     Animation outtoLeft = new TranslateAnimation(
     Dimension.RelativeToParent, 0.0f, Dimension.RelativeToParent, -1.0f,
     Dimension.RelativeToParent, 0.0f, Dimension.RelativeToParent, 0.0f);

    outtoLeft.Duration = 400;
    outtoLeft.Interpolator = new AccelerateInterpolator();
    return outtoLeft;
    }

    private Animation inFromLeftAnimation()
    {
    Animation inFromLeft = new TranslateAnimation(
    Dimension.RelativeToParent, -1.0f, Dimension.RelativeToParent, 0.0f,
    Dimension.RelativeToParent, 0.0f, Dimension.RelativeToParent, 0.0f);
    inFromLeft.Duration = 400;
    inFromLeft.Interpolator = new AccelerateInterpolator();
    return inFromLeft;
    }

    private Animation outToRightAnimation()
    {
    Animation outtoRight = new TranslateAnimation(
    Dimension.RelativeToParent, 0.0f, Dimension.RelativeToParent, +1.0f,
     Dimension.RelativeToParent, 0.0f, Dimension.RelativeToParent, 0.0f);
    outtoRight.Duration = 400;
    outtoRight.Interpolator = new AccelerateInterpolator();
    return outtoRight;
    }

    protected void onRightToLeftSwipe()
    {
        //Toast.MakeText(activity, "RightToLeftSwipe!", ToastLength.Short).Show();
        viewflipper.InAnimation = inFromRightAnimation();
        viewflipper.OutAnimation = outToLeftAnimation();
        viewflipper.ShowNext();

    }

    protected void onLeftToRightSwipe()
    {

       // Toast.MakeText(activity, "LeftToRightSwipe!", ToastLength.Short).Show();
        viewflipper.InAnimation = inFromLeftAnimation();
        viewflipper.OutAnimation = outToRightAnimation();
        viewflipper.ShowPrevious();

    }

    protected void onTopToBottomSwipe()
    {
        //Toast.MakeText(activity, "TopToBottomSwipe!", ToastLength.Short).Show();
        //activity.doSomething();
    }

    protected void onBottomToTopSwipe()
    {
        //Toast.MakeText(activity, "BottomToTopSwipe!", ToastLength.Short).Show();
        //activity.doSomething();
    }

    public bool OnTouch(View v, MotionEvent e)
    {
        switch (e.Action)
        {
            case MotionEventActions.Down:
                {
                    downX = e.GetX();
                    downY = e.GetY();
                    return true;
                }
            case MotionEventActions.Up:
                {
                    upX = e.GetX();
                    upY = e.GetY();

                    float deltaX = downX - upX;
                    float deltaY = downY - upY;

                    // swipe horizontal?
                    if (Math.Abs(deltaX) > MIN_DISTANCE)
                    {
                        // left or right
                        if (deltaX < 0) { this.onLeftToRightSwipe(); return true; }
                        if (deltaX > 0) { this.onRightToLeftSwipe(); return true; }
                    }
                    else
                    {
                        //Toast.MakeText(activity, "Swipe was only " + Math.Abs(deltaX) + " long, need at least " + MIN_DISTANCE, ToastLength.Short).Show();
                        return false;
                    }

                    // swipe vertical?
                    if (Math.Abs(deltaY) > MIN_DISTANCE)
                    {
                        // top or down
                        if (deltaY < 0) { this.onTopToBottomSwipe(); return true; }
                        if (deltaY > 0) { this.onBottomToTopSwipe(); return true; }
                    }
                    else
                    {
                        //Toast.MakeText(activity, "Swipe was only " + Math.Abs(deltaX) + " long, need at least " + MIN_DISTANCE, ToastLength.Short);
                        return false;
                    }

                    return true;
                }
        }
        return false;
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
    }

}
}

Comment: thanks for your code and idea but what is it written in? that's not Java...anyhow it gave me a good start point :);)
Comment: Its c# from a Xamarin.Android project should be pretty easily convertible.


Determining if a set of vectors spans a space. Why does the determinant have to be nonzero?

Question: I am reading this text:

and I'm wondering when determining the span, why does the determinant have to be non zero? If the determinant was zero, couldn't the random vector have many non-unique solutions? And if a random vector could be represented by several different combinations of the vectors... wouldn't the vectors still span R^3?
Comment: Check out the [Inverse Matrix Theorem](http://mathworld.wolfram.com/InvertibleMatrixTheorem.html), particularly points 3, 6, 7, and 19. One of the problem of doing linear algebra with determinants is that proving all the lovely properties of determinants is horrible, and the intuition behind it is not straight forward at all. I would convince yourself by other means (e.g. directly solving) that these systems of equations have unique solutions.
Answer: If there is a vector that can be written as a linear combination of $v_1,\dots,v_n$ in more than one way,  then the vectors are linearly dependent.   For, call the vector $v$.  We'd have $$\alpha_1v_1+\dots+\alpha_nv_n=v=\beta_1v_1+\dots+\beta_nv_n$$.  Then since at least one $\alpha_i\not=\beta_i$, we have the following nontrivial linear combination equal to zero: $$(\alpha_1-\beta_1) v_1+\dots+(\alpha_n-\beta_n)v_n=0$$.
So, in this situation, say we are in $\mathbb R^3$, and we have $3$ vectors (the columns of a matrix).  Call the matrix $A$.  We know the image is the span of the columns.   Say $Ax=v$ has more than one solution for some $v$ (that is, $\operatorname{det}A=0$)  as above.  Then the $3$ vectors couldn't span, because they would be linearly dependent.
Answer: If you remember the analogy for the determinant, that the length/area/volume... of a $N$-dimensional parallelepiped is equal to $|\det(V)|$ where $v$ is a set of vectors.
Take a $2$ dimensional example where the vectors point in different directions. The abs(determinant) will be the area of the parallelogram spanned by the vectors.
Whereas, if the vectors are linearly dependent, they will have area $0$ because they form a degenerate parallelogram.
If we extend this to $3$ dimensions and a set of linearly dependent vectors, one of the vectors may lie in the plane spanned by the two other vectors. Therefore, it will have $0$ volume.


Why isn't intellij giving me the option to create new classes?

Question: Here's what I'm seeing:

Normally I can choose "New Java Class" but for some reason I'm not getting this option.  I created this project by opening an empty directory and building it out from there.  I've seen this question, but that answer didn't help me.  Here's my module settings:

Even if I open my pom.xml directly as a project, it still has this problem.  How do I fix this?
Answer: The directory or one of the parent directories must be marked as Source Root (In this case, it appears in blue).
If this is not the case, right click your root source directory -> Mark As -> Source Root.
Answer: This worked for me :

Right click the java folder (myproject/src/main/java)
Click "Mark Directory as"
Click "Source Root"
Right click the myproject folder (myproject/src/main/java)
Click "Mark Directory as"
Click "Source Root"

So basically had to mark some inner folder as Source project and alter mark parent project again as Source project..
Hacky way but this worked for me.
Answer: For some reason, intellij didn't recognize my directories as packages.  If I created something directly from the java directory, it would give me the correct options.  I fixed this by deleting everything under java/ and recreating it.  This may be an intellij bug.
Answer: This happened when I was trying to add classes to a generated package using xjc plugin.
Intellij allows to add classes only to packages which are correctly names and have the "source root" status.
Can be fixed as-> right click on the directory where you're not able to add classes:
Mark sources root
refer image for clarity


Compiler Unaware of Provided Methods of Trait

Question: I'm using the prost crate in a very "hello world" way, with a basic ProtoBuf file:
foo.proto
syntax = "proto3";
package foo;

message Foo {
    string mystring = 1;
}

I can verify the types that prost produces at compile time by inspecting ./target/PROJECT/build/PROJECT-{some hash}/out/foo.rs:
foo.rs
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct Foo {
    #[prost(string, tag="1")]
    pub mystring: ::prost::alloc::string::String,
}

See that the prost::Message trait gets derived? Its docs claim I have tons of functions at my disposal for this trait, but only the two required ones, encoded_len() and clear(), can be called without error. Any of the provided ones (those with default implementations) result in a cannot find function in this scope error.
main.rs
use prost::Message;

pub mod foo {
    include!(concat!(env!("OUT_DIR"), "/foo.rs"));
}

fn main() {
    let f = foo::Foo { mystring: "bar".to_string() };
    let v = encode_to_vec(&f);
}

cargo run

error[E0425]: cannot find function `encode_to_vec` in this scope
   |
   |     let v = encode_to_vec(&f);
   |             ^^^^^^^^^^^^^ not found in this scope

And, worryingly, this warning implies it's not even looking at the trait it needs to:

warning: unused import: prost::Message

(edit) For reference:
Cargo.toml
[package]
name = "testing"
version = "0.1.0"
edition = "2018"

[dependencies]
prost = { version = "0.7.0", features = ["std"] }

[build-dependencies]
prost-build = "0.7.0"

Comment: Extra info: My Cargo.toml depends on `prost` using `features=["std"]`, and I ensured the Foo struct implements the `Sized` trait.
Answer: encode_to_vec is not a free function. You need to call it as one of

f.encode_to_vec()
foo::Foo::encode_to_vec(&f)
Message::encode_to_vec(&f)
<foo::Foo as Message>::encode_to_vec(&f)

The first method is the most normal, but the other ones may produce useful error messages when you get confused about what's going on.

[Edit:] Well, encode_to_vec was added in prost 0.8.0, so with 0.7.0, it won't be usable.
Comment: Nope, all 4 of those ways produce errors. Either `cannot find method or associated constant 'encode_to_vec' in trait 'Message'` or `function or associated item not found in 'Foo'`
Comment: Can't reproduce. What prost version are you using? (Maybe edit your question and add the entire `Cargo.toml`…)
Comment: Edited answer to include `Cargo.toml` but this was the problem - I was only on v. 0.7.0. Updating to 0.9.0 solved this.


WCF Restful Https para um único método

Question: Tenho um WCF RESTful que estou utilizando para um aplicativo mobile, preciso que um único método, o de pagamento, utilize HTTPS, não quero habilitar HTTPS para o serviço inteiro porque alguns métodos retornam uma quantidade grande de dados e ficaria muito pesado para um celular.
Isso é possível? como?
Gostaria de saber se tem alguma propriedade ou outra forma de permitir que este método seja acessado apenas quando utilizar uma conexão segura...
Algo do tipo...
<code>[OperationContract]
[ExigirHTTPS(true)]
[WebInvoke(Method = "POST", UriTemplate = "/Disponibilidade", RequestFormat =     WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
DisponibilidadeRS Disponibilidade(DisponibilidadeRQ request);
</code>
Comment: Para evitar que sua pergunta seja sinalizada, sugiro que você especifique um pouco melhor o que quer.
Answer: O IIS pelo menos deixe os dois protocolos (http, https) ser habilitados ao mesmo tempo. Se tiveres accesso ao servidor, uma posibilidade, embora nao muito elegante, é usar regras de 'url rewrite' (http://www.iis.net/downloads/microsoft/url-rewrite) que intercepte o url especifico e dirige ao https. Entao, os clientes podem usar http a vontade pelo resto do site.

WCF Restful Https para um único método


How to to get the prices centered in the node:teaser with commerce price savings formatter?

Question: I am pretty new to drupal and I have a problem with formatting the price in my drupal shop. I am using commerce sale price -module and commerce price savings formatter -module.
In the default view, the price shows ok, in the right position. But in the view (node:teaser) it shows the prices in the wrong position. I have tried everything to get the prices centered (modifying the css), but they are still on right side all the time. I would also like to remove the line above the price if its possible.
Here is the link to my shop: http://www.oladevelopment.fi/mifuko/content/home-shop
Ant ideas on how I can get the prices shown in the way I want?
Answer: Add this in your CSS:
table.commerce-price-savings-formatter-prices{
width: 100%;
}

Also, you can add:
.commerce-price-savings-formatter-price .price-amount{
display: block;
padding-top: 5px;
}

Prices looks much better with this.
If width:100% doesn't work try to use width:100% !important; because width is already defined in module's theme.
To remove line above price add this to your CSS:
table.commerce-price-savings-formatter-prices tbody{
border-top:0;
}

Also, if it doesn't work, use border-top:0 !important; instead border-top:0;
To minimize the space between prices add to CSS:
table.commerce-price-savings-formatter-prices-down{
margin: 0 auto;
width: 50%;
}

Important part here is width: 50%;, change this percent to see which space you want to have, the more percent is the more space will be between prices. Again, use !important if doesn't work.
You can also add this to your CSS to make prices look better (to make it equal at the bottom edge):
table.commerce-price-savings-formatter-prices-down tr td{
vertical-align: bottom;
}

Don't forget to clear cache.
Comment: Hi, thanks a lot for the help! Now I got them centered! But I would still like to know how I get that line above the price removed? And now there is a big space between the over-lined normal price and the sale price, how can I minimize that space?
Comment: I updated my answer, look there how to remove line. Be more specific about what you want to do with space, I don't see any other price, there is only one price.
Comment: Thanks a lot! This worked and I got the line removed! The prices that are on sale have the gap between the normal price and the sale price: http://www.oladevelopment.fi/mifuko/product-category/discount-items
How can I minimize that gap?
Comment: I updated the answer...


Para que serve o !=?

Question: Para que serve o != no C# e como posso utilizar adequadamente? Visualizei um exemplo em uma estrutura de repetição com for, no entanto não entendi muito bem a função dele.
int soma = 0;
for (int i = 1; i <= 100; i++)
{
    if (i % 3 != 0)
    {
        soma += i;
    }
}

Comment: É o operador binário de desigualdade.  Sugerido: https://msdn.microsoft.com/en-us/library/czs2584d.aspx
Comment: `!=` seria: não é igual a, diferente de, etc ... basicamente o contrário de `==`
Answer: Em c# != é um operador relacional que significa "diferente de".
Outros operadores relacionais são ==, <, >, <=, >=, que significam igual, menor que, maior que, menor ou igual e maior ou igual respectivamente.
São usados para fazerem condições com os comandos if, while, entre outros.
Alguns exemplos podem ser encontrados aqui: https://www.tutorialspoint.com/csharp/csharp_relational_operators.htm

Para que serve o !=?


Mistake in derivation about categorical distribution and Dirichlet distribution?

Question: $p(x|\pi)$ follows the categorical distribution (the multinomial with one observation), where $\sum\pi_i=1$ and $x$ is a one-hot vector, and $p(\pi|\alpha)$ follows the Dirichlet distribution.
$p(x|\pi)=\prod\pi_i^{x_i}$
$p(\pi|\alpha)=\frac{1}{B(\alpha)}\prod\pi_i^{\alpha_i-1}$
$p(x,\pi|\alpha)=\frac{1}{B(\alpha)}\prod\pi_i^{\alpha_i-1+x_i}$
$p(x|\alpha)=\int p(x,\pi|\alpha)d\pi=\frac{1}{B(\alpha)}\int\prod\pi_i^{\alpha_i-1+x_i}d\pi=\frac{B(\alpha+x)}{B(\alpha)}$
$\sum p(x^{(i)}|\alpha)=\sum\frac{B(\alpha+x^{(i)})}{B(\alpha)}=\sum\frac{\alpha_i+1}{1+\sum\alpha_j}\neq1$
where $x^{(i)}$ is the one-hot vector with the i-th bit equal to 1.
please correct me where I'm wrong, thanks in advance.
Comment: @whuber hi, sorry I didn't explain it clearly, i think it is the "categorical distribution" or the multinomial with one observation, where $\sum\pi=1$ and $x$ is a one-hot vector.
Comment: @whuber fair point. I guess I have always run into only one meaning of "Categorical distribution".
Comment: How do you obtain the second line (the expression for $p(x|\pi)$)?  Have you verified that it is a properly normalized probability distribution?
Comment: @whuber That is the pdf of a categorical distribution (a multinomial with number of trials = 1)
Comment: @Greenparker Where is it stated that the number of trials is $1$?
Comment: @whuber that is the definition of a categorical distribution (a multinomial with number of trials being 1)
Comment: @Greenparker It all depends on context.  It's easy to imagine using the same notation to describe samples of size larger than one from a categorical distribution.  It's important for the OP to explain themselves rather than leaving their intentions up to the imaginations of the readers.
Answer: I think the mistake was with simplifying the $B(\cdot)$ function. Suppose $x$ is a $K$ length vecto, and let $\sum_{k=1}^{K} \alpha_k = A$.
$$B(\alpha) = \dfrac{\prod_{k=1}^{K} \Gamma(\alpha_k)}{\Gamma(A )} $$
\begin{align*}
\dfrac{B(\alpha+x)}{B(\alpha)} & = \dfrac{\prod_{k=1}^{K} \Gamma(\alpha_k + x_k)}{\Gamma(\sum_{k=1}^{K} \alpha_k + \sum_{k=1}^{K} x_k )}\dfrac{\Gamma(A )} {\prod_{k=1}^{K} \Gamma(\alpha_k)}\\
\end{align*}
Since only one of the components of $x$ can be 1, $\sum_{k=1}^{K} x_k  = 1$. Also, note that $\Gamma(z + 1) = z\Gamma(z)$. Using this,
\begin{align*}
\dfrac{B(\alpha+x)}{B(\alpha)} & = \dfrac{\prod_{k=1}^{K} \Gamma(\alpha_k + x_k)}{\Gamma(A + 1 )}\dfrac{\Gamma(A )} {\prod_{k=1}^{K} \Gamma(\alpha_k)}\\
& = \dfrac{\prod_{k=1}^{K} \Gamma(\alpha_k + x_k)}{\prod_{k=1}^{K} \Gamma(\alpha_k)}\dfrac{1}{A}\\
& = \dfrac{1}{A} \prod_{k=1}^{K}\dfrac{\Gamma(\alpha_k + x_k)}{\Gamma(\alpha_k)}\\
& = \prod_{k=1}^{K} \dfrac{1}{A} \dfrac{\Gamma(\alpha_k + x_k)}{\Gamma(\alpha_k)} = \prod_{k=1}^{K} p(x_k|\alpha).
\end{align*}
To verify if this is a valid pdf
\begin{align*}
\sum_{k=1}^{K} p(x_k = 1|\alpha_k) & = \sum_{k=1}^{K}\dfrac{1}{A} \dfrac{\Gamma(\alpha_k + 1)}{\Gamma(\alpha_k)}\\
& = \sum_{k=1}^{K}\dfrac{\alpha_k}{A} =1.
\end{align*}
I am not sure what steps you skipped, but I think you misused the $\Gamma(\cdot)$ function property.
Comment: Ah, classic mistake. Glad I could help.
Comment: thank you so much! I mistakenly assumed that $\Gamma(z+1)=(z+1)\Gamma(z)$.
Comment: so we have $p(x|\alpha)=p(x|E[\pi])$ right? is that some common property? it would be great if you could take a look at my other question, http://stats.stackexchange.com/q/213389/95569, ty.


Kernel Panic on VMware Workstation 7.1.3

Question: I've been trying to install either Arch Linux or Fedora 17 on VMWare Workstation (7.1.3). After I point to the right ISO image, I get the following error:
<code>Booting the kernel
PANIC: early exception 0d rip:ffffffff81042dc4 error 0 cr2 0
</code>
I am trying to install it on a machine which has a 3rd generation i5 processor. After checking A VMWare panic early exception fix for ivy bridge i3, i5, i7, I tried to turn off the nosmep acpi. This is around, I get the same error but at a different address. Apparently, others have faced this issue before.
Thanks in advance.
Comment: I thought this qualified as a valid question as per the 1st point in the FAQ, as the machine is a Business Workstation and since it concerned virtualization.... Is there a better way to ask this question or is there another place I can ask this?
Answer: This happens when your hardware does not support virtualization or virtualization is not enabled in bios. Are you sure your hardware supports virtualization?
please reboot your computer to bios, search for Processor menu and enable VT (Intel Virtualization Technology) if it is present.
I hope it helps
What is your host operating system?
Comment: Thanks for the quick response. The hardware supports Virtualization. The machine runs both Win 7 and Fedora 17. We have Virtualbox on Fedora 17 upon which we run instances of Fedora, Ubuntu and XP. The host OS for the VMWare Workstation is Windows 7


How to Prevent a request from being cached for LANGUAGE SWITCH routing Laravel Spatie responsecache

Question: I am using Laravel Spatie response cache: https://github.com/spatie/laravel-responsecache and Multiple language (language switch..).
How to fix: Preventing a request from being cached for language switcher route in Laravel.
I tried to add: ->middleware('doNotCacheResponse'); in lang.switch route but without success...
Route::get('lang/{language}', ['as' => 'lang.switch', 'uses' => 'LanguageController@switchLang'])->middleware('doNotCacheResponse');

Expected results to prevent request when switching pages (links) between language to be cached....
Answer: Not sure if I understand you correctly. If the problem is that you get cached results after you select a different language, I think you should clear the entire cache:
LanguageController {

    public function switchLang() {
        // Switch language
        ResponseCache::clear();
    }

}

Also, seems like spatie/laravel-responsecache allows you to delete specific URIs with ResponseCache::forget('/some-uri');
To delete cache after altering your data, do something like this
PostController {

    public function index()
    {
        // Display list of posts
    }

    public function edit()
    {
        // Display form to edit post
    }

    public function update()
    {
        // Delete related cache here and update post
        ResponseCache::forget('/posts');
    }
}

Comment: Thanks Artjom Heinz,

Where I should add the second code you sent me: ResponseCache::forget('/some-uri');

?!

And please if you can see this problem how to solve it: https://github.com/spatie/laravel-responsecache/issues/156
Comment: Hello,

I am using laravel spatie response cache with my laravel app, when I add some new posts on my website, I dont see the new added post anywhere (on homepage, in posts index page listed).

Why I dont see new added posts?! And how to solve this.

I want to have cached homepage and all index pages but to see new added posts, articles etc?!

What is solution for this ?!

Thanks
Comment: @TarikS. I was just pointing out that it's possible to remove specific URIs **instead of** deleting the entire cache. Whether or not that's something you should do, I don't know. Regarding your second question, I suspect you don't see changes because you're getting the cached response. If so, don't cache dynamic data. https://stackoverflow.com/questions/5658417/handling-caching-dynamic-data
Comment: Helo @Artjom Heinz,

Yes I am getting cached response I am using spatie for all my routes except update/edit/delete, But when I add new posts/articles for example, I want to view new added articles on my index and show pages but now I dont see them, what should I do here.

You said to not cache, do you mean that than I dont cache index homepage and show pages, but what should than I cache ?!

thanks
Comment: @TarikS.Yes. Simply put, you don't cache somemthing that changes frequently. Typically, you cache things that don't change. The thread I linked to in my last comment explains some caching strategies for dynamic data. If you insist on caching, then you should delete the related cache after changing the data. So maybe if you expect users to add new data very rarely it would make sense to cache but to delete the cache after soemthing has been added.
Comment: yes that is great, for example I have index view page and with $posts , and users adding new data (posts) every 3 - 4 or 5 days, I want to use cache here but to to delete cache for that particular route (view) after new posts are added in database that is it.

I havent seen anything related to this in spatie doc on github can you tell me how can I implement that in my route for example for my homepage for email@example.com.... using SPATIE cache....

...Thanks
Comment: @TarikS. I've edited my answer with an example of how this could work.
Comment: I see your updated answer, but it is about update function when I updating some previously added posts for example. But my concern is VIEW AND SHOW blade files.

I explained everything here in this uploaded screenshot below what I need, spatie cache work well, site is fast and good but I have for example on some view blade pages some dynamic data 1 or 2 divs with dynamic data.
Comment: See this:

See this screenshot : https://imgur.com/a/GXPkvQg

 ;;"" I want to cache everything on this page (banners in header, navbar,
 head, footer, everything) except this div (Services) because this is only
DYNAMIC on this page.

That is what I ask you for...""
Comment: Good example.... I want to Cache partials in laravel blade for example just some partials im blade.php where foreach loop is.. that is it...
Comment: @TarikS. The package you are using caches the entire response. You can cache specific data with `Cache::put('key', 'value', $minutes);` as described [here](https://laravel.com/docs/5.7/cache)


$G$ is a finite solvable group. $M$ is a minimal nontrivial normal subgroup of $G$. Prove that $M$ is abelian

Question: Hint is to construct a subgroup $N \subset M$ of prime index, and prove that commutators of M lie in N.
There is an answer here but I'm not so familiar with commutators as I've only read about them in Dummit and Foote (we never did them in class). Also it's not clear to me how to create a subgroup of prime index.
Comment: So, your question is how to prove it without commutators, then?
Comment: Well, even that hint uses commutators, so I'd you should get acquainted with them, anyway...
Comment: I suppose my question is how to construct a subgroup of prime index and why commutators of M lying in N means it's abelian
Comment: This is true even if the group is infinite.
Answer: Take $\;M'=[M,M]\,=\;$ the commutator subgroup of  $\;M\;$ . This is a characteristic subgroup of a normal subgroup and thus normal in the whole group $\;G\;$. But $\;M\;$ is minimal normal (non-trivial), and of course also solvable, so it must be $\;M'=1\iff M\;$ is abelian.
Answer: A subgroup $H$ of $G$ is called characteristic, denoted by $H \ char \ G$, if $φ(H) =H$ holds for any $φ \in Aut(G)$.
Let $M$ be a minimal normal subgroup of $G$. You need to check:

$M$ is solvable.
There is a subgroup $N$ with $N<M$.
$N \ char \ M$ which implies $N=1$, so that $M$ is abelian.
If $p$ divides $|M|$, then $pM$ must be trivial in $G$.

Therefore, $M$ is an elementary abelian $p$-group.
Comment: What is meant by the notation $pM$?
Comment: @Raekye Did you understand what that notation stands for? (:
Answer: The other two answers helped me figure it out but I wanted to post a complete answer.
Consider the subgroup $M'$ generated by commutators of elements of $M$.
Note that $M'$ is characteristic in $M$; for any automorphism $\phi$ and a generator $xyx^{-1}y^{-1}$:
$$\phi(xyx^{-1}y^{-1}) = \phi(x)\phi(y)\phi(x)^{-1}\phi(y)^{-1} \in M'$$
$M'$ is characteristic in $M$ and $M \trianglelefteq G$ so $M' \trianglelefteq G$.
Since $M$ is minimal normal, $M' = \{1\}$ or $M' = M$.
Note that $M$ is solvable because $G$ is solvable.
By proposition 7 from section 5.4 of Dummit and Foote (page 169), $M/M'$ is the largest abelian quotient of $M$.
If $M' = M$ then $\{1\}$ is the largest abelian quotient, and $M$ is not solvable.
So $M' = \{1\}$ and therefore $M$ is abelian.

To see why the proposition is true (writing out the proof from Dummit and Foote), first note that $M/M'$ is abelian:
$$(xM')(yM') = xyM' = yx(x^{-1}y^{-1}xy)M' = yxM'$$
Now suppose $H \trianglelefteq M$ and $M/H$ is abelian.
Then:
$$1H = x^{-1}y^{-1}xyH$$
So $[x, y] \in H$ for all $x, y \in M$, so $M' \leq H$.
So $M/M'$ is the largest abelian quotient of $M$.


NullPointerException ao comparar duas matrizes String no java

Question: Possuo duas matrizes String e ao executar isto:
if (prod[i][0].equals(temporaria[j][0]) && prod[i][0]!= null && temporaria[j][0]!= null)

recebo NullPointerException sem ao menos entrar no laço IF.
Achei estranho justamente pelo if desconsiderar valores nulos.
Como é um sistema de vendas sem persistencia de dados primeiro cadastro os produtos e coloco tudo em uma matriz chamada prod.
Main:
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String prod[][] = new String[20][5];

        String cod, nome, desc, qtd, valor;
        boolean continuar = true;
        int escolha, cont_cod = 0;

        System.out.printf("Bem Vindo ao sistema de gerenciamento de loja");

        while (continuar == true) {
            System.out.printf(" \n Selecione uma opção \n 1- Cadastro de Produtos \n 2- Tela de vendas \n 3- Consulta todos produtos \n 4- Sair \n");
            escolha = in.nextInt();
            switch (escolha) {
                //CADASTRO
                case 1:
                    System.out.println("===CADASTRO DE PRODUTOS===");
                    System.out.println("insira o nome do produto");
                    nome = in.next();
                    System.out.println("insira uma descricao do produto");
                    desc = in.next();
                    System.out.println("insira a quantidade do produto");
                    qtd = in.next();
                    System.out.println("insira o valor do produto");
                    valor = in.next();

                    cod = Integer.toString(cont_cod);
                    cont_cod++;

                    Cadastrar.Cadastrar(prod, cod, nome, desc, qtd, valor);//metodo que cadastra na matriz

                    break;

                //===================================================================================//
                //VENDAS
                case 2:

                    Venda.Venda(prod);//metodo de venda

                    break;

                //===================================================================================//
                //CONSULTA DE TODOS OS PRODUTOS
                case 3:
                    for (int i = 0; i < prod.length; i++) {
                        if (!(prod[i][0] == null)) {
                            System.out.printf("codigo: " + prod[i][0] + " Produto: " + prod[i][1] + " descricao: " + prod[i][2] + "\n quantidade: " + prod[i][3] + " Valor: R$" + prod[i][4]);
                            System.out.println();
                        }
                    }

                    break;

                //===================================================================================//
                //SAIR
                case 4:
                    System.out.println("saindo da aplicacao, ate mais...");
                    continuar = false;
                    break;
                default:
                    System.out.println("insira apenas um valor válido para escolha(de 1 a 4)");
                    break;
            }
        }
    }
}

}
Classe Cadastrar:
public static class Cadastrar {

        public static void Cadastrar(String prod[][], String cod, String nome, String desc, String qtd, String valor) {
            for (int i = 0; i < 19; i++) {
                //para cadastrar o primeiro produto
                if (prod[0][0] == null) {
                    prod[i][0] = cod;
                    prod[i][1] = nome;
                    prod[i][2] = desc;
                    prod[i][3] = qtd;
                    prod[i][4] = valor;
                    //para cadastrar os proximos produtos usando a ultima posicao nao nula do vetor como referencia
                } else if (!(prod[i][0] == null) && prod[i + 1][0] == null) {
                    prod[i + 1][0] = cod;
                    prod[i + 1][1] = nome;
                    prod[i + 1][2] = desc;
                    prod[i + 1][3] = qtd;
                    prod[i + 1][4] = valor;
                    break;
                }

            }
        }
    }

Então comparo na classe venda:
 public static void Venda(String[][] prod) {
        Scanner in = new Scanner(System.in);
        int i, vlr_unit, vlr_tot = 0, qtd_prod, qtd_temp;
        boolean continua = true;
        String confirma, resposta;
        String temporaria[][] = new String[20][2]; //MATRIZ TEMPORARIA PARA SALVAR O "CARRINHO"
        System.out.println("===VENDA DE PRODUTOS===");

        while (continua == true) {
            for (i = 0; i < 20; i++) {
                System.out.println("insira o codigo do produto: ");
                temporaria[i][0] = in.next();
                System.out.println("insira a quantidade de compra deste produto: ");
                temporaria[i][1] = in.next();
                System.out.printf("deseja inserir outro produto? s ou n \n(respostas diferentes de s ou n serão considerado como nao) \n");
                resposta = in.next();
                if (!(resposta.equals("s"))) {
                    break;
                }
            }
            //IMPRIMINDO O RESUMO DA VENDA PARA CONFIRMACAO
            for (i = 0; i < 20; i++) {
                for (int j = 0; j < 20; i++) {
//O ERRO DO NULLPOINTER OCORRE AQUI NESTE IF
                    if (prod[i][0].equals(temporaria[j][0]) && prod[i][0]!= null && temporaria[j][0]!= null) {
                        qtd_prod = Integer.parseInt(prod[i][3]);
                        qtd_temp = Integer.parseInt(temporaria[j][1]);
                        if (qtd_temp > qtd_prod) { //VERIFICANDO SE HÁ ESTOQUE DISPONIVEL
                            System.out.println("O produto de codigo " + temporaria[j][1] + " possui quantidade insuficiente para venda requisitada");
                        } else {
                            //TRANSFORMANDO OS VALORES DOS PRODUTOS PARA INTEIRO PARA PODER CALCULAR PRECO UNITARIO E TOTAL
                            vlr_unit = Integer.parseInt(prod[i][4]);
                            vlr_tot += vlr_unit * (Integer.parseInt(temporaria[j][1]));
                            System.out.printf("codigo: " + prod[i][0] + " Produto: " + prod[i][1] + "\n quantidade: " + temporaria[j][1] + " Valor: R$" + prod[i][4]);
                        }
                    }
                }
            }

            System.out.println("Valor total da compra: " + vlr_tot);
            System.out.println();
            System.out.println("Confirma compra? s ou n");
            confirma = in.next();

            //EFETUANDO AS ALTERACOES NA MATRIZ DE PRODUTOS DANDO BAIXA NOS PRODUTOS VENDIDOS
            if (confirma.equals("s")) {
                for (i = 0; i < 20; i++) {
                    for (int j = 0; j < 20; i++) {
                        if (prod[i][0]!= null && temporaria[j][0]!=null && prod[i][0].equals(temporaria[j][0])) // SE O CODIGO DO PROD EM ESTOQUE E NO CARRINHO FOR IGUAL
                        {
                            qtd_prod = Integer.parseInt(prod[i][3]);
                            qtd_temp = Integer.parseInt(temporaria[j][1]);
                            if (qtd_temp < qtd_prod) {
                                //CONVERSAO DA QUANTIDADE PARA INTEIRO A FIM DE CALCULAR A NOVA QTD EM ESTOQUE

                                qtd_prod -= qtd_temp;
                                prod[i][3] = Integer.toString(qtd_prod);

                            }
                        }
                    }
                }
            } else {
                System.out.println("cancelando venda...");
                continua = false;
            }

        }
    }

Comment: Então o problema nem esta ai, adicione o codigo todo para melhor analise.
Comment: Poste o código dessa array de String?
Comment: pronto, adicionado
Comment: Não precisa entrar no `if` pra dar NPE. Se `prod[i][0]` for `null`, chamar `equals` nele certamente vai causar o erro.
Comment: então tenho que usar == ?
Comment: Primeiro deve-se sempre checar se o objeto é nulo, pra depois fazer qualquer verificação nele.
Answer: Seu problema está aqui:
//IMPRIMINDO O RESUMO DA VENDA PARA CONFIRMACAO
        for (i = 0; i < 20; i++) {
            for (int j = 0; j < 20; i++) {
//O ERRO DO NULLPOINTER OCORRE AQUI NESTE IF{

Você está incrementando a variável i e não a j. Com isso, quando você tenta acessar a matriz informando i, como a condição de comparação do laço interno é j, i chega ao valor 20 e o acesso a essa posição da matrix que não existe causa o NPE. Para corrigir basta apenas colocar o j para ser incrementado:
for (int j = 0; j < 20; j++) {

Comment: Era isso mesmo, algo tão simples. Obrigado


UMVUE for normal distribution $\sigma$

Question: Let $X_1,X_2,...,X_n$ be a random sample from a normal distribution with mean $\mu$ and variance $\sigma^2$.
I showed that $(\bar X,S^2)$ is jointly sufficient for estimating ($\mu$,$\sigma^2$) where $\bar X$ is the sample mean and $S^2$ is the sample variance.
Then assuming that$(\bar X,S^2)$ is also complete I have to show that $$\sqrt{ n-1\over 2}{\Gamma ({ n-1\over 2})\over\Gamma (\frac n2)} S$$
is a Uniformly Minimum Variance Unbiased Estimator for $\sigma$.
I think I have to use Lehman Scheffe theorem as $(\bar X,S^2)$ is jointly sufficient and complete for $\sigma$.
But how can I find a function which is unbiased for  $\sigma$ that contains both $(\bar X,S^2)$.
I don't understand how to work when there's  a joint sufficiency and completeness.
Comment: A reader notes this question has been cross-posted at http://math.stackexchange.com/questions/858677/umvue-using-complete-and-sufficient-statistic.  Please decide where on SE you would like this to appear and delete the duplicate version(s).
Comment: @Glen_b : I am studying UMVUE for a inference course and this was a question I came across in a note
Comment: @Glen_b : I included that tag.In my other questions I normally include it.But this time I forgot
Answer: Although the question was posted almost 4 years ago, I would like to answer this question. English is not my mother tongue and I am learning it so please don't mind my awkward sentences.
To solve this problem, we notice that $(n-1)S^2/ \sigma^2$ has a chisquare distribution with $n-1$ degree of freedom, while $S^2= \sum^n_{i=1}{(X-\bar{X})^2\over n-1}={{\sum^n_{i=1}X^2}-n \bar{X}^2\over n-1}$ and $X$ has a normal distribution with mean $\mu$ and variance $\sigma^2$.
Note that $S$ contains ${\sum^n_{i=1}X^2}$ and ${\sum^n_{i=1}X}$.
Let's evaluate $E[S]$. To simplify let $q=(n-1)S^2/ \sigma^2$, then $S=\sqrt{q  \sigma^2 /(n-1)}$.
$$E[S]=\int^{\infty}_0 \sqrt{  \sigma^2 \over (n-1)} q^{1 \over2}f_q dq \\=\int^{\infty}_0 \sqrt{  \sigma^2 \over (n-1)} q^{1 \over2} { q^{{n-1 \over 2} -1} e^{-q \over 2} \over \Gamma({n-1 \over 2}) 2^{n-1 \over 2}} dq  \\ = \sqrt{  \sigma^2 \over (n-1)} \int^{\infty}_0   { q^{{n \over 2} -1} e^{-q \over 2} \over \Gamma({n-1 \over 2}) 2^{n-1 \over 2}} dq \\=
 \sqrt{  \sigma^2 \over (n-1)} { \Gamma({n \over 2}) 2^{1 \over 2} \over \Gamma({n-1 \over 2}) } $$
After some rearranging you can get the desired result.
It would be appreciated if someone corrects any grammatical or mathematical mistakes.
Comment: Proper notation would be to use subscripts for X.
Comment: I made minor modifications to the text. But the grammar was not bad.

UMVUE for normal distribution $\sigma$


How can I derive the joint distribution for this Markov network?

Question: I am reading Bayesian Reasoning And Machine Learning and I'm not sure how to do exercise 4.6 on p.80.
The undirected graph:

represents a Markov network with nodes $x1, x2, x3, x4, x5$, counting
clockwise around the pentagon with potentials $\phi(x_i,x_j)$. Show that the joint distribution can be written as $$p(x_1,x_2,x_3,x_4,x_5)=\frac{p(x_1,x_2,x_5)p(x_2,x_4,x_5)p(x_2,x_3,x_4)}{p(x_2,x_5)p(x_2,x_4)}$$
What I have tried so far:
We have that
\begin{align}
\frac{p(x_1,x_2,x_5)p(x_2,x_4,x_5)p(x_2,x_3,x_4)}{p(x_2,x_5)p(x_2,x_4)} &= \frac{p(x_1|x_2,x_5)p(x_2,x_5))p(x_5|x_2,x_4)p(x_2,x_4)p(x_2|x_3,x_4)p(x_3|x_4)p(x_4)}{p(x_2,x_5)p(x_2,x_4)} \\
&=p(x_1|x_2,x_5)p(x_5|x_4)p(x_2|x_4)p(x_3|x_4)p(x_4) \\
&=p(x_1|x_2,x_5)\phi(x_4,x_5)\phi(x_2,x_3)\phi(x_3,x_4)p(x_4)
\end{align}
I'm not sure how to factorize it any further. Could anyone please help?
Answer: The conditional independencies induced by this Markov network are
$$
x_1 \perp x_3,x_4 \mid x_2,x_5 \\
x_2 \perp x_4,x_5 \mid x_1,x_3 \\
x_3 \perp x_5,x_1 \mid x_2,x_4 \\
x_4 \perp x_1,x_2 \mid x_3,x_5 \\
x_5 \perp x_2,x_3 \mid x_1,x_4
$$
Using the chain rule, the joint distribution can be written as
$$
p(x_1,x_2,x_3,x_4,x_5) = p(x_1 \mid x_2,x_3,x_4,x_5) \cdot p(x_3 \mid x_2,x_4,x_5) \cdot p(x_2,x_4,x_5)
$$
Apply the conditional independencies derived above such that
$$
p(x_1 \mid x_2,x_3,x_4,x_5) = p(x_1 \mid x_2,x_5) \\
p(x_3 \mid x_2,x_4,x_5) = p(x_3 \mid x_2,x_4)
$$
So,
$$
p(x_1,x_2,x_3,x_4,x_5) = p(x_1 \mid x_2,x_5) \cdot p(x_3 \mid x_2,x_4) \cdot p(x_2,x_4,x_5)
$$
Using Bayes' rule,
\begin{align}
p(x_1,x_2,x_3,x_4,x_5) &= \frac{p(x_1,x_2,x_5)}{p(x_2,x_5)} \cdot \frac{p(x_3,x_2,x_4)}{p(x_2,x_4)} \cdot p(x_2,x_4,x_5) \\
&= \frac{p(x_1,x_2,x_5) \cdot p(x_3,x_2,x_4) \cdot p(x_2,x_4,x_5)}{p(x_2,x_5) \cdot p(x_2,x_4)}
\end{align}
which is the desired result.
Comment: thanks a lot. Could you also check this https://stats.stackexchange.com/questions/549871/markov-networks please?


nginx echo while processing not working but the same server with apache can echo while processing

Question: PHP 8
I'm using the newest NGINX feature un WHM 96.... I can flip switch on or off to have nginx cache everything and it's working well and very fast.
**** BUT : when I have a script that does lots of echos, NGINX will WAIT untill ALL is processed.
In the SAME exact server, just by turning off NGINX : all echo are being pushed.
Simplest code example
<?php

for ($x = 0; $x <= 10; $x++) {
        echo "dot "; sleep(1);
    }
?>

with apache => I see dot (wait 1 sec), dot (wait 1 sec), dot (wait 1 sec), dot (wait 1 sec)
with NGINX => I wait 10 sec and see all 10 dot.....
Is there a way to keep NGINX on and have the same echo while processing effect ?
Answer: Basically, apache2 has a smaller buffer, causing it to stream, whereas nginx is buffering your output.
<?php

        $multiple = 1;
        $size = 1024 * $multiple;
        for($i = 1; $i <= $size; $i++) {
            echo ".";
        }
        sleep(5);
        echo "Hello World";
    ?>

If you run this example you will see that your browser's loading indicator didn't show that data is being received until after five seconds. Now, let's change $multipe from 1 to 8 and hit refresh. If there are no specific settings configured, you'll notice the browser telling us it started to receive some data almost immediately, no wait. Not having to wait for five seconds to realize the page has started loading is very good for customer experience.
You might be wondering why we have set $multiple from 1 to 8. The reason behind this is related to the webserver's buffers. At the first level there is the PHP buffering, which we can check via the output_buffering PHP settings. There may also be something on PHP's back end (CGI, mod_php, FastCGI) buffering and at the end there might be the webserver's buffering.
Normally, both Nginx and Apache buffer content up to either 4KB or 8KB depending on the operating system being used. Normally, on 64bit operating systems, the limit is 8KB and on 32bit operating systems it is 4KB.
Since nginx and apache2 both share support for PHP, the best way to implement a universal fix is to use the commonly supported layer, PHP.
All in all, what you need is the flush(); and ob_flush(); function to force data out of the buffer. Something like this out to do the trick:
<?php

for ($x = 0; $x <= 10; $x++) {
        echo "dot "; sleep(1);
        ob_flush();
        flush();
    }
?>

More information here: https://www.php.net/manual/en/function.ob-flush.php
Comment: I tried `ob_flush(); flush();` and it's not working, I think it could be related to "buffers"...
Answer: According to https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering
I changed the nginx.conf and virtual hosts to have proxy_buffering off; directive as below:
http {
    proxy_buffering off;
}

server {
    proxy_buffering off;
}

and it solved the issue ;)


Proving the orthocenter, circumcenter and centroid of a triangle are collinear.

Question: I just had a problem on a test related to Euler's Line theorem,
(Euler Line Theorem: The orthocenter H, the circumcenter O, and the centroid G of any triangle are collinear.  Furthermore, G is between H and O (unless the triangle is equilateral, in which case the three points coincide) and HG = 2GO.)
On the test problem, the professor gave us diagram of a triangle with three points in the interior of the triangle.  The question said,
"Use the following diagram to prove synthetically that the circumcenter O, the centroid G, and the orthocenter H of a triangle are collinear."
Nobody in the class got full credit on it.  He said it should be done this way:
Draw a line segment from O to G, and extend it such that OG=1/2 GH.  Then prove that H is the orthocenter.
This didn't sit well with me, and I don't know what to think about his method.

Instead of a proof by contradiction, it seems like a proof by, I don't know, acceptance?  Accept that what you are trying to prove is true, then use half of what the theorem says to work backwards to prove something in the given.  Is this a valid way to prove something?  I have never heard of this, and it seems like it wouldn't always be robust.

It rubs me the wrong way to be trying to prove that 3 points are collinear, and then your first step is to draw them so that they are collinear.  It seems like a circular argument, although in the end he proved that H was the orthocenter.  I like ending with what I am trying to prove, but maybe I am not right here.

Given the theorem, it seems like you are accepting that half of it is true, constructing them in this manner.  If you are using half of the proof, why wouldn't  it be valid to accept the whole thing is true and say, "By the Euler Line theorem, these three points are collinear."

Any help would be greatly appreciated.  This is really nagging at me.
Comment: Looks fine to me: you constructed a point $G$ and proved it was on all the altitudes. Thus $G$ is the orthocentre. Sounds good to me, and is constructive to boot.
Answer: The proof you described is perfectly valid: it follows from the similitude of triangles $AGH$ and $MGO$ (see diagram, where $M$ is the midpoint of $BC$), which in turn implies $OM\parallel AH$, so that $AH$ lies on the altitude from $A$ (and the same can reasoning can be repeated for $B$ and $C$). Triangles $AGH$ and $MGO$ are similar because $AG/MG=HG/OG=2$ and $\angle AGH=\angle OGM$ (SAS criterion).
Constructing point $H$ on line $OG$ and then showing that it is the orthocenter is indeed a very simple and clever way to avoid a direct collinearity proof. Compare it, for instance, with the proof given at cut-the-knot, which is more cumbersome.
Answer: Here is sketch of a different way to prove it.
Find the midlines of ABC.

The circumcenter of ABC is the othocenter of PQR
The centroid of ABC is the centroid of PQR
PQR is similar to ABC
Construct Euler line between the two orthocenter / Circumcenter of PQR / ABC and the Centroid, creating more similar triangles.  And there are corresponding points between the othocenter of PQR and the orhtocenter of ABC along that line.


Datatables plugin Loading json Data error from web service(.net)

Question: I'm trying to use DataTables (getting data from Ajax) on my website form.
I was experiencing some difficulties with that so I took a step back and tried to implement DataTables on a very basic table.
But I'm failing to get Datatables to work even on this basic table. What am I missing?  :(
$(document).ready(function () {
    $('#table_id_example1').DataTable({
        "processing": false,
        "serverSide": false,
        "ajax": {
            type: "POST",
            url: "AjaxTest.asmx/HelloWorld",
            contentType: "application/json; charset=utf-8",
            data: {},
            //dataSrc: "" ,
            dataType: "json",
            success: function (json) {
                alert(json.d);
            },
        },
        "columns": [
            { title: "ID"},
            { title: "Name"},
            { title: "Email"},
            { title: "Extension"}
        ],
    });
})

when the page loads, Datatables always shows "Loading".
Then I added
success: function (json) {
    alert(json.d);

This alerts the following:

[{"id":1,"Name":"Jack","Email":"email@example.com","Extension":"1001"},{"id":2,"Name":"Mike","Email":"firstname.lastname@example.com","Extension":"1002"},{"id":3,"Name":"Rose","Email":"firstname.lastname@example.com","Extension":"1003"}]

It that returned json string correct? Or are my Datatables params settings wrong?
Comment: Can you try to create snippet first? may be you will get your mistake on your own.
Comment: Thanks trincot, I'm newbie of stackflow :)
Answer: thanks all.
It works after converting json.d to js object

        $(document).ready(function () {

            $('#table_id_example1').DataTable({
                "processing": false,
                "serverSide": false,
                "ajax": {
                    type: "POST",
                    url: "AjaxTest.asmx/HelloWorld",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    ////data: {},
                    dataSrc: function (json) { return $.parseJSON(json.d); },
                    //success: function (json) {
                    //    alert(json.d);
                    //    //alert(JSON.stringify(json.d))
                    //}
                    //},
                },
                "columns": [
                { title: "ID",data:"id"},
                { title: "Name", data: "Name" },
                { title: "Email", data: "Email" },
                { title: "Extension", data: "Extension" }
                ],
            });
        })
Answer: You don't need to add success callback in datatables ajax, just bind your columns with appropriates keys like,
$('#table_id_example1').DataTable({
    "processing": false,
    "serverSide": false,
    "ajax": {
         url: "AjaxTest.asmx/HelloWorld",
         dataSrc: "d" , // add data source, in your case it is d
     },
     "columns": [
        { title: "ID",data:'d.id'}, /// bind data with their keys
        { title: "Name",data:'d.Name'},
        { title: "Email",data:'d.Email'},
        { title: "Extension",data:'d.Extension'}
     ],
});

Please refer ajax-configuration for more details.
Comment: Thanks for reply.
this time , page shows different error.   `DataTables warning: table id=table_id_example1 - Requested unknown parameter 'd.id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4`
Comment: In your json response it is `id` or `Id`, remember the capital `I`, or just try `'d.Id'`.
Answer: If you don't have any search parameters at the moment, simply specify the url for data loaduing following way:
 "ajax": {
           "url": "AjaxTest.asmx/HelloWorld"
         },

instead of your's one:
"ajax": {
        type: "POST",
        url: "AjaxTest.asmx/HelloWorld",
        contentType: "application/json; charset=utf-8",
        data: {},
        //dataSrc: "" ,
        dataType: "json",
        success: function (json) {
            alert(json.d);
        },

I had written posts on using the datatables with server side paging, searching which you can find in following location:
https://www.codeproject.com/Articles/1118363/GridView-with-Server-Side-Filtering-Sorting-and-Pa
https://www.codeproject.com/Articles/1170086/Grid-with-Server-Side-Advanced-Search-using-JQuery
https://www.codeproject.com/Articles/1191769/Grid-View-with-AJAX-based-CRUD-Operations-in-ASP-N


Using named pipes and fork in C / Linux

Question: I'm trying to write simple console application that reads text from user, then changes lowercase to uppercase and finally prints result in console.
It is working fine when I use only one pipe (e.g. without reading text from console), but works totally unpredictable when I use two.
Shouldn't '[Write]' wait for '[To upper]' until it send text?
I got following output:

[Write] Waiting for txt to diplay.
  [To upper] Waiting for txt to change.
  [Write] Received following txt:
  [To upper] Received txt ().
  [To upper] Changed txt send to [Write] ().
  [Scan] Type your txt:
  [Scan] Txt received. Sending to [To upper] (y)

My code:
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#define SIZE 16
int main()
{
    int i=0;
    int f1,f2;
    char x[SIZE]={0};
    if( fork() )
    {
        if( fork() )//[Write]
        {
            f1=open("upper-write",O_RDONLY);
            puts( "[Write] Waiting for txt to diplay." );
            read( f1, &x, sizeof( x ) );
            printf( "[Write] Received following txt: %s\n", x );
            close( f1 );
        }
        else//[Scan]
        {
            puts( "[Scan] Type your txt: " );
            //scanf ("%15s",x);//scanf not working now, so I change my char array by myself
            x[0]='y';
            f2=open("scan-upper",O_WRONLY);
            printf( "[Scan] Txt received. Sending to [To upper] (%s)\n", x );
            write( f2, &x, sizeof( x ) );
            close( f2 );
        }
    }
    else//[To upper]
    {
        puts( "[To upper] Waiting for txt to change." );
        f2=open("scan-upper",O_RDONLY);
        read( f2, &x, sizeof( x ) );
        close( f2 );

        printf( "[To upper] Received txt (%s).\n" ,x);
        for(i=0;i<SIZE;i++)
            if(x[i]>=97 && x[i] <=122)//lowercase -> uppercase
                x[i]-=32;

        f1=open("upper-write",O_WRONLY);
        write( f1, &x, sizeof( x ) );
        printf( "[To upper] Changed txt send to [Write] (%s).\n" ,x);
        close( f1 );
    }
}

Comment: You have no synchronization between calls. You have limited synchronization based on the nature of pipes -- can't read until the other end has written, but once the read is completed, the order of your printf's is not synchronized.
Comment: Could it be that your pipe is not empty initially? Then you have some non-printable byte read. And don't use your `SIZE` as a string length, since it isn't.
Comment: Any reason you need a named pipe instead of just using the [pipe system call](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pipe.html)?
Answer: I think you need to understand a couple of things to understand the problem.  First, after a fork() there's no guarantee as to which process gets to run first.  Second, read() returns immediately with a value of zero if the other end of the pipe isn't open for writing.
You're counting on the processes running in a certain order so that the pipes are all open on both sides before any reads take place.  Since that doesn't always happen, read() isn't always blocking.
You can solve this by opening both ends of all of your pipes before you fork().  All of the processes will have file descriptors to both ends of the pipes.  Just call close() on the file descriptors you don't need in the corresponding processes.
Comment: My C is a bit rusty, but this sounds right.  Like the [standard](http://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html) says, "When attempting to read from an empty pipe or FIFO:... If no process has the pipe open for writing, read() shall return 0 to indicate end-of-file."
Answer: Are you sure this isn't because your non-scan processes don't close stdin? You might want to do something like "close(0)" after the fork.
Alternatively, there's popen(), which might be interesting for this kind of stuff.
Comment: maybe the phrasing could've been better, but I actually do believe it's the answer :-)
Comment: If you do believe that, I rescind my comment :) But I don't think its a valid answer because of the OP's processes, only one is attempting to read from stdin (well, under his current code, none of them are). Closing the paths you don't need is nice but if you're not using them, you won't harm the other processes.
Comment: Unfortunately it didn't help.

Using named pipes and fork in C / Linux


How to enable bash completion on Google Compute Engine?

Question: The compute instances I'm running is a Debian Buster. Normally there's exists a /etc/bash_completion file. However for GCE, it's missing. There's even a section they've added in the default ~/.bashrc to refer to the bash completion files which none of them exists.
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

Comment: Did you install bash-completion?
Comment: *facepalm*, there we go. Now I'm embarrassed. I expected if it's mentioned in ~/.bashrc then GCE would've installed it by default.
Answer: You are right, it is not installed by default, I tried it in my own project creating a new Debian Buster VM instance, and /etc/bash_completion doesn't exist.
/etc$ ls -l bash_completion
ls: cannot access 'bash_completion': No such file or directory

Only after installing bash-completion, the  /etc/bash_completion file will appears.
sudo apt-get install bash-completion

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  bash-completion
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 208 kB of archives.
After this operation, 1397 kB of additional disk space will be used.
Get:1 http://deb.debian.org/debian buster/main amd64 bash-completion all 1:2.8-6 [208 kB]
Fetched 208 kB in 0s (960 kB/s)
Selecting previously unselected package bash-completion.
(Reading database ... 37801 files and directories currently installed.)
Preparing to unpack .../bash-completion_1%3a2.8-6_all.deb ...
Unpacking bash-completion (1:2.8-6) ...
Setting up bash-completion (1:2.8-6) ...
Processing triggers for man-db (2.8.5-2) ...

After the installation:
/etc$ ls -l bash_completion
-rw-r--r-- 1 root root 45 Feb 11  2019 bash_completion


Custom views filter to select roles

Question: I have scoured the internet trying to find information on how to achieve this functionality to no avail. I am hoping I can get an answer here.
I have a content type called 'Server' on my website. One of the fields on 'Server' is an 'Access Role' field, which is an entity reference of user roles.
When a new piece of content is made, the author selects one (or multiple roles) that have access to this piece of content (The author can't be granted the 'manage roles' permission, so they can't use the standard 'permissions' options available when creating content).
I have a view setup (that is a REST EXPORT of type key_auth. When a user accesses the endpoint using their auth key, the view should return a list of server content that matches ONLY if one of the users roles is in the access roles field for the piece of content. I can't seem to find out how to achieve this using views and filters.
As an example;
Server 1
Access Roles: Developer, Testing
Server 2
Access Roles: Administrator
The user accessing the endpoint does not have the administrator role, but does have the Testing role. When the user accesses the endpoint, only 'Server 1' should return for them, since that's the only server that matches one of their roles. If more servers matched, those servers would be displayed, too.
I have the access roles setup, and the view setup to connect the api key to the correct user, but can't figure out how to set the filter up to match user roles to one of the possible access roles on the server content.
Is there somebody that could offer me some assistance?
Answer: EDIT: I think this is actually wrong: Views doesn't evaluate hook_node_access() for performance reasons. How to filter a view according to nodes permissions
It's going to be difficult for Views to model the relationships needed for this correctly, because Roles are configuration entities in Drupal 8 (as opposed to content entities).
You may be going about this the wrong way, though. Views already respects entity access control, preventing entities from showing in results if the current user doesn't have permission to access those entities. You haven't made those access control rules explicit to Drupal yet, which is why they don't get automatically filtered out in Views. But you could implement hook_node_access() to formally describe those access permission rules to Drupal.
Here's the API documentation example: https://api.drupal.org/api/drupal/core!modules!node!node.api.php/function/hook_node_access/8.8.x
Your implementation would look something like this:
<?php

function MYMODULE_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
  if ($op == 'view' && $node->hasField('field_roles')) {
    $node_roles = array_column($node->field_roles->getValue(), 'target_id');
    $user_roles = $account->getRoles();
    if (array_intersect($node_roles, $user_roles)) {
      return \Drupal\Core\Access\AccessResult::allowed();
    }
    else {
      return \Drupal\Core\Access\AccessResult::forbidden();
    }
  }
  return \Drupal\Core\Access\AccessResult::neutral();
}

Comment: From my understanding, this would be on a content type basis, not a single piece of content basis. I need it to be single piece of content basis as the server content type itself is viewable by everyone, but individual nodes/entities in that content type are only visible by people with the correct roles as provided on the piece of content.
Comment: The ultimate goal, is for an author to create a new piece of 'server' content, specify what roles can access that piece of content, and move on.
Comment: @Ex0r: `hook_node_access()` actually is evaluated separately for each single piece of content. I've updated the answer with an implementation example to illustrate.
Comment: Wait, turns out that Views doesn't evaluate `hook_node_access()`. Edited the answer to link to a relevant topic - you would want to implement hook_node_access_records() and hook_node_grants() instead. I might re-answer this later.
Comment: Oy vey. Who makes these design decisions? Since when did a simple query to compare a value to a value become writing a novel?

Custom views filter to select roles


Uncaught ReferenceError: li is not defined

Question: This is to do list project, but I don't know why this isn't working.
Can anyone help me? I have checked this several times, and all files are good. Also, CSS code is not mine, it's copied.
Of course, this project is not finished, but I'm testing this now (I'm beginner).
I got this error when I click on span:
script.js:4 Uncaught ReferenceError: li is not defined
    at newTask (script.js:4:2)
    at HTMLSpanElement.onclick (index.html:14:46)

function newTask() {
    let task = document.createElement('li');
    let inputText = document.querySelector('#inputText').value;
    li.appendChild(inputText)
}
body {
  margin: 0;
  min-width: 250px;
}

* {
  box-sizing: border-box;
}

ul {
  margin: 0;
  padding: 0;
}

ul li {
  cursor: pointer;
  position: relative;
  padding: 12px 8px 12px 40px;
  list-style-type: none;
  background: #eee;
  font-size: 18px;
  transition: 0.2s;

  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

ul li:nth-child(odd) {
  background: #f9f9f9;
}

ul li:hover {
  background: #ddd;
}

ul li.checked {
  background: #888;
  color: #fff;
  text-decoration: line-through;
}

ul li.checked::before {
  content: '';
  position: absolute;
  border-color: #fff;
  border-style: solid;
  border-width: 0 2px 2px 0;
  top: 10px;
  left: 16px;
  transform: rotate(45deg);
  height: 15px;
  width: 7px;
}

.close {
  position: absolute;
  right: 0;
  top: 0;
  padding: 12px 16px 12px 16px;
}

.close:hover {
  background-color: #f44336;
  color: white;
}

.header {
  background-color: blue;
  padding: 30px 40px;
  color: white;
  text-align: center;
}

/* Clear floats after the header */
.header:after {
  content: "";
  display: table;
  clear: both;
}

/* Style the input */
input {
  margin: 0;
  border: none;
  border-radius: 0;
  width: 75%;
  padding: 10px;
  float: left;
  font-size: 16px;
}

/* Style the "Add" button */
.addBtn {
  padding: 10px;
  width: 25%;
  background: #d9d9d9;
  color: #555;
  float: left;
  text-align: center;
  font-size: 16px;
  cursor: pointer;
  transition: 0.3s;
  border-radius: 0;
}

.addBtn:hover {
  background-color: #bbb;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title> To Do List </title>
    <link rel="stylesheet" type="text/css" href="style.css">

 Lista zadataka

        <input type="text" id="inputText" placeholder=" Naziv zadatka ">
        Dodaj

Comment: the variable is named `task` not `li`.
Comment: If `task = document.createElement('li')`, then instead of `li.appendChild()`, try rather `task.appendChild()`.
Comment: You're also never appending the task to the ``.
Answer: First, you need to get the  ul element which has list id, also you need to set the value of the li element after create it with input value.
Also, If wanted to reset the input value after adding the task

const input = document.querySelector('#inputText')
function newTask() {
    let task = document.createElement('li');

    let inputText = input.value;
    task.textContent = inputText;
    input.value = ''
    const list = document.getElementById('list');
    list.appendChild(task)
}
body {
  margin: 0;
  min-width: 250px;
}

* {
  box-sizing: border-box;
}

ul {
  margin: 0;
  padding: 0;
}

ul li {
  cursor: pointer;
  position: relative;
  padding: 12px 8px 12px 40px;
  list-style-type: none;
  background: #eee;
  font-size: 18px;
  transition: 0.2s;

  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

ul li:nth-child(odd) {
  background: #f9f9f9;
}

ul li:hover {
  background: #ddd;
}

ul li.checked {
  background: #888;
  color: #fff;
  text-decoration: line-through;
}

ul li.checked::before {
  content: '';
  position: absolute;
  border-color: #fff;
  border-style: solid;
  border-width: 0 2px 2px 0;
  top: 10px;
  left: 16px;
  transform: rotate(45deg);
  height: 15px;
  width: 7px;
}

.close {
  position: absolute;
  right: 0;
  top: 0;
  padding: 12px 16px 12px 16px;
}

.close:hover {
  background-color: #f44336;
  color: white;
}

.header {
  background-color: blue;
  padding: 30px 40px;
  color: white;
  text-align: center;
}

/* Clear floats after the header */
.header:after {
  content: "";
  display: table;
  clear: both;
}

/* Style the input */
input {
  margin: 0;
  border: none;
  border-radius: 0;
  width: 75%;
  padding: 10px;
  float: left;
  font-size: 16px;
}

/* Style the "Add" button */
.addBtn {
  padding: 10px;
  width: 25%;
  background: #d9d9d9;
  color: #555;
  float: left;
  text-align: center;
  font-size: 16px;
  cursor: pointer;
  transition: 0.3s;
  border-radius: 0;
}

.addBtn:hover {
  background-color: #bbb;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title> To Do List </title>
    <link rel="stylesheet" type="text/css" href="style.css">

 Lista zadataka

        <input type="text" id="inputText" placeholder=" Naziv zadatka ">
        Dodaj

Comment: You should decalare `input` inside the `newTask` or add a `function parameter` : `input`
Comment: Why should I do that?
Comment: Ussualy concidered as "not the best" practice, it make the function less flexible, less reable ( as you don't know where this variable is declared ) and occording to some benchmark less efficient. After all this is just an opinion, you are free to do as you wish ;)


Binomial and Normal distribution X~N(18,5^2)

Question: I'm stuck with a problem related to binomial and Normal distribution.
Suppose the amount of time a laptop battery holds its charge is:
$X \sim N(18,5^2)$
Suppose there are 40 students and there is a power outage for 24 hrs.
What is the most most likely no. Of laptops which keep running. I believe this is:
$Y \sim B(40,p)$
How do I find p?
Comment: Welcome to CV. I edited your question for clarity. I hope it reflects what you want, if not, feel free to edit it further.
Answer: Step 1: Based on $X \sim N(18, 5^2)$ calculated the probability that one computer can run more than 24 hrs. It is $p$.
Step 2: The number of computers running more than 24 hrs follows Binomial distribution $Bin(40,p)$. The  most likely number Of laptops running is the mode of the $Bin(40,p)$. So you can find the answer use formula or using graph.


Should separate Drupal installations have separate temporary directories?

Question: Assuming one installs several Drupal sites on the same server (i.e., with multiple top-level directories, not multiple sites under a single top-level directory), can these installations share the same temporary directory or should they each have their own temporary directory?
Answer: They can all share the same folder if you want them to, but if you want to give each domain it's own tmp folder that's fine too...it really depends on how you want to set your server up.
Aside from being able to identify which tmp files have come from which site (which personally I've found no need to do up to this point in my life) I can't think of an argument either way to be honest.
Edit: Thinking about it a bit more, if you're running a shared host of any description it might make sense to provide a tmp folder for each domain so it's sandboxed from other sites, and from the main system tmp folder (and subsequently other parts of the system that don't relate to web).


show values of two columns from two different tables into one column in sql server

Question: there are two tables 1) participant and 2) logindatetime.
for first time login datetime value along with other user data like,Name, location, contact number, email gets inserted into participant table having datatime column...for any subsequent login of the same user we insert datetime value into logindatetime column to keep the records of how many times the user logged in....now i have to show all the login time (first login time and subsequent login time) in a single column along with name, location, contact I number, email of the same user.
(I do have an identity in participant table).
Have tried following query:
select a.firstname as 'Name', a.Email as 'Email', a.Address1 as 'Location',
    a.MobileNo as 'Contact', COALESCE(a.datetime, b.datetime) as DateTime
from eventonline.participant a, eventonline.logindatetime b
where a.Id = b.Rid";

but it show first login time multiple times.
Comment: I have tired following query :-
a.firstname as 'Name', a.Email as 'Email', a.Address1 as 'Location', a.MobileNo as 'Contact', COALESCE(a.datetime, b.datetime) as DateTime from eventonline.participant a, eventonline.logindatetime b where a.Id = b.Rid";
but it show first login time multiple times.
Comment: You need to post a LOT more information if you want any real help. This is a great place to start. http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ Also, based on your comment you should also read this article. https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins
Answer: You need to do something like this to fetch the first and then the other logons separately:
select a.firstname as Name, a.Email, a.Address1 as Location,
    a.MobileNo as Contact, a.datetime
from eventonline.participant a

union all

select a.firstname as Name, a.Email, a.Address1 as Location,
    a.MobileNo as Contact, b.datetime
from eventonline.participant a
join eventonline.logindatetime b on a.Id = b.Rid

It might be easier just to add the first logon to logindatetime
Comment: Can't add first logon to logindatetime...but Thank you a lot...your solution worked... :)
Comment: Just added one extra data to this query and found the exact result.

select a.firstname as Name, a.Email as Email, a.Address1 as Location, a.MobileNo as Contact, a.datetime, a.ID from eventonline.participant a where a.eventid = '130516'union all select a.firstname as Name, a.Email as Email, a.Address1 as Location, a.MobileNo as Contact, b.datetime, b.Rid from eventonline.participant a join eventonline.logindatetime b on a.Id = b.Rid where b.eventid = '130516'  order by datetime desc
Comment: but now i m stuck in other situation....where I have to get only last login date in the grid along with name, mobileno, contact, lastlogintime....i have tried 'top 1' but only getting one result....can some one advice??
Comment: @dhaval you need to do a cross apply to logindatetime and the top 1 should be inside the cross apply
Answer: JamesZ's answer gives the solution but a further note on why your approach isn't working. You're joining the two tables and using coalesce(a.DateTime, b.DateTime) to display login time. If the user has logged in before, a.DateTime has a non-null value. coalesce(x,y) only uses y if x is null. But that's not the real problem. The first login-time needs a record of its own in the logindatetime table. If the users logs in 5 times, your logindatetime will have 4 rows and that's all you'll see when joining the two tables. You need to either save the first login time as a row in logindatetime, or use a UNION to force that first login time to be added as an extra row.
Answer: I faced the same issue but according to James Z's answer I solved my problem:
select a.start_date as start, a.end_date as end, a.rooms_id as roomid from maintenance a UNION ALL SELECT b.check_in as start, b.check_out as end, b.room_id AS roomid from reservations b

The result of the query from both tables are here:
Answer: You could use joins in your sql statement, i just learnt them 3 days ago and they are very useful!
it would look something like this:
SELECT * FROM table1
LEFT JOIN table2 ON table1.column1 = table2.column1
WHERE table1.column1 = '$yourVar';

table1.column1 could be the id, and the corresponding id in the second table can be the id that links it to the first table (Foreign key), it will retrieve the data of the first table and bring all the data of the second table as well that would match the on the  ON criteria
Comment: if you down vote please explain why... it seems the answer is valid and i have used it for a problem similar to this.


Clang Profiling with Instrumentation on Android

Question: I'm compiling a shared library for Android, that someone else loads in their app. I want to profile my library as it runs on an Android device, using Clang's profiling with instrumentation.
I've added the Clang option -fprofile-instr-generate to compilation and linkage, and though this produces raw profiling data when the library is compiled and loaded on Linux, on Android I get the following error:

04-26 20:39:37.559  3313  3313 D AndroidRuntime: Shutting down VM
04-26 20:39:37.559  3313  3313 E AndroidRuntime: FATAL EXCEPTION: main
04-26 20:39:37.559  3313  3313 E AndroidRuntime: Process: com.my.process, PID: 3313
04-26 20:39:37.559  3313  3313 E AndroidRuntime:
java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "__start___llvm_prf_vnds" referenced by "/path/to/my.so"...
04-26 20:39:37.559  3313  3313 E AndroidRuntime:   at java.lang.Runtime.loadLibrary0(Runtime.java:1016)
04-26 20:39:37.559  3313  3313 E AndroidRuntime:   at java.lang.System.loadLibrary(System.java:1657)

When running nm -D my.so | grep prf I get:

00000000007f1cc8 d __start___llvm_prf_cnts
0000000000827918 d __start___llvm_prf_data
00000000008fb570 d __start___llvm_prf_names
000000000117bf58 d __start___llvm_prf_vnds
0000000000827918 a __stop___llvm_prf_cnts
00000000008fb568 a __stop___llvm_prf_data
000000000117bf54 a __stop___llvm_prf_names
0000000001181f58 a __stop___llvm_prf_vnds

So it looks like the symbols are there.
Is it possible to run the profiling instrumentation on Android?
Comment: Hi, I'm currently dealing with this kind of error, did you resolved this? Could you please share your insights :) Thanks
Comment: Hej! Unfortunately no, I never got the instrumentation to work. But I did get the perf tool in the sdk to work, where you run it from computer with adb connected (with wire or over wifi) and put in the process ID. It wasn't immediate though...
Comment: Oh Thanks. I will try the perf tool
Answer: Profiling works with the gold and LLD linkers. This error is caused only when using the BFD linker. The sh_info entry for .dynsym section should point to the first non-LOCAL symbol but in the error case, it is set too low.
To verify, run readelf -aW on the problematic shared library. In my repo, the sh_info for .dynsym is 3 whereas there are at least 11 LOCAL symbols.


Como ler arquivo txt e montar array php?

Question: Gostaria de saber se existe alguma maneira de ler um arquivo .txt e montar um array PHP com cada linha do arquivo .txt pra depois montar JSON se alguém puder me ajudar agradeço!
Quero que a exibição fique dessa maneira:
{
"empregados": [
    {
        "nome": "Jason Jones",
        "idade": 38,
        "sexo": "M"
    },
    {
        "nome": "Ada Pascalina",
        "idade": 35,
        "sexo": "F"
    },
    {
        "nome": "Delphino da Silva",
        "idade": 26,
        "sexo": "M"
    }
]

}
Este é meu código:
<?php $dadox = array();
$dado = fopen("new_2.txt", "r");

while (!feof ($dado)) {
//se extraio uma linha do arquivo e nao eh false
if ($linha = fgets($dado)){
$dadox[] = $linha;
}

$cpf = substr("$linha", 0, 11 );
$nome = substr("$linha", 11, 32 );
$end = substr("$linha", 43, 28 );
$com = substr("$linha", 75 , 8 );
$cidade = substr("$linha", 87 , 13 );
$uf = substr("$linha", 103 , 2 );

//fclose($arquivo);
header('Content-Type: application/json');

 $funcionario =
     array(
       'CPF'=>"$cpf",
        'Nome'=>"$nome",
        'Endereco'=>"$end",
         'Complemento'=>"$com",
         'Cidade'=>"$cidade",
          'UF'=>"$uf"

     );
     $dados = array(
       $funcionario
     );

    $dados_funcionario = array('funcionario' => $dados);

    $json_str = json_encode($dados_funcionario,JSON_PRETTY_PRINT);

    echo "$json_str";
//var_dump($funcionario);
} ?>

Comment: Sim, muitas maneiras, mas todas dependem do formato do seu arquivo. Poderia [edit] a sua pergunta e adicionar um exemplo e descrever qual é a saída desejada?
Comment: Acho que essa pergunta pode te ajudar: https://pt.stackoverflow.com/questions/189409/como-transformar-esse-texto-em-um-array-com-nome-e-descri%C3%A7%C3%A3o
Comment: Como ele está delimitado?
Answer: Como foi citado, existem N formas de resolver essa questão, abaixo vou apresentar uma supondo que os dados estão delimitados conforme seu exemplo.
Esse seria seu new_2.txt
12345678912primeiro nome do cliente        endereço 1                  comp 1  cidade 1     SP
12345678912segundo nome do cliente         endereço 2                  comp 2  cidade 2     MG

Segue como ficaria uma possível solução
<?php

$dadox['empregados'] = array();
$lines = file('new_2.txt');
foreach ($lines as $line) {
    if (preg_match('#^(?<cpf>[0-9]{11})(?<nome>[^\n]{32})(?<end>[^\n]{28})(?<com>[^\n]{8})(?<cidade>[^\n]{13})(?<uf>[^\n]{2})#iu', trim($line), $arr)) {
        $dadox['empregados'][] = array(
            'cpf' => $arr['cpf'],
            'nome' => $arr['nome'],
            'end' => $arr['end'],
            'com' => $arr['com'],
            'cidade' => $arr['cidade'],
            'uf' => $arr['uf']
        );
    }
}

echo '
';
print_r($dadox);

Não vou entrar em detalhes sobre o regex, pois você pode ver um exemplo do mesmo rodando aqui https://regex101.com/r/5TyRzk/1 e completamente detalhado.
Comment: Vlw mano! Exatamente isso que eu queria.


For each String S, print 's even-indexed characters, followed by a space, followed by 's odd-indexed characters

Question: Im trying to do hackerrank challenge but this code is solving 3/10 of the test case.
The challenge is Given a string, S , of N length that is indexed from 0 to N-1 , print its even-indexed and odd-indexed characters as space-separated strings on a single line. Note: 0 is considered to be an even index
import sys
cases = int(sys.stdin.readline())
for x in range(cases):
    str= sys.stdin.readline()
    str= [str[x] for x in range(len(str)) if x%2==0 and str[x]!="\n"] +[" "] + [str[x] for x in range(len(str)) if x%2!=0]
    str="".join(str)
    print(str)

Need some help.
Thanks
Comment: what's wrong with the code?  How is it not working?  Also, are you intentionally trying to solve the problem in one line of code?
Comment: @Kos sorry what im trying to do is Given a string, S , of N length  that is indexed from 0 to N-1 , print its even-indexed and odd-indexed characters as  space-separated strings on a single line.

Note: 0 is considered to be an even index.
Comment: @KevinWang i dont know what's the problem but when i submit the code to hackerrank it says it failed 7 out of the 10 test cases. And yes im trying to solve it in one line of code. Thanks for replying
Comment: have you tried making your own testcases to try to find instances where your code doesn't work as expected?
Comment: I solved it. I replaced str= [str[x] for x in range(len(str)) if x%2==0 and str[x]!="\n"] +[" "] + [str[x] for x in range(len(str)) if x%2!=0] for str= "".join(str[0::2]) + " " + "".join(str[1::2}) and also added the .strip() to str= sys.stdin.readline(). Thanks for the help @KevinWang
Answer: The solution depends on how you index characters.
If the first character is index 0:
s = "abcdefghijklmnopqrstuvwxyz"
r = "".join(s[0::2]) + " " + "".join(s[1::2])

print(r)
acegikmoqsuwy bdfhjlnprtvxz

If the first character is index 1:
r = "".join(s[1::2]) + " " + "".join(s[0::2])

print(r)
bdfhjlnprtvxz acegikmoqsuwy