How to perform a dynamic_cast with a unique_ptr?

Question: I have a class hierarchy as follows:
class BaseSession : public boost::enable_shared_from_this<BaseSession>
class DerivedSessionA : public BaseSession
class DerivedSessionB : public BaseSession

Within the derived class functions, I regularly call functions like this:
Func(boost::dynamic_pointer_cast<DerivedSessionA>(shared_from_this()));

Since I was working with shared_ptr to manage the sessions, this was working fine. Recently, I discovered that my use of shared_ptr is not optimal for this case. That is because these sessions are singleton objects that maintain one socket per client. If socket is reconnected, the session copies used to become zombies.
As workaround, I started passing shared_ptr by reference rather than copies. This solved the zombie problem.
Ideally, I felt I should be using unique_ptr to store the session and then pass references to other functions. That opened a whole can of worms.
How do I cast a base class unique_ptr object to derived class unique_ptr object? What is the unique_ptr version of the following line?
Func(boost::dynamic_pointer_cast<DerivedSessionA>(shared_from_this()));

I just want one copy of the session object, everything else should be reference.
Comment: @SharathKShetty Short answer: no. `unique_ptr` implies ownership. Weak pointers require observation logic that implies locking and refcounting. That comes at a price, which is why you need to use `shared_ptr` if you're so inclined. The good news is you can use `std::dynamic_pointer_cast<>` with that too (_and_ `weak_ptr`). Everybody wins.
Comment: What should happen with your pointed object if the dynamic cast fails?  Should it be deleted or do you only expect a move if the cast succeeds and never a delete?
Comment: If dynamic_cast fails, the Func gets a null object and it cancels the operation. I don't want to move, the owner should remain same.
Comment: I suspect I am looking for a weak_ptr to unique_ptr object. Short of going back to C pointer, is there any other choice?
Comment: I agree with sehe. Creating a unique_ptr that point to a resource already owned by another smart pointer without moving the resource between the two containers is wrong. A weak_ptr doesn't has the ownership of the resource pointed but a weak reference: so any operation from the weak_ptr to the unique_ptr is simply infeasible or greatly discouraged
Comment: @StefanoBuora: The resource will be owned only by unqiue_ptr, I want to do away with shared_ptr. Looks like the solution provided by Jarod42 is the best option for me.
Answer: Update
The question has been clarified:

sorry I was not clear. I want the ownership to remain with original owner, the called function should only get reference to it, not ownership. Not looking for two smart pointer for the same object.

In that case, the solution is simply:
dynamic_cast(*my_unique_ptr)

Done. It throws if the cast doesn't succeed.

Casting shared_ptr
For shared_ptr there is std::dynamic_pointer_cast<> (http://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast)
Casting unique_ptr
The simplest way would seem:
#include <memory>

struct A { virtual ~A() = default; };
struct B : A { };

int main()
{
    std::unique_ptr pa(new B);

    std::unique_ptr pb(dynamic_cast(pa.release())); // DO NOT DO THIS
}

As the commenter rightfully points out, this may leak the object if the conversion failed. That's not very helpful.
A reason why the dynamic_unique_ptr_cast<> doesn't exist might be that the unique_ptr type doesn't erase the deleter. It could be hard/impossible to choose an appropriate delete for the target pointer type.
However, for simple cases, you could use something like this:
template <typename To, typename From, typename Deleter>
    std::unique_ptr<To, Deleter> dynamic_unique_cast(std::unique_ptr<From, Deleter>&& p) {
        if (To* cast = dynamic_cast<To*>(p.get()))
        {
            std::unique_ptr<To, Deleter> result(cast, std::move(p.get_deleter()));
            p.release();
            return result;
        }
        return std::unique_ptr<To, Deleter>(nullptr); // or throw std::bad_cast() if you prefer
    }

auto pb = dynamic_unique_cast(std::move(pa));

Comment: Yeah, there's been a lot of noise coming from this post over the last two days. I tried to preserve value where possible the last time, but this discussion has gone on too long already and does not appear that it will bear fruit any time soon. Either take it to chat, or one of you can ask a new question about the problem and let a dispassionate 3rd party sort out the correct answer.
Comment: Thanks @sehe. That is a nice twist to Jarad42's solution. :-)
Comment: I could only get this to work by removing the `Deleter` template parameter completely, since `default_delete` would not convert to `default_delete`. But that's the "simple case" I was interested in anyway.
Comment: Thanks @Danra this might actually shed light for others who ran into similar cases before, which I wasn't aware of. If you have a minimal example you can add it to the answer in case it helps
Comment: I want to avoid moving the ownership of the session object. I want to pass unique_ptr by reference after the dynamic cast.
Comment: @SharathKShetty That makes zero sense. If ownership is to be shared, use shared_ptr or even a raw pointer (`dynamic_cast(p.get())`). Creating a two different smart pointers to the same object is **always a bad design smell** and asking for trouble. `unique_ptr`is precisely about transferring ownership. If you dont require it, use something else.
Comment: sorry I was not clear. I want the ownership to remain with original owner, the called function should only get reference to it, not ownership. Not looking for two smart pointer for the same object. I have mentioned that in the last line of my question.
Comment: @SharathKShetty in that case: `dynamic_cast(*my_unique_ptr)` done. It throws if the cast doesn't succeed.
Comment: @SharathKShetty I don't see how that's a twist. It's just doing what you want to do. Without needless complications. I've added it to my answer, just to be complete.
Comment: @Sharath I see why you say it's a twist - they're similar in intent. The difference is of course that (as said) casting the reference version will throw (`std::bad_cast`), but casting the pointer version won't (it can be null). I would argue both are appropriate, depending on how you want to handle a failed cast.
Comment: It worked in 2010, but this gives a compiler error C2440 in Visual Studio 2015.
Comment: You're doing something wrong (guesses: [your type is not polymorphic at all](http://rextester.com/LRZTPM83624) or [the types are not related](http://rextester.com/NCYZX35443) or [a simple mistake](http://rextester.com/LRZTPM83624)?)
Comment: I never asked you to troubleshoot my problem. I fixed my problem by taking out your code and replacing it with [common sense](http://rextester.com/YMT2386). To test your snippet, I copied pasted your code in a fresh shiny project in vc140 and it did not compile. Error C2440 definitely applies if you go look up the error.
Comment: @sehe Do you have a working example of the above code as-is? If so can you please share it so I can see what I did differently? If not I suggest you just amend your answer and remove the `Deleter` template parameter completely, was still helpful for me and probably for 99% of other users looking to do this for the simple case.
Comment: @Sharath Sure. It's literally the code from the answer pasted together: http://coliru.stacked-crooked.com/a/ed344ba1e80d54d9 - I donot like making the code less precise unless I know what problem that's solving. I'm also willing to find out there are compiler issues/library implementation issues to avoid, but right now I can only say that the code with deleter is correct and strictly more generic. I'm certainly hoping to see the problem demonstrated. If you can modify the code such that it fails on your platform, I'd happy to know the platform that it fails on.
Answer: Unless you want to transfer ownership of your std::unique_ptr<T>, your function should take pointer or reference to T.
So signature of Func should be something like Func(DerivedSessionA*)
and then your call may look like:
std::unique_ptr<BaseSession> ptr; // Initialize it with correct value

Func(dynamic_cast<DerivedSessionA*>(ptr.get()));

Or as you seems to call it directly from a method in BaseSession:
Func(dynamic_cast<DerivedSessionA*>(this));

Comment: The answer does not explain what to do if the cast fails.
Comment: `dynamic_cast` returns `nullptr` if dynamic type of this is not really a `DerivedSessionA*` (or child type).
Comment: @ChristopherPisz what to do if the cast fails depends on other context, and is the same as "what to do if a `dynamic_cast` from a raw pointer fails"
Comment: What if I do want to transfer ownership?
Comment: I think it will also be important to point out who owns the pointer before and after the cast, and mention unique_ptr::release vs get.
Comment: @aij: Other answers handle that case. But notice that is `dynamic_cast` fails, you free the resource (no owners).
Answer: This is dynamic_pointer_cast of boost. The idea is quite simple(but ignore the deleter).
//dynamic_pointer_cast overload for std::unique_ptr
template<class T, class U> std::unique_ptr<T> dynamic_pointer_cast( std::unique_ptr && r ) BOOST_SP_NOEXCEPT
{
    (void) dynamic_cast< T* >( static_cast( 0 ) );

    BOOST_STATIC_ASSERT_MSG( boost::has_virtual_destructor<T>::value, "The target of dynamic_pointer_cast must have a virtual destructor." );

    T * p = dynamic_cast<T*>( r.get() );
    if( p ) r.release();
    return std::unique_ptr<T>( p );
}

Answer: Simply get the stored pointer using the std::unique_ptr<>::get() method:
Func(dynamic_cast<DerivedSessionA*>(shared_from_this().get()))

that if shared_from_this() has that prototype:
std::unique_ptr<BaseSession>& shared_from_this();

Comment: But shared_from_this() always returns a shared_ptr, not unique_ptr.


CodeIgniter mostra erros estranhos

Question: Estou desenvolvendo uma aplicação CodeIgniter, porém reinstalei o WampServer. No lugar onde existia um form agora mostra este seguinte código.
'id', 'value' => $id, 'size' => '6', 'readonly' => 'true')); ?>
'login', 'value' => $login, 'size' => '15', 'readonly' => 'true')); ?>
'email', 'value' => $email, 'size' => '30', 'readonly' => 'true')); ?>
'senha', 'size' => '30')); ?>
'novasenha', 'size' => '30')); ?>
'novasenha2', 'size' => '30')); ?>

O que devo fazer para resolver ?
Comment: a sua tag inicial ta assim `<?php`, porque o `short_open_tag` deve ta `off`
Answer: Coloque <?php no inicio, porque, o short_open_tag deve estar off. Não é boa prática (porque é melhor usar sem habilitação desse item, por causa dos servidores aonde tu vai disponibilizar seu site e a tag de abertura padrão do php é <?php), mas, se quiser edite no seu php.ini a configuração do short_open_tag:
Ela deve ta assim:
short_open_tag = off

coloque assim:
short_open_tag = on

Ou seja, ele não ta executando código PHP.
Comment: Olá, outra dúvida, antes o Cde igniter me mostrava os erros de programação de uma maneira melhor, agora mostra assim http://pt-br.tinypic.com/view.php?pic=2qdr1ab&s=8#.U6JQ40Ck6So onde posso corrigir ?
Comment: @user11650 não entendi?
Comment: Antes ele mostrava os erros assim http://www.google.com.br/imgres?imgurl=http%3A%2F%2Fi.stack.imgur.com%2FDP67M.png&imgrefurl=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F13656999%2Ftrouble-in-codeigniter-taking-data-from-one-db-table-and-creating-a-entry-in-ano&h=800&w=1280&tbnid=gTzQnE5zDlkQiM%3A&zoom=1&docid=9T-6J6h8k7512M&ei=QFKiU4SUI7S_sQSDooGQDg&tbm=isch&ved=0CCQQMygJMAk&iact=rc&uact=3&dur=381&page=1&start=0&ndsp=14 , agora assim http://pt-br.tinypic.com/view.php?pic=2qdr1ab&s=8#.U6JQ40Ck6So
Comment: Vixe não sei...
Comment: @user11650 a primeira questão foi solucionada? se tiver outra dúvida faça outra pergunta, se sim fecha essa questão!

CodeIgniter mostra erros estranhos


Error applying matrix transformation to an image in matlab

Question: I have this transformation matrix and now I need to apply it to an image. I tried with imwarp (A, T) where A = imread ('image.jpg') and T is the following matrix transformation:
    0.3669    0.2443    0.0011
    0.4114    0.3224    0.0013
   -325.0508 -243.0855  1.0000

But gives me this error:
Error using imwarp>parseInputsDisplacementFieldSyntax (line 358)
The value of 'DisplacementField' is invalid. Displacement field D must be
of size MxNx2 or MxNxPx3.

Error in imwarp (line 156)
    parsedInputs = parseInputsDisplacementFieldSyntax(varargin{:});

Error in Untitled2 (line 66)
B=imwarp(A,transformada2)

Comment: More importantly, did you use `affine2d` to create the `tform` object required by `imwarp`?
Comment: How did you create `T`?
Answer: imwarp does not take the transformation matrix directly. It takes a transformation object, which can be of type affine2d or projective2d. So you should first create an affine2d object from your matrix, and then pass that to imwarp.


Use a valid integration method to calculate $\int_{\pi/2}^{3\pi/2}\frac{\sin x}{x}\,dx$

Question: We know that $f'(x)$ = $\dfrac{\sin x}{x}$ and $f(\pi/2)=0$, $f(3\pi/2)=1 $
Use a valid integration method to evaluate :
$$\int_{\pi/2}^{3\pi/2}f(x)dx$$
i think $\int_{\pi/2}^{3\pi/2}\frac{\sin x}{x}\,dx $ is the $f(x)$ function we're looking for, i used barrow theorem but i don´t know how to integrate it, any helps or hint will appreciate.
Comment: Then the problem is not correctly stated?
Comment: Isn't it $f(x)=\frac{\sin(x)}{x}$, and $\int f'(x) \mathrm{d}x$?
Comment: I think so, but what can we do about that?
Answer: If your function is $f(x)=\frac{\sin(x)}{x}$, and your task is to calculate
$$\int_{\pi/2}^{3\pi/2}f'(x)\mathrm{d}x$$
Then you can use the Fundamental Theorem of Calculus to calculate the integral:
$$\int_{\pi/2}^{3\pi/2}f'(x)\mathrm{d}x=f\left(\frac{3\pi}{2}\right)-f\left(\frac{\pi}{2}\right)$$
Answer: You can't.
$\dfrac{\sin(x)}{x}
$,
also called
$sinc(x)
$
(sometimes with a $\pi$),
is not integrable
in finite terms.
It has been given a name:
$Si(x)
=\int_0^x \dfrac{sin(t)}{t}dt
$.
Special forms,
such as
$\int_0^{\infty}$
can be evaluated.
Your case can only be done
numerically.
Wolfy says
$Si((3 π)/2) - Si(π/2)≈0.23761058579952225576304433203202186890796018928024067084207168096967568361245277161035797838127400
$
Answer: Thinking and trying, i got the solution :
$\int_{\pi/2}^{3\pi/2}f(x)dx $
Now we can use integration by parts, by it's definition , $u=f(x)$, $du=f'(x)dx$
and $dv=dx$, $v=x $,by ILATE rule :
\begin{align}
 =   f(x) x|_{\pi/2}^{3\pi/2}-\int xf'(x)dx                            \\
 & =\require{cancel} [\cancelto{1}{f(3\pi/2)}(3\pi/2)]-[\cancelto{0}{f(\pi/2)}(\pi/2)]-\int_{\pi/2}^{3\pi/2}\cfrac {\cancel{x}\ cosx}{\cancel{x}}                             \\
 & = \Bigl(\cfrac{3\pi}{2}-0\Bigr)  -\ sen x|_{\pi/2}^{3\pi/2}                             \\
 & = \cfrac {3\pi}{2}-[(-1)-1]                             \\
 & =  \cfrac {3\pi}{2}+2                            \\
\end{align}


Cox model with a predictor variable within only one stratum

Question: I'm investigating survival in a cancer patients cohort. The Cox model I'm using is stratified by stage and adjusted for several variables. I would like to add one variable RT (Radiotherapy) which is of particular importance in higher stages.
How should I modify my Cox model so that it include this variable only for certain stage strata? I am using SAS, but I would like to learn the concept rather than the application code.
Thanks in forward.
Comment: Is RT a yes/no variable, or are you also including information about dose per day, number of days, etc?
Comment: @EdM Yes it's a categorical variable and not continuous.

In another words, one of the strata can be split into two using the variable RT, in others however it's always 0.
My exposure variable isn't the variable RT, but I need to adjust for it to get precise my estimation.
Answer: If the proportional hazards (PH) assumption won't hold between your (+) RT and (-) RT groups for high-stage cases (e.g., RT was withheld because of prior cancer with radiation, or because of poor patient performance status, so a different shape of survival curve might be expected) then you can simply break your high-stage stratum in two: high-stage(+)RT, high-stage(-)RT. That just requires minimal recoding of the data.
If PH is expected to hold, then you could just add the +/- RT variable to all cases. Make sure that (-) RT is the reference level for that factor (whether the first or last level for a factor is the default for reference depends on software).
Then the RT value will be (-) for all low stages and the hazard ratios (HR) reported for the other predictors will be for (-) RT. The (+) RT HR will represent the (presumably lower) hazard for those at high stage receiving RT. You should avoid the temptation to use the (+) RT HR to estimate what might happen if RT were used in lower-stage cases.
Comment: I see. So you are saying that splitting the strata into low-stage, high-stage RT+, and high-stage RT- is the solution if the PH assumption doesn't hold. If PH hold I can add RT just as a adjustment variable in the model and I should used RT- as a reference value.

Is that correct?
Comment: @ebay that is my suggestion. The stratification might be a safer bet, and you probably want to evaluate the interaction of your 'exposure variable' with the strata (and RT, if you go that way) in terms of relation to outcome.


How to deny access to invalid $_GET parameters

Question: For example, there is a pager with 10 pages. How to deny access if $_GET['page'] is bigger than 9 or is not numeric?
Answer: There's no 'catch-all' method for this sort of thing, but on an individual basis you would probably want to perform a manual check in hook_init() in a custom module:
function MYMODULE_init() {
  if (isset($_GET['page'])) {
    if (!is_numeric($_GET['page']) || $_GET['page'] > 9) {
      drupal_access_denied();
    }
  }
}

I imagine you'll need to add further conditions to the above code to make it more contextual to your specific situation.
EDIT
As MPD mentions it might be better to use drupal_not_found() in place of drupal_access_denied()...it's a better semantic representation of what you're actually doing.
Comment: Personally, I would drupal_not_found() the request.
Comment: @MPD Yeah that would be better actually, it would represent the reason for the error better than an access denied


How can I simulate a modem over a VOIP connection?

Question: I have a hardware device I need a server to dial into at regular intervals. The problem is I no longer have a POTS line or a modem in any of development computers, and all my production servers are virtual. I went out and got a usb modem for development and will plug it into a broadvoice VOIP line, but this seems quite kludgey. I've googled around and have found "virtual modems" that simulate serial connections or "at based" modems over IP, but so far nothing supports SIP or any kind of VOIP.
Is there a way to connect a virtual modem to a real one?
Thanks.
Update
Putting a computer near the device isn't a good option as its in a public basement, (though the ALIX boards might work) and even then I'd have to dial into it. I also can't replace the modem with a serial device or an ip device as the only connection to location is the phone line and I don't know enough about the device to modify it. This is for some old smart meter equipment.
Comment: Your problem seems to be more of a physical one than software. Your options will depend upon the environment. If the smart meter is in the same building and your server is close to the punchdown panel, you MIGHT be able to hardwire a connection and use RS-485 adapters, but these are difficult to get working over UTP cable.

If you have no POTS lines in your server room and no structured network cabling in the basement, you are going to have to fix the problem on one end or the other; get a true POTS line in the computer room or extend your network to the basement (cabled or wifi).
Comment: You need the client & server device to support the [T.38](http://en.wikipedia.org/wiki/T.38) standard
Answer: To save your sanity, don't.
Modems (and fax) over VoIP are extremely sensitive to timing, and usually break over VoIP, it might even seem to work at first, but it's certain to break.
Adding virtual machines just makes the problem worse.
There are "short haul modems" around which can emulate a phone line.
Another option is just to attach the two modems back to back:
http://www.jagshouse.com/modem.html
Comment: I'd have to install a computer in the basement were the device is. I'm better off installing a computer where a phone line is =p
Comment: Or you could just run a cable
Comment: I think a small computer and a short haul modem might be the best bet. The computer can then get on the net via dial up and provide the data.
Answer: I have a similar need, and I've been searching for hours and hours for a solution.  The closest I've found is a free but not very well-written program called "TimeFax" (http://sourceforge.net/projects/timefax/), which installs a virtual COM port and connects it to an H.323 receiver.  You can make Windows install a legacy 14k modem on that COM port, and theoretically the program will take the COM port data and transform it to H.323 and pipe it to whichever receiver you specify.  Then all you need is a VoIP H.323 termination, and you might be good.
Note that to get TimeFax working on Windows Vista or 7, you have to disable desktop composition in the compatibility settings.  You'll also have to manually download the 2 dll files that it is missing, which it will complain about when you first try to run it.  A quick Google search finds them easily though.
You'll still have issues with VoIP compression, but if you lower the speed, you might be able to achieve something that works.  A few years ago I routed a dial-up modem through a Vonage connection, and it worked surprisingly well if I kept it at slow speeds (like 14k), so I know that dial-up over VoIP is possible, I just haven't quite got a completely software solution working.
Answer: We use Cisco ATA 186's to on all of our faxes and as a backup in case our WAN goes down and we need to get into our networking gear at the Datacenter ... 1900 miles away. They've served us very well
EDIT:
In that case of purely software devices ... they don't exist. I tried looking high and low. Including trying to hack something together with asterisk ( with the help of an asterisk hacker i work with ). I was looking for a situation where i could dial into the modem on our network gear anywhere even when all I had was my Cell card.
Comment: I'm looking for more of a software solution, I don't have any physical lines anywhere besides the device, and I don't have hardware access to my production servers. On the other hand I do have vo-ip accounts.
Answer: You might be able to use a serial device server such as the Lantronix UDS 1100.
You load com port redirector software on the host computer and connect the device server to your remote device in place of a modem.

(source: lantronix.com)
Answer: When this question was asked, there was no existing solution, but Vocal Technologies has a SAMS (SIP Analog Modem Server) which is what the OP was looking for. It is a purely software modem server that can connect to actual Physical Modems connected to the PSTN, from a Cloud server connected only via SIP/G.711.
Answer: I'm not an expert, but as an aside that I find a bit too long for a comment:
Even "true" POT lines use multiplexing to handle multiple calls over a single cable. This uses conversion of analog signals (the tones generated by the modem) into digital ones, and back. The digital capacity is limited by design, and thus the analog bandwidth is limited too. VOIP uses its own compression as well. Hence mixing the two, if possible at all, might only work with low speeds.
Comment: I know there are several different codecs and the ones optimized for voice are not good for data. I don't know much else though.
Answer: I can't say that this would work but it seems to be at least close:
http://www.dataremote.com/store/index.php?main_page=product_info&cPath=6&products_id=39&zenid=b989f7dc94e69989d81ad5fb49ec0a93
While I've not used DataRemote software I have used their hardware and dealt directly with their very accessible tech support for more than 3 years now. I'd give an A+ all around for my own personal DataRemote experiences.
Answer: The main issue with most "virtual modems" out there is that they're unable to interoperate with a physical modem (they require their software on both endpoints). There is a solution for this use case  https://www.vocal.com/voip/sip-analog-modem-server-sams/. IP networks have gotten good enough to reliably transmit modem calls and these purpose built solutions can account for modem timing requirements.


Anaconda prompt can't see my network drives when launch as Admin

Question: I have installed anaconda (last version) on my work laptop.
The only directory were I am allowed to work is a network one, mapped to the H: letter.
I also have to launch the prompt as admin if I want to use jupyter lab (if not there is a WinError 5 access denied).
Without the admin rights :

But with admin rights only the prompt can't see the H: drive

So I am stuck:

without the admin rights I can go in my H: but I can't launch jupyter lab
with the admin rights, I can launch jupyter lab but I can't go to my drive !

Any idea ?
Answer: The answer to your question can be found here. It's because starting a command prompt "As Administrator" it's running in a different user context than when you don't.


Question about linearity assumption in ANCOVA

Question: I'm running ANCOVA. My dependent variable is is IQ, and one of my covariates is sex. I know that to perform ANCOVA you should be thinking that there exists a linear relationship between your dependent variable and each of your covariates. I'm wondering if I even have to bother with worrying about the linearity assumption with respect to the relationship between IQ and sex given that sex is a categorical variable. And so in general my question is whether we ever have to worry about the linearity assumption with respect to the relationship between a dependent variable and a categorical covariate .
Thanks!!
FBH
Comment: Assuming you only have two sexes, it does not seem to be an issue
Answer: The linearity assumption only applies to continuous covariates, so the answer to your question is no. In a linear model, each level of a factor covariate is assumed to have an additive effect on the expected response.
Comment: Thanks a lot!!!


JavaScript - Building JSON object

Question: I'm trying to understand how to build a JSON object in JavaScript. This JSON object will get passed to a JQuery ajax call. Currently, I'm hard-coding my JSON and making my JQuery call as shown here:
$.ajax({
  url: "/services/myService.svc/PostComment",
  type: "POST",
  contentType: "application/json; charset=utf-8",
  data: '{"comments":"test","priority":"1"}',
  dataType: "json",
  success: function (res) {
    alert("Thank you!");
  },
  error: function (req, msg, obj) {
    alert("There was an error");
  }
});

This approach works. But, I need to dynamically build my JSON and pass it onto the JQuery call. However, I cannot figure out how to dynamically build the JSON object. Currently, I'm trying the following without any luck:
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };

$.ajax({
  url: "/services/myService.svc/PostComment",
  type: "POST",
  contentType: "application/json; charset=utf-8",
  data: json,
  dataType: "json",
  success: function (res) {
    alert("Thank you!");
  },
  error: function (req, msg, obj) {
    alert("There was an error");
  }
});

Can someone please tell me what I am doing wrong? I noticed that with the second version, my service is not even getting reached.
Thank you
Comment: Do you get any Javascript errors?
Comment: Excellent point - try running this with the Firebug debugger turned on and see what you get.
Comment: I am not getting any JavaScript errors. The error event handler in my $.ajax call is getting triggered though.
Comment: Well there you go... what error message are you getting back? Is it helpful?
Comment: Doh! It was a type mismatch issue.
Answer: You may want to look at the JSON JavaScript library. It has a stringify() function which I think will do exactly what you need.
Comment: That's what I thought initially, but from the code he is using in his example, jQuery is supposed to take care of this for you.
Comment: @Justin Ethier: no, jQuery has no JSON serialization (only deserialization). jQuery does something completely different with the data object @user208662 is passing to it.
Comment: @Crescent Fresh: the docs (http://api.jquery.com/jQuery.ajax/) have an example of doing `data: ({id : this.getAttribute('id')})`
Comment: Exactly. I use the same syntax in my application and it works just fine without `stringify` (which is still useful elsewhere, of course).
Comment: @Mark, @Justin Ethier: again, jQuery does not use JSON serialization. The data object passed in @Mark's example and answer simply gets routed to `jQuery.param()` (http://api.jquery.com/jQuery.param/), a different kind of serialization altogether.
Comment: @Crescent Fresh: I see. One passes the entire string, which happens to be a JSON object, and the other will create a set of name/value parameters from the JSON object you give it.
Answer: Your code:
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };

Take out the quotes ( line 3 ):
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { comments: comments, priority: priority };

Answer: Remove the quotes
data: '{"comments":"test","priority":"1"}',

becomes
data: {"comments":"test","priority":"1"},

JSONs are objects not strings.
Answer: This should work
var json = { comments: "comments",priority: "priority" };

Comment: As far as I understand it, in JSON all strings need to be double quoted, so "comments" and "priority".  That is a Javascript object, so if you were trying to show just a Javascript object, it is valid.  For the JSON format, though, strings need double quotes.
Answer: this works for me.
var json = "{ 'comments': '" + *comments* +"','priority:' '" + *priority* +"' }";

italics are the variables.
Comment: What happens if the comments and priority variables also includes double quotes? This fails. Not the ideal solution.

JavaScript - Building JSON object


Prediction with keras embedding leads to indices not in list

Question: I have a model that I trained with
common_embed = Embedding(
    name="synopsis_embedd",
    input_dim =len(t.word_index)+1,
    output_dim=len(embeddings_index['no']),
    weights=[embedding_matrix],
    input_length=len(X_train['asset_text_seq_pad'].tolist()[0]),
    trainable=True
)

lstm_1 = common_embed(input_1)
common_lstm = LSTM(64, input_shape=(100,2))
...

For the embedding I use Glove as a pre-trained embedding dictionary. Where I first build the tokenizer and text sequence with:
t = Tokenizer()
t.fit_on_texts(all_text)
text_seq= pad_sequences(t.texts_to_sequences(data['example_texts'].astype(str).values))

and then I'm calculating the embedding matrix with:
embeddings_index = {}
for line in new_byte_string.decode('utf-8').split('\n'):
  if line:
    values = line.split()
    word = values[0]
    coefs = np.asarray(values[1:], dtype='float32')
    embeddings_index[word] = coefs

embedding_vector = None
not_present_list = []
vocab_size = len(t.word_index) + 1
print('Loaded %s word vectors.' % len(embeddings_index))
embedding_matrix = np.zeros((vocab_size, len(embeddings_index['no'])))
for word, i in t.word_index.items():
    if word in embeddings_index.keys():
        embedding_vector = embeddings_index.get(word)
    else:
        not_present_list.append(word)
    if embedding_vector is not None:
        embedding_matrix[i] = embedding_vector
    else:
        embedding_matrix[i] = np.zeros(300)

now I'm using a new dataset for the prediction. This leads to an error:

Node: 'model/synopsis_embedd/embedding_lookup'
indices[38666,63] = 136482 is not in [0, 129872)
[[{{node model/synopsis_embedd/embedding_lookup}}]] [Op:__inference_predict_function_12452]

I do all of the steps for the prediction step again. Is that wrong and do I have to reuse the tokenizer from the training? Or why are the indices during prediction not existing?
Answer: You are probably getting this error because you are not using the same tokenizer and embedding_matrix during inference. Here is an example:
import tensorflow as tf

vocab_size = 50
embedding_layer = tf.keras.layers.Embedding(vocab_size, 64, input_length=10)

sequence1 = tf.constant([[1, 2, 5, 10, 32]])
embedding_layer(sequence1) # This works

sequence2 = tf.constant([[51, 2, 5, 10, 32]])
embedding_layer(sequence2) # This throws an error because 51 is larger than the vocab_size=50

Comment: Thanks for the quick support. This completely makes sense!


Escrever em um arquivo de outro site PHP

Question: Olá, tenho dois sites, preciso enviar dados de um para o outro com php
Site 1:
<!DOCTYPE html>

    <title>Site 1</title>

<form method="POST">
    Texto
    <input type="text" name="texto">
    <input class="btn btn-sucess" type='submit' name='submit' value='Gravar'>
</form>

Site 2: (Ele receberá os dados do form e gravará no próprio arquivo porém não sei como fazer o formulário ir para o outro site)
<?php
$pegou = $_POST['texto'];
$fp = fopen("index.php", "a");

$txt = "\n";
fwrite($fp, $txt);
$txt = " ".$pegou."\n";
fwrite($fp, $txt);

fclose($fp);

Comment: ``acho que vc quer colocar a ação do form, é isso. Ou vc quer em ajax?
Comment: Sim, mas os dados do formulário está no site 1, tem que ir para o site 2, o action serve para outros sites também?
Comment: Existe uma regra de segurança para cada site, o que vc quer fazer é basicamente RestFul, utilizar uma API, de um site e publicar em outro, primeiro vc precisa ter acesso as ambas as propriedades dos sites, ou ter uma acesso CORS, e para fazer isso, só utilizando ajax.
Answer: Existe "n" formas de se fazer isto, vou dar exemplo de 2.

Você redireciona seu formulário par enviar para o segundo site, os campos devem ter os mesmos ID's para o site que vai receber interpretá-los e concluir a ação. Exemplo:
<form action="http://www.siteexemplo.com.br/pagina.php" method="POST">

Você envia o formulário para você mesmo, recebe os dados e envia via php/curl para outro site. Desta forma, se o site retorna algum valor de confirmação você consegue tratar/validar, principalmente se for uma API. Fica mais ou menos assim como enviar:
$dadosParaEnviar = http_build_query($arrayDadosRecebidos);
$url = "http://www.siteexemplo.com.br/pagina.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dadosParaEnviar);
$result = curl_exec($ch);
if (curl_errno($ch)) {
    throw new \Exception('cURL error: '. curl_error($ch));
}
$resultHeader = curl_getinfo($ch);
curl_close($ch);

Comment: Muito obrigado, consegui adaptando os seus códigos
Answer: Como disse o @LeonardoGetulio, n formas de fazer isso, vou dar um exemplo de como fazer isso através de ajax:
Sua HTML no site um:
<!DOCTYPE html>

    <title>Site 1</title>

<form method="POST">
    Texto
    <input type="text" id="texto" name="texto">
    <button class="btn btn-sucess" id="send">Gravar</button>
</form>

O javascript:


Javascript if OR

Question: I want to make a prompt window ask for a code, I've got that part.
There is 50+ people accessing this page, I would like to give each person a different code.
if (var1 OR var2 OR var3 OR var4) //i want to be able to add as many 'var*; as I want here. Anywhere from 2 - lets say 50.
{
    access = true
}
else
{
    access = false
}

Comment: No. What you really want is an array of values.
Comment: Btw, don't do authentication/authorisation on the client if this is anything more than a learning exercise.
Comment: And you realize that this would not be secure?
Comment: In JavaScript `OR` is represented by `||`.
Comment: I realise it would be totally useless and insecure, yes. But I looks cool and me and my friends would like to try it. So long as it isn't a pain or a waist of time for you. @Bergi
Comment: @Tropilac This is wrong approach for that what you need.
Comment: Do you have a list of valid codes and you want to compare user's code with the list to determine access rights?
Answer: You should use an Array of dynamic options.
var options = ["var1", "var2", "var3"];

var access = options.indexOf(comparedValue) > -1;

Comment: `var access = options.indexOf(comparedValue) > -1;` Why even use an if. :)
Comment: ES6: `var access = options.includes(comparedValue)` :-)
Comment: Yeah, I overcomplicated it, thanks. @Bergi I'm assuming that he is not familiar with ES6 features and want to have [full browser support](http://caniuse.com/#search=includes). BTW: There is already [answer](http://stackoverflow.com/a/39270444/6475535) that uses `includes`.
Comment: @KonstantinAzizov: Given it's just a fun project for his friends he hardly cares about browser support
Answer: You could use Array#some for checking every element for a single truthyness.
if (my_vars.some(x => x)) {
    // ...
}

Comment: @sabithpocker, it is the equivalent of `function (x) { return x; }`.
Comment: You meant a comparison of some value against `x`, right?
Comment: I mean like in the question check `var1 || var2 || var3 ...` with an array of `[var1, var2, var3, ...]`
Comment: Should be `(my_vars.some(x => x == user_var))`
Comment: Can you explain `x=>x` if its fine :) I am not that acquainted with arrow functions.
Comment: i do not see any comparison with a value in the question.
Comment: If user enters say `1` and the array of codes is `[1,2,3]` How would you test if the `code` exists in the `array`? `[1,2,3].some(function(x){ return x;})` always returns `true` as per my understanding. Basically where is the check  against the user input!
Answer: Use Array.prototype.includes():
const access = ['var1', 'var2', 'var3'].includes(someVar)

If someVar equals any of the array's values ('var1', 'var2', 'var3'), access will be true; otherwise it will be false.

Javascript if OR


How do I know if my Button insersects with another button?

Question: I have a form with a button (btPlayer) then I wanna know if my button intersects with another button.
But I don't know the names of the buttons, I know only the name of "btPlayer".
How do I do something like this? :
<code> if(btPlayer.Bounds.IntersectsWith(>>>>>ANYBUTTON()<<) {

      // ... do something
}
</code>
Answer: You need to get the collection of buttons on your form. Note that this isn't necessarily as easy as it sounds, as:
<code>Controls.OfType<Button>();
</code>
Won't grab nested buttons (such as those in a panel or group box). Once you have your collection, its as simple as:
<code>//Not recursive, make sure we don't include ourself
IEnumerable<Button> allButtons = Controls.OfType<Button>()
                                 .Except(new List<Button>() { btPlayer })();
if (allButtons.Any(b => b.Bounds.IntersectsWith(btPlayer))
{
   //An intersection has occurred!
}
</code>
Answer: Assuming WinForms and all the Buttons are contained directly by the Form:
<code>    private void btPlayer_Click(object sender, EventArgs e)
    {
        foreach(Button btn in this.Controls.OfType<Button>())
        {
            if (!btn.Equals(btPlayer))
            {
                if (btPlayer.Bounds.IntersectsWith(btn.Bounds))
                {
                    Console.WriteLine("btPlayer intersects with " + btn.Name);
                }
            }
        }
    }
</code>
Comment: I really thought about this. But I didn't know if this way is efficient. But it solves my problem! Thanks a lot.


ubuntu install (tar 1.34) from source, issues with already installed (1.28b) package?

Question: On ubuntu 18.04, I need to install a more recent version or tar (1.34); the version installed with the system via the package system is 1.29b.  I've already downloaded and built the package (./configure  && make), but I'm wondering about the proper way to install it.  Essentially, I want to replace the existing tar with the new one, but I suspect if I just do a "make install" the package manager won't be happy.  Do I need to deinstall using the package manager first?  Will doing so mess up dependency checks the package manager does for other packages?
Am I better off installing in a different location and explicitly using that version of tar for the specific purpose for which I need it?  This
post says it should be installed in /opt.
Answer: The best practice is to use different directory. As example this can be /usr/local or /opt in both cases I will recommend you to use full path when execute the command. For example:
/opt/tar/bin/tar tvf tar_Archive.tar


Listview not getting generated as desired

Question: I have an activity where I want to generate a listview from an Arraylist, which is getting populated from a Hashmap. The list is getting generated, but only one item is showing in the list, its supposed to show two items.
This is the activity which is generating the ListView:
public class ExamNamesActivity extends Activity {
    TextView showUser;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> acList = new ArrayList<HashMap<String, String>>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_exam_names);

    //assigning objects to layout
    showUser=(TextView) findViewById(R.id.exam_names_user_full_name_textView);
    //showing user's full name
    showUser.setText("Welcome, "+getFromPreference("user_name"));

    //------------------for list-----------------------------

    // creating new HashMap
    HashMap<String, String> map = new HashMap<String, String>();

    // adding each child node to HashMap key => value
    map.put("Name", "Online Speed Test");
    map.put("Name", "Practice Test");

    acList.add(map);

    ListView list = (ListView) findViewById(R.id.ac_list_listView);
      if (null != list && null != acList) {
       list.setAdapter(new ListAdapter(ExamNamesActivity.this,
         R.id.ListViewContainer, new String[acList.size()]));

      }

    }

    //class for the list and on click handler
    private class ListAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final String[] values;

        public ListAdapter(Context context, int textViewResourceId,
                String[] objects) {
            super(context, textViewResourceId, objects);
            // TODO Auto-generated constructor stub
            this.context = context;
            this.values = objects;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            // return super.getView(position, convertView, parent);

            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            final View rowView = inflater.inflate(R.layout.list_layout, parent,
                    false);

            final HashMap<String, String> map =  acList.get(position);

            TextView textView = (TextView) rowView
                     .findViewById(R.id.list_label_name);
                     textView.setText(map.get("Name"));

            rowView.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {

                    rowView.setBackgroundResource(R.drawable.list_bg_pressed);

                    Handler handler = new Handler();
                    Runnable r = new Runnable() {
                        public void run() {
                            rowView.setBackgroundResource(R.drawable.list_bg);

                        }
                    };
                    handler.postDelayed(r, 200);

//                           Intent intent = new Intent(RegisterFirstActivity.this, RegisterSecondActivity.class);
//
//                              intent.putExtra("AC_Code", map.get(TAG_CODE));
//                              RegisterFirstActivity.this.startActivity(intent);

                }
            });

            return rowView;

        }
    }

    //getting content from preferences
    public String getFromPreference(String variable_name)
    {
        String preference_return;
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        preference_return = preferences.getString(variable_name,"");

        return preference_return;
    }
  //method to show double button alert dialog
    public void twoButtonAlert(String title, String message, String button1, String button2)
    {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(ExamNamesActivity.this);

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting Icon to Dialog
        //alertDialog.setIcon(R.drawable.delete);

        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton(button1, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {

                // Write your code here to invoke YES event
                //goto login activity
                Intent intent = new Intent(ExamNamesActivity.this, LoginActivity.class);
                finish();
                ExamNamesActivity.this.startActivity(intent);

            }
        });

        // Setting Negative "NO" Button
        alertDialog.setNegativeButton(button2, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // Write your code here to invoke NO event
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();

    }

    }

This is the layout of the activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AdapterActivity" >

    <TextView
        android:id="@+id/exam_names_user_full_name_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="Name Title"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <RelativeLayout
        android:id="@+id/ListViewContainer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/exam_names_user_full_name_textView"
        android:layout_marginTop="17dp" >

        <ListView
            android:id="@+id/ac_list_listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true" >
        </ListView>

    </RelativeLayout>

</RelativeLayout>

This is the layout for each row of the listview (list_layout.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/library_linear_layout"
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:layout_alignParentLeft="true"
    android:background="@drawable/list_bg"
    android:padding="5dp" >

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="44dp"
        android:background="@null" >

        <TextView
            android:id="@+id/list_label_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:text="name"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textSize="17sp" />

    </RelativeLayout>

</LinearLayout>

The output is like this:

Why is the list not showing both the items? Where am I going wrong?
Thanks in advance!
Comment: you can not use same key name to store different values in HashMap. and if you do this then it will replace old value with new value on same key.
Answer: Its because you are using same key "Name" which is over-writing your first value. In Map when you put values with same key it over-writes.
Doing this,
map.put("Name", "Online Speed Test");
map.put("Name", "Practice Test");

Will retsult in only 1 value inside your map that is,
map.put("Name", "Practice Test");

while the first one is over-written.
Did you try to get the size of the map? you will get size as 1 not 2.
Comment: Then what should I do? How should I insert both the values and show both the values in listview?
Comment: give different keys like name, name1
Comment: and then how would I traverse?
Comment: you can simply get the values of map using `ArrayList arrayList = new ArrayList(map.values());` And pass this arraylist to your adapter
Comment: @kittu88 Please check my answer you get the idea
Comment: You can give key as "0" , "1" , "2" and in getView traverse it `map.get(""+position)` @kittu88
Comment: @kittu88 you can pass that ArrayList to your adapter and set the value inside TextView using `arrayList.get(position);`
Answer: Check your array list size, i.e you are adding only one hash map to that list. that's why your list showing only one item. then about your hash map, your adding two items with same key so that the second item overrides the first value. So change your code as follows
// creating new HashMap
    HashMap<String, String> map = new HashMap<String, String>();

    // adding each child node to HashMap key => value
    map.put("Name", "Online Speed Test");
    acList.add(map);

    map = new HashMap<String, String>();
    map.put("Name", "Practice Test");
    acList.add(map);

Answer: Please follow this steps

Create a HashMap object
put value in hashmap object
add hashmap to arraylist

Perform this steps for each item.
For Your case. It Should like this
HashMap<String, String> map;

map = new HashMap<String, String>();
map.put("Name", "Online Speed Test");
acList.add(map);

map = new HashMap<String, String>();
map.put("Name", "Practice Test");
acList.add(map);


How can I avoid to return HTML markup for access denied?

Question: I've developed a custom controller that serves as a simple endpoint, POST method.
This controller has custom access control.
Custom access is done by looking for a header in the HTTP request, by making the controller object a service as well.
Everything works great. Except that when I return AccessResult::forbidden() .. I get the HTML of the access denied page .. and I don't really want that .. I'd like to return just a short bit of JSON.
What can I do to return something that is JSON, and not the Access Denied page HTML, for this particular route, when the access() method returns AccessResult::forbidden() ?
I've read that appending ?_format=json to the url works, and in my case it does. Is there anyway to achieve the same result without adding this url parameter?
Comment: You mean like [CSRF access checking](https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes/csrf-access-checking)?
Comment: I would check what the JSON:API module does, since it outputs JSON instead of HTML markup.
Comment: Actually, Drupal core itself, not a core module, has the class that outputs as JSON a 4xx error like the 403 error caused from `AccessResult::forbidden()`.
Answer: If you look into ParagraphAccessControlHandler you will find something similar.
Implement something similar in your Access callback.
<code>protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {

// Allow paragraph entities to be created in the context of entity forms.
  if (\Drupal::requestStack()
    ->getCurrentRequest()
    ->getRequestFormat() === 'html') {
    return AccessResult::allowed()
      ->addCacheContexts([
      'request_format',
    ]);
  }
  return AccessResult::neutral()
    ->addCacheContexts([
    'request_format',
  ]);
}
</code>


Market Basket Analysis using Clustering to discover *new* product combinations

Question: I have transaction data from a Quick Service Restaurant (QSR) client. Each record in this data set represents a transaction. My objective is to discover products that are the best candidates to be combined together and offered to customers.
Traditionally, I would have performed a Market Basket Analysis on this data, using metrics like 'confidence, lift, and support, to reveal items that are most frequently bought together. This is commonly known as Association Rules or Affinity analysis. [See the apriori algorithm that utilizes these principles.]
But, here's the rub: the QSR already offers combo meals to their customers. Due to this, the analysis "discovers" product groups that were historically offered together in combo meals. The analysis reveals nothing that is novel, i.e., products that were offered together were also most-frequently purchased together. This is expected because the way MBA is done traditionally is an empirical method – you will find products that were purchased together in the historical data; there's no "projection" (so to speak) in this method.
So now I am considering an alternative approach: use cluster analysis (e.g., k-means) to identify products that cluster together. In order to prepare the data for this analysis, I can create a dummy indicator (binary flag) for each item that exist in the data set. The cluster analysis would be performed based on (all or some of) those dummy indicators to group transactions. Let's say the cluster analysis yields five clusters. I would then look into each cluster and identify variables (dummy indicators) that are predominant in each cluster. One way to do this would be to look the ratio of between-cluster variance to within-cluster variance ($R^2$ to $(1-R^2)$) for each variable.
I briefly tested this approach, and it looks like this method is be able to look beyond what was offered together historically, and yield new product-bundle ideas (based on items that cluster together).
My questions are as follows: Does this approach make sense? Are there any references (books/papers) about this method of doing market basket analysis (aka product bundle analysis) using clustering?
Update: Please note that I am not asking how to solve the above stated problem. I have a specific solution in mind, and I am asking whether this approach has any theoretical, practical, empirical, or intuitive backing.
PS: There's a related question about this (link), but the answer -- that you can use frequent itemset mining -- is hardly satisfying, because this just appears to be yet another name for association rules mining. All of the following approaches/techniques would yield product that were purchased together in the past, rather than products that might not have been bought together in the past but are good candidates for bundling: association rules, affinity analysis, apriori algorithm, (and more generally) market basket analysis, and product bundle analysis.
Comment: Turf analysis is an applied marketing, combinatorial approach to finding high performing combinations of product attributes -- or products -- that are driven by some "dependent" measure, e.g., co-purchase frequency, revenues, etc. It's worth a look... https://en.wikipedia.org/wiki/TURF_Analysis
Comment: It's not clear what you're actually clustering on. Do you have qualitative features of the menu items?
Comment: I don't know why someone would down vote this question and not leave any comments
Comment: Interesting. I'd never heard of this technique; will check it out. Thanks @DJohnson!
Comment: Clustering on dummy indicators. The data set has one record for each transaction. And there is one column (feature) for each product. For each transaction, the products (i.e., columns) that are purchased in that transaction would have a value of 1, and 0 otherwise.
Answer: k-means or clustering won't get you anywhere.
Frequent itemset mining is most appropriate for this data type.
Yes, it will discover combos you have been offering before. But the solution is simple: clean your data.
Option 1) remove known combos
Option 2) treat known combos as a single item (i.e. customer hought combo-1, not burger and fries separately)
Option 3) ignore frequent patterns / association rules that you already use(d).
The ability to discover the combos that you had just demonstrates that it worked! Did you get anything remotely useful from k-means?!?
Comment: Because 1. k-means is for *continuous* variables, 2. k-means is sensitive to outliers, 3. k is hard to set, 4. k-means assigns every point to a cluster, but not every customer will be typical (not a problem with FIM).
Comment: Thanks for your response. Would you mind explaining *why* you think that k-means clustering won't get anything remotely useful?!?
Comment: Thanks. I've added further clarification to my question. Also, k-means is just an *example* I used -- there are other clustering approaches that can be utilized.
Comment: That largely have the same issues as k-means, too.


How many measures minimum in a repeat

Question: I know that a "repeated section" (i.e. I'm explicitly thinking about "enclosed in repeat-barlines") may be however long, 1 measure or 100. However, I'm wondering, whether there are "good" rule-of-thumb-like rules about when to use repeat signs in non-experimental pieces.
I came across a music sheet, where the first measures are like this:
ABCDBCE

And I'm wondering, whether it is OK to write it with a repeat on the measures BC with two different endings, something like:
A"BC"1D2E

Any pointers are welcome.
Comment: It doesn't work for your current example with different endings (hence comment rather than answer), but one common notation for a short number of repeated measures (1-2) is to use the symbol that looks like a **%**.  In the middle of the measure it means to repeat the last measure.  On the barline between 2 (otherwise empty) measures it means to repeat the last 2 measures.  You can also have multiples in a row to repeat the same measure or measures more than just twice.
Comment: Not really an answer, but "repeat with two different endings" is commonly indicated with [*D.S. al Coda*](https://en.wikipedia.org/wiki/Dal_segno), but only for entire sections, and limited to only once in a score. It would be unusual to use that with just a measure or two.
Comment: @JohnWu - From my experience, "D.S. al Coda" is typically done only when there are already repeat signs in the composition (often themselves with first and second endings).
Answer: With music notation, one important consideration is legibility; and on that count I'd suggest that your single-bar example fails the test, in that it introduces navigational complexity without saving much space on the page.
There may well be musicologists who have devoted treatises to the subject, but I suspect a good 'rule of thumb' would be 'does this repeat make the music easier or harder to read'?
Comment: Another factor is the form of the piece, if it has one. As an example, a song in AABA form.  If you write out the AA as opposed to A, Repeat A, it may not be quite as clear as you'd like that you're actually repeating the A section.
Comment: Thanks for your answer. Yes, I think legibility is the deciding factor, which does not give an explicit answer, but close enough :) With the "1 bar repeat" I was thinking of for example "In C" by Riley that's why I explicitly mentioned in the question that I'm asking about *non*-experimental pieces.
Answer:
...measures BC with two different endings...

Are the alternate "endings" in your example actual endings? If not, using voltas and repeats would seem to send the wrong visual clues about what is happening musically.
In other words, internal repetition within a phrase and alternate endings are not the same.
Regarding a rule of thumb, it seems to me the important thing is distinguish formal types of repetition. I can think of three types (I'm naming categories on the fly here:)
Mechanical...

...pretty obvious in the case of exercises, but could also be sensible for something like an ostinato part. Repeat signs visually reinforce the idea to just keep doing something over and over. Perhaps when the exact number of repeats is lost upon the listener.
Proportional...

...or...

...the two-bar ideas could be enclosed in repeats, but they are written out. Often in classical music such repeats have some small variation necessitating the second iteration be written out, but even when it's a literal repeat it's still written out.
I call this "proportional" because I think the purpose of the repeat is to simply extend 2 bars to fill the space of 4. In both examples the sonatas both have phrase groups based on 4 bars. Composers could achieve 4 bars a number of ways in terms of repetition: 4 unique bar, a repetition with variation, or a literal repetition. If all three are consider just the same thing - a 4 bar phrase - then we can see why repeat signs aren't normally used for the literal repeat. It isn't so much that musical idea is about repetition, but filling the space of the proportions.
I think the listener is normally very aware of the repetitions, usually 2, maybe 3.
Structural...

...it's hard to show with a short example, but these are the repeats demarking the first and second halves of a sonata. Of course sectional repeats like this simply double the play time. But, especially in the case of sonata form, the repeats emphasize the structural significance of the sections. You could abbreviate it like ||: I  V :||: ? I :|| where ? means the "development" part. The repeated sections help emphasize that the first part sets up an incomplete ending (ends on the dominant) which is then made whole by the second part ending on the tonic. Repeats like this make the structural organization clear. In the case of classical form, it's tonal/harmonic contrasts demarked by sections and their repetition, but I suppose structure/repeats could be based on other aspects rhythms or melody.
I think for a casual/untrained listener these repeats may not be apparent regardless whether there is a clear stop at the end of sections.
Comment: @LarsPeterSchultz, I didn't say "end of the piece." I meant phrase/section ending. I'm sure you can find all sorts of uses of repeat signs if you look at enough scores. But part of the question is about "rule of thumb." I'm trying to reason out _why_ we see these typical uses of repeat sign in some cases, but written out, literal repeats in others.
Comment: You did say QUOTE: 'Are the alternate "endings" in your example actual endings?' UNQUOTE. But that is irrelevant, it doesn't matter whether it is actual endings or not. What matters is legibility as @SteveMansfield pointed out in his answer.
Comment: "prima volta and seconda volta" simply means "1st time and 2nd time". It does not need to be an ending at all. The "1st time bracket" just tells what should only be played the first time which means you skip that when you play the repeat and instead continue from the "2nd time bracket". Yes you can certainly find those brackets a lot in endings whether it is the end of a section or the end of a piece but it can also appear other places, any place where you want a different continuation at the end of a repetition. Thus it is about the end of the repetition, not the end of the piece.
Comment: Yes, but legibility comes from understanding. And using voltas for endings (of phrases, section, or whole pieces) helps understanding that "here we could do the same, but here is the difference". In my example those aren't endings, it's just an internal repeat withit the phrase. If I understand currently correct.
Comment: The point I'm make through actual example scores is small internal repeats are usually written out instead of using repeat signs. IMO it's best to follow that convention.
Answer: Typically repetition is used for a whole section, a closed piece of music, like a verse of a song, a part of a dance. I don't believe there are strict rules there. Perhaps you may ask yourself: would the score make logical sense if you put a double bar line at the boundaries of the repetition? In practice I rarely see repeated sections shorter than 8 bars.
If you're desperately looking to shorten the length of the score, e.g. to fit it on one page, then anything is permitted, but you are likely sacrificing readability, especially with something as short as two measures with voltas. I wouldn't recommend doing it on a regular basis.
Answer: I suspect it depends on whether the musician playing it primarily sight reads or plays by ear.
I finally stopped flunking site-reading tests when I learned to sight sing, so that I could just ignore the printed music and concentrate on playing what I'd just sung. I eventually got better at sight reading, but I like short marked repetitions as they allow me to read once and then play twice.
In contrast, my mum could sight-read music as a child before she learned to read English, so for her using repeats on short blocks is pointless, and having to relocate her visual focus on a repeat block is somewhat of a distraction.
That said, repeats that go back to previous pages are worse distractions, and short be avoided if possible.
Comment: Michael Curtis's answer makes a good case that repeats that go back to previous pages are not only permitted but also common in classical music pieces such as sonata-allegros and scherzo and trios.

How many measures minimum in a repeat


Dropdown as an unexposed field in views

Question: I'm developing a complaint portal for administration. All complaints are submitted by sites users. I'm fetching these complaints using views and don't know how to add active/Inactive as drop down options in each complaint. As everybody knows complaints' status stays active until it resolves. Active/inactive field is not existed in content type form.
This is for admin ease, admin can change the status of the complaint active or inactive.
Please let know if anyone has any experience regarding this.
Comment: The question is, who will set this option? The user? Or someone else? If it's the latter you could work with the field-permissions module (https://www.drupal.org/project/field_permissions) and set the field visibility only for those people who are editing this. Ah, i just saw you answered the question already. So, give field permissions a go...
Comment: Please see the comment below in first answer for more clarification what I needed.
Answer: You can use the Field Permissions module according to module's page:

The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

Then set permissions for your active/inactive field to be for admins only, then the field will not show for general users but admins will be able to change the status when they view each complaint.
Comment: Thanks for the response. I tried to add field permission module it will only hide fields from the restricted roles. However, my main purpose is to add this field in views as dropdown with all values so admin role can change the values. Is this possible?
Comment: Do you mean that you want to get the admin to change the values in bulk?
Answer: I have done this task. Use Field Permissions module to hide a field from user end. You can set permissions when you create or edit field. Then install editable fields and in creating views, add a field that have multi values (like list type field) and change the Format from default to editable. That's it

Dropdown as an unexposed field in views


A question on roots of a Quadratic.

Question: If roots of the equation ${ax}^2+bx+c=0$ are of the form $$\frac{\alpha}{\alpha-1},\frac{\alpha+1}{\alpha}$$
Then the value of $$({a+b+c})^2$$
I have no clue how to approach this one, any help is appreciated!
Comment: Right. Now solve for ??.When that's done, plug ?? back into ?? to get one of the roots of the quadratic in terms of a,b,c.
Comment: You only need one of the roots. Take that root, now expressed in terms of a,b,c and plug that back into the quadratic equation. Hopefully, it will reveal the value of (a + b + c)^2.
Comment: Do you know how to express the product of the roots the equation
$$ax^2 + bx + c = 0$$ in terms of $a,b,c$?
Comment: That would be c/a right?
Comment: Yes, that's right. So set c/a = ?? and solve for ??
Comment: c/a=$\frac{\alpha+1}{\alpha-1}$
Comment: Oh so we solve for $\alpha$ and plug it back into the roots, thanks a lot!
Comment: Yes that did the trick thanks!
Answer: From the form:
$\frac{1}{x} + x = 2$ => $x^2 + x -2 = 0$, and first equation is $kx^2 + kx - 2k = 0$.
So, $(a+b+c)^2=0$
Comment: Slick, and much easier than what I was suggesting (but my idea would also work).
Comment: Does that mean the other form has no use at all?

A question on roots of a Quadratic.


$\lim_{x\to -\infty} x+\sqrt{x^2-3x}$

Question: Hey so I'm having a bit of a hard time understanding this one.

$\lim_{x\to -\infty} x+\sqrt{x^2-3x}$
1) $x+\sqrt{x^2-3x}$ * $(\frac{x-\sqrt{x^2-3x}}{x-\sqrt{x^2-3x}})$
2) $\frac{x^2-(x^2-3x)}{x-\sqrt{x^2-3x}}$
3) $\frac{3x}{x-\sqrt{x^2(1-\frac{3}{x}})}$
4) $\frac{3x}{x-\sqrt{x^2}*\sqrt{1-\frac{3}{x}}}$
5) $\frac{3x}{x-x(\sqrt{1-\frac{3}{x}})}$
6) $\frac{3}{1-(\sqrt{1-\frac{3}{x}})}$

Now I would just take the limit, it would result in $\frac{3}{1-1}$ which would be undefined. For some reason, the $x$ in the denominator of step 5 should turn into $-(-x)$ which in turn would be positive and therefore be $\frac{3}{1+\sqrt{1=\frac{3}{x}}}$ which would equal $\frac{3}{2}$.
I really don't get it. Apparently the $-\infty$ would mean that $\sqrt{x^2}$ = $-x$. We didn't even evaluate the limit yet.. how does that turn into $-x$, just because we know the limit is negative does not mean we evaluated it yet..., why not simplify until there is no more simplification to be done, which is what I did in my steps, which would evaluate to undefined?
Would love some help, thanks!
Comment: $\sqrt{x^2}$ has two solutions for $x$: $\pm x$; if $x<0$ the only solution is $-x$.
Comment: So based on that we know that $x$ is negative before we even evaluate the limit, we just take $-x$? If so, do we replace $x$ by $-\infty$ or by  $\infty$ after we get $\sqrt{x^2}$ = $-x$
Comment: You take $\lim_{x\to -\infty} x+\sqrt{x^2-3x}$. If this limit exists and equals $a$, is means that given $\epsilon>0$ there exists $M\in\mathbb{R}$ such that for all $x<M$, we have $|x+\sqrt{x^2-3x}-a|<\epsilon$. Since this holds for all $x<M$, we can assume without loss of generality that $M<0$, for if this holds for an $M\geq0$, it certainly holds for any negative $M$.
Comment: You might do better with $lim_{y\to \infty} \sqrt{y^2+3y}-y$ by using $y=-x$. Your approach then leads to $\frac{3}{2}$ without worrying about the ambiguity of the square root.
Comment: Just test it for a few values of $x$ (approaching $-\infty$)! When $x=-10$ you have $x^2=100$. So $\sqrt{x^2}=\sqrt{100}=10=-x$. When $x=-100$ you have $x^2=10000$ and $\sqrt{x^2}=\sqrt{10000}=100=-x$. Do you see what happens?
Answer: In such cases, to avoid confusion with signs, I often suggest, at least as a check, to take $y=-x \to \infty$ and then
$$\lim_{x\to -\infty} x+\sqrt{x^2-3x}=\lim_{y\to \infty} -y+\sqrt{y^2+3y}$$
and from here we can proceed as usual.
Answer: $a^2-b^2=(a-b)(a+b).$
$y:=-x$ , and consider $\lim y \rightarrow + \infty.$
$\sqrt{y^2+3y}-y= \dfrac{(y^2+3y)-y^2}{\sqrt{y^2+3y}+y}=$
$\dfrac{3y}{\sqrt{y^2+3y}+y}= \dfrac{3y}{y(\sqrt{1+3/y}+1)}$
$=\dfrac{3}{\sqrt{1+3/y}+1}.$
Take the limit.
Answer: The problem is indeed that, for $x<0$, $\sqrt{x^2}=-x$, so when you pull $x^2$ outside the square root it must become $-x$ and not $x$. We can assume $x<0$ because we're doing a limit for $x\to-\infty$, so restricting the function to an interval of the form $(-\infty,a)$, for any $a$, is possible and doesn't affect the limit.
You avoid most problem of this kind if you switch to positive infinity ($x=-y$) or to "positive $0$" ($x=-1/t$). With the latter method, the limit becomes
$$
\lim_{x\to-\infty}\bigl(x+\sqrt{x^2-3x}\,\bigr)=
\lim_{t\to0^+}\left(-\frac{1}{t}+\sqrt{\frac{1}{t^2}+\frac{3}{t}}\right)=
\lim_{t\to0^+}\frac{\sqrt{1+3t}-1}{t}
$$
which should be much easier (either as a derivative or using the usual technique with the conjugate). Here we can simplify $\sqrt{t^2}=t$ because we're working in a right neighborhood of $0$.
Answer: We are near $-\infty$, so $x<0$ and $|x|=-x$.
thus
$$x+\sqrt{x^2-3x}=x+\sqrt{x^2(1-\frac 3x)}$$
$$=x+|x|\sqrt{1-\frac 3x}$$
$$=x(1-\sqrt{1-\frac 3x})$$
$$=x\frac{\frac 3x}{1+\sqrt{1-\frac 3x}}$$
the limit is $\frac 32$.
Answer: Using Taylor's expansion:
When x approches $-\infty$:
$x + \sqrt{x^2-3x} = x - x(1 - \frac{3}{2x}+\text{o}(x)) = x - x + \frac{3}{2}+\text{o}(1) \rightarrow \frac{3}{2}$.
So, yeah
$
\begin{align}
\lim_{x\to-\infty}x + \sqrt{x^2-3x} =\frac{3}{2}.
\end{align}
$

$\lim_{x\to -\infty} x+\sqrt{x^2-3x}$


AutoCompleteTextView creates a margin for dropdown list

Question: Dropdown list comes with right and left margin even though I didn't set margin in my dropdown list item layout. I want it to match to the autocompletetextview's width. How can I achieve that?
Here is my AutoCompleteTextView xml code:
<LinearLayout
                android:id="@+id/headerlogo"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_margin="0dp"
                android:layout_weight="1"
                android:clickable="true"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:weightSum="9" >

                <AutoCompleteTextView
                    android:id="@+id/autocomplete_name"
                    android:layout_width="wrap_content"
                    android:layout_height="fill_parent"
                    android:layout_weight="7"
                    android:background="@drawable/edittextback"
                    android:ems="10"
                    android:textSize="15sp"
                    android:hint="@string/codehint"
                    android:textColorHint="@color/hintgrey"
                    android:paddingRight="30dp"
                    android:paddingLeft="10dp"
                    android:singleLine="true"
                    android:ellipsize="end"
                    android:completionThreshold="1">
                </AutoCompleteTextView>

                <Button
                    android:id="@+id/btnsearch"
                    android:layout_width="wrap_content"
                    android:layout_height="fill_parent"
                    android:layout_weight="2"
                    android:background="@drawable/buttondarkblue"
                    android:text="X"
                    android:textColor="@color/white" />
            </LinearLayout>

And item layout for dropdown list:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">
      <TextView
        android:id="@+id/route"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="15sp"
        android:singleLine="true"
        android:ellipsize="end"
        android:padding="5dp"
        android:textColor="@color/loginblue"
        android:text="ASD"></TextView>
</LinearLayout>

Answer: You can use 2 methods
setDropDownHorizontalOffset(int) and setDropDownWidth(int)
For example, you can do something like this to match to autocompletetextview:

input.setDropDownHorizontalOffset(0)
input.setDropDownWidth(input.getWidth())

FYI 1st method can use negative values. So you can set a dropdown layout width more the autocompletetextview width:
int offset = 64
input.setDropDownHorizontalOffset(-1 * offset)
input.setDropDownWidth(input.getWidth() + offset * 2)

Answer: I don't know, you've got your answer. But may helps.
If you assign a layout for dropdown list in the custom adapter and set margins for the TextView or paddings for the root view (for example, LinearLayout), it doesn't work. I did as follow:
I set background for the dropdown list in style.xml file:
<item name="android:popupBackground">@drawable/dropdown_list_bg</item>

And then in dropdown_list_bg.xml file i wrote these lines:
<item android:right="1dip" android:left="1dip">
    <shape>
        <solid android:color="@color/dropdownListBg"/>
        <corners android:radius="@dimen/corner"/>
    </shape>
</item>

As you can see i set "padding right" and "padding left" with "android:right" and "android:left" attributes in the drawable xml file.


Get ip address and set as variable bash shell script

Question: I am trying to write a bash script to configure an app (unattended install). All I need to do is this. I need to get the IP address for the server and set it as a variable. I am writing this script to simplify that. What I have noticed is that when I test this in a vps though eth0 is listed its not the default, its something along the lines of venet0:0. Is there any way of getting this ip set as a vaiable (I know how to if I know the interface name, i am trying to do this without knowing as its hard to plan for every possible device naming). if not then i will just add a prompt for the ip address for the user right as they run the script.
This is not a duplicate question as I am asking for the server's IP not just the public IP of the server. Even though this is aimed at building a public mail server I am building it to work on an internal one as well.
Answer: 'The' IP address... servers have so many, default management, application, DB listener?
Does this do it for you?
IP_ADDR=$(getent hosts `hostname` | awk '{print $1}')

Comment: This worked Perfectly for me! thanks! I am a better PHP programmer than a shell scripter i swear! :)
Comment: This approach is quite nice on a server that was properly setup. However, it won't work until system administrator adds external IP address in /etc/hosts
Comment: However, note that on IPV6 enabled system, it returns IP V6.
Answer: If you have one interface:
ip addr show | grep "inet " | grep -v "127.0.0.1/8" | awk '{print $2}'
10.10.1.254/16


Difference between a Student-T vs Cauchy distribution

Question: What are the real and practical differences between the student t distribution and the Cauchy distribution? The results I get when I use them as priors in Bayesian linear models appear to be interchangeable.
Comment: Cauchy is Student t with 1 degree of freedom.
Answer: Student's t-distribution becomes the Cauchy distribution when the degrees of freedom is equal to one and converges to the normal distribution as the degrees of freedom go to infinity.  The primary distinction is that for either one or two degrees of freedom, then there is no defined variance for Student's distribution.  This allows you to model the existence of a variance or not by choosing the number of degrees of freedom.  With the Cauchy distribution, the scale parameter is not identical to the variance nor does it have a defined variance.  The variance is infinite.
For small degrees of freedom and a very large sample size, the difference between a Student's t prior distribution and a Cauchy prior distribution may not be different enough for computational differences to arise.


Connectedness of centralizer exercise

Question: I'm having trouble understanding connectedness from a group theoretic perspective.
Let $G$ be the symplectic group of dimension 4 over a field $K$,
$$G = \operatorname{Sp}_4(K) = \left\{ A \in \operatorname{GL}_4(K) : A^T J A = J \right\} \text{ where } J = \left(\begin{smallmatrix}.&.&.&1\\.&.&1&.\\.&-1&.&.\\-1&.&.&.\end{smallmatrix}\right)$$
and let $C$ be the centralizer of a specific unipotent element $t$,
$$C=C_G(t) \text{ where } t = \left(\begin{smallmatrix}1&1&.&.\\.&1&.&.\\.&.&1&1\\.&.&.&1\end{smallmatrix}\right)$$
The exercise asks one to, Show that $t$ does not lie in the connected component of the identity when the characteristic of $K$ is 2. I think K is algebraically closed, though this is perhaps not specified here (and is specified in a nearby exercise).
I calculate the centralizers to be:
$$C_{\operatorname{GL}_4(K)}(t) = \left\{ \left(\begin{smallmatrix}a&b&c&d\\.&a&.&c\\e&f&g&h\\.&e&.&g\end{smallmatrix}\right) : a,b,c,d,e,f,g,h \in K, ag-ec \neq 0 \right\} \cong \operatorname{GL}_2\left(K[dx]/{(dx)}^2\right)$$
$$C_{\operatorname{Sp}_4(K)}(t) = \left\{ \left(\begin{smallmatrix}a&b&c&d\\.&a&.&c\\e&f&g&h\\.&e&.&g\end{smallmatrix}\right) : a,b,c,d,e,f,g,h \in K, ag-ec = 1, ah+bg=cf+de \right\}$$
I am clueless how to find their connected components.

What are the connected components of $C_{\operatorname{GL}_4(K)}(t)$ and $C_{\operatorname{Sp}_4(K)}(t)$?

Especially describe the exceptional behavior in characteristic 2.

Does the connectedness have anything to do with them being matrices?

I would prefer some group theoretic way to find the components, but I worry that the components have nothing to do with the matrices, and depend only on the equations $ag-ec=1$ and $ah+bg=cf+de$, regardless of where these variables are in the matrix.
If they don't have anything to do with the group structure, then why would I care if it is connected?
Comment: @MichaelJoyce: There is no mistake in that part. If the characteristic of K is 2, then t is in the RHS, and if the characteristic of K is not 2, then t is not in Sp4(K) so is not in the RHS.
Comment: @LeonidKovalev: the topology doesn't seem to come coordinate by coordinate (from K), but rather fairly directly on the 8-tuples (or 16-tuples, I'm not sure) from the Zariski topology (which ensures that points are closed and polynomials are continuous). The centralizers are both closed, as they are the solutions of polynomial equations. Using some multi-variate polynomial factoring ideas, one can decide connectedness, but it seems unrelated to the group structure. This is troublesome due to the large number of group theory theorems that definitely require connectedness.
Comment: I am even more clueless: I don't know what connected components even mean in the absence of topology. (And I don't know where a topology on K is going to come from)... A common way to prove that elements x and y lie in different components is to exhibit a continuous real valued function f which is never zero and satisfies $f(x)<0<f(y)$.
Comment: @JackSchmidt: It seems like there must be a mistake in your calculation of $C_{Sp_4(K)}(t)$ because the element $t$ is not in the set on the RHS.
Comment: Ahh, I see now.  Thanks.
Comment: As you computation shows, the points lying in the centralizer of t in Sp(4) is an algebraic variety over $K$ (same in the Gl4 case but slightly more complicated). The relevant topology topology is the Zariski topology. More concretely, look at the ring $ K[x_{1}. \ldots, x_{8}]$ and quotient it by the ideal $(x_{1}x_{7} -x_{5}x_{3}, x_{1}x_{8} + x_{2}x_{7} - x_{3}x_{6} -X_5}x_{4})$ and show that the resulting quotient has idempotents.
Comment: Look at any discussion on Spec of a commutative ring (like exercise to the fist chapter of Atiyah Macdonald).
Comment: This is a rather interesting exercise.  Where does it appear?
Answer: I wrote up my findings in this short note. In brief: the exercise is incorrect. Both centralizers are connected. I confirmed with the authors that the intention of the exercise was an exhibition of Springer's 1966 result that a regular element does not lie in the connected component of its centralizer in a few cases, including symplectic groups in characteristic 2. Unfortunately the element given is not regular. The short note contains an example regular element, a calculation of its centralizer, and the decomposition into its connected components.
To find the connected components one has to factor the defining equations. For $C_{GL}$ this is easy: they are irreducible, and the entire centralizer is its own irreducible component. For $C_{Sp}$ this is a bit more challenging as the two polynomials together still define an irreducible system of polynomial equations. The exercise was intended to be easy: for the regular element, the centralizer factors into two obviously irreducible systems.
Since writing up the solution, I have had help proving the centralizer is connected using more elementary methods, mostly using pre-1920s mathematics. However, a few of the details are still too complicated to justify giving here (where I believe one would like a clear and simple explanation for LVK, and a group theoretic explanation for me).
As far as the importance of connectedness in group theory, this remains a mystery.  Certainly no-one who helped me over the course of several weeks used the group structure to solve it, though I believe it could be possible to do so.
Answer: I think the claim in the OP is mistaken, because of the following : define for $t \in K$,
$$
p(t)= \left(\begin{smallmatrix}1&t&.0&0.\\0.&1&0.&0.\\0.&0.&1&-t\\.0&0.&0.&1\end{smallmatrix}\right)
$$
Then $p$ is polynomial and hence continuous for the Zariski topology. As the image of a connected set by a continuous map stays connected, we deduce that $p(K)$ is connected. So $p(O)=I$ and $p(1)=t$ are in the same connected component, (they are in fact "arcwise connected") contrary to the original claim.

Connectedness of centralizer exercise


Question on AIC and stepAIC

Question: AIC(lm(Fertility ~ ., data=swiss))
[1] 326.0716

ok, since AIC is calculated as
-2*logLik(lm(Fertility ~ ., data=swiss)) + 2*7

Why does stepAIC return a smaller AIC?
stepAIC(lm(Fertility ~ ., data=swiss))
Start:  AIC=190.69

Answer: Read ?AIC. From the Details section we have:
 The log-likelihood and hence the AIC is only defined up to an
 additive constant.  Different constants have conventionally be
 used for different purposes and so 'extractAIC' and 'AIC' may give
 different values (and do for models of class '"lm"': see the help
 for 'extractAIC').

So you are seeing the effect of different additive constants, as stepAIC() (in the MASS package) is using extractAIC() to compute the AIC of the models.

Question on AIC and stepAIC


How can I center a relatively sized element in an Android app?

Question: If I am using:
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:weightSum="1.0"
    android:background="@drawable/mainpgbg">
<RelativeLayout
    android:layout_width="0dip"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_weight="0.50"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_gravity="center_horizontal">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Log In"
            android:textSize="24sp"
            android:id="@+id/logInBtn"
            android:layout_gravity="center_vertical"
            android:layout_weight="0.50"
            android:background="@drawable/round"
            android:padding="20dp"
            android:layout_marginBottom="128dp"
            android:layout_alignParentBottom="true" />
</RelativeLayout>
</LinearLayout>

I anticipated that the RelativeLayout would be displayed centered on the screen, but it seems that you need a RelativeLayout to center elements, however you need a LinearLayout to create relative size elements.
How can I do both? Center a relatively sized element?
Answer: Add android:gravity="center" to your LinearLayout's xml to center its children (anything inside of it):
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:weightSum="1.0"
android:background="@drawable/mainpgbg"
android:gravity="center">

Comment: `android:gravity="center"`

Thank you!!! That worked perfectly, I knew it was something simple I was missing. I didn't realize gravity was to be applied to parents. I had gravity on children.
Answer: As per your requirement your xml is correct, You can also try using TableLayout,
http://www.mkyong.com/android/android-tablelayout-example/
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dip" >

    <TextView
        android:id="@+id/textView1"
        android:text="Column 1"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:text="Column 2" />
</TableRow>

<TableRow
    android:id="@+id/tableRow2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dip" >

    <EditText
        android:id="@+id/editText1"
        android:layout_span="2"
        android:text="Column 1 & 2" />
</TableRow>

<View
    android:layout_height="2dip"
    android:background="#FF0000" />

<TableRow
    android:id="@+id/tableRow3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dip" >

    <TextView
        android:id="@+id/textView2"
        android:text="Column 1"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button2"
        android:text="Column 2" />

    <Button
        android:id="@+id/button3"
        android:text="Column 3" />
</TableRow>

<TableRow
    android:id="@+id/tableRow4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dip" >

    <Button
        android:id="@+id/button4"
        android:layout_column="2"
        android:text="Column 3" />
</TableRow>

<TableRow
    android:id="@+id/tableRow5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dip" >

    <Button
        android:id="@+id/button5"
        android:layout_column="1"
        android:text="Column 2" />
</TableRow>

Comment: Thank you ksarmalkar! Much Appreciated!


How to make all render caches update on a configuration override?

Question: Short version:
I am using a configuration override to override the site name. Changes are reflected in the HTML title, but not in the system branding block. Drupal keeps serving this block from the render cache.
Long version:
I am using a configuration override service that implements ConfigFactoryOverrideInterface, which overrides configs on demand. Slightly simplified, it looks like this:
class MyConfigOverride implements ConfigFactoryOverrideInterface {

  /**
   * {@inheritdoc}
   */
  public function loadOverrides($names) {
    $overrides = [];

    if ($override_required) {
      if (in_array('system.site', $names)) {
        $overrides['system.site']['name'] = 'My name';
      }
    }
    return $overrides;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheSuffix() {
    return 'MyConfigOverride';
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata($name) {
    $metadata = new CacheableMetadata();

    if ($name === 'system.site') {
      $my_entity = MyEntity::Load(1);
      if ($override_required && !empty($my_entity)) {
        // Append entity cache metadata (cache tags and context).
        $metadata->addCacheableDependency($my_entity);
      }
    }
    return $metadata;
  }

  /**
   * {@inheritdoc}
   */
  public function createConfigObject($name, $collection = StorageInterface::DEFAULT_COLLECTION) {
    return NULL;
  }

}

However, as soon as this override kicks in, the render cache for the System branding block does not get updated with the new site name. This is because the SystemBrandingBlock class does implement getCacheTags() in which it merges the system.site cache tags (see below), but it does not implement getCacheContexts() (which my module uses since I serve a variation of the page).
/**
 * {@inheritdoc}
 */
public function getCacheTags() {
  return Cache::mergeTags(
    parent::getCacheTags(),
    $this->configFactory->get('system.site')->getCacheTags()
  );

}

I have tried to overcome this by adding additional 'empty' cache metadata to my class for the cases where the override does not apply.
  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata($name) {
    $metadata = new CacheableMetadata();

    if ($name === 'system.site') {
      $my_entity = MyEntity::Load(1);
      if ($override_required && !empty($my_entity)) {
        // Append entity cache metadata.
        $metadata->addCacheableDependency($my_entity);
      }
      else {
        // Append 'empty' cache metadata.
        $metadata->addCacheContexts(['mycachecontext']);
        $metadata->addCacheTags(['myentity', 'myentity:0']);
      }
    }
    return $metadata;
  }

Since the block does not inherit the cache contexts of system.site and I do not update or otherwise invalidate any of the provided cache tags ('myentity', 'myentity:0'), the render cache still persists. I can append cache context to the system branding block in a hook_block_build_BASE_BLOCK_ID_alter implementation, but I'd prefer not to implement such specific exceptions as they will never cover all situations.
I am somewhat hoping for a hook to update all renderable elements (blocks?) and append cache contexts to those that inherit cache tags provided by system.site. But I am open to alternative solutions as well.
How can I make any block or other entity in the render cache, that is depending on the system.site config aware of the config override?
Answer:
In the meantime I have come up with this approach, but I am still open to other solutions.

I have found a solution in a pre_render callback for the blocks, by deconstruction the cacheable metadata, searching it for a system.site tag and append my own context and tags (if required).
/**
 * Implements hook_block_view_alter().
 */
functionmymodule_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  $build['#pre_render'][] = 'mymodule_block_view_pre_render';
}

/**
 * #pre_render callback: Sets my module cache tags.
 */
function mymodule_block_view_pre_render(array $build) {
  $cacheable_metadata = CacheableMetadata::createFromRenderArray($build);
  $tags = $cacheable_metadata->getCacheTags();

  if (in_array('config:system.site', $tags)) {
    // Always add a cache context, so we have a variant without overrides as well.
    $cacheable_metadata->addCacheContexts(['mycontext']);

    if ($entity = MyEntity::Load(1)) {
      $cacheable_metadata->addCacheableDependency($entity );
    }
  }

  $cacheable_metadata->applyTo($build);

  return $build;
}


How to handle seekbar for dragging in android

Question: I have a seekbar in my app, which shows the level of age in it. If i touch that seekbar it updates the age in the textview, but i can't able to drag continuously and it stops dragging. for every value have to make touch event separately but not continous
Comment: What have you tried so far? Are you using the OnSeekBarChangeListener? http://developer.android.com/reference/android/widget/SeekBar.OnSeekBarChangeListener.html
Comment: i have tried onSeekBarChangedListener only, but it doesn't work, i want to handle motion event
Comment: Does not work? Could you post some code?
Answer: Finally,it works
<code>holder.ageSeekbar.setFocusable(false);
</code>
I removed focus for seekbar
Comment: Hi ADR, what is holder here instead of holder.ageSeekbar.setFocusable(false); ??