using if statement under using case

Question: this says need to return path but i cant reach if cases is there any way ? thanks
public IEnumerable<RequestCall> GetRequests(string erisim, string sube, string sicil)
{
    using (var redisclient = RedisManager.GetClient())
    {
        var redisUser = redisclient.As<RequestCall>();

        if (erisim == "A")
        {
            return redisUser.GetAll();// .Where(c=>c.Sube=="Y");
        }
        else if (erisim == "P")
        {
            return redisUser.GetAll().Where(c => c.Sube == sube);
        }
        else if (erisim == "C")
        {
            return redisUser.GetAll().Where(c => c.CagriAcan == sicil);
        }

    }
}

this says need to return path but i cant reach if cases is there any way ? thanks
Comment: add one more `else` block and `return` the defualt value
Comment: What if `erisim` isn't any of `A`, `P` or `C`? You're describing a function that's meant to return an `IEnumerable` but don't tell the compiler what to do in this case.
Comment: its only char; example if erisim char == p return sube if erisim == c return sicil like
Comment: @user3790322 - that's not what the function signature says - you've defined it as `string` which means it *could* be `I am the very model of a modern major general` - there's nothing here to tell the compiler (or anyone else) that it's strictly limited to one of only 3 options.
Comment: Can you clarify your question? You say "this says" - *what* says? I'd assume that you're getting a compilation error, but this isn't clear from your question. If you are getting a compilation error, can you include the *exact* text of the error?
Answer: You could try this one:
if (erisim == "A")
{
    return redisUser.GetAll();// .Where(c=>c.Sube=="Y");
}
else if (erisim == "P")
{
    return redisUser.GetAll().Where(c => c.Sube == sube);
}
else if (erisim == "C")
{
    return redisUser.GetAll().Where(c => c.CagriAcan == sicil);
}
else
{
    return Enumerable.Empty<RequestCall>();
}

Answer: Sudhakar Tillapudi, absolutely right, you need to add deafult clause:
using (var redisclient = RedisManager.GetClient())
{
    var redisUser = redisclient.As<RequestCall>();

    if (erisim == "A")
    {
        return redisUser.GetAll();// .Where(c=>c.Sube=="Y");
    }
    else if (erisim == "P")
    {
        return redisUser.GetAll().Where(c => c.Sube == sube);
    }
    else if (erisim == "C")
    {
        return redisUser.GetAll().Where(c => c.CagriAcan == sicil);
    }
    else return null;
}

Answer: The problem is you aren't accounting for the scenario where erisim does not equal A, B or C therefore the compiler doesn't know what to return.
It's generally neater to have a single exit point in a function, so instead of having multiple return statements, have a single return value e.g.
var result = null;
if (erisim == "A")
{
    result = ...;
}
else if (erisim == "P")
{
    result = ...;
}
else if (erisim == "C")
{
    result = ...;
}
return result;

This approach will force you to define something to return (even if none of the statements are true) so you should never get those types of compiler errors.
Comment: Um. The compiler error forces you to return something. You can't have a logical error and forget to return something. Unlike here where you can now have a logical error and forget to assign to `result` in one of your branches. Congratulations, you've transformed a potential compile time error into a potential runtime error.
Comment: @Damien_The_Unbeliever well first of all, as far as I am aware the compiler won't let you use an unassigned variable so your logical error comment is void (little programming pun for ya). And secondly, that's exactly what I was referring to, the compiler is going to force you to return something, this approach forces you to *think* about what to return if none of those statements pass. It's purely a style choice and I was simply offering a different angle.
Comment: you assigned it `null` at the top of your `if` stack. The OP was *already* receiving a compiler error.
Comment: @Damien_The_Unbeliever yeah, purely an example. `null` might be an acceptable return value for that function (I have no idea what the function does so I can't elaborate on that). The point was demonstrating setting up a default value and overriding it but having a single exit point.
Comment: But my point is now that someone comes along and adds a new `if` block - they do a bit of work and forget to assign `result`. This will not be caught by the compiler. Compare that with the original code/accepted answer where, if I had done the same but forgotten to `return` I'd now be getting a compiler error that not all paths return a result.
Comment: @Damien_The_Unbeliever ah ok, I see the point you are making. However, that's easily resolved by not setting the initial default value at the top which would throw "*use of unassigned*" error if `result` was *never* set. Like I said, it's a style choice, the chances of the developer forgetting to set `result` using an approach like this is pretty slim in my opinion. However, I do take your point.
Answer: Just to clarify:
Not all code paths in your code are returning IEnumerable<RequestCall>. For example, what if I pass the parameter erisim the value "X". That won't pass the 1st, 2nd or 3rd if statements. Then, your method exits, without returning anything (which is giving you the error message).
param erisim:

   -> "A" -> return something
   -> "P" -> return something
   -> "C" -> return something
   -> Anything else -> (this part is missing!)

As others said, you need else to cover the remanining cases. Or just return Enumerable.Empty<RequestCall>(); before the end of the method.
Also, as a word of advice, you could use enums instead of "magic" strings if possible, or at least constants.

using if statement under using case


ServerXMLHTTP60 WebAPI authentication (special character: & - "commercial and")

Question: i try to authenticate on a "private" web-api in MS-Access with ServerXMLHTTP60. It works fine until i try to use a the special character "&".
Here is the example:
Private m_xml_auth As MSXML2.ServerXMLHTTP60

Private Function do_connect() As Boolean
Dim json_obj As Object
Dim credential_str As String

If m_password = "" Then
    do_connect = False
    Exit Function
End If

credential_str = "grant_type=password&username=" & m_username & "&password=" _
                   & m_password & "&client_id=" & m_client_id & "&client_secret=" & m_client_secret & ""

m_xml_auth.Open bstrMethod:="POST", bstrURL:=m_auth_url, varAsync:=False
m_xml_auth.setRequestHeader bstrheader:="Content-Type", bstrValue:="application/x-www-form-urlencoded"
m_xml_auth.send (credential_str)

If m_xml_auth.Status <> 200 Then
    do_connect = False
    m_password = ""
    MsgBox "Error while authentication: " & m_xml_auth.responseText

    'Err.Raise Number:=M_ERR_API_RESPONSE, _
        'DESCRIPTION:="Authentication failed - response-status: " & m_xml_auth.Status

Else
    Set json_obj = JsonConverter.ParseJson(m_xml_auth.responseText)
    m_bearer_token = "Bearer " & json_obj("access_token")

    Debug.Print m_bearer_token
    do_connect = True
End If
End Function

If there is a "&" in one of my variables -> for example in m_password the authentication fails. Is there a way to escape the special character "&" for "x-www-form-urlencoded" content-type?
Thanks,
Mr. Dev
Answer: Run each String through this function:
Public Function URLEncode( _
   ByVal StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String
  Dim bytes() As Byte, b As Byte, i As Integer, space As String

  If SpaceAsPlus Then space = "+" Else space = "%20"

  If Len(StringVal) > 0 Then
    With New ADODB.Stream
      .Mode = adModeReadWrite
      .Type = adTypeText
      .Charset = "UTF-8"
      .Open
      .WriteText StringVal
      .Position = 0
      .Type = adTypeBinary
      .Position = 3 ' skip BOM
      bytes = .Read
    End With

    ReDim result(UBound(bytes)) As String

    For i = UBound(bytes) To 0 Step -1
      b = bytes(i)
      Select Case b
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Chr(b)
        Case 32
          result(i) = space
        Case 0 To 15
          result(i) = "%0" & Hex(b)
        Case Else
          result(i) = "%" & Hex(b)
      End Select
    Next i

    URLEncode = Join(result, "")
  End If
End Function


Counting number of connections in a pcap file

Question: What tool can I used to get a count of the number of TCP and UDP connections inside of a pcap file?
Answer: Wireshark can do this via Statistics→Conversations. TShark can do it via -q -z conv,tcp -r /path/to/capture.pcap and -q -z conv,udp -r /path/to/capture.pcap. Ntop should be able to do it as well.
Answer: For TCP connections you could get a fairly good approximation by counting the SYN-ACK packets.
tcpdump -nr trace.pcap 'tcp[tcpflags] & (tcp-syn|tcp-ack) = (tcp-syn|tcp-ack)' | wc -l

For UDP there is no such thing as a connection, so you'll first have to define, what you want to count. You could count how many distinct pairs of source and destination are present in the file. This command will count packets in each direction separately, so if every "connection" sends packets in both directions, you'd have to divide by two.
tcpdump -nr trace.pcap 'udp' | cut -f2-5 -d' ' | sort -u | wc -l

If you prefer a GUI based tool, Wireshark can analyze TCP connections. It assigns a number to each TCP connection it finds in the file, so you can just scroll to the bottom of the file and look what number the last connection got assigned. (You may have to check multiple connections, if they are overlapping and some other connection continues after the last packet from the highest numbered connection.)
Comment: the first cmd for counting TCP connections may not give you a correct answer if there is retranmission.


Django DetailView Filter by Foreign Key

Question: I am little puzzled and would like to utilized the DetailView functionality using the foreign key as my filter to display the data. Basically my model looks like this:
class Category(models.Model):
    name = models.CharField(max_length=30)
    slug = models.SlugField(help_text="A short name for Category")

    def __unicode__(self):
       return self.name

    class Meta:
       ordering = ["-name"]
       verbose_name_plural = "categories"

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    slug = models.SlugField(help_text="A short name for Publisher")

    class Meta:
       ordering = ["-name"]

    def __unicode__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(help_text="A short name for book")
    pub_date = models.DateField()
    publisher = models.ForeignKey(Publisher)
    category = models.ForeignKey(Category)

    class Meta:
       ordering = ["-title"]

    def __unicode__(self):
       return self.title

My Urls.py:
url(r'^categories/(?P<slug>[\w-]+)/$', DetailView.as_view(model=Category,template_name="books/category_detail" )),

My Category_detail.html
{% block content %}

{{ category.name}}

Book Title: {{ book.title }}

Book publisher: {{ book.publisher }}

Book Published Date: {{ book.pub_date }}

{% endblock %}

Basically I would like to display in my category_detail.html the following information:
         Category Name
Book Title
Publisher Name
Published Date
Any help would be appreciated.
Thank you - Keoko
Answer: Thank you for your kind response. I created a views.py file with the following information:
from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from mysite.books.models import *

class BooksCategoryListView(ListView):

   context_object_name = "book_list"

   "get_queryset = query all the objects in the database"
    def get_queryset(self):
      category_slug = get_object_or_404(Category, slug=self.kwargs['slug'])
      return Book.objects.filter(category=category_slug)

And updated my application urls.py:
from django.conf.urls import patterns, url, include
from django.views.generic import ListView, DetailView
from mysite.books.views import BooksCategoryListView
from mysite.books.models import *

urlpatterns = patterns('',
   ...snip....
   url(r'^categories/(?P<slug>[\w-]+)/$', BooksCategoryListView.as_view()),
)

And finally modified the category_detail.html with the following:
{% block content %}

Book Details

Category: {{ book.category}}

Title: {{ book.title }}

Author: {{ book.authors }}

Publisher: {{ book.publisher }}

Published Date: {{ book.pub_date }}

{% endblock %}

Answer: In template you have category object. you can iterate all over the books;
{% for book in category.book_set.all %}
   Book Title: {{ book.title }}
   Book publisher: {{ book.publisher }}
   Book Published Date: {{ book.pub_date }}
{% endfor %}

or just first book;
   Book Title: {{ category.book_set.all.0.title }}
   Book publisher: {{ category.book_set.all.0.publisher }}
   Book Published Date: {{ category.book_set.all.0.pub_date }}

Django DetailView Filter by Foreign Key


Should we introduce a "non-developer" tag?

Question: We clearly get more questions of merchants and other non-developers, but its not clear for everyone which could cause some questions to get closed.
To improve this situation, and offer a way to have an overview over such questions I think we need to introduce some tags.
What Systems do you think are suited for this?
Comment: The need for this may be mitigated as soon as we (Magento Small Business group + Piotr) get the new forums & Small Business portal online.
Answer: Solutions which comes to my mind, and is only very simple.
mark questions with a "non-developer" and/or "merchant" tag.
Comment: `backend` / `administration` might be different possibilities. `non-developer` implies that the default settings is for developers, which is not the only scope of the site.
Comment: Seems reasonable.
Answer: Do you mean closed as off-topic?
Do you have any examples where a question on magento.stackexchange.com has been closed because it's not developer-y enough? Because that shouldn't be happening.
In my humble opinion we shouldn't separate them. Developers are usually well placed to answer merchant-type questions. I guess it could improve searchability, e.g. you have a techy question and want to avoid the threads about admin panel usage; but personally I find a well-worded search phrase does the trick, and also there may be occasions when the answer you seek actually does lie there.
Comment: Developers are able to answer them, but they need to answer them in a different way then for other developers. And not every developer is good in explaining things to non devs. And I think its easier dor non devs to find suxh questions, because they will not be able to answer much else
Comment: Also, if you have a question about how to get a list of all products, the answer for a merchant would be different from an answer for a developer. The developer would get "Use the catalog/products model and get the collection", whereas the merchant would get "Visit Catalog > Manage Products"


JS - If condition with only 1 else, does checking order affect performance?

Question: I was working on a project and this problem popped into my head. I am not sure if there is already a post like this but I have found none.
Let say if I have this:
function checks(s) {
    if (s.length == 4 && s[0] == "a") {
        //action
    } else {
        //other action
    }
}
checks("a001");
checks("else");
checks("else");
checks("else");

and this:
function checkb(b) {
    if (b) {
        //action
    } else {
        //other action
    }
}
checkb(true); //Suppose i'm passing these through another function
checkb(false); //so it makes sense for me doing these
checkb(false);
checkb(false);

Since either way the if-statement is going to have to check once of the conditions, if the frequency of the actions are known (e.g. I know that the else part is performed most often). Does checking for "not conditions" make the code run faster or does the checking of "not condition" don't even affect the performance? (Suppose I'm building a complicated node.js server that has many of these type of functions.)
Addition question: Do most programming languages do the same too theoretically?
I was just wondering if it affects the performance (practically or theoretically).
Comment: It's negligible and makes no sense to optimize.
Comment: I wouldn't care of performance in this case unless this function is executed 100 million times in the loop.
Comment: I wouldn't care even if it was 100 billion times in a loop.
Comment: *Premature optimisation is the root of all evil* - Donald Knuth
Comment: I agree with @zerkms no difference at all in term of performance
Comment: `checkb(true);` has a comparison inside ... so what is the deal?
Answer: Short answer: No, it does not effect the computation time.
Long answer: Most Javascript engines (Spider Monkey and V8) internally use a Just in Time compiler which will iron over those differences during runtime.
In low level programming languages (read: C/C++ and the ilk), you may gain something if you are able to prevent branch mis-predicts, like in C++ code, but the gain is usually worth it only if you are doing Kernel programming or doing extreme micro-optimizations.

Theoretically, whether it makes a difference or not depends on what kind of compiler you are looking at. If you are looking at a compiler which can learn from code traces, e.g. a Just in Time compiler, then it will make a difference if a certain pocket of code is the hot spot or not. If you are looking at static compilers, it may mean that the compiler may use one less clock cycle in one of the cases (either if or else) by preventing a jmp, but it'll depend on the compiler implementation.
Comment: thank you for giving a juicy answer. i've learnt many things today! :)


Green's representation on a compact domain

Question: This is from page 17-18 of Trudinger and Gilbarg
Let $\Omega$ be a domain for which the divergence theorem holds. Let $\Gamma(x-y)$ be the normalised fundamental solution of the Laplace's equation, then Green's representation formula
$$u(y)=\int_{\partial\Omega}\bigg(u\frac{\partial\Gamma}{\partial\nu}(x-y)-\Gamma(x-y)\frac{\partial u}{\partial v}\bigg)\text{d}s+\int_\Omega\Gamma(x-y)\Delta u\text{d}x$$
If $u$ has compact support in $\mathbb{R}^n$, then this yields
$$u(y) = \int \Gamma(x-y)\Delta u(x)\text{d}x$$
I do not really understand this. I assume the first term disappear by taking a domain, say $\Sigma$ is large enough so that $u$ is $0$ on $\partial\Sigma$, but then $\Delta u$ may not necessarily be well defined on $\partial\Omega$, so why does it hold?
Comment: I think the reasonable assumption is that $u$ is compactly supported in $\Omega$. The discussion is a little vague in that regard; I think there's reason to be confused.
Comment: @T.A.E. I have trouble with (maybe) a similar argument later in the book too. It makes me grit my teeth.
Answer:
If $u$ has compact support in $\mathbb R^n$...

This is what happens when people try to pack too much information into too few words. They meant to say

If $\Omega=\mathbb R^n$ and $u$ has compact support...

Notice that there is no $\Omega$ under the integral on the next line, indicating they are thinking of $\mathbb R^n$.

Why $\mathbb R^n$, and not general $\Omega$? We have that same representation whenever $u$ is compactly supported in $\Omega$. But then it does not quality as frequently useful (the words they use to describe (2.17)). When working within a domain, one would integrate $\Delta u$ against Green's function of that domain, not against $\Gamma$. Green's function enforces the Dirichlet boundary condition, not matter what is plugged in instead of $\Delta u$. Convolution with $\Gamma$ does not; it returns a function with zero boundary values only when given that very special input $\Delta u$.


What is a suitable probability distribution for monetary amounts?

Question: In my Bayesian model, I have a random variable representing the amount of money received due to a user's click on an affiliate link on a website. There are several such links with different payouts; in my model I want to capture the uncertainty due to the unknown behaviour of the user. The amounts are typically in the range of 0.30 EUR to 0.80 EUR.
I am wondering: what is a suitable probability distribution for monetary amounts?
Comment: That would depend on characteristics we don't possess knowledge of. If there are several links with different payouts it will be a [finite mixture distribution](http://en.wikipedia.org/wiki/Mixture_distribution#Finite_and_countable_mixtures) across the distributions of the payouts, but you haven't suggested what those might be and even if those are known, we have no basis here on which to assume relative probabilities for each, so those would need to be estimated.
Answer: There can be no 'correct distribution' for this problem, as this involves too many unknowns  (silly humans, or perhaps there is one link paying 10$…). But what you are looking for is a parametrisation of the 'real' density. As there is not a single process involved (like a decay probability…) something like a single Poisson distribution will most probably not be sufficient. Have a look at 'folded' distributions like a gamma-poisson mixture, which is much more flexible for fitting your real (dirty) distribution. Have fun, just search for distributions on google which look the most like yours and take it!


java.lang.NullPointerException in Android application

Question: I am fairly new to java and I have been trying to learn, so I made a webview app for my website that I have published and a few people have reported an error as listed below:
java.lang.NullPointerException
at com.alexriggs.android.mafiastreetwars.MafiaStreetWarsActivity$MyWebViewClient.shouldOverrideUrlLoading(MafiaStreetWarsActivity.java:87)
at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:227)
at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:334)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3704)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)
at dalvik.system.NativeStart.main(Native Method)

No I know enough to know that java.lang.NullPointerException means that a variable is empty but being used as not empty. And after looking back at my code, it should never be empty and I cannot reproduce it. So here is my code, can anyone figure out what is wrong?  And please remember that I am new to Java, so please use as much detail as possible!
package com.alexriggs.android.mafiastreetwars;

import com.alexriggs.android.mafiastreetwars.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MafiaStreetWarsActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.exit:{
                Toast.makeText(this, "Thanks For playing Mafia Street Wars!", Toast.LENGTH_LONG).show();
                finish();
                break;
            }
            case R.id.select_and_copy:
            {
                Toast.makeText(getApplicationContext(), "Select Text by dragging over the text you want to copy.", Toast.LENGTH_LONG).show();
                selectAndCopyText(myWebView);
                return true;
            }
        }
        return true;
    }
    private void selectAndCopyText(WebView view) {
        try
        {
            KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
                                                    KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
            shiftPressEvent.dispatch(view);
        }
        catch (Exception e)
        {
            Log.e("dd", "Exception in emulateShiftHeld()", e);
        }

    }
    final Activity activity = this;
    WebView myWebView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Remember...");
        alertDialog.setMessage("This app is just for mobile access. This game is meant to be played on the computer at MafiaStreetWars.com");
        alertDialog.setButton("Thanks for the reminder!", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int which) {
              // here you can add functions
           }
        });
        alertDialog.setIcon(R.drawable.icon);
        alertDialog.show();
        myWebView = (WebView) findViewById(R.id.webview);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.setWebViewClient(new MyWebViewClient());
        myWebView.getSettings().setBuiltInZoomControls(true);
        myWebView.getSettings().setLoadWithOverviewMode(true);
        myWebView.getSettings().setUseWideViewPort(true);
        myWebView.getSettings().setPluginsEnabled(true);
        Toast.makeText(getApplicationContext(), "Page is loading... Please wait!", Toast.LENGTH_LONG).show();
        myWebView.loadUrl("http://mafiastreetwars.com/?pk_campaign=Android&pk_kwd=MainApp");
    }
    private class MyWebViewClient extends WebViewClient {

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals("mafiastreetwars.com")) {
                return false;
            }
            // Otherwise, give the default behavior (open in browser)
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
        }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

Comment: Please learn to use a debugger. It will tell you where your problem is.
Comment: @AdamArold  Like I said, I cannot reproduce the problem..
Answer: It's probably due to Uri.parse(url).getHost() returning null. Check this before you call equals().
Answer: Line in question if (Uri.parse(url).getHost().equals("mafiastreetwars.com")) {
Looks like your url is null, or the parse result is null but that is less likely. Check to see if things are null before using them!
Answer: I suggest you to do it a little bit more nullsave:
if (url==null)
   return false;
Uri lUri = Uri.parse(url);
if ("mafiastreetwars.com".equals(lUri.getHost())) {
            return false;
}

that solves your technical problem but maybe not youre business case.


mysqli recebendo boolean

Question: meu site não está fazendo buscas ! Não consegui descobrir como se faz consultas pela caixa de pesquisa, tento acessar os carros do banco de dados e ele me traz o seguinte erro:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in /home/u374984363/public_html/newcars/functions.php on line 61

meus códigos:
functions.php :

function buscarCarros($conexao, $nome){
    $carro = array();
    $conexao = mysqli_connect('mysql.hostinger.com.br','u374984363_ozzy','******', 'u374984363_ncars');
    $query = "select * from carros where nome = {$carro}";
    $resultado = mysqli_query($conexao, $query);
    while ($carros = mysqli_fetch_assoc($resultado)) {
        array_push($carro, $carros);
    }
    return $carro;
}

result_pesquisa.php :

<?php
include('menu.php');
include('conecta.php');
include('functions.php');

$carro = buscarCarros($conexao, $nome);
    foreach ($carro as $carros) :
        $carros['nome'];
?>

menu.php :

Home

Comprar

Vender

Contato

        <form id="searchbox" action="result_pesquisa.php" method="POST">
            <input type="text" class="search-top remove-bottom" name="pesquisas" placeholder="Qual carro você procura?">

        </form>

Comment: Coloque `var_dump($conexao->error);` embaixo do `mysqli_query` pra ver qual foi o erro.
Comment: Troque a senha do seu banco de dados.
Comment: Trocada ! Desculpem pelo vacilo... quanto ao erro, fiz o indicado e recebi isso:
string(40) "Unknown column 'Array' in 'where clause'"
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in /home/u374984363/public_html/newcars/functions.php on line 62
Comment: Troque onde diz `{$carro}` por `'{$nome}'` na sua query e veja o que acontece.
Comment: Obtive isso: string(148) "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1"
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in /home/u374984363/public_html/newcars/functions.php on line 62.. parece que esse codigo nao quer rodar :/
Comment: Colocou as aspas simples também, do jeito que está no comentário?
Comment: Agora sim e ele me trouxe isso: string(0) ""... o que houve ? ele não encontrou o que pesquisei ? olhando no banco de dados, o nome estava certissimo !
Comment: Vou colocar na resposta, já já você vai ver.
Comment: Ok ! obrigado, estarei aguardando !
Answer: Você está passando a array $carros para o campo nome da tabela do banco de dados, imagino que você quis passar a variável $nome ao invés.
functions.php
Use prepared statements para evitar ataque de sql injections. Dê uma lida na discussão sobre os dois assuntos, em uma pergunta daqui do S.O. PT.
function buscarCarros($pConexao, $nome){
    $carro = array();
    //$conexao = mysqli_connect('mysql.hostinger.com.br','u374984363_ozzy','******', 'u374984363_ncars');
    // a variável $conexao deve vir do 'conecta.php', não precisamos conectar de novo
    $query = "SELECT nome FROM carros WHERE nome = ?";

    if ($stmt = mysqli_prepare($pConexao, $query)) {

        mysqli_stmt_bind_param($stmt, "s", $nome);

        mysqli_stmt_execute($stmt);

        mysqli_stmt_bind_result($stmt, $nomeResultado);

        while (mysqli_stmt_fetch($stmt)) {
            $carro[]['nome'] = $nomeResultado;
        }

        mysqli_stmt_close($stmt);
    }

    return $carro;
}

result_pesquisa.php
include_once('menu.php');
include_once('conecta.php');
include_once('functions.php');
//use include_once ao invés de include quando puder, para evitar de algum dia incluir
//sem querer 2 vezes o mesmo arquivo, que pode gerar fatal errors e interromper
//a execução dos scripts caso você esteja declarando alguma função nesses arquivos

//pegamos o conteúdo que foi pesquisado
$nome = $_REQUEST['pesquisas'];

$carro = buscarCarros($conexao, $nome);
foreach ($carro as $carros) {
    echo $carros['nome'];
}

No menu.php faltou colocar o atributo method do <form> e um botão de submit, ao invés de um link que apenas leve a página para outra:

Home

Comprar

Vender

Contato

        <form id="searchbox" action="result_pesquisa.php" method="POST">
            <input type="text" class="search-top remove-bottom" name="pesquisas" placeholder="Qual carro você procura?">
            <input type="submit" value="Pesquisar" />
        </form>

Comment: Não sei o motivo, mas o fundo do meu site ficou completamente preto, e alguns icones mudaram... a pesquisa também não retornou resultados...

mysqli recebendo boolean


finding the derivative of a square root function

Question: I need to find $y'$ if $y=\sqrt x(x-1)$
I distributed the sqrt of x:
$\sqrt x(x)-\sqrt x$
what do I do now? I need to get rid of the square root in order to find the derivative but I'm not sure how.
Answer: Hint: Observe that:
$$
y = \sqrt{x}(x - 1) = x^{1/2}(x^{2/2} - 1) = x^{3/2} - x^{1/2}
$$
Comment: I get where x^3/2 comes from, but why is there the "-x"? if you're just distributing the x^1/2, wouldn't it be "x^3/2 - x^1/2"?
Comment: Yes, my mistake.
Answer: $$y=x\sqrt x-\sqrt x$$
$$=x(x^{1 \over 2})-x^{1 \over 2}$$
$$=x^{3 \over2} - x^{\frac 12}$$
So
$$\frac{d}{dx}\left(x^{3 \over2} - x^{\frac 12}\right) = \dfrac 32x^{\frac 12}-\dfrac 12x^{-\frac 12}$$
$$=\dfrac {3\sqrt x}{2}-\dfrac 1{2\sqrt x}$$
We are technically done, but lets rationalise the denominator
$$\frac{d}{dx}\left(x^{3 \over2} - x^{\frac 12}\right) = \dfrac {3\sqrt x}{2}-\dfrac{\sqrt x}{2x}$$
Answer: First,
$(\sqrt{x})'
=(x^{1/2})'
=(1/2)x^{-1/2}
$
since
$(x^a)'
=a x^{a-1}
$.
By the product rule
$\begin{align}
(\sqrt{x}(x-1))'
&=\sqrt{x}(x-1)' + (\sqrt{x})'(x-1)\\
&=\sqrt{x}+(1/2)x^{-1/2}(x-1)\\
&=\sqrt{x}+(1/2)(x^{1/2}-x^{-1/2})\\
&=\sqrt{x}+(1/2)\sqrt{x}-1/(2\sqrt{x})\\
&=(3/2)\sqrt{x}-1/(2\sqrt{x})\\
&=(3/2)\sqrt{x}-\sqrt{x}/(2x)\\
&=\frac{\sqrt{x}}{2}\left(3-\frac{1}{2x}\right)\\
\end{align}
$
Those last three lines
are all, in my opinion,
acceptable ways
to wrote the result.


mySQL master-master replication

Question: I have a 3 server mySQL/PHP/Apache cluster (each on different continents for maximum resilience). I have read a lot of advice which all says - don't do this!
Essentially the reasons I want to do this is:

Resilience - 2 of 3 servers could go down and the users can still log in and see their data/ do their work
Backup - kind of as above
Load share - I can distribute the front-end load AND back-end server processes across the different boxes

I have looked at different options including percona galera, all seem to have drawbacks. The main being transparency - at some point a link or server will go down, then you get vague BINLOG errors, then its all a massive problem...
So I have implemented this myself instead - I have a set of scripts that build INSERT/UPDATE/DELETE triggers on each table - any changes are logged in a replication table. An every minute process pushes these changes to the other 2 servers. I also have processes which check the CHECKSUM and alert on any discrepancies.
Its works great. Not easy I grant you! Multiple fiddly things, including:

not using float column type (0.3434 does not equal 0.3434...)
avoiding auto-increment keys (if data is inserted on 2 different servers at the same minute, they could both take the next value, then the reciprocal inserts will fail).
remember to re-run that create triggers script if you change a table structure

So, my question is... What could go wrong? Where/why is this going to go fail? What don't I know??
Comment: Get yourself a copy of "Designing Data-Intensive Applications" by Martin Kleppmann. I think it has a detailed description of the CAP theorem with pictures.
Comment: I'm voting to close this question because you are asking us to appraise a design and implementation without enough detail. Providing that detail goes WAY beyond the scope of a stackoverflow Q&A.
Answer: On the contrary to the above, i think this is an excellent question. They are not asking for an analysis of what they have done, just the general "4th window" of what are the unknown unknowns.
Data intensive applications is an excellent book
They call it Multi-leader replication rather than master-master and has a good discussion of why this has pitfalls. As as you have seen, services with Galera and Percona don't do it -- so there must be a good reason (I have not played with Blackhole yet).
I think the key message is that you need to ensure the table structure can cope with multi-lead replication - so if 2 new entries are added on separate servers, you wouldn't (as you say) want to have an auto-increment key field - you need to have designed the table and application to use maybe user id and timestamp etc... (so thats a manual work pain).
You also probably need decent tools to be able to quickly compare and tables across databases and spot inconsistencies.

mySQL master-master replication


Hold out validation. Exactly what is left out?

Question: I'm studying validation and I've seen multiple examples of hold out validation. Some will hold the tail of the data, while others will leave out $n$ random points.
I assume it has to do with whether you're testing for interpolation or extrapolation, but is there something I'm missing as far as general practice goes? Because when you just leave out random points it just seems like 1 step of k-fold validation, without training and validating over the rest of the folds.
Thanks!
Comment: Selecting the tail of data is a terrible idea if your data is sorted in some systematic way that affects prediction. For example, if your data is sorted by date and you are modeling something that might be affected by date, experience, etc., holding out the most recent records might paint a worse (or better) picture of your model than selecting random records.
Comment: @StatsStudent Holding out the "tail" if they mean the most recent records (I would not call this tail though..) might make sense if you are comparing models intended to test on future data. In that case, testing against the most recent data is more like the real-world situation and might help you know if it makes sense to use a model that favors more recent data in fitting the model parameters. I agree in most cases it is a bad idea, though, just not necessarily terrible in every case.
Comment: Agreed 100% Bryan.  I think Yilun Zhang's answer below addresses this aspect well.
Answer: The point of hold out validation set is that you want part of your data to be left out from training so that you can test out the performance of your model on unseen data. Therefore, you need your validation set to have the same distribution as your training data. Thus, random selection is always the way to go since the data you use are obtained from somewhere else and you don't know how the data points are sorted, and you don't want the original sorting to affect which data goes into training and which goes into validation.
However, sometimes you do want to use the tail of the data. One obvious case is time series predictions. The data you have should usually be sorted by time. Thus, it makes a lot of sense to use the first X% as training data and use the remaining (100-X)% as validation since those are the future time points. If you did the random validation set split, you will be in trouble. For example, if values at time point 1,3, 4, 5 are in training and 2 is in validation, the model will be able to use time point 3, 4, 5 to infer the value at time point 2, which is completely not acceptable as you are leaking information.
How you select your validation set may vary depends on the objective and the modeling goal. However the principle is to make sure:

The training and validation set are from the same distribution/population.
Your training data does not leak information to your validation data.
Comment: Your explanation is very concise, but I'm not sure I understand the "leaking information" part.

For example you have a time series from 2008 to 2018 and you want an estimate for a missing value, i.e. 2010. In that case it wouldn't make much sense leaving out only 2016,2017,2018, but random values in the range. Obviously if you want to predict 2019, it would make sense to leave the last values out.
Comment: @George I think what I meant is that it's not reasonable to make a prediction for a time point in the middle of two training data points for time series data since the value can possibly be inferred from a future time point. Moreover, if you already have data point for $t_{2018}$, then why do you want to make a prediction for $t_{2017}$ ?


App webview session ou cookie

Question: Olá, galera!
Estou criando um app (híbrido) para android, a partir do HTML5, CSS e JAVASCRIPT, como WebView.
Usarei API através do PHP usando MYSQL, trocando informações com JSON.
A minha dúvida é seguinte, a onde devo guardar o token para fazer requisição? Pois como vou pegar a identificação do cliente?
Não sei se expliquei direitinho, espero que sim.
Answer: Augusto,
Você pode gerar o token no php e devolvê-lo no success do login e então passar a informá-lo em todas as demais requests.
Normalmente as requests por API fazem a checagem de autenticação por requisição, inclusive isso depende da sua lógica e do tempo de inatividade.
Por exemplo, se você não for expirar o usuário no app até que ele faça o logout, pode criar uma tabela de relacionamento de usuário com sessão. E armazenar o token nesta tabela. Sempre que você achar o usuário nesta tabela ele está logado. E para deslogá-lo, só excluir o registro.
Se você irá utilizar 100% webview, pode armazenar os dados do cliente na sessão do javascript.
Algo parecido com isso:
window.sessionStorage.setItem("token", "meutoken")
Para recuperar:
window.sessionStorage.getItem("token")

Adicionalmente...
Supondo ainda que você tenha jQuery carregado e o token está no header Authorization pode definír como padrão em todas as requisições assim:
$.ajaxSetup({
    headers: { 'Authorization': window.sessionStorage.getItem("token") }
});

Comment: Ericson, muito obrigado.

Aproveitando para finalizar, você acha seguro fazer requisição via URL com token ou utilizar frameworks como Auth0, Slim etc...
Comment: Augusto, sinceramente não estou familiarizado com estes frameworks. Particularmente prefiro manter o controle da lógica na própria aplicação, resolvendo as compatibilidades de escalabilidade, mas é claro que vc vai precisar se preocupar com a segurança neste modelo (por exemplo uso de RSA na criptografia do token) , ja nos frameworks devem ter se preocupado bastante, principalmente nos open sources com o apoio da comunidade. Isso também depende do seu projeto inclusive com outros meios de autenticação-supondo que o seu maior publico seja Android, poderia utilizar a autenticação do Google.

App webview session ou cookie


java.lang.UnsatisfiedLinkError: The specified procedure could not be found

Question: I'm trying to develop a JNA wrapper of a C++ DLL.
I do not have access to the code of the DLL. I checked the DLL using depends.exe and I saw that there is no decorator around the C++ methods. And it seems that extern "C" is also set in the C++ *.h file I retrieved.
But I have the following error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up function 'compute': The specified procedure could not be found.
at com.sun.jna.Function.(Function.java:252)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:600)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:576)
at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:562)
at com.sun.jna.Library$Handler.invoke(Library.java:243)
at com.sun.proxy.$Proxy0.compute(Unknown Source)
at com.JNA.main(JNA.java:171)

See my cpp *.h file:
#ifdef __cplusplus

extern "C" {

#endif

typedef struct s_mine
{
    e_color           color;    //e_color is enum type made of int values
    his               data;
    int               str;
    unsigned int      wild;
    unsigned int      hello;
    float             rice;
} mine;

typedef struct s_his
{
    unsigned char * data;
    unsigned int    size;
} his;

// compute function which raised the exception

int compute(const his* const input, void ** outputPointer);

// treat function raised also the same exception

int treat(const mine* inputParameter, mine* outputParameter);

#ifdef __cplusplus

}

#endif

See below my JNA wrapper:
public interface MyInterface extends Library {

    @FieldOrder({"data", "size"})
    public static class his extends Structure {
        public static class ByReference extends his implements Structure.ByReference {}
        public static class ByValue extends rt_buffer implements Structure.ByValue {}
        public Pointer data;
        public int size;
    }

    @FieldOrder({"color","data","str","wild","hello","rice"})
    public class mine extends Structure {
        public static class ByReference extends mine implements Structure.ByReference {}
        public int color;
        public his data;
        public int str;
        public int wild;
        public int hello;
        public float rice;
    }

    public int compute(his input, Pointer[] outputPointer);

    public int treat(mine inputParameter, mine outputParameter);
}

Thus in my test class I set:
// COMPUTE

MyInterface.his.ByReference input_ref = new MyInterface.his.ByReference();

ByteBuffer init_buffer;

// init_buffer is initialized with some not null values

Pointer init_p = Native.getDirectBufferPointer(init_buffer);

input_ref.data = init_p;

input_ref.size = init_buffer.capacity();

Pointer[] outputPointer = null;

int resultCompute = compute(input_ref, outputPointer);

// TREAT

MyInterface.mine.ByReference inputParameter_ref = new MyInterface.mine.ByReference();

MyInterface.his.ByValue buffer = new MyInterface.his.ByValue();

// initialize buffer with an input buffer value different from null value

// Set other fields of inputParameter_ref with none null values

inputParameter_ref.data = buffer;

MyInterface.mine.ByReference outputParameter_ref = null;

int resultTreat = treat(inputParameter_ref, outputParameter_ref);

Thus I have the feeling that the raised exception does not come from my implementation but from the DLL. But I do not have any clue to explain why regarding my assertions at the beginning of my post.

Could there be another reason except decorator and extern declaration issue?

How could I check that extern declaration has been set from the DLL inspection with depends.exe?

@dbwiddis Thanx for your reply but :

const his* const input means that input is a constant pointer on a constant his structure.
This means that the pointer is a readonly parameter on a readonlyvalue.

I set outputPointer as an array because I was not sure about the way to use it.
Indeed I need it as an input parameter for another method. For c++ I have something like :

int compute(const his* const input, void ** outputPointer); // **outputPointer is an output of compute method
int manage(void * inputPointer); // As *outputPointer becomes an input of manage method
Thus I have in my jna  Wrapper :
public int compute(his input, Pointer[] outputPointer);
public int manage(Pointer inputPointer);
In my test class I have :
Pointer[] outputPointer = null;
int resultCompute = compute(input_ref, outputPointer);
int manage(outputPointer[0]);
Anyway I tried also with your recommandation as follow :
Thus I have in my jna  Wrapper :
public int compute(his input, PointerByReference outputPointer);
public int manage(Pointer inputPointer);
In my test class I have :
PointerByReference outputPointer = null;
int resultCompute = myInterface.compute(input_ref, outputPointer);
int myInterface.manage(outputPointer.getValue());
But I still have the same issue.
As reminder whatever the method defined in the c++ dll I have the same raised exception.
I really feel that the issue does not come from my jna implementation.
Also important detail, in my test class I perform a upload of the dll :
Map options = new HashMap();
options.put(Library.OPTION_FUNCTION_MAPPER, new StdCallFunctionMapper() {
public String getFunctionName(NativeLibrary library, Method method) {
System.out.println("method names = "+method.getName());
return super.getFunctionName(library, method);
}
});
MyInterface myInterface = (MyInterface) Native.load("dllName",MyInterface.class,options);
The sysout above displays the name of the current method which is called i.e I have method names = compute displayed.
Debugging the code, I noticed that their was an issue on the method name.
But as the sysout displays the name of the method I declared in my jna wrapper, it is not helpful.
I 've just performed a quick test with a fake method which is not defined in the c++ dll and I have the same error :
the procedure is not found. Thus I really think that there is an issue with that dll but I don't know how to find it out...
Comment: This could just be a typo in your C wrapper. Is there an extra `const` in `const his* const input` ?  If that doesn't fix it, does it work if you map the `void ** outputPointer` as a `PointerByReference` rather than an array?
Comment: Thanx but see my answers above in my updated question i.e see part starting by "@dbwiddis Thanx for your reply but :"
Comment: Your JNA mappings look good. Does [this answer](https://stackoverflow.com/a/15405792/1161484) help?  I addition to the `extern "C"` you may need to export the function with `__declspec(dllexport)`
Answer: Finally, I had to add in my java Test main class which calls my wrapper the following line to solve my issue :
System.setProperty("jna.library.path", "C:\myWrapper\src\main\resources");
where C:\myWrapper\src\main\resources is the folder in which my dll file is stored.
But It does not explained why I did not need to set this line for other dll stored in the same folder as I declared also jna.library.path in my environment variables as well.


Recurrence relation $T(n+1)=T(n)+⌊\sqrt{n+1}⌋$?

Question: Consider the following recurrence relation
$T(1)=1$
$T(n+1)=T(n)+⌊\sqrt{n+1}⌋$ for all $n≥1$
The value of $T(m^2)$ for $m≥1$ is

$(m/6) (21m – 39) + 4$
$(m/6) (4m^2 – 3m + 5)$
$(m/2) (m^{2.5} – 11m + 20) – 5$
$(m/6) (5m^3 – 34m^2 + 137m – 104) + (5/6)$

My attempt :
I've used counter example to choose correct option.
$m = 3$
$T(9) = T(4) + 2*5 + 1 = 5 + 10 + 1 = 16$
Both options $(1)$ & $(2)$ produces $16$.
$m = 4$
$T(16) = T(9) + 3*7 + 1 = 16 + 21 + 1 = 38$
Only option $(2)$ produces $38$, $(1)$ produces $34$ which doesn't match.

Can you explain in formal way, please?
Comment: A trivial observation that might help. The corresponding sequence is: $1, 1, 1, 2, 2, 2, 2, 2, 3, \dots$ and $T_i$ is a partial sum of this. Notice that for any number $n$, there are $(n+1)^2 - n^2 = 2n + 1$ occurrences of $n$ in the sequence. This may (or may not) help you reformulate the function $T$.
Comment: I think this question is asking about the order of growth of $T(m^2)$.
Comment: @Mithlesh Upadhyay Here is an ingenious explicit formula: $T(n) = \left\lfloor \sqrt{n}\right\rfloor  \left(n-\frac{1}{6} \left(2 \left\lfloor \sqrt{n}\right\rfloor +5\right) \left(\left\lfloor \sqrt{n}\right\rfloor -1\right)\right)$ - Yong Kong (ykong(AT)curagen.com), Mar 10 2001 , https://oeis.org/A022554. For a square this gives $T\left(n^2\right)=\frac{1}{6} n \left(4 n^2-3 n+5\right)$
Answer: Note that $T(1)=\left\lfloor\sqrt1\right\rfloor$; from this and the recurrence it's straightforward to see that
$$T(n)=\sum_{k=1}^n\left\lfloor\sqrt k\right\rfloor$$
for all $n\ge 1$. Thus
$$T(m^2)=\sum_{k=1}^{m^2}\left\lfloor\sqrt k\right\rfloor\;.\tag{1}$$
Now for $k=1,\ldots,m^2$ the possible values of $\left\lfloor\sqrt k\right\rfloor$ are the integers $1,\ldots,m$, and we can calculate $(1)$ quite easily if we can determine how often each of these integers appears. We have $\left\lfloor\sqrt k\right\rfloor=n$ if and only if $n^2\le k<(n+1)^2=n^2+2n+1$, so there are $2n+1$ integers $k$ such that $\left\lfloor\sqrt k\right\rfloor=n$. This holds for $k=1,\ldots,m-1$, and we have one value of $k$, $k=m^2$, for which $\left\lfloor\sqrt k\right\rfloor=m$. Thus, the sum in $(1)$ is equal to
$$\begin{align*}
m+\sum_{n=1}^{m-1}n(2n+1)&=m+2\sum_{n=1}^{m-1}n^2+\sum_{n=1}^{m-1}n\\
&=m+2\cdot\frac{(m-1)m(2m-1)}6+\frac{(m-1)m}2\\
&=m+\frac{m(m-1)\big(2(2m-1)+3\big)}6\\
&=m+\frac{m(m-1)(4m+1)}6\\
&=\frac{m}6\big(6+(m-1)(4m+1)\big)\\
&=\frac{m}6(4m^2-3m+5)\;.
\end{align*}$$
Comment: @Mithlesh: You're welcome.
Comment: Thanks for nice explanation.
Answer: Hint All of the choices have different orders of growth, so it suffices to determine the order of growth of the given function $T$.
It's easier to analyze the recurrence giving by adding $\sqrt{k}$ (rather than the $\lfloor \sqrt{k} \rfloor$) to each term to give the successive term, and the two resulting sequences are close enough that we can work with the former instead of the latter when analyzing the order of growth. More precisely: Since $$0 < \sqrt{k} - T(k) + T(k - 1) < 1$$ for all $k$, we have (adding each expression in this equality for $k = 2, \ldots, n$ and observing that the middle sum telescopes) that
$$0 < \sum_{k = 1}^{n} \sqrt{k} - T(n) + T(1) < n - 1 ,$$
and so
$$T(n) = \sum_{k = 1}^{n} \sqrt{k} + O(n).$$
We can regard the sum as a (left or right) Riemann sum for the integral of $\sqrt{x}$, and since that function is increasing, we have
$$\int_0^n \sqrt{x} \, dx < \sum_{k = 1}^n \sqrt{k} < \int_1^{n + 1} \sqrt{x} \, dx,$$
Both of these integrals have the form $\frac{2}{3} n^{3 / 2} + O(n)$, and hence so does the sum.

Additional hint Thus, $T(n) = \frac{2}{3} n^{3 / 2} + O(n)$ and hence $$T(m^2) = \frac{2}{3} m^3 + O(m^2).$$ The only option of this form is (2).
Comment: Thanks for nice explanation.
Comment: You're welcome, I'm glad you found it useful.
Answer: Intending to be even lazier than Travis, here we just check some values.
Note that 3. and 4. violate the initial condition. 3. has $T(1) = 0$ and 4. has $T(1) = 9/6$.
Now check the next value $m=2$ thus $T(2^2) = T(4)$:
$$
T(2) = T(1+1) = T(1) + \lfloor \sqrt{1+1} \rfloor = 1 + 1 = 2 \\
T(3) = T(2+1) = T(2) + \lfloor \sqrt{2+1} \rfloor = 2 + 1 = 3 \\
T(4) = T(3+1) = T(3) + \lfloor \sqrt{3+1} \rfloor = 3 + 2 = 5 \\
$$
then for 1. we get $5$ and for 2. we get $5$ as well. Heck. Next one.
Now check the next value $m=3$ thus $T(3^2) = T(9)$:
\begin{align}
T(5) = T(4+1) &= T(4) + \lfloor \sqrt{4+1} \rfloor = 5 + 2 = 7 \\
T(6) = T(5+1) &= T(5) + \lfloor \sqrt{5+1} \rfloor = 7 + 2 = 9 \\
T(7) = T(6+1) &= T(6) + \lfloor \sqrt{6+1} \rfloor = 9 + 2 = 11 \\
T(8) = T(7+1) &= T(7) + \lfloor \sqrt{7+1} \rfloor = 11 + 2 = 13 \\
T(9) = T(8+1) &= T(8) + \lfloor \sqrt{8+1} \rfloor = 13 + 3 = 16 \\
\end{align}
Unfortunatly, both 1. and 2. give $16$. Cunning bast*s! Sigh, so much for the laziness. It turns really into brute force.
Now check the next value $m=4$ thus $T(4^2) = T(16)$:
\begin{align}
T(10) = T(9+1)  &= T(9)  + \lfloor \sqrt{9+1} \rfloor = 16 + 3 = 19 \\
T(11) = T(10+1) &= T(10) + \lfloor \sqrt{10+1} \rfloor = 19 + 3 = 22 \\
T(12) = T(11+1) &= T(11) + \lfloor \sqrt{11+1} \rfloor = 22 + 3 = 25 \\
T(13) = T(12+1) &= T(12) + \lfloor \sqrt{12+1} \rfloor = 25 + 3 = 28 \\
T(14) = T(13+1) &= T(13) + \lfloor \sqrt{13+1} \rfloor = 28 + 3 = 31 \\
T(15) = T(14+1) &= T(14) + \lfloor \sqrt{14+1} \rfloor = 31 + 3 = 34 \\
T(16) = T(15+1) &= T(15) + \lfloor \sqrt{15+1} \rfloor = 34 + 4 = 38 \\
\end{align}
And 1. gives only $34$. 2. gives $38$. And the winner is option 2.!
Comment: +1 for finally not being lazy. There exists some multiple choice questions where no answer is valid, so brute force may not be an option.
Answer: $$T(m^2)=T(m^2-1)+m$$ $$T(m^2-1)=T(m^2-2)+(m-1)$$  $$T(m^2-2)=T(m^2-1)+(m-1)$$  $$...........$$  $$...........$$  $$T((m-1)^2)=T((m-1)^2-1)+(m-1)$$ Hence (because of telescopic)
$$T(m^2)=T((m-1)^2-1)+(2m-1)(m-1)+m=T(m^2-2m)+(2m^2-2m+1)$$ Now we try to verify with the values $m=2,3$ or $4$ in order to find the correct option; the first two values $m=2,3$ given two possible options but the value $m=4$ ensure us that the correct option is the second one $$\boxed{(m/6) (4m^2 – 3m + 5)}$$ with the value $38$ in both expressions
(obviously calculating before $T((4-1)^2-1)=T(8)$which is easy starting with $T(1)=1$)
Comment: @MithleshUpadhyay: You are welcome. I'm glad that I can write in English a "nice" mode (it is certainly the first time!)
Comment: Thanks for nice explanation.


Como verificar e imprimir valores que se repetem em um vetor em Algoritmo

Question: Criar um algoritmo que dada uma sequência de n números reais, determinar os números que compõem a sequência e o número de vezes que cada um deles ocorre na mesma.
Exemplo: n = 8
Sequência:
-1.7,
3.0,
0.0,
1.5,
0.0,
-1.7,
2.3,
-1,7

Saída:
-1.7 ocorre 3 vezes

 3.0 ocorre 1 vez

 0.0 ocorre 2 vezes

 1.5 ocorre 1 vez

 2.3 ocorre 1 vez

Fiz no VisualG
Código:
ALGORITMO "QUESTAO 9"
VAR
C,X,SEQ,I: INTEIRO
VSR: VETOR[1..100] DE REAL
SEQUENCIA: VETOR[1..100] de REAL

INICIO
ESCREVA("QUANTOS NÚMEROS REAIS COMPÕEM A SEQUÊNCIA? ")
LEIA(SEQ)
ESCREVAL("INFORME A SEQUÊNCIA: ")
PARA I DE 1 ATE SEQ FACA
LEIA(SEQUENCIA[I])
SE (SEQUENCIA[I])<>(VSR[I]) então
VSR[I]<-SEQUENCIA[I]
fimse
fimpara
para X de 1 ate SEQ faca
C <- 0
para I de 1 ate SEQ faca
se (VSR[X] = SEQUENCIA[I]) então
C <- C + 1
fimse
fimpara
escreval(VSR[X], " OCORRE ", C, " VEZES")
fimpara
escreval(" ")
escreval(VSR[X], " OCORRE ",SEQUENCIA[SEQ], " VEZES")

fimalgoritmo

Comment: Isto responde à sua pergunta? [Obter quantas vezes cada elemento de uma lista se repete](https://pt.stackoverflow.com/questions/414937/obter-quantas-vezes-cada-elemento-de-uma-lista-se-repete)
Comment: Bem vindo ao Stack Overflow em Português. Parece que a sua pergunta contém alguns problemas. Nós não faremos o seu trabalho da faculdade ou lição de casa, mas se você estiver com dificuldade em alguma parte específica, compartilhe o seu código, diga o que já tentou fazer e qual está sendo a dificuldade, assim você aumenta as suas chances em conseguir uma boa resposta. Não deixe de ler o [Manual de como NÃO fazer perguntas](https://pt.meta.stackoverflow.com/a/5486/100416) para ter uma experiência melhor por aqui.
Comment: A menos que tenha ocorrido erro de digitação o valor -1.7 ocorre duas vezes, e não três, em sua lista de 9 elementos.
Comment: O método `Counter` da lib `collections` resolve isso. Veja [aqui](https://pt.stackoverflow.com/questions/176255/contar-o-n%c3%bamero-de-ocorr%c3%aancias-de-um-valor-numa-list)
Comment: @OverPeas, fica difícil de ver o código no `comments`. Atualiza seu post, por favor.
Answer: Acho que é isso que vc busca.
Update
N = int(input("Quantos números? "))

lista = []
for i in range(1, N+1):
    lista.append(float(input(f"{i} - Entre com o número: ")))

NOTA: Não estão sendo tratados erros de digitação
from collections import Counter

c = Counter(lista)

Exemplo de Resultados
print(f"Lista de numeros: {list(c.keys())}")

Lista de numeros: [-1.7, 3.0, 0.0, 1.5, 2.3]

for numero, repeticoes in c.items():
    print(f" O numero {numero} repete {repeticoes} vezes")

 O numero -1.7 repete 3 vezes
 O numero 3.0 repete 1 vezes
 O numero 0.0 repete 2 vezes
 O numero 1.5 repete 1 vezes
 O numero 2.3 repete 1 vezes

Espero que ajude
Comment: Isso mesmo @Paulo Marques, muito obrigado.


Equivalence between constant and positive metric and usual $\Re^3$ metric

Question: I'm trying to answer the following question:
Is any positive and constant metric in $\Re³$ equivalent to the usal metric defined as $$ds² = dx² + dy² + dz² \tag{*}\label{1} $$ with $ds = g_{ij}dx^{i}dx^{j}$ and $g_{ij} = \delta_{ij}$. Or alternatively, does always exist a coordinate transformation from the coordinates $y^\mu$ to the coordinates $x^i$ such that \eqref{1} is recovered from $$ds² =    \tilde{g}_{\mu\nu}dy^{\mu}dy^{\nu} $$ with $\tilde{g}_{\mu\nu}$ being constant in the $y^\mu$ coordinates.
My initial guess it's that this is true, however I'm not sure on how this could be proved.
Answer: Any symmetric matrix can be diagonalized by an orthogonal matrix, say $O$ - so $O^{T}gO = \Lambda$, $\Lambda$ diagonal with constant eigenvalues. We have positive eigenvalues, and since $O$ is constant, $dy^i = O^i_{j}dx^j$. Now our metric is diagonal - we scale each variable by the square root of its corresponding eigenvalue; that will turn the metric to the identity.
Note this doesn't work if the metric has negative eigenvalues.
Comment: That's it. I thought it had something to do with diagonalizing the metric but didn't link the symmetry of the metric with that result. Thank you.


mysql select query search one word in multiple columns

Question: Help is required.
i am preparing a search form. need help in select query
is it possible that i can search "building" word in all columns of my table
following is the query i've tried.
$search = $_POST['search'];
$sql = mysql_query("SELECT * FROM property WHERE posthead,requestto,ptype,requestby,owner,bed,bath,price,sqft,descp = '".$search."'");
$result = (mysql_fetch_array($sql));

echo "Post Head : ". $result['posthead']."
";
echo "Request To : ". $result['requestto']."
";
echo "Type : ". $result['ptype']."
";
echo "Request By : ". $result['requestby']."
";
echo "Owner : ". $result['owner']."
";
echo "Bed : ". $result['bed']."
";
echo "Bath : ". $result['bath']."
";
echo "Price : ". $result['price']."
";
echo "Sq ft. : ". $result['sqft']."
";
echo "Description : ". $result['descp']."
";

Comment: Yes, read: http://dev.mysql.com/doc/refman/5.0/en/where-optimizations.html
Answer: $sql = mysql_query("SELECT * FROM property WHERE posthead = '".$search."' OR requestto= '".$search."' OR ptype= '".$search."' OR requestby = '".$search."' OR owner= '".$search."' OR bed = '".$search."' OR bath= '".$search."' OR price= '".$search."' OR sqft,descp = '".$search."'");

and change $result = (mysql_fetch_array($sql)); to $result = (mysql_fetch_assoc($sql));
NOTE :

your query is vulnerable to sql injection
mysql_* functions are deprecated use mysqli_* or PDO
Answer: TRY THIS:
Better is to use "CONCAT" for the columns:

$sql = mysql_query("SELECT * FROM property WHERE
  CONCAT(posthead,requestto,ptype,requestby,owner,bed,bath,price,sqft,descp)
  LIKE "%.$search."%'");

OR will work but CONCAT can reduce query size.
Answer: Try SELECT * FROM property WHERE posthead = $search OR requestto = $search ... etc
Answer: Since you are creating a searching form you might want to be able to find records by partial match and not exact word. In order to do that you can use LIKE
$q = "SELECT * FROM property
WHERE posthead  LIKE '%$search%' OR
      requestto LIKE '%$search%' OR
      ptype     LIKE '%$search%' OR
      requestby LIKE '%$search%' OR
      owner     LIKE '%$search%' OR
      bed       LIKE '%$search%' OR
      bath      LIKE '%$search%' OR
      price     LIKE '%$search%' OR
      sqft      LIKE '%$search%' OR
      descp     LIKE '%$search%'";

$sql = mysql_query($q);


Is it good to use boost::tuple to indicate if T was found or not?

Question: Assume we need a function that returns something. But that something can be not found. I see options:
1. T find(bool &ok); //return default T value if not found

We can make a struct:
template <typename T>
class CheckableValue
{
public:
    CheckableValue(),
    _hasValue(false)
    {

    }
    CheckableValue(const T &t):
    _value(t),
    _hasValue(true)
    {

    }

    inline bool hasValue() const {return _hasValue}
    const T &value() const
    {
        assert(hasValue());
        return _value;
    }

private:
    T _value;
    bool _hasValue;
};

and make the function:
2. CheckableValue<T> find();

Or we can use:
3.boost::tuple<bool, T> find()

What do you think is preferable ?
Answer: I prefer:
4. boost::optional<T> find();

The problem with the tuple is that the T part is invalid when the bool part is false; this behaviour is not enforced by the tuple. Your CheckableValue class is the same remedy as boost::optional for the same problem.
Comment: boost optional http://www.boost.org/doc/libs/1_41_0/libs/optional/doc/html/index.html is really great. I use it in many places that look like the poster's one.
Answer:
returns something. But that something can be not found.

Are you actually planning to return a copy, or some kind of reference for the thing? "not found" implies that the function works by "finding" a pre-existing value in a data structure somewhere.
In that case, the simple solution is to return a pointer to the existing value, using NULL for not-found.
Comment: It can not necessary be in some collection. The value can be computed on the go and returned. But if some input was incorrect it may raise a flag, indicating bad input. Returning pointer to the just allocated on the heap object is not convenient i think (you may say that auto_ptr will do the work, but I think boost::optional is much better)


OLS, Logistic, or Poisson Regression for Data?

Question: I'm a relative novice at statistics and would appreciate some help with a dataset I'm trying to crunch. I'm currently looking at factors that predict increasing utilization of healthcare resources following surgery in a set of 130+ patients. Some of the independent variables I'm looking at include age, BMI, Marital Status, Length of Stay after Surgery, Smoker Status (Y/N), etc. The dependent variables are number of ED visits, readmissions, post-op visits following surgery.
Initially, I was planning to run univariate linear regression on the data set, followed by multivariate regression. However, I tried running the analysis with age vs. ED visits on SPSS and got the following output after checking for assumptions of linearity and normality of residuals:

So based on this, I feel like linear regression is not the way to go and I have to consider analyzing the data via another method. Currently, the variables are coded as continuous variables (both age and ED_visits). What are your recommendations on how to run the data, or maybe recommendations to transform the data in some way to fix better meet assumptions of OLS? Other thoughts I've had include transforming the dependents into nominal variables and doing logistic regression or doing a Poisson regression, but honestly not sure if either of these would solve my problem. Thanks for the help!
Comment: You could try Poisson regression with $\log(\text{time under risk after surgery})$ as an offset. See https://stats.stackexchange.com/questions/142338/goodness-of-fit-and-which-model-to-choose-linear-regression-or-poisson/142353#142353
Answer: I would do some exploratory analysis before trying to fit a model. Plotting usually is a really good way to have a first hand on your problem.
What I would do in order:

Plot your observed variables against your explanatory variables and see if there is any clear pattern.
Try to aggregate some of the explanatory variables and see if the situation improves. Your dataset is not huge, maybe if you consider age groups (so age as a discrete variable) some sort of trend can appear.
If you start with a linear model you can also build the correlation matrix to see which explanatory variables are better correlated with your observations.
Start fitting a simple model and add the explanatory variables in rounds, checking how the goodness of fit measure compare. You can also plot the predicted values against the observed ones to have a direct feeling of how your model performs.
Check the model's hypothesis.


$N$ is a simple normal subgroup of a group $G$ and $G/N$ has a composition series...

Question: A question in section Normal and Subnormal Series of Hungerford Algebra.

If $N$ is a simple normal subgroup of a group $G$ and $G/N$ has a composition series, then prove that $G$ has a composition series.

$G/N$ has a composition series means that there exists  a series $G = G_0 > G_1 > · · · > G_n = (e)$ is a normal series such that  each factor $G_i/G_{i+1}$ is simple.
But I am unable to think how to deduce that G has a composition series using it.
Can you please help?
Comment: Perhaps if you write down *correctly* what it means for $G/N$ [*not* $G$] to have a composition series you'll be able to proceed.
Comment: I don't see a question  here, I see a statement. (This seems to be happening more and more frequently, I am not sure why!)
Answer: Hint:
By definition, there exists  a series $G/N = G_0 > G_1 > · · · > G_n = (e_{G/N})$ is a normal series such that  each factor $G_i/G_{i+1}$ is simple.
(1) By Correspondence Theorem, a subgroup $A$ of $G/N$ must be in the form $H/N$ where $H$ is a subgroup of $G$ containing $N$ and $A$ is a normal subgroup of $G/N$ if and only if $H$ is a normal subgroup of $G$. Use this theorem to get a normal series $H_0>H_1>\dots>H_n=N>(e_G)$.
(2) Use Third Isomorphism Theorem to deduce that $H_i/H_{i+1}$ is simple.


Lagrange Multipliers; two inequalities.

Question: Suppose I want to min/max $f(x,y,z)$ under the constraint $c_2 \leq g(x,y,z) \leq c_1$. I would first check $\nabla f = 0$ and find critical points in $c_2 \leq g(x,y,z) \leq c_1$. Afterwards, I do the boundary with Lagrange Multipliers.
Is this the correct setup? Let $g(x,y,z) = c_1$ and $g(x,y,z) = c_2$
$\nabla f = \lambda \nabla g + \mu \nabla g$
s.t
$g = c_1$
$g = c_2$
I tried it and I got a contradiction.
Comment: You are mixing two things here. You are looking for the extremum of $f(x,y,z)$ and all of a sudden you have constraints on a function $g(x,y,z)$. I think you should write $$g(x,y,z) \leq f(x,y,z) \leq h(x,y,z) $$

Then the equation for a constraint extremum becomes:
$$\nabla f = \lambda \nabla g + \mu \nabla h $$

with $g(x,y,z)=c_1$ and $h(x,y,z)=c_2$
Comment: @michielm : I think OP knows what he wants to do, he just doesn't know how to do it, and it seems like a plausible hypothesis. Unless he is asking the wrong question.
Comment: It seems odd that you would have $g=c_1$ and $g=c_2$ simultaneously. Don't you want to consider those as two disjoint cases?
Comment: I could, but then I would get two different extremes on $A$.
Comment: I am skeptical. My interpretation is below.
Answer: I don't know how advanced your level of mathematics is, but the general problem
$$
\min_{(x,y,z) \in A}  f(x,y,z), \quad A = \{ (x,y,z) \in \mathbb R^3 \, | \, c_1 \le g(x,y,z) \le c_2 \}
$$
where say, $f, g$ are differentiable "a lot" (let's be friendly) is actually very hard (feasible, the techniques are developed, but it's not for a beginner undergraduate student). I suspect that you formulated homework in a weird way and it got out this way. I am saying it is very hard because this is exactly what the Karush-Kuhn-Tucker multipliers deal with, and these multipliers are usually met in an optimization course at an advanced level of calculus/analysis. I suggest you clarify what was your original problem, perhaps it would make things easier to answer.
Hope that helps,
Comment: How does one apply the KKT to this problem then?
Comment: @sizz : It's painful. Very painful computations. See here for an example of the use of the KKT techniques. http://www.math.ubc.ca/~israel/m340/kkt2.pdf
Comment: Essentially the idea is to replace the inequality by an equality with an extra variable but the fact that you have intervals of values and not equations makes it harder to develop the theory. I can't do it here, there are too many details.

If you didn't have such a problem as homework but were simply interested in knowing if such a problem was solvable and if we had techniques to do it, then my answer is yes, but unless you can understand (at least vaguely) what's on the wikipedia page of Karush-Kuhn-Tucker conditions, don't think about it. If you're still curious, I can find a reference.
Answer: Here is my interpretation, based on what you've explained:
Consider a simple situation. $g(x,y,z)=z$. Then $z$ is allowed to vary from $z=c_1$ to $z=c_2$. We look for how $f$ varies in these layers of $(x,y,z)$ (such that $c_1\le z\le c_2$). To check for critical points on the interior, that is, for $c_1<z<c_2$, we simply check for where $\nabla f=0$. To check for critical points on the boundaries, we use the method of lagrange multipliers, so that $\nabla f=\lambda \nabla g$. These vectors will be checked for parallelness at the two boundaries separately. We cannot be at both boundaries simultaneuously. So, we check if this is possible for $z=c_1$, then, we check if it is possible at $c_2$.
In my simple example, your method would immediately get a contradiction, since then
$$c_1=z=c_2,$$
contradiction. This may be the source of your contradiction.

Lagrange Multipliers; two inequalities.


magento with nginx frontend and REST API url

Question: We have magento configured with nginx, we are trying to use http//magentohost/api/rest to manage customers, but when we try to access that url i get 404.
Just wondering anybody proper configuration for the magento REST api url with nginx
our configuration
server {
  listen 80;
  server_name store.magentohost.com;
  access_log /var/log/nginx/store.magentohost.com.access.log;
  error_log  /var/log/nginx/store.magentohost.com.error.log;

  root /home/store/public_html;

  location / {
    index    index.php index.html index.htm;
    try_files $uri $uri/ @handler; ## if missing pass the URI to magento's front handler
    expires 30d; ## assume all files are cachable
  }

  ## These locations would be hidden by .htaccess normally
  location /app/                { deny all; }
  location /includes/           { deny all; }
  location /lib/                { deny all; }
  location /media/downloadable/ { deny all; }
  location /pkginfo/            { deny all; }
  location /report/config.xml   { deny all; }
  location /var/                { deny all; }

  location @handler { ## Magento uses a common front handler
    rewrite / /index.php;
   }
  location ~ .php/ { ## Forward paths like /js/index.php/x.js to relevant handler
    rewrite ^(.*.php)/ $1 last;
  }

  location ~ \.php$ {
    if (!-e $request_filename) { rewrite / /index.php last; } ## Catch 404s that try_files miss
    expires        off; ## Do not cache dynamic content
    include fastcgi_params;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param  MAGE_RUN_CODE default; ## Store code is defined in administration > Configuration > Manage Stores
    fastcgi_param  MAGE_RUN_TYPE store;
  }

  location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml)$ {
    access_log        off;
    log_not_found     off;
    expires           36d;
  }
  location ~ /\.ht {
    deny all;
  }
  location ~ /\.hg {
    deny all;
  }

  location /nginx_status {
     stub_status on;
     access_log   off;
     allow ip;
     deny all;
    }

}

Comment: This seems like a good solution for this: http://stackoverflow.com/a/25197466/5650083
Answer: Edit your Nginx configuration, relatively to your Magento application, by adding a location handler for the API requests as follow:
location /api {
    rewrite ^/api/(\w+).*$ /api.php?type=$1 last;
}

source: https://gist.github.com/mklooss/7300787#gistcomment-1245474
Comment: I do not get it
Comment: Is it not working? Or the answer isn't clear?
Comment: The answer isn't clear ...
Answer: Add api configuration.
location /api {
    rewrite ^/api/rest /api.php?type=rest last;
    rewrite ^/api/v2_soap /api.php?type=v2_soap last;
    rewrite ^/api/soap /api.php?type=soap last;
}


Run PHP when node and/or profile is updated?

Question: I wanted to run an external script when a user profile(2) is updated, and/or when a node is updated. I've added the code to the themes template.php, but no go.
What have I missed?
<code><?php

$api_script_url = "http://www.aaa.com/test/test.php";
$msg = "File updated.";

// WHen a node is updated, be it new or old, update file.
function theme_node_update($node) {
    include($api_script_url."?q=".$node->nid);
    drupal_set_message($msg, 'status');
}

// WHen user profile2 profile is updated, be it new or old, file.
function theme_profile2_update($profile) {
    include($api_script_url."?q=".$profile->uid);
    drupal_set_message($msg, 'status');
}

?>
</code>
Answer: Theming functions are the wrong place for something like that. To run some PHP code after an node or profile (thus entity) is updated you should use the Rules module or use the following hooks, hook_entity_insert, hook_entity_update
Comment: You need the PHP Filter module enabled to be able to see it. Maybe that's your problem. See discussion [here](https://drupal.org/node/964494).
Comment: I'll give the entity_update a look. How do I run an external PHP script ( an URL ) from Rules?
Comment: Rules is a pretty advanced system. There are many tutorials out there such as [this](https://drupal.org/node/1866108). There is an action "Execute PHP Code" which then gives you a box where you can put code. Within that you can do include or any other way to run php code in another script
Comment: Tried hook_entity_update instead, but no change. I'll try to find that PHP code than instead, although I've never seen it before.


For normally distributed random variables, if X is independent of Y and X is independent of Z, is X independent of max(Y,Z)?

Question: Suppose $X,Y,Z\sim N(0,\sigma^2)$. $X$ is independent of $Y,$ $X$ is independent of $Z$ (but $Y$ and $Z$ are not independent),  is $X$ independent of $\max(Y,Z)$?
Comment: If the normality is of the marginal distributions rather than the joint, X can be independent of Y and independent of Z but might not be  independent of (Y,Z)
Answer: If $X$ were not independent of $\max(Y,Z),$ that would seem  to contradict a basic theorem that when two variables $U$ and $V$ are independent, then measurable functions of them $f(U),$ $g(V)$ are necessarily independent.  That applies here to $U=X$ and $V=(Y,Z)$ with $f$ the identity and $g$ the maximum function. I suppose such a counterexample, if it exists, must involve a case where $X$ is not independent of $(Y,Z)$ even though $(X,Y)$ and $(X,Z)$ are independent.  There is a standard example of that, which I will briefly describe.
Let $(U,V,W)$ be independent standard Normal variables.  Define $S$ to be the sign of $UVW:$ that is, $S=1$ when $UVW \ge 0$ and otherwise $S=-1.$  Set $(X,Y,Z)=(SU,SV,SW).$  This guarantees $XYZ\ge 0,$ as you can readily check.
It is straightforward to check that all three pairs $(X,Y),$ $(X,Z),$ and $(Y,Z)$ have standard binormal distributions: in particular, all three pairs are independent.  However, consider the case $\max(Y,Z)\lt 0.$   A negative maximum requires both $Y$ and $Z$ to be negative. Yet, because $XYZ\ge 0,$ $X$ must be positive.
Since the unconditional distribution of $X$ is Normal, it has positive chances of being negative.  Consequently, conditioning $X$ on the event $Y\lt 0, Z \lt 0$ has changed the probability distribution of $X.$  Since the conditioning event does not have zero probability $$\Pr(\max(Y,Z)\lt 0)=\Pr(Y\lt 0,Z\lt 0)=\Pr(Y\lt 0)\Pr(Z\lt 0) = \left(\frac{1}{2}\right) \left(\frac{1}{2}\right) = \frac{1}{4},$$ it demonstrates a lack of independence between $X$ and $\max(Y,Z),$ QED.
Here is a scatterplot matrix of one thousand draws from $(X,Y,Z,\max(Y,Z)).$  The circular clouds indicate independent pairs, while the distorted clouds demonstrate lack of independence.

We are not quite done.  The question asks about the case where $(Y,Z)$ is not independent, whereas in this example $(Y,Z)$ is independent.  We can fix that by using a mixture of the previous example and another one.  Consider, for instance, the distribution of $(X_1, Y_1, Y_1)$ where $(X_1,Y_1)$ is standard Normal.  A mixture of this "contaminating distribution" with the previous one does the trick.
Rather than dwelling on the mathematical details, let me just show you a couple thousand observations from this mixed distribution which is 90% the original example (blue dots) and 10% of the contaminating distribution (red dots).

The top row has the key characteristics of the previous example--especially an obvious lack of independence between $X$ and $\max(Y,Z)$ (the correlation coefficient is around $-0.19,$ far from zero), but now the $Y,Z$ scatterplots show lines of red dots, demonstrating the lack of independence of $(Y,Z).$
Comment: +1 The joint density of pairwise independent but not mutually independent standard normal random variables is stated explicitly in the latter half of [this answer](https://stats.stackexchange.com/a/180727/6633) from 6 years ago. The answer also includes a sketch of the proof of pairwise independence.   Also, a minor typo: in your third paragraph, $(X,Y), (X,Z), (Y,Z)$ all have standard _normal_ distributions, not  standard_binomial_ distributions.
Comment: Thanks, @Dilip: I knew that answer was around here somewhere!  I have corrected "binomial" to the intended "binormal" and linked to your answer.


Remove unwanted top space from QLPreviewController

Question: In my application I have used a QLPreviewController to display some pdf files. Everything works fine, but there is an unwanted space in the top of content of QLPreviewController and couldn't find a way to remove it.
This is how I wrote it. (Please note that I am new to Xamarin.iOS and QLPreviewController)
public partial class ReportsViewController : UIViewController
{
    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        //Customize navigation bar for QLPreviewController
        if(UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) // There is a bug with barTintColor on QLPreviewController for iOS 11 if you are showing it via presentViewController: animated:
        {
            var color = UIColor.FromRGB(red: 23, green: 61, blue: 86).CGColor;
            var rect = new CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0);
            var alpha = color.Alpha;
            var opaque = alpha == 1;
            UIGraphics.BeginImageContextWithOptions(rect.Size, opaque, 0);
            var context = UIGraphics.GetCurrentContext();
            context.SetFillColor(color);
            context.FillRect(rect);
            var image = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();

            UINavigationBar.AppearanceWhenContainedIn(typeof(QLPreviewController)).SetBackgroundImage(image, UIBarMetrics.Default);

        }
        else // If iOS version is below 11.0
        {
            UINavigationBar.AppearanceWhenContainedIn(typeof(QLPreviewController)).BarTintColor = UIColor.FromRGBA(red: 255, green: 0, blue: 0, alpha: 1.0f);
        }

        UINavigationBar.AppearanceWhenContainedIn(typeof(QLPreviewController)).BarStyle = UIBarStyle.Black;
        UINavigationBar.AppearanceWhenContainedIn(typeof(QLPreviewController)).TintColor = UIColor.White;

        var reportSavedPath = "path to pdf file";
        var reportName = "Report name";
        var previewController = new QLPreviewController();
        var url = new NSUrl(reportSavedPath, true);
        var _dataSource = new PreviewControllerSource(this, url, reportName);
        previewController.DataSource = _dataSource;
        PresentViewController(previewController, true, completionHandler: null);
    }
}

public partial class ReportsViewController : UIViewController
{
    class PreviewControllerSource : QLPreviewControllerDataSource
    {
        ReportsViewController _parentClass = null;
        NSUrl _url = null;
        string _title = null;

        public PreviewControllerSource(ReportsViewController parentClass, NSUrl url, string title)
        {
            _parentClass = parentClass;
            _url = url;
            _title = title;
        }

        public override nint PreviewItemCount(QLPreviewController controller)
        {
            return 1;
        }

        public override IQLPreviewItem GetPreviewItem(QLPreviewController controller, nint index)
        {
            return new PreviewItem { title = _title, url = _url };
        }
    }
    public class PreviewItem : QLPreviewItem
    {
        public string title { get; set; }
        public NSUrl url { get; set; }
        public override string ItemTitle { get { return title; } }
        public override NSUrl ItemUrl { get { return url; } }
    }
}

This is how it looks like when the pdf is loaded

Can someone please help me to get this unwanted space removed?
Comment: Could you try a different PDF File of a different dimension and see if the unwanted space is the same amount? Also, which iOS version are you running into that error?
Comment: @Saamer I already tried with different different pdfs. But the space remains for all of them. Im using iOS 12.2
Comment: var rect = new CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0);
What would happen if you reduced these values to 0.1 ?
Comment: @Saamer It didn't work :(
Answer: Have no idea about why you have to Customize navigation bar for QLPreviewController in your code. I removed it and it works perfect.
I would give you two ways to get rid of the unwanted sapce:
1.remove the code:
//UINavigationBar.AppearanceWhenContainedIn(typeof(QLPreviewController)).SetBackgroundImage(image, UIBarMetrics.Default);

2.if you really need the code to Customize navigation bar, add this line of code before PresentViewController:
//Add this line before PresentViewController
UINavigationBar.AppearanceWhenContainedIn(typeof(QLPreviewController)).SetBackgroundImage(null, UIBarMetrics.Default);

PresentViewController(previewController, true, completionHandler: null);

Update:
Spent the whole afternoon and only find a solution not so perfect. First, I would like to say that the navigationBar of your viewController and the navigationBar of QLPreviewController are two different bars.
To set the navigationbar color, you can simply set it in AppDelegate, this will affect the whole navigationBar color in your project.:
 public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
        // Override point for customization after application launch.
        // If not required for your application you can safely delete this method

        UINavigationBar.Appearance.BarTintColor = UIColor.FromRGBA(red: 255, green: 0, blue: 0, alpha: 1.0f);
        UINavigationBar.Appearance.BarStyle = UIBarStyle.BlackOpaque;
        UINavigationBar.Appearance.TintColor = UIColor.White;

        return true;
    }

To change the navigationbarColor of QLPreviewControl, you can use the code in test function:
public partial class ViewController : UIViewController
{

    QLPreviewController previewController;

    public ViewController(IntPtr handle) : base(handle)
    {
    }

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        this.AutomaticallyAdjustsScrollViewInsets = false;
        this.ExtendedLayoutIncludesOpaqueBars = false;
        this.EdgesForExtendedLayout = UIRectEdge.None;

        string path = NSBundle.MainBundle.PathForResource("myPdf.pdf","");
        var reportName = "Report name";
        previewController = new QLPreviewController();
        var url = new NSUrl(path, true);
        var _dataSource = new PreviewControllerSource(this, url, reportName);
        previewController.DataSource = _dataSource;

        this.NavigationController.PresentViewController(previewController, true, test);

    }

    public void test() {

            var firstChild = previewController.ChildViewControllers[0];

            if (firstChild is UINavigationController)
            {
                var naviVc = firstChild as UINavigationController;
                naviVc.NavigationBar.BarTintColor = UIColor.Red ;
            }
        }
}

The only thing that is not so perfect is that the test function will call until the presenting completed, so you would see the default color of navigationBar a while and then it will change to the color you want.
If you use a push action instead of modal, you can call test function inside the WillShowViewController(UINavigationController navigationController, [Transient] UIViewController viewController, bool animated):
public class naviDeleagte : UINavigationControllerDelegate {

    public override void WillShowViewController(UINavigationController navigationController, [Transient] UIViewController viewController, bool animated)
    {
        //call test here if you use a push instead of modal
    }
}

I uploaded my sample here and you can check it:navigationBar-color-xamarin.forms
Comment: The thing is I need to keep the navigation bar color same in every view. So 2nd option won't work :(
Comment: Thank you very much for the effort friend. I will try this out. sorry for being late to comment here. Cheers.


$_POST doesnt send empty checkboxgroup

Question: I have been working on a contact form for a website and I got this problem:
I have 4 checkboxgroups, every each of them have at least 3 checkboxes that are available to check. We don't want them to be required to send the email. So the code is this:
$CheckboxGroup1 = array();
if(isset($_POST['submit'])){
    $name = $_POST['name'];
    $attending = $_POST['attending'];
    $CheckboxGroup1 = isset($_POST['CheckboxGroup1']) ? $_POST['CheckboxGroup1'] : 'Nothing checked';

HTML:

What kind of set-up would you like?

Additional fees may apply for living room/specialty set-ups.

             <input type="checkbox" name="CheckboxGroup1[]" value="Living Room">
            Living Room

            <input type="checkbox" name="CheckboxGroup1[]" value="Conference Room">
            Conference Room

            <input type="checkbox" name="CheckboxGroup1[]" value="Other">
            Other (please specify at the end of the form)

When none of the checkboxes is selected I get the message "Nothing checked" and when one of them is selected I get the value of it. The problem is when I select more than one, I get this in my email:
What kind of set-up will you like?: Array (not the name of those selected).
I do not know what I have to change to make it work the right way.
Any help would be very much appreciated.
Answer: You cannot print array with echo. Echoing array will give you string Array. Simple way in your case to get array values is to use implode:
echo implode(', ', $yourArray);

Comment: your answer is right i vote your answer, but just for easy understand i have post my answer.
Answer: you have to change below line
Your code
$CheckboxGroup1 = isset($_POST['CheckboxGroup1']) ? $_POST['CheckboxGroup1'] :  'Nothing checked';

Change it to
if( isset($_POST['CheckboxGroup1']))
{
 $CheckboxGroup1 =implode(", ",$_POST['CheckboxGroup1']);
}
else{
  $CheckboxGroup1="Nothing checked";
}

Comment: Welcome @dileoh :)

$_POST doesnt send empty checkboxgroup


In a hybrid exchange environment, how to send email from a mailbox in exchange on-prem to another mail box in exchange online?

Question: We deploy hybrid exchange using the HCW, AADC has been deployed as well. Mailbox A is created on exchange online. Mailbox B is created on exchange on-prem.
Now I can send an email from A to B. But I cannot send an email from B to A. It says "We won't be able to deliver this message to A because the email address is no longer valid"
A friend told me, it is because A is created on the Exchange online, so B cannot find it. Or the other hand, B is created on on-prem and have is synchronized to the cloud by AADC, so A knows it and can send email to it.
Is it true? In my opinion, once a hybrid exchange environment has been deployed, the exchange online and exchange on-prem should be able to talk with each other. So there should not be an issue when you send email across online and on-prem.
If my friend is true, what should i do the synchronized the mailbox from online to on-prem?
If my friend is wrong, which part of the setting could be wrong?
Thanks!!!
Answer: When you are in a Hybrid deployment, then you have to create the AD Account locally, ideally using EAC using the option to create an Office365 account. Then let the account sync to the cloud and licence it. If the entire account and mailbox was created in the cloud (so there is no local AD account) then it will not work correctly.
Comment: Then for those accounts have to be created in cloud, for example, those group accounts created by system when you create teams or sharepoint sites, is any way you can synchronize them back to exchange on-prem?
Answer: You can refer to the following article to merge an Office 365 account with an on-premises AD account:
[How to merge an Office 365 account with an on-premises AD account after hybrid configuration?][1]
[1]: https://www.codetwo.com/admins-blog/how-to-merge-an-office-365-account-with-an-on-premises-ad-account-after-hybrid-configuration/#no-local-account --A user has an Office 365 account and no local AD account


VBA: Populate a 'Time' column based on a range of cells and interval

Question: I have an excel worksheet where I need to populate a range of cells in a time column where the range is user input, and so is the time interval.
I could achieve this using a For loop, but there could potentially be ~50000+ cells, and writing to each of these cells takes a long time.
I gather there is a way to achieve this in VBA by creating an array which is the size of the range, populating this array, and then copying the array into the worksheet? I am fairly familiar with general C style programming, but not VBA specifically.
If my cells were arranged where A1 contains the start cell (1 for example) and B1 contains the end cell (100 for example), A2 contains the start time (00:00:00) and B2 contains the time interval (00:05:00) how would I use VBA to populate the cells D1:D100 like 00:00:00, 00:05:00, 00:10:00... etc.
(In reality the cell references are across sheets and a much larger range, but I can sort this later).
Thanks in advance.
Comment: What happens after 24:00:00? Does it start over again. Also, it sounds like this is something you'll be doing repeatedly. If not, a non-VBA solution would be easy. Is that of interest?
Comment: Doug, in reality the time will really be a date.

And yes, it will be done fairly repeatedly, with different time intervals and ranges of dates, so I'd think VBA is the easiest way to do it.
Comment: Okay. Not sure why you have it as a time then. I'm going to answer it as stated above.
Comment: Doug, see my edited comment. Hit return by accident ;)

The problem is that depending on the interval the range will change, so what I'm really struggling with is that dynamic aspect of it.
Answer: Here's some VBA that doesn't use arrays but is pretty fast. It uses formulas and then pastes over them as values. It takes about a second for 50,000:
Sub FillColumn()
Dim ws As Excel.Worksheet
Dim FillRange As Excel.Range
Dim FirstValue As Double
Dim ValueIncrement As Double
Dim FirstCell As Long
Dim LastCell As Long

Application.ScreenUpdating = False
Set ws = ActiveSheet
With ws
    FirstCell = .Range("A1")
    LastCell = .Range("B1")
    FirstValue = .Range("A2")
    ValueIncrement = .Range("B2")
End With
Set FillRange = ws.Range("D" & FirstCell).Resize((LastCell - FirstCell) + 1, 1)
With FillRange
    .Cells(1) = FirstValue
    .Offset(1, 0).Resize(.Rows.Count - 1, 1).Formula = "=R[-1]C+" & ValueIncrement
    .Value = .Value
    .NumberFormat = "hh:mm:ss"
End With
Application.ScreenUpdating = True
End Sub

EDIT: Explaining this line .Offset(1, 0).Resize(.Rows.Count - 1, 1).Formula = "=R[-1]C+" & ValueIncrement
Offset(1,0) refers to a range 1 row lower than FillRange, e.g. D2:D50001
.Resize(.Rows.Count - 1, 1) takes the previous and makes it one row shorter, e.g., D2:D50000
.Formula = "=R[-1]C+" & ValueIncrement applies a formula to that range. The formula simply says to add the ValueIncrement to the cell above. If I stop the code after this line, the formula looks like =D1+0.0000578703703703704. I got the R1C1-style formula used in the code by following this most excellent tip by Dick Kusleika.
Here's an array version. It seems a bit faster with 50,000. However, it's only good for 65536 elements, due to the limitations of Application.Transpose. I'm not sure if there's a a better way to fill the array, i.e., not using a loop:
Sub FillColumn2()
Dim ws As Excel.Worksheet
Dim FillRange As Excel.Range
Dim FirstValue As Double
Dim ValueIncrement As Double
Dim FirstCell As Long
Dim LastCell As Long
Dim arr As Variant
Dim i As Long

Application.ScreenUpdating = False
Set ws = ActiveSheet
With ws
    FirstCell = .Range("A1")
    LastCell = .Range("B1")
    FirstValue = .Range("A2")
    ValueIncrement = .Range("B2")
End With
ReDim arr(FirstCell To LastCell)
arr(1) = FirstValue
For i = FirstCell + 1 To LastCell
    arr(i) = arr(i - 1) + ValueIncrement
Next i
Set FillRange = ws.Range("D" & FirstCell).Resize((LastCell - FirstCell) + 1, 1)
FillRange = Application.Transpose(arr)
Application.ScreenUpdating = True
End Sub

Comment: Doug, perfect, thanks very much. The second is the kind of thing I was initially shooting for. I think it's unlikely that my list would ever be longer than 65536. However, if it's not too much to ask, could you briefly explain to me what's happening in the line that starts `.Offset` in the first example. Other than that I follow what's occurring there.
Comment: Again, thank you. Also for the source of the R1C1 notation - should come in very useful for editing some of my previous, sloppy, code.
Comment: @doug the way to avoid the transpose time hit and size limitation is to redim the array as 2d from the start `redim arr(firstcell to lastcell, 1 to 1)`


How to add dynamic opengraph meta data to page in NuxtJS

Question: I am using NuxtJS with Nuxt3 and in my component, I want to update the head of the page with dynamic opengraph meta data. In my component, I am showing a gallery and for that I am fetching the data from an asynchronus API. Since I am facing data from API, so it is taking a little time to to mount the data in the component.
But, in the nuxt.config.ts file I have already defined the meta tags with hasd coded data for the website landing page or anyother page where I dont need to show dynamic opengraph meta data -
export default defineNuxtConfig({
  //SEO
  app: {
    head: {
      title: 'Talking Lands',
      charset: 'utf-8',
      viewport: 'width=device-width, initial-scale=1',

      meta: [
        { charset: 'utf-8' },
        { name: 'viewport', content: 'width=device-width, initial-scale=1' },
        { hid: 'description', name: 'description', content: '' },
        { hid: 'og-title', property: 'og:title', content: 'Vuetify + Nuxt'},
        { hid: 'og-type', property: 'og:type', content: 'website' },
        { hid: 'twitter-card', property: 'twitter:card', content: '' },
        { hid: 'og-image', property: 'og:image', content: 'https://new.example.com/static-assests/images/TLlogo_Dark.svg'},
        { hid: 'og-description', property: 'og:description', content: 'This is amazing example of opengaph protocols made using Nuxt and Vuetify'},
        { name: 'format-detection', content: 'telephone=no' }
      ],
    },
    pageTransition: { name: 'page', mode: 'out-in' },
  },
// ... other configurations

In the component I am using script setup and there I am updating the head with useHead property of NuxtJS like this -