Can't get PHP errors to go to a log file (other than the Apache log)

Question: On a Ubuntu web server [LAMP], I'm trying to get PHP errors to write into a php_error file, but no matter what I do, they keep going to the apache log.
Here's what I have tried/done:

Edited the php.ini file:

error_reporting = E_ALL | E_STRICT
display_error   = Off
log_errors      = On
error_log       = /var/log/php_errors.log

Restarted Apache
Checked the phpinfo() output to verify that the changes I made to the php.ini file took -- they did.
After verifying that the errors were still going to the Apache log, I physically created the php_errors.log and tried again.  Still going to the Apache log!
Rebooted the web server!  Still...!

Anybody have a solution?
Comment: check `log_errors_max_len` is greater than 0
Comment: And does the web server have permission to create `/var/log/php_errors.log`? You may need to place that inside a location Apache can write to like `/var/log/httpd/php_errors.log` or `/var/log/apache2/php_errors.log`
Answer: Check the directory permissions for /var/log. Ensure that the user your Web service is running as has write permissions to that folder. Alternatively, create a subfolder (/var/log/phplogs?) and assign explicit permissions on that for the user in question then change the error_log value to be a file in that folder
Answer: It had to do with ownership.  One or the other has worked [for reasons that are not clear to me]:
chown www-data:www-data /var/log/php_error.log

chown same-user-as-www-home:same-user-as-web-home /var/log/php_error.log

Also, the following has made a difference:
chmod 664 /var/log/php_error.log

[as opposed to chmod 644...again for reasons that are not clear to me]
Answer: For the record, Ubuntu uses AppArmor and it limits what Apache does.
Additionally, to change the permissions to the file and editing the php.ini file, you must do the next steps:
Go to the next file

/etc/apparmor.d/abstractions

Edit this file

apache2-common

Add the next line
/var/log/php_errors.log rw,

where rw means the process could read and write this file
or you could also do:
sudo nano /etc/apparmor.d/abstractions/apache2-common

And finally, reload the configuration of apparmor
systemctl reload  apparmor

Note: Centos/Redhat/Oracle Linux uses SELinux and it requires the same step but the configuration is different.


how to remove unwanted values from an array in PHP?

Question: I got the below o/p
["1-3","2-3","1-4","2-4"]

in that how can i remove 1-, 2-, 1-, 2-
i want o/p like this
["3","3","4","4"]

Answer: Just walk every element in the array and explode it:
$arr = ["1-3","2-3","1-4","2-4"];

array_walk($arr, function(&$val){
    $val = explode("-",$val)[1];
});

var_dump($arr);

//array(4) { [0]=> string(1) "3" [1]=> string(1) "3" [2]=> string(1) "4" [3]=> string(1) "4" }

Comment: instead of `var_dump` use `print_r`. var_dump shows you the "hidden" keys.
Comment: sorry array(4) { [0]=> string(1) "3" [1]=> string(1) "3" [2]=> string(1) "4" [3]=> string(1) "4" }
Comment: Isn't that exactly what you want @KarnaGowtham ?
Comment: i want o/p like this "["3","3","4","4"]"
Comment: That is exactly the outcome of what I wrote. You can't have array values without keys.
Answer: If you assume the dash it the split between the two strings (or number) then you'd need some regex
/[^-]+$/

This would return the value after the - dash
This would cover you for more than 1 digit should you need it.
Answer: try this one..
<?php
$input= array('1-3','2-3','1-4','2-4');
$newArr = array();
foreach($input as $key =>$val)
{
    $a = explode('-',$val);
    $newArr[]= $a[1];
}
echo "
"; print_r($newArr);
?>

This will output
Array
(
    [0] => 3
    [1] => 3
    [2] => 4
    [3] => 4
)

Comment: Thank U dear @ Barnala


How to change the page of a view block display programmatically

Question: I have a view with a block display. Is there any way to change the block pager page programmatically?
Currently i am embedding theview using the views_embed_view and i am passing the url arguments. What i need is to pass also the pager index argument also. Is this possible?
Thanks in advance
Answer: This is how you can get a view programmatically:
<code>  $view = views_get_view('view_name');
  $view->set_display('view_block_name');
  $view->set_arguments(array($argument_goes_here));
  $view->pre_execute();
  $view->execute();
  print $view->render();
</code>
The views object has many functions which can be viewed here.
You can set current page for the pager with <code>$view->set_current_page($page);</code>


C# overloading resolution?

Question: From the article Anders Hejsberg interview, "the way we do overload resolution in C# is different from any other language"
Can somebody provide some examples with C# and Java?
Comment: @James: That is *overriding*, not *overloading*.
Comment: I would start at [Eric Lippert's](http://blogs.msdn.com/b/ericlippert/archive/tags/overload+resolution/) blog.  There are 8 posts marked taged with **overload resolution**.
Comment: @Robert Harvey: I feel like that's kind of a half-assed answer.  There are quite a few people on SO that could answer the question in much better detail than "read X."  Content of said answers would also be more valuable to SO.
Comment: Why do you need an example? In Java you can easily replace a function in a subclass, in C# you mark the function as virtual, then can override it.
Comment: @R0MANARMY: That's the correct answer to this question. If you post it as an answer, I will upvote it.
Comment: @james, I am talking about overloading instead of overriding.
Answer: What Anders was getting at here was that the original design team explicitly designed the overload resolution algorithm to have certain properties that worked nicely with versioning scenarios, even though those properties seem backwards or confusing when you consider the scenarios without versioning.
Probably the most common example of that is the rule in C# that if any method on a more-derived class is an applicable candidate, it is automatically better than any method on a less-derived class, even if the less-derived method has a better signature match. This rule is not, to my knowledge, found in other languages that have overload resolution. It seems counterintuitive; if there's a method that is a better signature match, why not choose it?  The reason is because the method that is a better signature match might have been added in a later version and thereby be introducing a "brittle base class" failure.
For more thoughts on how various languages handle brittle base class failures, see
Link
and for more thoughts on overload resolution, see
Link
Comment: Do you get paged whenever your name is mentioned in a question to make sure it's answered regardless of time of day ;) ?
Comment: C++ automatically hides all functions with the same name, if one is defined in a more derived class. So unless you use a "using base::functionname" declaration (which "unhides" the name again), the effect is similar. It's not exactly the same though, because in C++ those hidden names will not be considered at all, even if no overload in the more derived class is applicable. It serves the same prupose though - new functions in base classes will not be called unintentionally.
Answer: The way that C# handles overloading from an internal perspective is what's different.
The complete quote from Anders:

I have always described myself as a
  pragmatic guy. It's funny, because
  versioning ended up being one of the
  pillars of our language design. It
  shows up in how you override virtual
  methods in C#. Also, the way we do
  overload resolution in C# is different
  from any other language I know of, for
  reasons of versioning. Whenever we
  looked at designing a particular
  feature, we would always cross check
  with versioning. We would ask, "How
  does versioning change this? How does
  this function from a versioning
  perspective?" It turns out that most
  language design before has given very
  little thought to that.
Comment: Well....that explains his [other question](http://stackoverflow.com/questions/2926470/c-language-design-pillars).

C# overloading resolution?


Use well-known relation: $\det(I + \epsilon X) = 1 + \operatorname{tr}(X) \epsilon + O(\epsilon^2).$ for evaluate $\det(I + M)$.

Question: Let $d_1$, $d_2\in[0,1]$. Use well-known relation:
$$\det(I + \epsilon X) = 1 + \operatorname{tr}(X) \epsilon + O(\epsilon^2).$$
for evaluate
$$\det(I + M)$$
where $I$ is the $2\times2$ identity matrix and
$$M=\left(
  \begin{array}{cc}
    d_1(1-d_1) &\ \ \ \ \ d_1(1-d_2)  \\
    d_2(1-d_1) & d_2(1-d_2) \\
  \end{array}
\right)$$
I notice that $m_{ij}\in[0,1]$, for all $i,j=1,2$. But, what is $\epsilon$ in this case? Maybe could I take out of the matrix some parameters $d_i$?
Thanks in advance.
Answer: Presumably $d_1$ and $d_2$ are each very close to either $0$ or $1$. Supposing they are both nearly zero, you can choose $\epsilon$ to be the bigger one, and then write $M=\epsilon (M/\epsilon)$. So supposing $d_1$ is the bigger one, you wind up with
$$\text{det}(I+M)=1+d_1 \text{tr} \left ( \begin{bmatrix} 1-d_1 & 1-d_2 \\ \frac{d_2(1-d_1)}{d_1} & \frac{d_2(1-d_2)}{d_1} \end{bmatrix} \right ) + O(d_1^2).$$
It is best to "factor" the bigger one so that the matrix whose trace you are taking remains bounded. Otherwise some additional cancellation is required to isolate the leading order correction term.
Alternately, your asymptotic equality is equivalent to $\text{det}(I+X)=I+\text{tr}(X)+O(\| X \|^2)$. Then by picking a matrix norm, you get an asymptotic. This approach is nice because it doesn't really care what the form of $X$ was, so for your situation it would work in any of the four possibilities I mentioned in my first sentence.


Is there any event triggered when a new window is added to the desktop

Question: I want to know whether there is any event triggered when a new window appears/comes on the desktop. I am open to using COM,WMI,WinApis, UIAutomation or any other method but the language of choice is C#.
The actual requirement:
A process has 1 main window and many other windows. The class name of one of the windows is, say, X, (i got this info using pinvoke). Now this window pops up some times whenever there is some notification in the process. I do not want to show this window. I do not have code access to that process so that i can disable that window. So is there any way that i can get an event or any other mechanism which keeps track of the desktop and anytime a window with classname X comes/about to come it hides it.
Do tell if i am not clear with the question.
Thanks
EDIT : Simon's answer is really good. I tried that and am able to get notification for all windows except notifications/toast windows such as that of lync's im toast notification or outlook new mail notification. I tried with different elements of Automation Element and Windows Pattern but still could not get those...Any ideas how i can get those...you may read comments in Simon's answer for more context/detail. Once again thanks to Simon for introducing to the great power of UIAUtomation...Loving it!
Comment: I think you can use the [UI Automation](http://msdn.microsoft.com/en-us/library/ms753107(v=vs.110).aspx) - it supports a [`WindowOpened`](http://msdn.microsoft.com/en-us/library/system.windows.automation.windowpattern.windowopenedevent(v=vs.110).aspx) event
Answer: As Damien said in his comment, you can use UI automation, like this in a C# sample console app:
class Program
{
    static void Main(string[] args)
    {
        Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, TreeScope.Subtree, (sender, e) =>
            {
                AutomationElement src = sender as AutomationElement;
                if (src != null)
                {
                    Console.WriteLine("Class : " + src.Current.ClassName);
                    Console.WriteLine("Title : " + src.Current.Name);
                    Console.WriteLine("Handle: " + src.Current.NativeWindowHandle);
                }
            });

        Console.WriteLine("Press any key to quit...");
        Console.ReadKey(true);
    }
}

Comment: hey...thanks...i have one more question...can we also get information about windows such as notificatios, for example the ones that come when new mail in outlook, or new im in lync/skype etc... I tried the above code but it did not show for such kind of windows...Through other win apis i have found that , for ex, the window class of lync toast notification is different than the conversation window class. SO i was hoping that on getting the event  here i would just hide that window
Comment: The Windows tree is huge. The sample uses AutomationElement.RootElement (which is the Desktop window) as the parent, and it does not get all sub windows notifications. But you can use other elements as the start. You can get other elements using the AutomationElement.FromHandle, FromPoint methods, etc.
Comment: I'm using the .NET automation library on Windows 10.  I added an event handler just like your example -- rooted at RootElement, scope Subtree.  But the odd thing is we nearly always see two events each time a window opens.  Occasionally, there may be just a single event, but >95% of the time there are two.  The events are distinct objects but contain the same EventId and from same source.  Any clues where to look?
Comment: @SteveRobbins - I've tested my answer's code today with Windows 10 and it works fine. Do you have a problem with my sample or other code? If it's another code you should ask another question.
Comment: @SimonMourier good question.  I was using my own code previously, but today I compiled your code exactly as presented above.  I do see the same behaviour -- but only a few applications (two so far) exhibit double open events.  One of them is my company's  application, but the other one is Adobe Acrobat Reader DC Version 2020.006.20034.  So the mystery deepens.
Comment: @SteveRobbins - ok, I guess these apps create multiple windows for some reason, but as an end-user you only see one
Comment: @SimonMourier: I definitely only see one window, but it's not clear that two are created -- the two events have the same window handle, for example.  The only thing that comes to mind is temporally filter them -- i.e. ignore a second event for the same handle if it occurs within X seconds of the first.
Answer: One option is RegisterShellHookWindow. You supply a window handle that can receive notification messages. The notifications that could be useful to you are HSHELL_WINDOWCREATED or HSHELL_WINDOWACTIVATED.
Answer: Here MSDN has provided code for registering for windows notifications. But this is specific  to Windows Sever 2008. I think similar you can find for your version of Window.


Which template used for adding nodes

Question: I want to add some custom checks to all of my Drupal pages (except the administration pages).
I am using Bartik theme that comes with Drupal 7.26
I added the custom check in node.tpl.php and the check worked for all urls of type /node/%

However, I also want to add this check for node add, edit and delete pages.
I cannot do this.
What I have already tried:
-> Creating a node--add.tpl.php in bartik folder and adding check there.
-> Creating a custom module, and using hook_menu to route /node/%/id to a custom page.
-> Adding this function
<code>function bartik_preprocess_page(&$vars, $hook) {
  if ((arg(0) == 'node') && (arg(1) == 'add' && arg(2) == 'product')) {
    $vars['template_files'][] =  'node-add-product';
  }
}
</code>
in my bartik template.php file. After adding this function I created node-add-product.tpl.php file and added check there.
For all the methods I have tried, the node creation page does not change at all.
I also tried creating page--node--add.tpl.php. Then the custom check works. But the header, footer, and sidebars disappears. (Only node creation template is rendered)
Answer: I think you are using the wrong tpl file to edit the node/add/[content-type] form.
You need to create (if I remember correctly) a [content-type]-node-form.tpl.php and add the required elements you wish from there. See here for more details:
https://drupal.org/node/1092122

Which template used for adding nodes


How to record guitar outdoor and in studio and then sync both perfectly

Question: Some guys on youtube make very professional videos of themself playing guitar outside, like Peter Gergely or Eddie Van Meer.
How do they record that? I mean in the second post a user commented:

Ramesh lg: Peter Gergely  bro..  Yu plz make a outdoor video of behind scenes...
  Plzzz... How it sounds so clear..
  Everytime i see yur videos i get motivated..
  Love yu bro...
[...]
Lucas Izquierdo: Im pretty sure he goes out records the video and then records the songs indoor in a semi studio, then after that he runs the tracks over and syncs them perfectly!

How to they record two separate pieces and then sync them perfectly, when obviously on their outdoor sessions they do not use a metronom and just play "by feeling"?? Either they must be extremly good in holding the timing when they play solo (I doubt someone can perfectly(!) play 120bpm over many minutes without some reference...), or they use some tricks? (maybe record them outside in bad quality and use this as a reference in studio, or something else?)
Comment: They might record in the studio first then listen to that and mime while recording the video.
Comment: People have been miming to pre-recorded tracks since 1967 [Strawberry Fields, 'first ever' video] - over time, they got better at it.
Comment: You don't even have to mime if you just throw away the audio from the video recording. You just play along with yourself.
Comment: @ToddWilcox You mean the other way around, play along your outdoor recording in the studio?
Comment: You can do it either way. It's just like playing along with a band. You record one of them first. Either one. Then all subsequent recordings/videos you are playing along with the first recording.
Comment: This video might be a hint: https://www.youtube.com/watch?v=NHuLpjyZPPs#t=1m52s
Answer: We do this quite often with my current band - because we accurately track tempo from our drum track, we can interleave studio audio with stage or other audio as needed, giving us some flexibility to have the energy of the live show, the accuracy of our studio work, or extras.
The only things you need to watch for are:

Initial synchronisation: you can use a clapperboard, or play along to your own audio track
Playback tempo: make sure your playback is accurate, i.e. Don't use an old tape deck that varies in speed...
Answer: My Answer- Pre-record your audio part in any DAW (like reaper ,cubase,garageband) and go outside and shoot your video playing to that pre recorded audio and then in video editor delete the sound from camera and sync up it with the audio
Comment: I believe this is the simplest answer that also applies to most cases. The videos OP linked have pre-recorded audio and the performance is to a playback. To interleave live portions as the accepted answer states you would need recording equipment (microphone, pickup) and possibly a controlled environment (i.e. no fountain in the background that produces noise).
Answer: The Peter Gergely video definitely has the sound recorded somewhere else. The ambiance / reverb doesn't sound like being outdoors at all, and there are no microphones or other recording equipment in sight. The Eddie Van Meer one as well.
It's pretty evident when they slap / tap on the guitar, you can hear the room reverberations, which wouldn't happen outdoors..


Why does this snippet cause a leak?

Question: I have a class method:
+ (UIBarButtonItem*)navItemWhichAddsNewAction{
    UIBarButtonItem* addActionButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_add"] style:UIBarButtonItemStylePlain target:nil action:nil];
    addActionButton.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        return [RACSignal empty];
    }];
    return addActionButton;
}

Then, in –viewDidLoad, I assign the result of this method to the right button of the navigationItem:
self.navigationItem.rightBarButtonItem = [MyClass navItemWhichAddsNewAction];

If I then profile the app with Instruments, the rac_command block above is always reported as allocated even when the view controller (and the navigation controller) is deallocated.
Why?
Comment: RAC implements a few common objects -- `[RACSignal empty]`, `[RACUnit defaultUnit]`, some others -- as singletons in release builds to reduce unnecessary allocations. As a result, those objects are never deallocated in the lifetime of your app, which can make it *look* like you're leaking a signal. If you call `[MyClass navItemWhichAddsNewAction]` ten times, do you wind up with ten signals sticking around, or just the one?
Comment: what is `rac_command`? could you please post the entire related `UIBarButtonItem` category as well, please?
Comment: rac_command is part of ReactiveCocoa (reactivecocoa.io).
Comment: have you asked the author of that framework about this issue yet?
Comment: Yes, I've posted it on their github issues page and I also tagged it with reactive-cocoa here, hopefully there are some RAC devs here as well ;).
Comment: I think you might be right there. I never thought that [RACSignal empty] might return a singleton, but of course it probably does :).
But then it also retains the block, doesn't it ?
Comment: If I re-create the view controller multiple times, used memory keeps increasing, and this block (plus a lot of other allocations created by RAC) are shown as persistent in each new marked generation.
Comment: @Florin Hmmmm. This is beyond my ability to diagnose. Are you sure that's from this method? I don't see anything wrong with it -- that block is retained as long as the `RACCommand` is retained, which is retained as long as the `UIBarButtonItem` is around, which is in normal country. Is it possible you're not tearing down the view hierarchy properly?
Comment: Yeah, I know, I've spent the last two days on this. I use this pattern for navItems a lot and the signal blocks instantiate view controllers, but these things are always shown as persistent each time I open and close a VC. In this simple case, no other objects are leaking, just this single block plus a bunch of allocations inside RAC (shown as  in Instruments).
Answer: Signal doesn't complete, and leak may be caused by this. Another side-effect may be that action is not called second time because of this.

Why does this snippet cause a leak?


My require_once has a right path but doesn't work

Question: This is what my directory looks like:
>admin
  >scripts
     file.php
>config
  database.php

I'm trying to use
require_once '../config/database.php';

on the file.php, but it doesn't seem to be able to find said file. Gives me the error

Warning: require_once(../load.php): failed to open stream: No such file or directory in C:/path_to_file.php
Comment: load.php is not listed in your question
Comment: Does this answer your question? [PHP include relative path](https://stackoverflow.com/questions/17407664/php-include-relative-path)
Answer: require_once '../../config/database.php';

Try this. I think you have to go backwards twice :)


positive definite of a matrix(diagonal decay)

Question: Is this matrix positive definite:
$$\begin{bmatrix}a & b &c & d\\b & b & c & d\\c & c & c & d\\d&d&d&d\end{bmatrix}$$
when $a>b>c>d>0$?
I tried several $a,b,c,d$, the result seems to be true, but I cannot prove it. Thanks!
Comment: See [Sylvester's Criterion](https://en.wikipedia.org/wiki/Sylvester%27s_criterion)
Comment: https://en.wikipedia.org/wiki/Min-max_theorem#Cauchy_interlacing_theorem may be even better.
Comment: Hi @JackD'Aurizio, thanks for your insightful comment! Could you please elaborate a little bit about why you want to use this theorem? Is it a tool to bound the eigenvalues of the above matrix? What it the projection matrix $P$ in this case?
Answer: Thanks to @Friedrich Philipp and @Omnomnomnom's comments, I notice huge defects in my original proof. Instead, I would like to present an another
proof followed by @Omnomnomnom's method.
Denote the given matrix by $A$. Observe that
\begin{align}
A=\begin{bmatrix}a & b &c & d\\b & b & c & d\\c & c & c & d\\d&d&d&d\end{bmatrix}
&=
\begin{bmatrix}a-b & 0 &0 &0 \\0 &  0& 0 &0 \\ 0& 0 & 0 & 0\\0& 0& 0&0\end{bmatrix}
+
\begin{bmatrix}b-c & b-c &0 &0 \\b-c &  b-c& 0 &0 \\ 0& 0 & 0 & 0\\0& 0& 0&0\end{bmatrix}\\
&+
\begin{bmatrix}c-d & c-d &c-d &0 \\c-d &  c-d& c-d &0 \\ c-d& c-d & c-d & 0\\0& 0& 0&0\end{bmatrix}
+\begin{bmatrix}d & d &d &d\\d&  d& d &d \\ d& d & d & d\\d& d& d&d\end{bmatrix}\\
&=A_1+A_2+A_3+A_4,
\end{align}
where $A_i$ denotes the above corresponding decomposed matrix. Then given
$x=(x_1,x_2,x_3,x_4)\in{\sf R}^4$, we see that
\begin{align}
x^tAx&=x^tA_1x+x^tA_2x+x^tA_3x+x^tA_4x\\
     &=(a-b)x_1^2+(b-c)(x_1+x_2)^2+(c-d)(x_1+x_2+x_3)^2+d(x_1+x_2+x_3+x_4)^2.
\end{align}
That is, $x^tAx$ is the sum of the four non-zero terms. Now, if $x\neq{\it 0}$, we discuss the following cases.

$x_1\neq 0$: It is clear that
$x^tAx\geq(a-b)x_1^2>0$.
$x_1=0$ and $x_2\neq 0$: It follows that $x^tAx\geq(b-c)x_2^2>0$.
$x_1=x_2=0$ and $x_3\neq 0$: It follows that $x^tAx\geq(c-d)x_3^2>0$.
$x_1=x_2=x_3=0$ and $x_4\neq 0$: It follows that $x^tAx= dx_4^2>0$.

Hence we conclude that $x^tAx>0$ for all $x\neq{\it 0}$, that is, $A$ is positive definite.
Comment: Row-reduction (and column reduction) do *not* preserve the characteristic polynomial.
Comment: If it "preserved similarity", then also the char.polynomial. So, no.
Comment: Thanks. This solves the problem(and can help find the determinant).
Comment: Elementary column operations don't help finding eigenvalues.
Comment: Column reduction does not generally give you the eigenvalues directly.  How did you deduce that the eigenvalues of the original matrix are positive?
Comment: Seems true. It preserves determinant and similarity(but not char. poly.), right?
Comment: OK, so then only preserve determinant(product of eigenvalues). Does it preserve the sign of eigenvalues? Seems I need to check my linear algebra textbook once more...
Answer: Note that this matrix is definitely positive semidefinite, since it is the sum of positive semidefinite matrices.  In particular, we can write
$$
A = (a-b)A_1 + (b-c)A_2 + (c-d)A_3 + dA_4
$$
Where the $A_i$ are rank 1 matrices that I claim are "obviously positive semidefinite".  To show that it's invertible, row-reduce.
Comment: I'd say this decomposition is not really obvious.
Comment: Thanks! This decomposition is interesting and I think it may help for further analysis the properties of this matrix.
Comment: @FriedrichPhillip it's not that the decomposition is obvious, but once it's pointed out, I think the implication is clear.
Answer: By Sylvester's criterium $A$ is positive definite if all main determinants are positive. They are $D_1=a>0$, $D_2=b(a-b)>0$, $D_3=c(a-b)(b-c)>0$ and $D_4=d(a - b)(b - c)(c - d)>0$. Hence the matrix is positive definite.
Comment: BTW, how did you find the determinant(so quickly)? from the above row/column operation to upper/lower triangular matrix? Thanks!
Comment: The $1\times 1$ and $2\times 2$ determinants are easy; for the $3\times 3$ I used the [Sarrus rule](https://en.wikipedia.org/wiki/Rule_of_Sarrus). The last one I have guessed :)


Toolbar escondendo um pedaço do textview

Question: Segue código:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
      <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar"
        app:layout_scrollFlags="scroll|enterAlways" />
        <LinearLayout
            android:id="@+id/linearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:orientation="vertical">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <Button
                    style="@style/Widget.AppCompat.Button.Colored"
                    android:id="@+id/anterior"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:padding="30dp"
                    android:text="Anterior"
                    android:layout_marginEnd="16dp"
                    android:layout_marginStart="16dp"
                    android:layout_marginTop="16dp"
                    android:layout_marginBottom="16dp" />
                <Button
                    style="@style/Widget.AppCompat.Button.Colored"
                    android:id="@+id/proximo"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:padding="30dp"
                    android:text="Próximo"
                    android:layout_marginEnd="16dp"
                    android:layout_marginStart="16dp"
                    android:layout_marginTop="16dp"
                    android:layout_marginBottom="16dp" />
            </LinearLayout>
        </LinearLayout>
        <TextView
            android:id="@+id/textview_test"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/linearLayout"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:gravity="center"
            android:text="TextView"
            android:textColor="@color/blue"
            android:textSize="28sp"
            android:textStyle="bold|italic"
            android:layout_marginEnd="16dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp" />
    </RelativeLayout>
</android.support.v4.widget.DrawerLayout>

toolbar.axml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

Segue a foto:

Cor azul = toolbar e cor preto = textview.

Na primeira foto é o que está acontecendo agora, porem atrás do toolbar.
Como posso resolver igual na segunda foto ?
Answer: Esse layout possui o comportamento que você precisa:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <include
            android:id="@+id/toolbar"
            layout="@layout/toolbar"
            app:layout_scrollFlags="scroll|enterAlways" />

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="?attr/actionBarSize">
            <LinearLayout
                android:id="@+id/linearLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:orientation="horizontal">
                <Button
                    style="@style/Widget.AppCompat.Button.Colored"
                    android:id="@+id/anterior"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:padding="30dp"
                    android:text="Anterior"
                    android:layout_marginEnd="16dp"
                    android:layout_marginStart="16dp"
                    android:layout_marginTop="16dp"
                    android:layout_marginBottom="16dp" />
                <Button
                    style="@style/Widget.AppCompat.Button.Colored"
                    android:id="@+id/proximo"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:padding="30dp"
                    android:text="Próximo"
                    android:layout_marginEnd="16dp"
                    android:layout_marginStart="16dp"
                    android:layout_marginTop="16dp"
                    android:layout_marginBottom="16dp" />
            </LinearLayout>
            <TextView
                android:id="@+id/textview_test"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@+id/linearLayout"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:gravity="center"
                android:text="TextView"
                android:textColor="@color/blue"
                android:textSize="28sp"
                android:textStyle="bold|italic"
                android:layout_marginEnd="16dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp" />
        </RelativeLayout>
    </RelativeLayout>
</android.support.v4.widget.DrawerLayout>

O que eu fiz foi agrupar tudo, tirando o toolbar, num RelativeLayout e setando o atributo layout_marginTop para "?attr/actionBarSize".


If correlation between two variables is affected by a factor, how should I evaluate this correlation?

Question: Here is my example. Supose we evaluate a characteristic using two different methods (a and b) and we want to study if both methods performs in a same way. We also know that these two measures have been recorded from two different groups, and the mean values for each one of these groups are highly different. Our data set could be as follows:
a <- c(22,34,56,62,27,53)
b <- c(42.5,43,58.6,55,31.2,51.75)
group <- factor(c(1,1,2,2,1,2), labels=c('bad','good'))
dat <- data.frame(a, b, group)

The association between a and b could be calculated as:
lm1 <- lm(a ~ b, data=dat)
summary(lm1)

Call:
lm(formula = a ~ b, data = dat)

Residuals:
      1       2       3       4       5       6
-13.810  -2.533  -3.106   8.103   7.541   3.806

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -25.6865    19.7210  -1.302   0.2627
b             1.4470     0.4117   3.514   0.0246 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 9.271 on 4 degrees of freedom
Multiple R-squared: 0.7554, Adjusted R-squared: 0.6942
F-statistic: 12.35 on 1 and 4 DF,  p-value: 0.02457

As we can see, it seems to be a high association between both measures. However, if we perform the same analysis for each group separately, this association disappears.
lm2 <- lm(a ~ b, data=dat, subset=dat$class=='bad')
summary(lm2)

Call:
lm(formula = a ~ b, data = dat, subset = dat$group == "bad")

Residuals:
      1       2       5
-6.0992  5.8407  0.2584

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  22.9931    35.1657   0.654    0.631
b             0.1201     0.8953   0.134    0.915

Residual standard error: 8.449 on 1 degrees of freedom
Multiple R-squared: 0.01769,    Adjusted R-squared: -0.9646
F-statistic: 0.01801 on 1 and 1 DF,  p-value: 0.915

and,
lm3 <- lm(a ~ b, data=dat, subset=dat$class=='good')
summary(lm3)

Call:
lm(formula = a ~ b, data = dat, subset = dat$group == "good")

Residuals:
     3      4      6
-2.394  5.047 -2.652

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  34.9361    70.4238   0.496    0.707
FIV           0.4003     1.2761   0.314    0.806

Residual standard error: 6.184 on 1 degrees of freedom
Multiple R-squared: 0.08959,    Adjusted R-squared: -0.8208
F-statistic: 0.09841 on 1 and 1 DF,  p-value: 0.8065

How should we assess the association between the two methods? We should take into account the group factor? Maybe it is a trivial question, but I have doubts about how to deal with this problem.
Answer: This might be a case of locally uncorrelated, but globally correlated variables. The variance in each group might be limited because of group homogeneity, therefore there is no evidence for a relationship within each group. But globally, with the full variance, the relationship can be strong. A schematic illustration of the joint distribution within three groups, and the resulting global joint distribution:

Edit: Your question also seems to be if the global correlation is still "real", even if the theoretical correlation within each group is 0. Random variables are defined on a probability space $<\Omega, P>$ where $\Omega$ is the set of all outcomes (think of different observable persons in your case), and $P$ is a probability measure. If your natural population $\Omega$ includes members from all groups, then: yes, the variables are "really" correlated. Otherwise, if the members of different groups do not form a natural common $\Omega$, but each belong to separate populations, then: no, the variables are uncorrelated.
Answer: Therefore, it is important to evaluate whether the homogeneity of groups is due to low number of data, or actually these groups are quite homogeneous and different. In the first case, we could ensure the presence of a high correlation even when this has not been observed for each group separately.
But what would happen in the second case? If even using a large number of data we could not observe a correlation within each group, we could say that this correlation exist?
Perhaps the value of one of these measures will be only useful for predicting membership in one of the two groups, but not to predict the value of the other measure.


Arithmetic Progression Problem

Question: The sum of 1st six terms of an Arithmetic Progression is 42, while the ratio of its 10th term to its $30$th term is $1:3$.
Calculate the first and the $13$th term of this Arithmetic Progression?
What I'd done yet,
Given that,

Sum of first $6$ terms of the given AP is $42$
$a_{10}$ : $a_{30}$ = $1:3$

So, Let...
According to the ratio, $a_{10} = 1k =k$
$a_{30} = 3k$
We know that,

$S_{n} = n/2(a + l)$    {where, $S_n$= Sum of AP till term $n$, $a$ = First term of AP, $l$ = last term of AP(also known as $a_{n}$) }
$a_{n} = a + (n-1)d$   {where, $a_{n}$ = Any no. of given AP of $n_{th}$ term, $d$ = Common difference of the consecutive numbers of the AP, $n$ = Term no.}

Now I want to know that how can I equate it?
Comment: What have you tried so far? It would be particularly helpful for you to describe your progress on a question like this, so that we can post an answer using the same notation you have already been using.
Answer: In an arithmetic progression $a,a+d,a+2d,...$, the $n$th term is $a+(n-1)d$ and the sum to $n$ terms is $\frac{n}{2}(2a+(n-1)d)$.
If the ratio of the tenth term to the thirtieth term is $\frac{1}{3}$, then $3(a+9d)=a+29d$. If the sum of the first six terms is $42$, then $3(2a+5d)=42)$.
Solve for $a$ and $d$ and then find the first and thirteenth term.
Answer: In airthmatic progression the terms are a,a+d,a+2d,a+3d,.......a+(n-1)d where 6th term is a+5d
and sum of first six terms is equal to 6a+10d.
and in question it is given that (a+9d)/(a+29d) = 1/3
by these two equations we can easily find out a and d and then you can calculate first and 13th term of an airthmatic prograssion.
Answer: General therm of AP is $a_n=a_1+(n-1)d$ and sum of first n-therms is$$S_n=\frac{n}{2}(a_1+a_n)=\frac{n}{2}(2a_1+(n-1)d)$$
from conditions we have
$$a_1+a_2+...+a_6=\frac{6}{2}(2a_1+5d)=42$$and$$a_{10}:a_{30}=1:3$$or
$$6a_1+15d=42$$
$$a_1+29d=3(a_1+9d)$$finally we get the system
$$2a_1+5d=14$$
$$2a_1-2d=0$$
the solutions are$$a_1=d=2$$
Answer: Since $a_{10} : a_{30} = 1 : 3$, we have $\dfrac{a_{10}}{a_{30}-a_{10}}=\dfrac{1}{3-1}$ which implies $a_{10}=\frac{20}{2}d = 10d$ since $a_{30}-a_{10}=(30-10)d$. Therefore $a_1=d$, and so $42 = S_6 = 6d + \frac{6(6-1)}{2} d = 21d$. So, $a_1 = d= 2$.
Answer: A short cut and a symmetrical approach:
$$a_{10}:a_{30}=1:3 \Rightarrow a_n\propto n \Rightarrow a_n=kn\\
S_6=k\sum_{n=1}^6 n=21k=42 \Rightarrow k=2\\
\therefore a_1=2, a_{13}=26\qquad \blacksquare$$
Comment: Just to clarify, I have seen proofs that end in $\Box$ and I have seen proofs that end in $\blacksquare$ as well. What is the *real* way to end it, do you know? The expression $\Box A\Rightarrow B$ reads, *it is provable that $A\Rightarrow B$* so to avoid confusion, perhaps $\blacksquare$ is best, but I see $\Box$ more commonly.

Arithmetic Progression Problem


Clean urls - auto path alias - how to remove accents (Á É Ó Í Ñ ) from the urls?

Question: I´m using Drupal 7.9 and pathauto 7.x-1.0-rc2
I want to remove the accents from the paths and replace them with normal letters
Á=A
É=E
Ó=O
Í=I
Ñ=N

etc.
I'm using a taxonomy field type and node title to build the path:
[node:field_provincia]/[node:title]

resulting into e.g. ávila/mérida
Does pathauto have some kind of hooks that I could use to apply this function?
function removeAccents($str)
{
  $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', ''n', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
  $b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
  return str_replace($a, $b, $str);
}

Comment: Relevant issue in [pathauto's queue](https://drupal.org/comment/7747561#comment-7747561).
Answer: Have you seen transliteration module ?  The project summary says it could be used with pathauto 2.x to use transliteration for URLs.
Comment: But the problem is that it changes all language chars in URL to English ones which look weird. For example רשימה של מדינות בעולם in Hebrew becomes /rshymh-shl-mdynvt-bvlm. The OP is asking how to remove only accented chars.
Comment: This is exactly what I use and it works beautifully.  I had yet another issue with "ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ" while using Drupal's mail function as well and Transliteration cleaned those up too.
Comment: @AgA you can fine tune what it transliterates by hacking the files that come with the module (or overriding, it's OOP if I recall correctly).
Answer: The simplest way to perform this remains transliteration module.
To answer specifically to "Does pathauto have some kind of hooks that I could use to apply this function",
you can use hook_pathauto_alias_alter() :
function YOURMODULE_pathauto_alias_alter(&$alias, &$context){
  $alias = removeAccents($alias);
}

function removeAccents($str){
  $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', ''n', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
  $b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
  return str_replace($a, $b, $str);
}

Just adapt removeAccents() to your specific language needs... You'll find many functions trying to list all kind of accents, see Remove diacritics from a string i.e., but I'm afraid none is universal.
There is also an elegant way to transliterate, using php iconv function, which removes most of the diacritics. If you are getting question-marks in output, it might be convenient to setlocale first. In context  :
function YOURMODULE_pathauto_alias_alter(&$alias, &$context){
  setlocale(LC_CTYPE, 'es_ES');//Spanish Spain i.e
  $alias = iconv('UTF-8', 'ASCII//TRANSLIT', $alias);
}

EDIT : after reading some comments, I found useful to add this:

D8 : transliteration functionality is now part of Drupal 8 core, use hook_transliteration_overrides_alter(&$overrides, $langcode) if yo need some custom overrides.
D7 : seems that transliteration next release 7.x-4.x will be a backport of the codebase from D8 core, including the above hook. In the meanwhile, transliteration module supports language-specific variations (see Language-specific replacements how-to at the bottom of the doc page). And a couple of relevant issues : Add hook to allow customization of character mappings, alter hook for transliteration_clean_filename.
Comment: Thanks .. are those the only accented chars in the world? Do you have working examples of the iconv use case?
Comment: In pathauto settings I've added Â,Ã,Ä,À,Á,Å,Æ,Ç,È,É,Ê,Ë,Ì,Í,Î,Ï,Ð,Ñ,Ò,Ó,Ô,Õ,Ö,Ø,Ù,Ú,Û,Ü,Ý,Þ,ß,à,á,â,ã,ä,å,æ,ç,è,é,ê,ë,ì,í,î,ï,ð,ñ,ò,ó,ô,õ,ö,ø,ù,ú,û,ü,ý,þ,ÿ, but don't know why it's not working.
Comment: Linked: http://stackoverflow.com/questions/3371697/replacing-accented-characters-php and http://stackoverflow.com/questions/465990/how-to-handle-diacritics-accents-when-rewriting-pretty-urls/466117#466117 and http://stackoverflow.com/questions/3635511/remove-diacritics-from-a-string
Comment: @AgA I edited the answer to reflect your comments. Pathauto settings is not the right place to specify accents to clean, as the lone text field is 'Strings to Remove'. You'd better try hook_pathauto_alias_alter() if module transliteration doesn't fit your needs. Clean url is a wide subject if you consider all alphabets, Hindi, Greek, Cyrillic, Hebrew...
Comment: I always use the transliteration module, works like a charm
Answer: As per Kojo's suggestions and and source from here: https://stackoverflow.com/questions/3371697/replacing-accented-characters-php -- I'm using this code which seems to be working fine:
function mymodule_pathauto_alias_alter(&$alias, &$context) {
    removeAccents($alias);
}

function removeAccents(&$str) {
    $unwanted_array = array('Š' => 'S', 'š' => 's', 'Ž' => 'Z', 'ž' => 'z', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E',
        'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ù' => 'U',
        'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'a', 'ç' => 'c',
        'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o',
        'ö' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'ý' => 'y', 'þ' => 'b', 'ÿ' => 'y',
        'G' => 'G', 'I' => 'I', 'S' => 'S', 'g' => 'g', 'i' => 'i', 's' => 's', 'ü' => 'u',
        'a' => 'a', 'A' => 'A', '?' => 's', '?' => 'S', '?' => 't', '?' => 'T'
    );
    $str = strtr($str, $unwanted_array);

}

I've added Turkish and Romanian chars too as in the post comments.
I don't want to use iconv as suggested by Kojo mainly because locale will need to be set and there is added burden to coin the locale string.
Answer: You can use pathauto_cleanstring() for remove the accents character from URL.
function MYMODULE_pathauto_alias_alter(&$alias, &$context) {
  if (isset($context['data']['node'])) {
    // Include the pathauto module.
    module_load_include('module', 'pathauto');
    // Clean up a string segment to be used in an URL alias.
    $alias = pathauto_cleanstring(preg_replace('/\s+/', '', $alias));
  }
}

Comment: I tried your module but its not working
Comment: @Yuri Have you installed transliteration module?


Show that $f_n \rightarrow f$ uniformly on $[0,1]$.

Question: Consider $f$ be a  continuous function on $[0,1]$. Let $\{f_{n}\}$ be a sequence of functions defined by $$f_n (x) = \begin{cases} f(\zeta_k),& x\in[\frac{k}{n},\frac{k+1}{n}),\\
0, &\text{otherwise}.\end{cases}$$ for some $\zeta_{k}\in (\frac{k}{n},\frac{k+1}{n})$.
I want to prove that $f_n \rightarrow f$ uniformly on $[0,1]$.
Answer: Since $f$ is continuous on $[0,1]$ (a compact interval) it is also uniformly continuous, that means for each $\epsilon>0$ there is a $\delta >0$ such that $|f(x)-f(y)| < \epsilon$ for all $|x-y| < \delta$.
Let $\epsilon >0$. Choose $n$ so big that $|f(x)-f(y)| < \epsilon$ for all $|x-y| < \frac 1n$ (i.e. choose $n$ bigger than $\frac{1}{\delta}$ where $\delta$ is the corresponding $\delta$ from above for our $\epsilon$) . Then
$$\sup_{x \in [0,1]} |f_m(x)-f(x)| < \epsilon$$
for all $m \ge n$, because the expression $f_m(x)-f(x)$ is the same as $f(\zeta_k)-f(x)$ for some $\zeta_k$ that satisfies $|\zeta_k - x| < \frac 1m \le \frac 1n$.
Comment: Thanks for your answer. Can I avoid these definition approaches to prove $f_n \rightarrow f$ uniformly?


Iterate plots through the group by pandas

Question: df =

         id_easy    latitude    longitude
level_0
0        6454       11          3
0        6454       12          4
2        2323       23          5
2        2323       23          7
3        25603      13          5
3        141        14          6

Want to plot:

first plot: all long and lat values of id_easy 6454 in one color by showing the first points
second plot: all long and lat values of id_easy 2323 in other color by showing the first points
...

same logic in the len(df)
My try:
for index_in_red in df.index.unique():
    plt.plot(df.loc[df.index != index_in_red,'longitude'],df.loc[df.index != index_in_red,'latitude'] ,
             color='silver', marker='o',linestyle='')

    plt.plot(df.loc[index_in_red,'longitude'],df.loc[index_in_red,'latitude']  ,
              color='maroon',marker='o',linestyle='')
    plt.show()

Desired output:
Comment: What do you mean "by showing the first points"?
Comment: @ScottBoston For example `id_easy` `6454` two couples of geo data. I want to show first couple special, to understand that trip started in that location
Answer: for i in df.index.unique():
    plt.plot(df[df['id_easy'] != i]['longitude'],df[df['id_easy'] != i]['latitude'] ,
         color='silver', marker='o',linestyle='')

    plt.plot(df[df['id_easy'] != i]['longitude'],df[df['id_easy'] != i]['latitude'] ,
         color='maroon',marker='o',linestyle='')
    plt.show()


Apple software update frequency and successor of Software Updates Service

Question: 1) Looking at https://support.apple.com/en-us/HT201222 it seems to me that Apple doesn't have a regular patchday like Microsoft. Is there any?
2) At https://support.apple.com/en-us/HT206871 I read that Apple deprecated their Software Update Service in macOS Server 10.12, but found no further information about the successor and how it works. Can somebody help me please getting more reliable information?
Answer: I found the answers myself and share them for the records:
1) No, there is no regular patchday.
2) The Software Update Service is deprecated and will be removed in future. For the time being it is still available, but hidden. Updates are now handled by the Caching Service (see https://support.apple.com/macos/server and linked pages). It handles updates different to the former Software Updates Service: it is not possible anymore to test and release updates internally. Every macOS client tries to fetch its updates from Apple and is actually served by the transparent Caching Service (which is the nature of a cache). If the client is in another environment it fetches its updates from the Caching Service there. The Caching Service has no clientmanagement like the Software Update Service.
Pro: increased download performance; easier client setup
Con: it has become harder or impossible now to enforce an organisational update policy to ensure stability.


Having an issue with an exception (Stack overflow) being thrown when using an In Order traversal member function

Question: I'm trying to test out my recursive In Order traversal function on a Binary Search Tree but I keep getting an exception thrown (Stack Overflow) when I call that particular function to display nodes on the tree. Am I missing a key part of code?
I've tried looking up how to handle the exception elsewhere but nothing has worked so far. I've also changed the function to a const because I wasn't sure if that's what the compiler (Visual Studio 2017) wanted. I have tested the Pre-Order and Post-Order traversal functions and both work as intended.
In-Order traversal function is a private member function of another class and is called by a separate public function that simply passes the root of the tree to displayInOrder.
void displayInOrder(TreeNode *&root) const {

        if (root == NULL) {

            return;

        }

        else if (root) {

            displayInOrder(root);
            cout << root->value << " ";
            displayInOrder(root->right);
        }
    }

Exception thrown at 0x00C22FE9 in Binary Tree Application.exe:
  0xC0000005: Access violation writing location 0x00CA0F60.
Comment: I always find it amusing when question on StackOverflow is about stack overflow.
Comment: Haha, that's exactly what I thought too!
Comment: `else if (root)` -- You already tested if `root` is NULL.  No need for the `else if (root)`
Answer: displayInOrder(root);

should be
displayInOrder(root->left);

The first version is infinitely recursive because you are calling the same function with the exact same parameters. This leads to stack overflow, as you've found.
Comment: Wow, that worked! I can't believe I missed that! You're a god send!
Comment: @ChristianDominguez If this is Visual Studio, when the exception is thrown look at the Stack Frame. That would tell you a lot.
Comment: Noted. Thanks for the tip! @drescherjm


How to make a .NET ClickOnce application a "published application" via Citrix?

Question: We have a WPF ClickOnce application that needs to be deployed both directly to user-desktops via ClickOnce (which works fine) AND as a Citrix Published Application (not a published desktop).
This citrix forums post has some discussion but no obvious answer to the problem.
If we just 'publish' a ClickOnce URL (from IE, for example) I don't understand how it would work - where does the executable get downloaded to? Even if it works, does every unique Citrix user download the application to unique disk locations?
A ClickOnce link might look like this, and trigger a boostrapper EXE that downloads the latest application EXE before starting it up. This seems difficult to do with the 'published application' model, which I think wants to point to a single, existing EXEcutable to run...
<code>http://webservername/foldername/ApplicationName.application#ApplicationName.application
</code>
Does anyone know if it is definitely impossible? Or if possible, how to make it work?
UPDATE: we are using .NET 3.5 SP1
Answer: Couple things here.
When working with ClickOnce apps, pay particular attention to your profile situation.  As of .NET Framework 3.0 you could not run ClickOnce apps with mandatory profiles.  This was supposed to be remedied in .NET 3.5 but I haven't had the opportunity to verify that claim.
If you're using roaming profiles you have a couple options here.  If you're running your TS in relaxed security mode, each user would download the ClickOnce app if you published it as an argument to Internet Explorer and run it out of their profile.  In enhanced security mode, the TS will not allow the executable to run.
The second option would be to run it out of an Application Streaming profile if you have that feature available to you.  You can then either pre-stage the ClickOnce app during the profile or give the users a streamed IE with relaxed security turned on for that streaming profile only and they would be able to download it themselves.
Comment: This worked! "each user would download the ClickOnce app if you published it as an argument to Internet Explorer and run it out of their profile". Now we are finding that a ClickOnce WPF app is awfully resource hungry on a Citrix server... but that's another story :) THANKS
Comment: Thanks - we normally err on the side of 'high security'. I will have to read up on Application Streaming... what do you mean by "pre-stage"?
Comment: That will make more sense once you understand some basic concepts about Application Streaming.

Here's an article from the Citrix KB: http://support.citrix.com/article/CTX112526 that explains the feature.

Essentially, you do what the user would do upon first-run in such a way that when the next user opens the streamed application, the first-run process is already done for them.
Answer: I am a developer and we create a non clickonce package (set of files) specifically for citrix. Can you please give more details on how you configured IE (passing arguments, running out of their profile etc). I can then hopefully take this to our citrix administrators for them to understand and see feasibility of doing it.
Answer: I have a little Workaround for this:

create a separate Account
Log in into the account and install the clickonce Application
You'll find an *exe-file in the Appdata folder of this user. For me it was in %userprofile%\Appdata\local\2.0{string}{string}{clickoncename}. The path will certainly differ depending on installed application.
Create a new hidden share for this folder and give access to all users that should use the published Application.
publish the *exe-file over the hidden share
be happy that it works! :D


Inline block confirm messages

Question: I have a contact (web)form in my sidebar on my site and I would like to display a custom confirm message when a users submits the form. However, this message should replace the contact form.
I've tried with Inline Messages or with the form-settings (no-redirect), but every solutions just redirects the entire website to the node and displays the message inline. So, that not what I want, obviously...
So, is there a solution where the content of the page remains unchanged, but when submitting the form in the sidebar, only the sidebar refreshes and shows the confirmation message?
Comment: You could also use a modal dialog to show the message (see [Ctools](http://drupal.org/project/ctools)).
Comment: Unfortunately, that's not an option... I need the message to be ìn the block.
Answer: The Webform Ajax module will give you the functionality you describe. Here is a quote about it (from the module's project page):

... adds AJAX support to Webform (3.0 and above).
As a first step it focusses to simply add form AJAX paging and submit. Form submissions get ajaxified including prev/next pages. Especially for multipage forms, this leads to faster loading (less data transfer), better usability and finally smaller server load.

Inline block confirm messages


Expected Value of Binomial Distribution

Question: What is the expected value of the absolute value of the difference between the number of incoming tails and the number of incoming heads  when a coin is tossed 5 times?
Here is what I think :  Let  $X$  is random variable of number of incoming heads then
$p=\frac{1}{2}$ and $n=5$ so $X\sim Binom(5,\frac{1}{2})$
$X$ and $Y=5-X$ ($Y$ is random variable of number of incoming tails) then $E(K)=E(\left|X-(5-X)\right|)=E(\left|2X-5\right|)=E(2X-5)=2E(X)-5=2.\frac{5}{2}-5=0$ where $K=\left|X-Y\right|=\left|2X-5\right|$ and $E(X)=n.p=5.\frac{1}{2}=\frac{5}{2}$
But the right answer is $\frac{15}{8}$. Where am I making a mistake? Any help will be appreciated.
Comment: Nope , but stated in problem with paranthesis.
Comment: That's weird, I keep  getting $\frac{25}{3}$
Comment: Yes but the truth is $\frac{15}{8}$  :( @Alex
Comment: Did you get it?
Answer: Since $X\sim Binom(5,\frac{1}{2})$, the range of $X$ is $\{0,1,2,3,4,5\}$, which implies that $2X - 5$ is not necessarily always positive. Therefore in your proof, it is not true that $E(\left|2X - 5\right|) = E(2X - 5)$.
Comment: I would assume that you prefer to work out the problem on your own, but feel free to let me know if you would like to have a corrected solution :)
Comment: Calculation the expected value from the scratch is done in 90 seconds ...
Answer: Your random variable $Z=|X-Y|$ can take only the values
$$\{1,3,5\}$$
with probabilities
$$\left\{\frac{20}{32};\frac{10}{32};\frac{2}{32}\right\}$$
This because
$Z=5$ when you get 5 consecutive tails (or heads)
$Z=3$ when you get 4 tails (or heads)
$Z=1$ when you get 2 tails (or heads)
No other situations are possible.

Thus its expectation is
$$\mathbb{E}[Z]=1\times \frac{20}{32}+3\times\frac{10}{32}+5\times\frac{2}{32}=\frac{15}{8}$$

Expected Value of Binomial Distribution


Como somar valor de variáveis com o valor de uma variável salva no userdefaults

Question: vou tentar ser objetivo, preciso salvar uma variável que o valor que estiver guardado dentro vai ser o texto de uma label e esse valor é alterado quando é realizado um input de outra variável. Por exemplo:
Variável saldo tem o valor de 50.0, o usuário consegue realizar um input que é salvo na variável recarga, vamos dizer que o valor da recarga foi 70.0, então eu preciso que seja calculado ao valor já existente na variável saldo e atualizar o label, que no caso ficaria em 120.0.
Não tenho muita experiência com OO e estou com muitas dificuldades, acredito que preciso ler primeiro o valor salvo no userdefaults da variável saldo e depois incrementar com o valor da variável recarga, desculpa se estiver sendo leigo demais, alguém poderia me dar uma direção? Pois o usuário conseguir realizar varias recargas e nisso o valor do saldo é alterado
Answer: Ficaria mais ou menos assim...
<code>var saldo = NSUserDefaults.standardUserDefaults()

let valorInicial = "50"
saldo.setObject(valorInicial, forKey: "Valor")

//Salve a informação
saldo.synchronize()

//Carregar Informação
var VL = NSUserDefaults.standardUserDefaults()
let Dados = VL.objectForKey("Valor")
//Some os valores e converta
var inteiros = Int(Dados) + Int(input.text) //input é o nome do campo que o
//usuário irá digitar o segundo valor.

print(Inteiros)

//Make some changes
let novoValor = Inteiros
NV.setObject(novoValor, forKey: "Update")
//Lembre de salvar
NV.synchronize()
</code>


Objective-C to Swift: Facebook iOS API requestUserInfo method

Question: Hi I am trying to figure out how to rewrite this in swift:
<code>- (IBAction)requestUserInfo:(id)sender
{
  // We will request the user's public picture and the user's birthday
  // These are the permissions we need:
  NSArray *permissionsNeeded = @[@"public_profile", @"user_birthday", @"email"];

  // Request the permissions the user currently has
  [FBRequestConnection startWithGraphPath:@"/me/permissions" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
      if (!error){
        // Parse the list of existing permissions and extract them for easier use
        NSMutableArray *currentPermissions = [[NSMutableArray alloc] init];
        NSLog(@"The fucking class is: %@", [result class]);
        NSArray *returnedPermissions = (NSArray *)[result data];
        for (NSDictionary *perm in returnedPermissions) {
          if ([[perm objectForKey:@"status"] isEqualToString:@"granted"]) {
            [currentPermissions addObject:[perm objectForKey:@"permission"]];
          }
        } // cut cut here

}
</code>
EDIT:
I was having trouble trying to get the required data out of the FBGraphObject but figured it out after some further inspection. I have posted the swift version below so that people can just cut and paste it and get on with using swift. Hope it saves someone some time.
Answer: Here:
<code>@IBAction func requestUserInfo(sender: AnyObject){
    // These are the permissions we need:
    var permissionsNeeded = ["public_profile", "user_birthday", "email"]

    // Request the permissions the user currently has
    FBRequestConnection.startWithGraphPath("/me/permissions", completionHandler: {(connection, result, error) -> Void in

        if error == nil{
            // Parse the list of existing permissions and extract them for easier use

            var theResult = result as? [String:[AnyObject]]
            var currentPermissions = [String]()
            let returnedPermissions = theResult?["data"] as [[String:String]]

            for perm in returnedPermissions {
                if perm["status"] == "granted" {
                    currentPermissions.append(perm["permission"]!)
                }
            }

            // Build the list of requested permissions by starting with the permissions
            // needed and then removing any current permissions
            println("Needed: \(permissionsNeeded)")
            println("Current: \(currentPermissions)")

            var requestPermissions = NSMutableArray(array: permissionsNeeded, copyItems: true)
            requestPermissions.removeObjectsInArray(currentPermissions)

            println("Asking: \(requestPermissions)")

            // TODO PUT A POPUP HERE TO TELL WHAT PERMISSIONS WE NEED!

            // If we have permissions to request
            if requestPermissions.count > 0 {
                // Ask for the missing permissions
                FBSession.activeSession().requestNewReadPermissions(requestPermissions, completionHandler: {(session, error) -> Void in
                    if (error == nil) {
                        // Permission granted, we can request the user information
                        self.makeRequestForUserData()
                    } else {
                        // An error occurred, we need to handle the error
                        // Check out our error handling guide: https://developers.facebook.com/docs/ios/errors/
                        println("error: \(error?.description)")
                    }
                })
            } else {
                // Permissions are present
                // We can request the user information
                self.makeRequestForUserData()
            }

        } else {
            // An error occurred, we need to handle the error
            // Check out our error handling guide: https://developers.facebook.com/docs/ios/errors/
            println("error: \(error?.description)")
        }
    })
}

private func makeRequestForUserData() {
    FBRequestConnection.startForMeWithCompletionHandler({(connection, result, error) -> Void in
        if (error == nil) {
            // Success! Include your code to handle the results here
            println("user info: \(result)")
        } else {
            // An error occurred, we need to handle the error
            // Check out our error handling guide: https://developers.facebook.com/docs/ios/errors/
            println("error: \(error?.description)")
        }
    })
}

// Show an alert message
func showMessage(text : NSString, title : NSString){
    var alert = UIAlertController(title: title, message: text, preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
    UIApplication.sharedApplication().delegate?.window!?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
}
</code>
Comment: "An active access token must be used to query information about the current user


Fazer busca na database com dados encriptados

Question: Possuo uma database onde os dados inseridos são encriptados através de uma função escrita em PHP, essa função encripta e desencripta. Preciso fazer busca nessa tabela.
Por exemplo, eu busco por "BRASIL", mas na tabela o "BRASIL" está encriptado como: cdlddzfqm3b3szyxvvk2u3n6lzb1ut09
Uso PHP e MySQL, e para fazer as buscas uso LIKE % %
Answer: Não foram dados muitos detalhes mas pela forma descrita acredito que seja só criptografar o que você deseja procurar, aí a comparação será feita do dado criptografado com outro dado igualmente criptografado.
$query = "select * from tabela where campo = " . crypt("BRASIL");

Coloquei no GitHub para referência futura.
Isto pode não funcionar dependendo de alguns fatores como a a forma como é feita a criptografia, configuração do banco de dados para comparação (collation), etc. Mas acredito que você está usando uma forma simples e esta forma funcionará.
Com LIKE em condições normais não é possível, pelo menos desconheço uma forma. Talvez seja possível com algum módulo adicional ao MySQL mas desconheço algum que faça isto. Na verdade não sei se é uma boa ideia fazer isto.
Talvez seja possível criar uma função para o MySQL (possivelmente em C) que possa ser usado no lugar do ou com o LIKE para fazer esta busca. nem vou especular muito em cima disto porque não parece ser a melhor das ideias.
Uma possível solução horrorosa seria pegar todos os dados criptografados, descriptografar no PHP e fazer a seleção. É mais fácil de fazer que a solução anterior mas pavorosa para usar.
Achei essa solução no SO para criptografia builtin do MySQL. Não saberia dizer todas as limitações exceto a performance já citada lá.
select * from tabela where aes_decrypt(campo, salt) like '%BRASIL%'

Coloquei no GitHub para referência futura.
Obviamente isto só funcionado se o dado está gravado da mesma forma.
Veja outras funções de criptografia builtin do MySQL.
Comment: Poise, porem preciso usar o LIKE e nao funcionaria este metodo.
Comment: Só que você não colocou isto na pergunta.
Comment: Perdao, eu omiti detalhes, ja arrumei. Irei ler sua resposta.
Comment: Dessa forma só seria possivel com esse tipo de encriptaçao correto?
Comment: Poderia ser com qualquer tipo de criptografia *builtin*.
Comment: Eu uso uma funçao em php que encrypta com base64 e chaves
Comment: Como falei, aí complicaria muito, teria que usar soluções extramente complexas. Fora que Base64 não criptografa nada.
Comment: Veja, AES-256-CBC é o metodo que a funçao utiliza
Comment: Mas não é a função *builtin* do MySQL. Pelo menos de acordo com o que você disse.
Comment: Oi, fiz minhas adaptações e cheguei a uma duvida, estou inserindo agora usando a funçao AES do mysql, e em seguida usando o TO_BASE64 para "encapar" o código, tentei usar agora `select * from tabela where FROM_BASE64(aes_decrypt(campo, salt)) like '%BRASIL%'` porém nao funciona, por que?
Comment: Não sei dizer, não há informações suficientes http://pt.stackoverflow.com/help/mcve. Note que este já um problema diferente do que você postou originalmente na pergunta.


How should I upgrade debian/xen machines from etch to lenny

Question: I manage a server that currently runs Debian/Etch, and Xen 3.0. Each virtual machine is also running Debian/Etch.
Lenny is the next release of Debian, and includes Xen 3.2. Unfortunately, I believe there is no automatic upgrade path (via dist-upgrade) between Xen 3.0 and Xen 3.2. (Xen 3.0 is listed as an obsolete package in the lenny release notes).
What steps should I follow to end up with the server running lenny/xen3.2 and the virtual machines running lenny?
Comment: I want to use official debian packages, so I can benefit from debians general security update management, etc.

So yes, I am opposed to building Xen from source.
Comment: Are you opposed to building Xen from source, or using the official release tarballs? I know its a tricky question.
Answer: I was able to migrate a Debian Etch/Xen 3.0 server to Lenny/Xen 3.2 using dist-upgrade. All apt-get did was download the appropriate packages and install them. After making sure the grub config is correct and will be booting 3.2 all of my paravirtual machines booted up. All of the PV machines are Gentoo so I can't comment on the client upgrade for Debian but it shouldn't be that difficult. I did have some issues with an HVM machine and had to rebuild it.
Comment: On my etch setup, the apt-get dist-upgrade did not touch xen, leaving 3.0 in the lenny image. Unfortunately, xen 3.0 was dependent on python 2.4, and lenny replaces this with 2.5. This resulted in machine that could no longer boot any xen vms. The issue appears to be a problem for many folks on the interweb. I wonder why it did not impact your configuration?
Comment: Lenny still has python 2.4, it's just no longer the default.  Install xen 3.2 package by hand and remove the 3.0 ones.
Answer: I find changing Xen packages on the fly extremely risky. Since this is virtualization, you should build a new lenny Xen 3.2 server (or maybe 3.3 or 3.4 from source since it's out), do a migration test with a copy of your actual domains and then update your actual server to see if it works. This allows you to be on the safe side of things and avoid a potential server crash/reinstallation/downtime.
I have had several bad experiences so I tend to try to avoid these updates unless really necessary.
Answer: I have performed the same upgrade, and have taken some notes:
Start with the guests:

dist-upgrade
Install packages. Some scripts I used had removed udev, so had to reinstall it.
aptitude install udev  linux-modules-2.6-xen-amd64
Add the following to /etc/inittab, otherwise you lose your xm console option (Then no ssh means no access without manual mount & modify)
0:2345:respawn:/sbin/getty 38400 hvc0

I shut down guests at this stage, until dom0 reboot. This may not be suitable for all, but I do to be on the safe side.
Continue with host:

dist-upgrade
Have all relevant packages installed, make sure xen package versions are all 3.2
aptitude install xen-utils bridge-utils xen-hypervisor linux-image-xen-amd64 linux-modules-xen-amd64
Check grub menu.lst
Check domU configs and update them with new kernel
Reboot
Comment: did you observe dist-upgrade migrating xen from 3.0 to 3.2 on your setup? That is not what happened for me :-(
Comment: I guess the lack of metapackages(xen-hypervisor etc.) prevented that upgrade, so the second step in the upgrade of dom0 takes care of it.


How to get CMake's ExternalProject_Add to work in Visual Studio (git-submodule problem)?

Question: I am trying to build Pangolin to build directly on Windows 10 in Visual Studio 2017.
Pangolin's CMake involves the following command:
ExternalProject_Add( __glew
  PREFIX "${CMAKE_CURRENT_BINARY_DIR}/glew"
  GIT_REPOSITORY https://github.com/Perlmint/glew-cmake.git
  GIT_TAG 7574ab4d00b683e56adbfdec7da636529dfe65d8
  INSTALL_DIR ${CMAKE_INSTALL_PREFIX}
  CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX}
             -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
             -DCMAKE_C_FLAGS_RELEASE=${CMAKE_C_FLAGS_RELEASE}
             -DCMAKE_C_FLAGS_DEBUG=${CMAKE_C_FLAGS_DEBUG}
             -DCMAKE_C_FLAGS_MINSIZEREL=${CMAKE_C_FLAGS_MINSIZEREL}
             -DCMAKE_C_FLAGS_RELWITHDEBINFO=${CMAKE_C_FLAGS_RELWITHDEBINFO}
)

When this code is run, I get the following error:
fatal: 'submodule' appears to be a git command, but we were not
able to execute it. Maybe git-submodule is broken?

My analysis shows that this happens during the execution of the following generated CMake code (from build-dir/external/glew/tmp/__glew-gitclone.cmake):
execute_process(
  COMMAND "C:/Program Files/Git/mingw64/bin/git.exe"  submodule update --recursive --init
  WORKING_DIRECTORY "C:/Users/scrambledusername/Garage/Pangolin/build/external/glew/src/__glew"
  RESULT_VARIABLE error_code
  )
if(error_code)
  message(FATAL_ERROR "Failed to update submodules in: 'C:/Users/scrambledusername/Garage/Pangolin/build/external/glew/src/__glew'")
endif()

In other words, the command git submodule update --recursive --init results in an error. However, it does not result in an error when run manually via Git Bash.
Some research (also here in the related commits and here) shows this may be related to either the git path or the path with the git-submodule script (C:\Program Files\Git\mingw64\libexec\git-core for me) should be added to system path. Prepending these to the system path (for system OR user) didn't affect the outcome (restarted system, VS just to make sure new paths were registered). I also made sure to the best of my abilities that the script file itself has run permissions for any user (are there caveats to this?).
Copy/pasted from cmd:
C:\WINDOWS\system32>echo %PATH%
C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\mingw64\libexec\git-core;C\Program Files\...

Does anyone know how to get this working or have any suggestions?
Current workaround: set BUILD_EXTERN_GLEW=OFF in CMake and manually check out and build the version of GLEW Pangolin needs based on its CMake.
Versions:

git 2.23.0.windows.1
VisualStudio Community 2017 15.9.16
CMake 3.15.3
Pangolin 25159034e62011b3527228e476cec51f08e87602 (latest commit to master at time of writing)

[EDIT (additional info)]

I got the same results when running cmake from Git Bash, command
prompt, or via CMake-gui.
I got a perfect build on another machine with older
versions of both Git and CMake.
Answer: I was able to work around this problem by running cmake from normal command prompt instead of git bash. Seems like git bash produces non-ascii paths which causes some git commands to fail. (see https://stackoverflow.com/a/58192041 - hopefully gets fixed in git 2.24)
Comment: Thank you for the tip, hopefully it helps someone. Unfortunately, in my case, running CMake from git bash, command prompt, or git-gui yields the same error when I try to build the external projects in VS 2017.
Comment: Yes. This. This is exactly what worked for me. FSCK VISUAL STUUDIO.


How do I use the jQUERY Ajax to call the JSP in different port?no response when put in the diffrent directory

Question: <code>The html is on the
C:/xampp/htdocs/load/index.html
The jsp is on the
C:/xampp/tomcat/webapps/ROOT/jspmysql/load.jsp

the code in the index.html is as follow:
ajax({
type:"GET",//POST cannot work when the two files in the same tomcat directory.I donnot know why?
dataType: 'jsonp',
//I chang this to "json" will work well when I put the two files in the same tomcat directiory and use the http://localhost:8080/index.html.But not the "jsonp".
//json and jsonp don't work and get the ajax error message.
contentType: "application/json; charset=utf-8",
data: {
Esites:123,
Ssites:456
},
url: 'http://127.0.0.1:8080/jspmysql/load.jsp',
error: function(xhr) {
alert('Ajax request error');
},
success: function (response) {
alert("succeed");
alert("suceed="+response.msg);  // do stuff
},
complete: function () {
alert('After Send'); //this was fired
}
});
the load.jsp is as follows:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html;charset=utf-8" %>
<%
request.setCharacterEncoding("UTF-8");
String es = request.getParameter("Esites");
String ss = request.getParameter("Ssites");
out.println("{\"msg\": \"newsvgtemple.svg\",\"Esites\":\""+es+"\", \"Ssites\":\""+ss+"\"}");
%>
</code>
But when I run the index.html
I got the error function.
How do I fix the situation?Is it the cross-domain question? The different can be solve on the http://blog.yam.com/u9323523/article/25178591 php and jsp work together.Can I do the same thing on the xampp?
Answer: First of all, are you sure that your java server is running on port 8080?  If so, then what you have here is correct for calling the JSP.
The 500 - Internal Server Error means that there was some error on the JSP page, not the port you're calling it on.  Try calling the JSP page without jQuery, in another browser window, and see what output you get.  If it is still a 500 error, then you have a coding problem in your JSP, not with your jQuery.
Comment: Thanks for your reply!I try to put the two files in the same tomcat directory! It can work well when I change the "jsop" to "json".But when I put the two files in the different directory, such as above metioned.It will fire the error function(whenever the "json" or "jsonp". I cannot understand how to fix it.Can you give me another suggestion.Thanks a lot.
Comment: Okay, I see your problem a bit more clearly now. I wasn't aware that you were trying to access them from across domains. The JSONP request should be taking care of that.  Can you put some debugging code into the .JSP page to log what's happening there, or is it simply not firing any code at all in that file?
Comment: I fix my jsp file at the last out.println.The XMLHttpRequest page is nothing on firebug when I put them in different directory(different port?80 and 8080);But when I use the json(not the jsonp) it works well in the same port 8080.I dont know how to explain my question and where to put the debug....As nothing happend just fire the error function "Ajax request error".


Programmatically enable the entity view display

Question: I would like to programmatically enable the Layout Builder module. I  followed the instructions given on Layout Builder — building Drupal 8 layouts, but they don't seem to work. They might be outdated for Drupal 9.1. Specifically, I'm having a hard time getting the following piece of code to work.
$entityViewDisplay = \Drupal::entityTypeManager->getStorage('entity_view_display')
  ->load('ENTITY_TYPE.ENTITY_BUNDLE.VIEW_MODE');

Can anyone help me understand it? I just keep getting a NULL result.
Answer: I figured it out. You can enable Layout Builder by running the following code in a custom module:
$entity_type = 'node';
$content_type = 'article';
$view_type = 'default';

\Drupal\layout_builder\Entity\LayoutBuilderEntityViewDisplay::load("{$entity_type}.{$content_type}.{$view_type}")
  ->enableLayoutBuilder()
  ->setOverridable()
  ->save();

Hopefully this helps someone else. Having to do it via the UI is painful if you have a lot of content types. I'm actually surprised this isn't a Drush command yet. Oh well.
Source: https://www.drupal.org/project/drupal/issues/3158916


when to use PCA in this scenario

Question: I have a feature matrix n by p, where n is small.
I want to do leave-one-out cross validation (LOOCV).Should I apply some dimension reduction technique (like PCA) for once at the very beginning, and perform LOOCV based on the new feature matrix, or apply PCA during each loop of LOOCV (so I get different features matrices in different loop)?
Comment: what you mean by SVD?
Comment: I changed it into PCA.
Answer: I think you have to do it without the sample you are assessing.  In a real scenario when you are using your technique (I don't know if it is classification, regression, etc) the incoming samples will not be in your dataset and thus you will be dealing with something not perfectly fit by your example.  By leaving it in you are effectively overfitting your eigenvectors to contain some of the variance in the sample you are attempting to validate.
Comment: But I just want to decide the optimal dimension k via PCA. Is it more convenient to do it once?
Comment: Its more convenient, but it less correct.  You could run PCA with all of your data initially and determine the cutoff point for whatever level of variance captured you want and then use that K through your cross validation.
Comment: It sounds like a trade-off. Is there any way to show how much it will overfit the data?
Comment: The only tradeoff that I see is the extra time taken to re-calculate PCA, which isn't really that important.  What you could do to see how overfitted it is would be to run it with both methods, the entire dataset and the dataset minus the sample you are considering and see how the results compare.
Comment: IMHO there is no way to know the extend of the bias without measuring it for the actual problem (including the chosen model compexity).
Answer: You need to recalculate the PCA for each of the CV surrogate models. Acutally the same already applies to possible previous pre-processing steps that use more than just one case for their calculation (e.g. centering, variance scaling).

But I just want to decide the optimal dimension k via PCA. Is it more convenient to do it once?

More convenient, maybe, but the result will be overfit as @aplassard explains. This means that you cannot get the correct $k$ without recalculating the PCA: doing the PCA on the whole data will yield too high $k$. This will be particularly serious with small $n$.

When optimizing the model complexity, in theory a constant optimistic bias does not hurt the decision. However, in practice, the optimistically biased "shortcuts" I've encountered so far are not even close to constant but point towareds too high model complexity.
You say that you are in a small $n$ situation. In that case, is there any chance that you could fix $k$ for the PCA by your knowledge about data and application? In small sample size situations, two things happen

You likely do not have enough samples to do the model comparisons necessary for the optimization (fixing of $k$).
But nevertheless attempting to do this means that you need a second, outer (independent) validation, thus splitting your data again. Unless, of course,  you'll validate against a data set that you don't have before.

For what it is worth, for the data sets I usually work with (spectroscopic classification, p ca. 10² - 10³, n < 100, sometimes even n < 10 (but 100 - 1000 measurements/rows per patient/batch/case) not recalculating the PCA within the CV loop underestimates the error typically by a factor of at least 2 - 3, and I've seen "perfect" classification internally being only 80 % or even 65% with proper separation of test and training data in the crossvalidation.
Comment: what if n is considerably large? Is it the same conclusion?
Comment: @OMG: If n is large enough then PCA with test data == PCA without test data, and it doesn't matter. However, you'd need to show that this is the case, and for that again you need to do the proper calculation (PCA for each of the surrogate models). The one thing that  genuinely  changes is that you may actually be able to get a statistically meaningful model comparison: you can afford the nested validation/double splitting.

when to use PCA in this scenario


Creating a double array with 3 million elements

Question: I am trying to create an array of doubles with 3 million random elements:
#include <iostream>
#include <cstdlib>
#include <random>
#include <ctime>

using namespace std;

int main(int argc, const char * argv[]) {

    // generating random numbers
    mt19937 rng_engine(0); // seed = 0
    uniform_real_distribution<double> dist2(0,10);

    clock_t begin = clock();

    // create a random 2d array 1 million x 3
    double coords[1000000][3];
    for (int i=0; i<1000000; i++) {
        for (int j= 0; j<3; j++) {
            coords[i][j] = dist2(rng_engine);
            //cout << "i = " << i << ", j = " << j << ", val = " << coords[i][j] << endl;
        }
    }

    clock_t end = clock();
    double elapsed = double(end - begin) / CLOCKS_PER_SEC;

    cout << "elapsed: " << elapsed << endl;

    return 0;
}

When I try to run this in Xcode, I get EXC_BAD_ACCESS (code=2, address=0x7fff5e51bf9c). I tried to compile it and run it in the command line, which gave Segmentation fault: 11. When I change the array size to [100000][3], making the number of elements 300,000, the code runs. What I don't understand is why is it a problem to have 3 million doubles. Wouldn't the array size be 24 MB? (8 bytes * 3,000,000 = 24 MB) What am I missing?
Comment: You should dynamically allocate huge arrays (stack space is limited)
Comment: If you declare it as global variable (outside main()) it will work.
Answer: You're almost certainly overflowing the stack.
Obvious choices to avoid that would be to make the array static (doesn't really change much when it's in main, but typically allocates it differently) or (usually better) use an std::vector instead.
Comment: Thanks. I'm really new to this, could you suggest some reading? What difference does `static` make?
Comment: `static` makes it have static lifetime (like a global) instead of lifetime local to the function in which it's defined. In the case of `main`, the difference in lifetime is almost unnoticeable--but it still means it's allocated statically instead of on the stack.
Answer: double coords[1000000][3];

This is way too big for the stack. Use a std::vector instead,
std::vector<double> coords(1000000 * 3); // flatten vector

or
std::vector<std::vector<double>> coords(1000000, std::vector<double>(3));

Answer: You need to dynamically allocate huge arrays with malloc or calloc since declared variables are stored in the stack, which has limited size. malloc or calloc allocate heap space instead.
Comment: There's almost never a good reason to use `malloc` or `calloc` in C++ (and this doesn't seem to be one of the rare cases where it could make some sense).
Comment: @JerryCoffin It works just as well. Im sorry my background is in c programming and I know little of other methods. But I know that malloc and calloc work in c++
Comment: They work, but not even close to "just as well". Just for one obvious example, exception safety is nearly impossible to achieve unless you wrap them in a `vector`-like class. In addition, in C++ they require ugly, error-prone casts.
Comment: @JerryCoffin I guess a vector class is easier since you don't have to worry about freeing them by hand and exception handling. But malloc and calloc definately work in c++, so my answer does solve the asker's problem, just not as easily, no?
Comment: They solve this specific problem, at the expense of introducing others in its place, so it's not really fixing the problem, just replacing one problem with several others.
Comment: @JerryCoffin out of curiosity, what would be some of the problems introduced by this other then have to handle freeing and error handling by hand?
Comment: You also have to add a cast because they return `void *` and (unlike in C) you can't convert `void *` to other pointer types without a cast. You also end up with readability problems because correct usage isn't just `a = malloc(size);`, but has to always check for it returning a null pointer. That leads to the fact that you're mixing return error codes with exception handling, which tends to be ugly, unreadable, and hard to reason about (not to mention being all too easy to ignore error returns).
Answer: 24 mb is way above the typical stack size. You are walking off your stack.
Try allocating dynamically or using a container class (it will internally allocate dynamically).


Adding a quantity to multiple indexes in an array (java)

Question: So my problem is that I have a vending machine. The vending machine has slots with a max number of items per slot.
If I run the restock method with a product name and quantity, I need to add the quantity to the product supplied. I have a string array, and a stock array, for which the index is the slot number.
The problem is that if I have the same named product twice in the list, the first index of the product will reach the max, but the second instance of the product is always 1 less than I need it to be.
Ex.
I have candies at slot 0 and 1 with a max of 10.
running restock(candies, 8) then restock(candies, 5) should provide 10 in slot 0 and 3 in slot 2. But instead I get 10 and 2.
public void restockProduct(String product, int quantity) {
    int index = -1;
    // If there is nothing to add, quit
    if (quantity == 0) {
        return;
    }
    for (int i = 0; i < products.length; i++) {
        //Find location of product
        if (products[i].equals(product)) {
            index = i;
            if(stock[index] <= max)
            break;
        }
    }
    if(index >=0){
        stock[index]++;
        restockProduct(product, quantity-1);
    }

THanks
Comment: You shouldn't have two arrays. You should have a `Item` array, where `Item` is a class you write. Java is an OOP language, embrace it and you'll get self-documenting and easy to maintain code.
Comment: I agree, but I need to do it this way for a class
Answer: It seems with this code and a max of 10 that you would get 11 in the first match and 2 in the second match, because of this line:
if(stock[index] <= max)

If the slot is already full, equal to max, then you are still choosing it for incrementing later.  Try strictly less than.  Additionally for clarity, combine the two if conditions.  You'll only want to choose the slot if the product name matches and it's not full.
if (products[i].equals(product) && stock[i] < max) {
     index = i;
     break;
}

You'll also have to handle the case when no slot matches both conditions.
Comment: I messed around with the conditionals quite a bit, as being off by 1 is usually an indication of bad conditionals. But doing this gives me 9 in slot 0, and 3 in slot 2.
Comment: Your off-by-one error must be elsewhere.  Mocking up your code produces values 10 and 3 with the `<` operator.
Answer: You're thinking way too hard on this one
public void restockProduct(String product, int quantity)
{

    for (int i = 0; i < products.length; i++)
    {
        //Find location of product
        if (products[i].equals(product))
        {
            int diff = max = stock[i];
            stock[i] += diff;
            quantity -= diff;
        }
    }
}

Comment: THere has to be more to it than that. DOn't i need to take into account the quanitiy being <0 and stuff
Comment: @user2133337  that all depends on what the requirement is.  If you add negative quantities, it will do just that(subtract)


How do I fix these errors?

Question: I've been currently developing a module, which was working fine. Now, the console throws an error every time I click a link in the administrator menu.

For example, when I click the Content link, I get this error.

When I click the Dashboard link, I get this error.

I added the jquery-1.11.2.min.js file with hook_init() to make the module work.
function myid_init () {
  drupal_add_js(drupal_get_path("module", "myid") . "/js/jquery-1.11.2.min.js");
}

How can I fix these errors?
Answer: I would wager a guess it's because (or related to) Drupal including it's own version (1.4) of jquery, and you trying to include a second copy at version 1.11.2 - some functionality is deprecated in later versions of jquery, items that drupal and its modules are expecting to find. If you need to increase the version use something like the module Jquery Update instead of your own add_js and see if that solves it.

Upgrades the version of jQuery in Drupal core to a newer version of
jQuery.
Updates...
Drupal 5 to jQuery 1.2.6
Drupal 6 to jQuery 1.3.2
Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x and jQuery UI 1.10.2
Drupal 8: TBD

How do I fix these errors?