Android Organise overlapping views?

Question: I have a RelativeLayout which has 4 LinearLayouts (that are overlapping one another). Is there a way for me to better organise them? I mean create a separate xml for each and them link all the xml's back to the container?
Im not sure if ViewPager is the right way to go, because in the code im animating the Alpha value of these views, and need all of them to be while the Activity runs.
For now the main activity is pretty simple, but later on Im gonna be adding a few TextViews/EditTexts etc, so its gonna get really confusing to manage it all.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/details_pure_white"
        android:orientation="vertical" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout1b"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/details_pure_green"
        android:orientation="vertical" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="right"
        android:background="@drawable/settings_pure_white"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#28bda9" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2b"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
         android:gravity="right"
        android:background="@drawable/settings_pure_green"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/TextView01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Large Text"
            android:textColor="#FFFF"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>

Comment: Okay, just found an option in the Palette that allows you to add other XMLs statically. Will update if its a solution
Answer: Used this thing called <include>
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >

    <RelativeLayout
    android:id="@+id/relativeLayout2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true" >

    <include
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        layout="@layout/ref_details_green_activity" />

    <include
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        layout="@layout/ref_details_white_activity" />

    <include
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        layout="@layout/ref_settings_green_activity" />

    <include
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        layout="@layout/ref_settings_white_activity" />
    </RelativeLayout>
</RelativeLayout>

Android Organise overlapping views?


SPF and Gmail as mail client

Question: I have mail server hosted by some "3rd party provider" (https://www.neoserv.si/) and I want to use Gmail as email client. In Gmail I have set POP3 to copy all incoming messages and IMAP so I can send messages directly from Gmail.
I'm not sure if I need to configure SPF for Gmail client, since I'm sending messages over IMAP?
My current SPF record contains only ip of my "3rd party provider". Is this enough?
Answer: You do not need to make any alterations to your SPF records.  The mail is still being sent by the "3rd party provider" and not by the Gmail Mobile App on your phone/device.
All IMAP/POP are responsible for is the moving of messages between the 3rd party mail server and your mobile device; they aren't handling sending mail to other mail servers (which is when SPF comes into play).
So just leave your already working SPF records alone, you'll be just fine.

SPF and Gmail as mail client


Is $\sin^2 x$ uniformly continuous on $\mathbb R$?

Question: Is $\sin^2 x $ uniformly continuous on $\mathbb{R} $ ? I think it might be because it is really similar to $\sin( x) $
Comment: Use the periodicity.
Comment: Or, if you know calculus, use the fact that the derivative is bounded.
Answer: Yes, every continuous periodic function $\mathbb R\to \mathbb R$ is uniformly continuous.
Comment: Proof outline for OP: consider the restriction to the closure of a fundamental domain. As a continuous function on compact set, we get uniform continuity. By periodicity, we may use the same $\delta$ for each $\epsilon > 0$ on all of $\mathbb R$ that we used on the restriction.
Answer: Let $x \not =y$, reals.
$|\sin ^2 x -\sin^2 y| = $
$|\sin x - \sin y||\sin x+\sin y| \le $
$2|\sin x -\sin y| = 2| \cos t||x-y| \le$
$2|x-y|.$
Choose $\delta =\epsilon/2$
Used : MVT
$\sin x -\sin y = (x-y) \cos t$, where
$t \in (\min (x,y), \max (x,y)).$


Get/Set for a Private Static Collection?

Question: I've defined a class with the following property:
 private ObservableCollection<Job> allJobs;

Access is defined as follows:
    public ObservableCollection<Job> AllJobs
    {
        get
        {
            return this.allJobs;
        }
        set
        {
            this.allJobs = value;
        }
    }

The get set works fine when I assign a whole ObservableCollection to the property, the set works fine for retrieving it obviously. But why have I lost all the methods that normally allow me to 'Add' (i.e. add 1 job to the collection)?
At the moment I'm having to create a temporary collection to populate to then assign to the allJobs property and I shouldn't have to.
Any ideas??
Comment: What do you mean lost? You can't go `AllJobs.Add(newItem)`??
Comment: Note, that property is supposed to read as "ObservableCollection", don't know what happened to the "" bit.
Comment: The collection in code is private but NOT static. What is all about this question?
Answer: What do you mean with 'lost methods'? Have you tried AllJobs.Add()? The following code works for me:
void Main()
{
    AllJobs = new ObservableCollection<Job>();
    AllJobs.Add(new Job());
}

public class Job { }

private ObservableCollection<Job> allJobs;

public ObservableCollection<Job> AllJobs
{
    get
    {
        return this.allJobs;
    }
    set
    {
        this.allJobs = value;
    }
}

EDIT:
Based on your comment I've amended my code as follows but everything still works for me, I have noticed however that you don't seen to initialise the allJobs collection anywhere.
void Main()
{
    PresentationManager.Instance.AllJobs.Add(new Job());
}

public class Job { }

sealed class PresentationManager
{
    public static readonly PresentationManager Instance = new PresentationManager();

    private PresentationManager()
    {
        allJobs = new ObservableCollection<Job>();
    }

    private ObservableCollection<Job> allJobs;
    public ObservableCollection<Job> AllJobs
    {
        get { return this.allJobs; }
        set { this.allJobs = value; }
    }
}

Comment: That doesn't work for me. The difference between our code is that I'm using singleton instantiation, I should've probably mentioned that:
    sealed class PresentationManager
    {
        public static readonly PresentationManager Instance = new PresentationManager();

        private ObservableCollection allJobs;

public ObservableCollection AllJobs
        {
            get
            {
                return this.allJobs;
            }
            set
            {
                this.allJobs = value;
            }
        }
}
Comment: @DanielMcNulty: What error message do you get when you try it? Saying it doesn't work is much better with an error message. :)
Comment: @DanielMcNulty so go `PresentationManager.Instance.AllJobs.Add(newItem)`
Comment: Yes that's the exact line of code I have written in the 'main' method Ray. It doesn't like it, there are no error messages, it's just stops executing the rest of the code in the load method, it doesn't actually break it tho. The app doesn't crash!?
Comment: BTW apologies for my use of code formatting and commenting here, it's the first thread I've made.
Comment: Do you have any try/catch code around it? I have noticed that you never seem to set the allJobs collection to a valid collection - you might have a null-reference exception being caught somewhere.
Comment: @DanielMcNulty - Edit your question with the new code. Comments are meant for people to *request* more information. That information should be edited into the question or answer, not supplied as a new comment.
Comment: J.Kommer nailed it with that answer. Thanks a lot mate. Thanks for everyone's help, appreciated.
Comment: Ok Chris I'll bear it in mind for next time. I'd add to your rep J.Kommer but I can't yet.
Answer: Normally you wouldn't want a setter for such a property, as you would lose all events bound to the ObservableCollection when the setter is used.
public ObservableCollection<Job> AllJobs { get; private set; }
Comment: It's acting strange this, the code breaking on the line that I'm adding to the collection but even in debugging mode is not lettin me know about any sort of exception being thrown. I'm gonna have to come back and make a thread when I've got more specifics because this is baffling me.
Comment: An excellent point and getting a +1 from me despite not technially being an answer to the question. :)
Comment: @DanielMcNulty: Show us the line where you are adding that is breaking on and we may be able to shed some additional light on things...
Comment: Job job5 = new Job();
job5.Task= "ToDoSomething";
PresentationManager.Instance.AllJobs.Add(job1);


How to sum cumulative costs across price ranges for a given quantity?

Question: I have a table that looks like this:

Quantity
Price (Per Item)

10000 or less
$50

10001 - 15000
$40

15001 - 30000
$30

30000 or more
$20

So for example, if I order quantity 16000, the total price will consist of:

$50 for the first 10000 items ($500000)
$40 for the next 5000 items ($200000)
$30 for the last 1000 items ($30000)

Hence, total price will be $730000 (cost is cumulative based on various price ranges for a given quantity).
I am trying to code a Python function that takes in quantity as a parameter and returns the overall price. I am able to do it by hardcoding the quantity ranges, using multiple if else conditions and doing some basic math, but was wondering if there is an optimal way to do this?
Thanks!
Answer: I am not sure whether the following is optimal, but you can try something like the following:
<code>def get_price(quantity):
    p_schedule = [(10000, 50), (5000, 40), (15000, 30), (None, 20)]
    price = 0
    while quantity: # while we still have quantity to exhaust
        q, p = p_schedule.pop(0) # get current price schedule bracket
        # q_now: quantity to exhaust in the current bracket.
        # if q == None, then use all the remaining quantity.
        q_now = min(q, quantity) if q else quantity
        price += p * q_now # add to the price
        quantity -= q_now # subtract the quantity used in this bracket
    return(price)

print(get_price(16000)) # 730000
</code>


Where do Magento2 Questions Belong?

Question: I certainly don't think inquiries about Magento 2 belong in the magento.stackexchange; can we hurry up and confirm/enforce this? I feel all inquiries should be directed at the brand and/or the repository.
Comment: Just seems kind of crazy to dilute the SE before a production ready stable release is out, esp. when there is a repository which users can create issues on.
Comment: Can you explain your reasoning?
Answer: Magento 2 questions are allowed.
They should just be tagged with the proper version to make a difference between pre-alpha, alpha, beta, rc and official release.
Answer: I think some question which fit squarely into the "issues" bucket belong on GitHub. But for questions which do not rise to the level of "hey something's broken" or "hey I have an architectural suggestion / improvement" are noise in a GitHub context. My opinion of course, and curious to hear the opinions of others.
Answer: Here is my two cents. Magento 2 is the newest edition of Magento. If a question clearly states it is related to Magento 2 I see absolutely no reason why it does not belong on magento.stackexchange.com.

Where do Magento2 Questions Belong?


What is that thing called that Ed Sheeran is doing with his voice on the word "no"?

Question: What is that thing called that Ed Sheeran is doing with his voice on the word "no". It sounds like shouting but how does he do that?
Comment: Surely '*know*'/
Comment: @Tim Sorry, I didn't paid attention to the lyrics. Yes it's definitely  "know".
Answer: It's one of the many forms of vocal "distortion".
You'll hear it far more often in rock and metal singing styles.
You might want to check out youtube videos on singing with rasp and distortion by the likes of Ken Tamplin (other vocal coaches are of course available!).
If you are wanting to do it and starting out as a singer that has never done it, go easy on your voice.
Comment: When I was a boy I tried to sing like Louis Armstrong and I think I disturbed my voice by distortion in the age  of 14.
Comment: Yes, but why of all things Ken Tamplin? He's spreading so much misconception/bad technique and we know how dangerous this can be with harsh vocals.


Method called when new activity starts

Question: When I start a new android activity the methods that are being called before the activity actually appears in the screen are onCreate() -> onStart() -> onResume()? or there are some more called before I see the activity on the screen?
I've written an application in which I overrode only the onCreate() method from the three I mentioned before, but from some reason the application crashes, although the onCreate() finishes successfuly.
onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d("SMARTGAN", "starting ChildActivity onCreate()");

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_child);

    // find child for the activity
    child = (Child) getIntent().getSerializableExtra(MainActivity.CHILD);

    // initialization
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    adapter = new TabsPagerAdapter(getSupportFragmentManager(), child);

    viewPager.setAdapter(adapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // set action bar properties
    actionBar.setTitle(child.getName());
    actionBar.setIcon(R.drawable.ic_action_person);

    // adding the tabs to the action bar
    for (int i = 0; i < tabs.length; i++) {
        actionBar.addTab(actionBar.newTab().setText(tabs[i])
                .setTabListener(this));
    }

    // set OnPageChangeListener so that whenever the user changes the page
    // the selected tab in the action bar also changes
    viewPager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) { }

        @Override
        public void onPageScrollStateChanged(int arg0) { }
    });
    Log.d("SMARTGAN", "ChildActivity onCreate completed");
}

Comment: Post your code and the stacktrace. This may be helpful too : http://developer.android.com/reference/android/app/Activity.html and http://developer.android.com/images/activity_lifecycle.png
Comment: Post your logcat output
Comment: How can I get the stacktrace?
Comment: Either share your code or your logcat output or both.
Answer: Maybe you will find your answer in this android activity lifecycle
Comment: It makes no sense, why does my application crash if the onCreate has finished and I haven't override onStart and OnResume? I cant even find where the error occurred.
Answer: Did you add your activity to the AndroidManifest.xml file? The second way: maybe you have problem with you content view (when setting view with setContentView() method)?
Comment: The setContentView has finish long before the application crashed

Method called when new activity starts


Doing more than one COUNT on the same column in one php script SELECT query

Question: I have two columns 'Team' and 'WLD' in a mysql database. WLD stands for Won, Lost, Drawn and contains either a W, L or D on every line of hundreds. I want to output how many W's, L's and D's there are in the column in one SELECT.
If I do this with one of them it works:
SELECT Team, COUNT(WLA) AS Won FROM ResultsTest WHERE WLA = 'W'

However, as soon as I add another COUNT statement it starts to complain:
SELECT Team, COUNT(WLA) AS Won
FROM ResultsTest
WHERE WLA = 'W',
COUNT(WLA) AS Lost FROM ResultsTest WHERE WLA = 'L'

Where am I going wrong?
Comment: Possible duplicate of [Conditional Count on a field](https://stackoverflow.com/questions/1288058/conditional-count-on-a-field)
Comment: SQL does not have such syntax. In cases like this you need to use `CASE` and emulate `COUNT` with `SUM`.
Comment: Have a look at [conditional sum](https://stackoverflow.com/questions/16517298/conditional-sum-in-group-by-query-mssql)
Comment: Which [DBMS](https://en.wikipedia.org/wiki/DBMS) are you using? "SQL" is just a query language, not the name of a specific database product. Please add the tag for the database product you are using `postgresql`, `oracle`, `db2`, `sql-server`, ...
Answer: You need a GROUP BY clause in order finalize your data aggregation. On the top of that, if you don't want to create two distinct extractions for wins and losses and join them, you can use a binary sum in cases:
SELECT Team,
       COUNT(*) AS Matches,
       SUM(CASE WHEN WLD = 'W' THEN 1 ELSE 0 END) AS Wins,
       SUM(CASE WHEN WLD = 'L' THEN 1 ELSE 0 END) AS Losses,
       SUM(CASE WHEN WLD != 'W' AND WLD != 'L' THEN 1 ELSE 0 END) AS Draws
FROM ResultsTest
GROUP BY Team

Answer: Thanks guys. It works. Saved me a lot of time:
SELECT Team,
       COUNT(*) WLD,
       SUM(CASE WHEN WLD = 'W' THEN 1 ELSE 0 END) AS Won,
       SUM(CASE WHEN WLD = 'L' THEN 1 ELSE 0 END) AS Lost,
       SUM(CASE WHEN WLD = 'D' THEN 1 ELSE 0 END) AS Drawn
FROM ResultsTest
GROUP BY Team


Is there a way to register python scripts to run "by themselves" under PowerShell?

Question: This question nicely covers getting python scripts running under CMD.EXE without having to type a bunch of extra stuff - that is "> script" rather than "> python script.py".
However, I can't seem to get the same behavior under PowerShell.  Entering "PS > script.py" there just gets me the "is not recognized as a cmdlet, function, operable program, or script file" error.
How do I get PowerShell to recognize the same file associations that CMD does?
Answer: Aha, I've found the answer myself.
In PowerShell, scripts to be executed need to be proceeded by ".\"
So, "PS > script.py" doesn't work, but "PS > .\script.py" does.
Also, using this syntax adding ".py" to PATHEXT works fine under PowerShell.
Answer: The same solution should work under Powershell: did you try adding .py to the PATHEXT environment variable?
Comment: Yes. Clearly, PowerShell isn't looking at the environment variables for this kind of thing.
Comment: Scratch that, yes it is; I was just running commands the wrong way.  See my answer.
Answer: Completely different direction but you could use IronPython to make .net executables and call those.


How can prevent local access to my server (either host or virtualbox Ubuntu 16.04 )

Question: I have a web application (PHP) which i need to leave in a customer premise. They have no internet and are not willing to use internet to use my app.
So i have to leave a linux server at their place. But i'm worried about someone accessing my server and getting my PHP code. In addition to encrypting PHP (Ion encoder, Zend Guard) and LUKS disk encryption i don't know what else i can do to prevent my machine.
I know, Microsoft said long time ago that as far as someone has physical access to a machine it should be considered breakable so my app/server will be in "hostile territory" but i have no choice. But i can do as much as i can to prevent it. I'm considering disabling TTY's and enabling login via SSH with keys so only i can access it remotely (which means when i get there with my laptop).
Which one would be better ? having my whole setup in a server or inside a vm inside a server ? because the disk will be encrypted i don't care too much about someone copying my disk (i can't doo too much either). But then, how can i prevent someone changing the root password from grub ?
Also, even if i password protect the BIOS, won't it unlock when the board be flashed ?
Comment: Most companies rely more on copyright, law and contracts to protect their interests beyond what can be achieved with reasonable technical means.
Comment: Yes but that's unfeasible in my case. My clients are local governments and corruption is "normal" all around so it wouldn't be unlikely that my server be analyzed by a rival that has friend in the mayor's office.
Answer: Yes, if they're able to take the box apart and pull the BIOS battery, they can unlock the BIOS.  I'm also not sure that putting your app on a VM would provide what you're looking for.
You probably want to store it in a colo cage.  Something like this:

(photo credit)
If they can't physically lay hands on it, they can't tear open the case, access grub, etc.  This is the industry standard for this sort of thing.
There's an associated cost, and you might need to consider at what point you're spending more than protecting your code is worth. (I can't answer that;  only you know the monetary value of your code.)
Comment: I've read the hard drive encryption is useless as after editing grub, LUKS can be used to decrypt a system. Then, what for encryption is used if anyone can break it ??


ifstream + opening random txt file (c_str)

Question: I want to open a random .txt file and put the data into some strings.
It works if I write the path into the code.
I don't get it why this doesn't work.
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    string file;

    ifstream filein(file.c_str());

    cout << "Insert Path" << endl;
    cin >> file;

    cout << file << endl;

    filein.open(file.c_str(), ios::in);

    for (string line; getline(filein, line);) {
        cout << line << endl;
    }

    return 0;
}

Comment: When you ran over this in a debugger, what was `file`? What is it supposed to be?
Answer: Your filename string is empty because std::string defaults to empty.
You are passing an empty string (or the nul string) to the ifstream constructor, which is at best, undefined behavior.
Answer: first what are you opening? as long as you string doesn't contain anything??
second even if the string contains a valid path and the opening was successfull at the first time but in the second will fail as long as you use the same file stream on multiple files without clearing its buffer and closing the previous file:
string file "C:\\MyProject\\data.txt"; // let's say a valid path

ifstream filein(file.c_str());

if(filein.fail()) // the condition fails as long as the opening was successfull
    cout << "failed to open file!" << endl;

cout << "Insert Path" << endl;
cin >> file; // let's say the user enters a valid path again: "C:\\MyProject\\test.txt"

cout << file << endl;

filein.open(file.c_str(), ios::in); // fail to correct it:

filein.close();
filein.clear(); // very important

filein.open(file.c_str(), ios::in); // now it's ok!

for (string line; getline(filein, line);) {
    cout << line << endl;
}

Answer: Try writing your code like this:
#include <iostream>
#include <fstream>

int main()
{
    std::string file;

    std::cout << "Insert Path" << std::endl;
    std::getline(std::cin, file);

    std::cout << file << std::endl;

    std::ifstream filein(file);

    for (std::string line; std::getline(filein, line); )
    {
        std::cout << line << std::endl;
    }

    return 0;
}

Notable edits include:

We're now constructing the ifstream object only when we need it, after file has had data stored, which means no more undefined behavior, and that we only attempt to open a file after we know what the path is.
We're retrieving a whole line when storing to file, instead of only the first word, which is crucial if your path includes any spaces.
We're just using the file string directly. There's no need to call c_str().
We're no longer using using namespace std;. There are many, many reasons why this is bad practice.

EDIT:
If you have a C++17-compliant compiler, I'm going to propose you write code that looks like this instead:
#include <iostream>
#include <fstream>
//You may need to write #include <experimental/filesystem>
#include <filesystem>
#include <string>

int main()
{
    std::string input_line;

    std::cout << "Insert Path" << std::endl;
    std::getline(std::cin, input_line);

    //You may need to write std::experimental::filesystem
    std::filesystem::path file_path{input_line};
    //This will print the "absolute path", which is more valuable for debugging purposes
    std::cout << std::filesystem::absolute(file_path) << std::endl;

    std::ifstream filein(file_path);

    for (std::string line; std::getline(filein, line); )
    {
        cout << line << endl;
    }

    return 0;
}

Explicit use of path objects will make your code more readable and make errors more explicit, as well as grant you access to behavior you otherwise would not be able to access.
Comment: So, why should anybody write code like that?  What does this do for the OP?  Please edit your answer with clarifications, such as the difference between your answer code and the OP's.
Comment: @ThomasMatthews Just did.
Comment: Why even default construct the `ifstream`?  You can easily make it work using `std::string filename; std::cin >> filename; std::ifstream fin(filename)`.
Comment: Remember variables should be declared when you need them, which is where they are used, not at the top of the function.
Comment: @NathanOliver Edited.
Comment: So ok i understand your suggestions. The declaration in the second row makes no sense. The path has no spaces. So it should work either way.    But the code Xirema postet doesn't work for me. I'm using CodeBlocks 16 with gnu compiler.
Comment: @TF107 When you say "It doesn't work", what precisely do you mean? Are you getting a compilation error? Are you getting a runtime error? Is the output incorrect?


$A,B$ are complex matrices in $M(n,\mathbb{C})$ and rank$(AB)$=rank$(BA)$=rank$(ABA)$. Prove that $AB$ is similar to $BA$.

Question: $A,B$ are complex matrices in $M(n,\mathbb{C})$ and rank$(AB)$=rank$(BA)$=rank$(ABA)$. Prove that $AB$ is similar to $BA$.
I tried by using JCF..but could not complete
Comment: Regarding the last sentence: if $B$ is invertible for instance, we have similarity because
$$
BA = B(AB)B^{-1}
$$
Comment: Could you tell us more about your approach and where exactly you got stuck on this problem?
Comment: I don't have a complete approach in mind, but here are some hopefully helpful initial thoughts: from the statements about rank, we know that the image of $A$ only trivially intersects the kernel of $AB$ and the kernel of $A$ trivially intersects the image of $BA$. If we could somehow reduce this problem to the case where either $A$ or $B$ are invertible, then the problem becomes simple.
Comment: One more observation: we can show that the restriction $A|_{\operatorname{im}(BA)}$ defines an isomorphism between the images of $BA$ and $AB$. Similarly, $A|_{\ker(BA)}$ defines an isomorphism between the kernels of $BA$ and $AB$. If we could show that these subspaces are disjoint (equivalently $\operatorname{rank}(BABA) = \operatorname{rank}(BA)$), then the result would follow.
Comment: I think this can be done via an induction combined with repeated application of Frobenius Rank Inequality, but it's ugly.  Where does this problem come from?
Comment: @user The Frobenius inequality, if applied directly, yields
$$
\operatorname{rank}(AB) + \operatorname{rank}(BA) \leq \operatorname{rank}(B) + \operatorname{rank}(ABA) \implies\\
\operatorname{rank}(AB) \leq \operatorname{rank}(B),
$$
which doesn't tell us anything we couldn't deduce directly
Comment: @BenGrossmann I've posted my proof using Frobenius Rank Inequality + induction
Comment: @user Neat! I wouldn't have thought of that
Answer: The main idea is to use your rank information to get a detailed view of the Jordan structure of eigenvalue zero.  The Jordan structure for the non-zero eigenvalues take care of themselves (see end).
The Frobenius Rank Inequality says
$\text{rank}\big(XY \big) +\text{rank}\big( YZ\big) \leq \text{rank}\big(XYZ\big) + \text{rank}\big(Y\big)$
we also know
(i) $\text{rank}\big(A(BA)^{m}\big)=\text{rank}\big((BA)^{m}\big)$
for all natural numbers $m$
because $\text{span}\Big((BA)^{m}\Big)\subseteq  \text{span}\Big((BA)\Big)$
and $A$ is injective on the vector (sub)space generated by $\text{span}\big((BA)\big)$
Note: this also implies for all natural numbers $m$
$\text{rank}\Big((AB)^{m+1} \Big)=\text{rank}\Big(B(AB)^m\Big)=\text{rank}\Big((BA)^mB\Big)$
(why?)
Base Case
$Z:= A$
$X:=B$
$Y:=AB$
and apply Frobenius Rank Inequality
$\text{rank}\big(BAB \big) +\text{rank}\big(AB \big)=\text{rank}\big(B(AB) \big) +\text{rank}\big((AB)A\big) \leq \text{rank}\big(B(AB)A\big) + \text{rank}\big(AB \big)$
$\implies \text{rank}\big(BAB \big)\leq \text{rank}\big(BABA\big)\leq \text{rank}\big(BAB \big)$
(by submultiplicativity of rank on the right)
we conclude
$\text{rank}\big((AB)^2\big)= \text{rank}\big(BAB \big)=\text{rank}\big((BA)^2\big)$
(where the LHS follows by (i), setting  $m:=1$)
Inductive Case
(ii) the induction hypothesis is
$\text{rank}\big((AB)^{k}\big)=\text{rank}\Big(B(AB)^{k-1}\Big)= \text{rank}\big((BA)^k\big)$
for $k\geq 2$
and need to show this implies
$\text{rank}\big((AB)^{k+1}\big)=\text{rank}\Big(B(AB)^{k}\Big)= \text{rank}\big((BA)^{k+1}\big)$
To prove this, apply Frobenius Rank Inequality
$X:=B$, $Y:= (AB)^k$, $Z:=A$
$\text{rank}\Big(B(AB)^k \Big) +\text{rank}\Big((AB)^kA\Big) \leq \text{rank}\Big(B(AB)^k A\Big) + \text{rank}\Big((AB)^k \Big)$
an equivalent statement is
$\text{rank}\Big(B(AB)^k \Big) +\text{rank}\Big(A(BA)^k\Big) \leq \text{rank}\Big((BA)^{k+1}\Big) + \text{rank}\Big((AB)^k \Big)$
$\implies\text{rank}\Big(B(AB)^k \Big) +\text{rank}\Big((BA)^k\Big) \leq \text{rank}\Big((BA)^{k+1}\Big) + \text{rank}\Big((AB)^k \Big)$ (by (i))
$\implies \text{rank}\Big(B(AB)^k \Big)\leq  \text{rank}\Big((BA)^{k+1}\Big)\leq \text{rank}\Big((BA)^kB\Big) =  \text{rank}\Big(B(AB)^k \Big)$  (by (ii))
$\implies \text{rank}\Big((BA)^{k+1}\Big) = \text{rank}\Big(B(AB)^{k}\Big)=\text{rank}\Big((AB)^{k+1}\Big)  $
where the RHS follows by (i) and completes the induction
Since
$\text{rank}\Big((AB)^{m}\Big) = \text{rank}\Big((BA)^{m}\Big) $
for all natual numbers $m$, we know that $(AB)$ and $(BA)$ have the same Jordan structure with respect to eigenvalue $0$.  And by
AB and BA have identical nonsingular Jordan blocks
they have the same Jordan structure with respect to non-zero eigenvalues.
Thus $(AB)$ and $(BA)$ are similar to the same jordan matrix $J\implies (AB)$ and $(BA)$ are similar.

alternative to induction
one way to bypass the Inductive Case is to just note that the Base Case tells us
$\text{rank}\Big(BAB \Big)=\text{rank}\Big((BA)^2\Big)=\text{rank}\Big((BAB)A\Big)$
i.e. it tells us that $A^T$ is injective on the space generated by  $\text{span}\Big((BAB)^T\Big)$
but then for all natural numbers $k$
$\text{rank}\Big(B(AB)^{k}\Big)= \text{rank}\Big((BA)^k B\Big)= \text{rank}\Big((BA)^{k-1}(BAB)\Big)= \text{rank}\Big((BAB)^T\big((BA)^{k-1}\big)^{T}\Big)= \text{rank}\Big(A^T(BAB)^T\big((BA)^{k-1}\big)^{T}\Big)= \text{rank}\Big(\big((BA)^{k-1}\big)(BAB)A\Big) = \text{rank}\Big((BA)^{k+1}\Big)$
since transposition doesn't change rank and because $\text{span}\Big((BAB)^T\big((BA)^{k-1}\big)^{T}\Big)\subseteq \text{span}\Big((BAB)^T\Big)$
and $A^T$ is injective on the space generated by RHS, hence injective on any subspace.  This is a slightly faster route but still rather ugly.
Answer: Let $r=\operatorname{rank}(A)$. Then $X:=PAQ=\pmatrix{I_r&0\\ 0&0}$ for some invertible matrices $P$ and $Q$. Let $Y=Q^{-1}BP^{-1}$. Then
$$
XY=PABP^{-1},\ YX=Q^{-1}BAQ\ \text{ and }\ XYX=PABAQ.
$$
It follows that $\operatorname{rank}(XY)=\operatorname{rank}(YX)=\operatorname{rank}(XYX)$ and it suffices to show that $XY$ is similar to $YX$. Let
$$
Y=\pmatrix{E&F\\ G&H}
$$
where $E$ is $r\times r$. The condition $\operatorname{rank}(XY)=\operatorname{rank}(YX)=\operatorname{rank}(XYX)$ thus implies that
$$
\operatorname{rank}\pmatrix{E&F}=\operatorname{rank}\pmatrix{E\\ G}=\operatorname{rank}(E).
$$
Therefore $F=EZ$ and $G=WE$ for some matrices $Z$ and $W$. Hence
\begin{aligned}
XY&=\pmatrix{E&EZ\\ 0&0}=\pmatrix{I&-Z\\ 0&I}\pmatrix{E&0\\ 0&0}\pmatrix{I&Z\\ 0&I}\text{ and}\\
YX&=\pmatrix{E&0\\ WE&0}=\pmatrix{I&0\\ W&I}\pmatrix{E&0\\ 0&0}\pmatrix{I&0\\ -W&I}
\end{aligned}
are similar to each other and we are done.
Comment: This feels like a natural approach one you take the initial step of introducing the "rank factorization" of $A$. Very nice


How do I use a different template for the anonymous users?

Question: If the user is the anonymous user or an authenticated user, I want to use the page1.tpl.php; with other roles, I want to use page.tpl.php.
How do I write the code?
Answer: If you want to handle different templates for different scenarios the context module is a great tool. This case is quite simple, so you could handle it with code like suggested. But using the context module, makes it a bit more manageable, and allows you not only to decide what template to use, to also what blocks to insert. It's a great module and is one of those I use for almost all of the sites I make.
Comment: +1 for suggesting to use Context. I would rather avoid to alter a theme template, when it is not necessary. Altering theme templates of a third-party theme would mean to override the theme templates used by the theme all times the theme is updated; it would also mean to alter the theme templates of every theme users could select for themselves.
Comment: many thanks, i will make a try to the module that you suggested.
Comment: i want to know What's the  main use of the  context module?
Comment: The Context **Layout** module would offer you this ability. It's main purpose is to setup **conditions** and **reactions** one of which is to use a different page.tpl.php with a different set of regions setup in your .info file.
Answer: You should not need an additional page1.tpl.php. In the page.tpl.php you can use:
<?php
  global $user;

  if ($user->uid > 0) {
    print /* Insert content only for authenticated users. */;
  }
?>

If you want to show some content when the user has the "administrator" role, then you can use:
<?php
  global $user;

  if (in_array('administrator', array_values($user->roles)))) {
    print /* Insert content only for users with "administrator" role. */;
  }
?>

Comment: I updated the answer with the content of the comment.
Comment: if i want to print other things when the user role is admin, how to get that?
Comment: Actually, a cleaner way to figure out if the user is anonymous is to call the function user_is_anonymous()
Comment: [user_is_anonymous()](http://api.drupal.org/api/drupal/modules--user--user.module/function/user_is_anonymous/6) returns TRUE also when the user is not the anonymous user, but the variable `$GLOBALS['menu_admin']` is not empty (e.g. it is not `FALSE`).
Answer: I think you can use a preprocess function. Something like that:
function yourtheme_preprocess_page($vars) {
   global $user;
   if (!$user->uid || in_array('user authenticated', array_values($user->roles))) {
      $vars['template_files'][] = 'page1';
   }
}

Comment: what's this '(!$user->uid |' meaning? thank you
Comment: It is not necessary to verify if the user as the "user authenticated" role. The user ID for anonymous users is 0, and authenticated users have an user ID that is greater than 0; the user with ID equal to 1 is the user who has all the permissions.
Comment: i don't know "if (!$user->uid | "  meaning.could you explain it. thank you.
Comment: @enjoylife It's a typo; it should be `if (!$user->uid || in_array('user authenticated', array_values($user->roles)))`.
Answer: Every user on a Drupal site is an anonymous user, or an authenticated user. Requiring to use the page1.tpl.php template for anonymous, or authenticated users would mean that the page1.tpl.php template is always used.
if by authenticated users you mean users that don't have any other specific role, then you could use the following code in your page.tpl.php file.
if (empty(array_diff(array_keys($GLOBALS['user']->roles), array(0, 1))) {
  // The user is anonymous, or the user doesn't have other roles
  // apart the one of authenticated user.
}


Questions about surface integrals and an example problem

Question: It is   double integral $(x + y) dS$   where $S$ is the part of the cylinder $y^2 + z^2 = 4$ . With $x$ being between $0$ and $5$
First question, if we want to get the integral of the surface of a cylinder, I don't quite understand why $(x + y)$ is being multipled by $dS$? What is the applications of doing something like that?
In terms of just the surface being described, is my parametrization correct?
$x = v$
$y = cos (u)$
$z = sin (u)$
$0 < u < 2\pi$
$0 < v < 5$
This problem is so hard for me visualize and wrap my head around, I think it would be easier if instead of " $y^2 + z^2 = 4$ " it was "$x^2 + y^2 = 4$". IS it correct to treat the variables $y$ and $z$ as I would treat them if it was $x$ and $y$, which is what I did? It seems logically sound, but I could be missing something maybe.
Assuming my stuff is correct, I take the cross product of the partial derivatives of this vector valued function and integrate across the region right? This is not taking into account the $(x + y)$ that's being multiplied by the surface, of course.
Answer: What is so hard to visualize?  $f(x,y)=x+y$ is just a plane through the origin (i.e. $z-x-y=0)$ and the cylindar $y^{2}+z^{2}=4$ is just oriented along the $x$-axis instead of the $z$-axis as you claim is easier to visualize (it's not, if you think about it for a second).
The integral is then just a surface integral of the scalar field $x+y$ over the portion of the cylindar bounded between the planes $x=0$ and $x=5$, that is
$$\int_{S}(x+y)\;dS,$$
$dS$ being the induced surface measure over the cylindar.  It is taught in your class of course that $dS=|\phi_{u}\times\phi_{v}|\;du\;dv$ where $\phi(u,v)=(v,2\cos u,2\sin u)$ is the parametrization of the cylindar, once the integration is pulled back onto the parameter domain of $\phi$, which is as you indicated the rectangle $[0,5]\times[0,2\pi]$.
We have $\partial_{u}\phi(u,v)=(0,-2\cos u,2\cos u)$ and $\partial_{v}\phi(u,v)=(1,0,0)$, and so $|\phi_{u}\times\phi_{v}|=|(0,2\cos u, 2\sin u)|=2.$
The integral now becomes
$$2\int_{0}^{5}\int_{0}^{2\pi}(v+2\cos u)\;du\;dv.$$
Now finish the job.
Comment: I thank you a lot for your help, but what is the point of multiplying a scalar field by the area of a surface? And thanks for pointing out that I forgot to multiply my y and z parameters by 2. haha
Comment: What do you mean? It's just notation for integrals; you're not literally multiplying anything by $dS$. $\int_{S}(x+y)\;dS$ just means integrate $(x+y)$ over $S$ with respect to the surface measure $dS$. To reduce matters to an ordinary iterated Riemann integral, you parameterize the surface and pull back $S$ to the parameter domain $D$, and along the way $dS$ becomes $|\phi_{u}\times\phi_{v}|\;du\;dv$. This can all be made rigorous, and indeed, if you looked in your calculus text book you would find a sketch of the proof.
Comment: I don't get it. I'm almost positive it's because I must have no been paying attention in class one day. Say the (X + y) Wasn't there and i integrated without it, wouldn't I get the surface area still? Or am I misunderstanding?


mkdir(): Permission Denied in core/lib/Drupal/Component/PhpStorage/FileStorage.php

Question: On every site page, I am getting these errors:
User warning: mkdir(): Permission Denied in Drupal\Component\PhpStorage\FileStorage->createDirectory() (line 123 of core/lib/Drupal/Component/PhpStorage/FileStorage.php).
Drupal\Component\PhpStorage\FileStorage->createDirectory('sites/default/files/php/twig', 509) (Line: 73)

Drupal\Component\PhpStorage\FileStorage->ensureDirectory('sites/default/files/php/twig') (Line: 66)
Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage->save('65cd8eafb5bac_status-messages.html.twig_GfCMeKK44m7xVsgW6vKS2K1IN', '<?php

[followed by contents of a twig php file it looks like]

I am also getting the same or very similar errors when I try to clear caches from the site but not if I use drush cr on the cli.
My sites/default/files directory has 777 permissions and is owned by the webserver (apache).
I did see this issue which seems very similar but I can't add any comments there. How do I debug Drupal\Component\PhpStorage\FileStorage::createDirectory()?
I would be happy to try using the \Drupal::logger('my_module')->notice($message) but can you tell me where to put that? Thanks.
Answer: It's possible to reproduce this error by changing the ownership/permission of sites/default/files/php, so that the web server no longer can access it, and clearing the content of the directory (this is only a cache and can be cleared without data loss). The next site visit will create a ton of these warnings.
Since you have full error reporting already enabled, you see all debugging details and don't need the linked topic.
What you need to do is to set up Drupal according to web/core/INSTALL.txt. If this is not a new install, this depends on the steps you did before to cause the error. If, for example, you have migrated the site to a different host, you might need to adjust the directories/files ownership and permissions. See this great tutorial https://www.singlemindconsulting.com/blog/fixing-permissions-on-the-files-directory-in-drupal/
Comment: Thanks. Good to know that I don't need more debugging messages. I went through the tutorial you linked, but my permissions were already set as it recommends. (And I'm still getting the errors.)
Comment: OK, the docs I've mentioned are for traditional Unix systems. If you use something else you have to adapt the commands, but the concept of the Drupal file system still applies.
Answer: Turns out the reason for the permissions errors in my case is SELinux not allowing the Apache httpd process to write to the filesystem. The fix is:
sudo chcon -R -t httpd_sys_rw_content_t /path/to/sites/default/files/

See https://unix.stackexchange.com/questions/50639/httpd-cant-write-to-folder-file-because-of-selinux


Postfix - how to redirect email after they are rejected?

Question: I have a problem with spam and postfix + postgray. Generally it works fine, but I have these problems:

false-positives.
good emails get rejected.

Can I configure postfix (and postgray) so that when an email is rejected, then redirect to email@example.com (change recipients).
Or maybe copy each emailand send it to email@example.com, and then apply
filtering? If hit restriction than just reject (another copy is in email@example.com).
How to do it?
Answer: You can't do it. You can either REJECT (or DEFER) the mail or ACCEPT (or REDIRECT) the mail. If you REJECT the mail, then the mail doesn't even arrive at your server as it is canceled right away during connection attempt. When you ACCEPT the mail then you can analyze the mail content but then it is impossible to REJECT the mail afterwards.
So you can only have the one or the other. But not both.
Comment: Thank you for answer. Can you give me any advice what should I do in postfix? My target is the same: fight with spam without lost email ? Alone spamassasin was to weak because I get huge count of spams.


How does the CEM package (R/Stata) handle missingness on outcome variable?

Question: I'm trying to understand how coarsened exact matching works when there is missingness in the outcome variable. I need to match observations on several predictors and then estimate different models using various outcome variables, some of which include missing values.
Replication in R (automatic coarsening for simplicity of replication):
library('cem')

set.seed(12345)
treat <- rbinom(100, 1, 0.5)
x1 <- rnorm(100, mean = 50, sd = 20)
x2 <- rnorm(100, mean = 10, sd = 5)
y1 <- rnorm(100, mean = 30, sd = 3)
y2 <- y1; y2[90:100] <- NA

df <- data.frame(treat, x1, x2, y1, y2)

Note that y2 is identical to y1, except that missing values have been introduced for the last 10 observations.
matched <- cem('treat', drop=c('y1', 'y2'), data=df, keep.all = T)
matched

m1 <- att(matched, y1 ~ treat + x1 + x2, data = df)
m1

This simple linear estimation using y1 as outcome yields:
          G0 G1
All       48 52
Matched   35 39
Unmatched 13 13

Linear regression model on CEM matched data:

SATT point estimate: -0.799485 (p.value=0.177235)
95% conf. interval: [-1.949084, 0.350114]

m2 <- att(matched, y2 ~ treat + x1 + x2, data = df)
m2

Using y2 yields:
          G0 G1
All       48 52
Matched   35 39
Unmatched 13 13

Linear regression model on CEM matched data:

SATT point estimate: -0.925112 (p.value=0.135748)
95% conf. interval: [-2.124466, 0.274241]

The results are different, but I cannot find out (from package documentation or the objects returned in R) what happens under the hood. Does it use listwise deletion to remove the observations with missing values? If so, what if a case with a missing value on y2 is matched to a case without missingness? Does it drop the whole stratum (both cases)?
Comment: Why is Stata mentioned in the title and given as a tag?
Comment: Since the CEM package is implemented in both R and Stata (by the same developers), I expect it treats missingness the same way in both programs. But I might be wrong.
Comment: I can't comment on that, but there is (still) nothing in your question about Stata.
Answer: The default is to run lm on the data using the estimating matching weights as weights in a weighted regression. att() simply calls lm(). The default in lm() is to call na.omit() on the model matrix, which discards all units that have missing values for the predictors or outcome. Because the matching strata are used only to produce weights with model = "linear", information about stratum membership is lost when estimating the treatment effect, so the missing value processing ignores stratum membership and only deletes observations with missing outcomes regardless of the missingness of the other members of their stratum.


If A is invertible and orthogonally diagonalizable, is $A^{-1}$ orthogonally diagonalizable as well?

Question: I know that the answer is yes. Are the reciprocal of the eigenvalues of A the eigenvalues for $A^{-1}$? If the eigenvalues for A are $3$ and $2$, would the eigenvalues for $A^{-1}$ be $1/3$ and $1/2$?
What does it mean when an orthonormal eigenbasis of A is also an orthonormal eigenbasis of $A^{-1}$?
Comment: If $A=MDM^{-1}$ where $D$ is diagonal and $M=M^T$, can you write down a formula for $A^{-1}$?
Comment: Do you need a proof of the claim in the title?
Comment: Yes @AhmedHussein
Answer: Let the orthogonal decomposition of $A$ be denoted as $$A = Q^TDQ$$ where $Q$ is orthogonal and $D$ is diagonal. Since A is invertible,
$$A^{-1} = {\left(Q^TDQ\right)}^{-1} = Q^{-1}D^{-1}{(Q^T)}^{-1} = Q^TD^{-1}Q$$ as the transpose of an orthogonal matrix is is its inverse. Now recall that the inverse of a diagonal matrix is simply a diagonal matrix with the reciprocals of each diagonal element (assuming no zeros). For instance
$$\begin{pmatrix}
2 & 0 \\
0 & 3
\end{pmatrix} ^{-1} =
\begin{pmatrix}
\frac{1}{2} & 0 \\
0 & \frac{1}{3}
\end{pmatrix}$$
Since $A$ was invertible there will be no zeros on the diagonal of $D,$ so $A^{-1} $ is orthogonally diagonalizable with the same orthogonal matrix, $Q$ as $A$.
Note that in a orthogonal diagonalization, the diagonal elements in $D$ are you eigenvalues and $Q$ is an orthogonal eigenbasis. For more information, read up on similarity transformations.


Formal representation of cases in mathematics

Question: Trivial part:
Solving a quadratic equation $ax^2 + bx + c = 0$, where $a,b,c$ are real numbers, requires to consider two cases: (i) $a=0$ and (ii) $a \neq 0$. In the first case there is only one solution: $x=-c/b$, while in the second one there are two (complex) solutions: $x=(-b \pm \sqrt{b^2-4ac})/2a$.
My problem (I believe that it is tricky, otherwise I would not ask you for help):
I am looking for the most formal representation of the facts stated above expressed in formalism of logic or set theory or any other, without any comments that are essential for understanding it (such solution can be found on Wikipedia's site). The part that is bothering me the most is: how to deal with cases in formal logic/mathematics, without any comments and explanations? There are some formal and explicit ways to do it in many programming languages (e.g. "select case" construct in Fortran), however I do not see the right way to do it using formal mathematical notation.
Comment: The method is formalized by [Disjunction elimination](https://en.wikipedia.org/wiki/Disjunction_elimination) rule.
Comment: I have formalized proof by cases in my proof-checking software (DC Proof 2.0) as follows: In your case, you would first invoke the equivalent of the law of the excluded middle to obtain: $a=0\lor a\neq 0$. Then prove in turn that $a=0\implies P$ and $a\neq 0 \implies P$. Combining these three results, you can infer using the Cases Rule that $P$ is true, where $P$ is the proposition you want to prove.
Comment: Thanks for your response. Nevertheless, I did not want to have a proof, I wanted to have a "formal representation" of the facts stated in "the trivial part" of my question. Do you think this is the same?
Comment: A quadratic equation cannot have $a=0$...(by definition)...
Comment: True, let's then think of it as a general equation.
Comment: The "general method" is [Poof by cases](https://en.wikipedia.org/wiki/Proof_by_exhaustion).
Comment: It seems to be somewhat pointless to ask for a formal way to represent proofs-by-cases without telling us **which proof formalism you want the answer to work with**. There are several quite different concepts of formal proof available (which all work for formalizing mathematics in general, and provably prove the same things, but differ in how they do this) -- and they generally handle proofs-by-cases in different ways to. It won't help you much to know how a proof by cases is represented in classical sequent calculus, for example, if what you know already is Hilbert-like systems.
Answer: $$(\forall a\in\Bbb{R}-\{0\})(\forall b,c,x\in\Bbb{R})($$
$$(ax^2+bx+c=0\ \Rightarrow\ (x=(-b+\sqrt{b^2-4ac})/2a\ \vee\ x=(-b-\sqrt{b^2-4ac})/2a)))$$
$$\wedge\ (\forall b\in\Bbb{R}-\{0\})(\forall c,x\in\Bbb{R})(bx+c=0\ \Rightarrow\ x=-\tfrac{c}{b})$$
There are many other ways to put it, and you could also take $x\in\Bbb{C}$ in stead of $x\in\Bbb{R}$.
Comment: This is wrong because you cannot have division by $a$ when it could be zero. Now you're going to argue that you're not supposed to evaluate the consequent of the implication when the condition is false, but that is not the mathematical definition of implication, so no go. Same for $b$.
Comment: I'm no logician, as you can tell. I was just trying to make a point. Anyway is it better now?
Comment: It's the first reasonable step in attempting to get rid of the problem. However, depending on your logic system, the restricted quantifier may face the same problem, because typically logicians say that "$\forall x \in S\ ( ... )$" is simply short-form for $\forall x\ ( x \in S \rightarrow ... )$. You would be fine if your logic system **natively** allows restricted quantification (which I would also agree is a good thing).
Comment: The best way in my opinion is to allow guarded conditionals (just like in programming language), but somehow mathematicians never bothered to invent notation for them even though they mentally guard consequents.
Comment: Servaes, thank you for the answer. I was almost sure that sooner or later something like this will pop out. I do not know what are your feelings, but I find it ugly and highly unpractical. How are yours?
Comment: user21820, thank you for your comments. Could you elaborate on the "guarded conditionals"? Do you have any knowledge about projects, attempts to make mathematical notation resemble programming language (as we both pointed out, such problems are easily resolved in programming)?
Comment: @user21820 Most logical systems don't even allow partial functions. So you would define division even when the denominator is zero (just setting it to some arbitrary value). Whenever you use division, you add the condition that the denominator be non-zero (like in this answer). Then it is irrelevant that the results are non-sensical in case the denominator is zero because the implication is true in that case anyways.
Comment: @Cat: I have my own ideas, but have never seen it used in conventional mathematics. For example, We can write "$A {?\land} B$" to mean "$A$ and then $B$" (don't check $B$ if $A$ is already false), which allows $B$ to syntactically depend on the truth of $A$. Similarly for $A {?\rightarrow} B$ for the guarded conditional. This is how people think in practice so I don't see why not. It seems however that people who devise logic don't really care whether it is practical...
Comment: @EikeSchulte: I know that that's the standard way of dealing with it. But that's clearly not the way people do things in practice. Don't think that it just has to do with partial functions. In ZFC you have no such thing as the function application syntax "$f(x)$". Why then do we write it? Furthermore we only write it in the context where we have proved that $f$ is a function whose domain includes $x$, and this syntax is meaningless if $f$ is not a function. I of course know how to get around this, but most people don't even bother to think about it.
Comment: @Cat "I was almost sure that sooner or later something like this will pop out ... I find it ugly and highly unpractical." Well, that's the tradeoff: more "purely formal" representations are harder to actually use (think machine code versus, say, Python).


Prebid in react native

Question: has anyone managed to use prebid within a react-native project?
I need to handle many bidders, and cannot fin any way to do it as prebid.js uses window variable
Answer: Though Prebid.js is written in JS, it must be used under web environment.
To use Prebid within a react-native project, you should checkout prebid-mobile-react-native or official Prebid Mobile SDKs (iOS / Android)

Prebid in react native


NestJS returning always 200 even if end point does not exists

Question: I created new NestJS app, and defined the controller like this:
<code>@Controller('/risks')
export class RisksController {
  constructor(private readonly risksService: RisksService) {}

  @Get()
  getRisks(
    @Headers('companyId') companyId: string): Promise<EmoRisk[]> {
    return this.risksService.getRisks(companyId);
  }
}
</code>
I'm calling to end point that does not exists: /risks/something
And getting HTTP response 200
Why I'm not getting 404 error ?
Thanks in advance
Answer: I figure it out.
I need to build the app each time before running it


Incrementar URL através de concatenação e usando urllib2.urlop

Question: Estou usando o código abaixo para acesso e fazer o scrapp dos e-mails que, pelo menos até onde vi, estão em três URLs idênticos que variam apenas o Numconsulta_cadastro=. Ao executar o código abaixo ele consegue pegar os e-mails apenas da primeira página repetindo-os três vezes.
from bs4 import BeautifulSoup
import urllib2
import re
num=0
while num < 3:
strnum = str(num)
html_page = urllib2.urlopen("http://www.fiepb.com.br/industria/pesquisa.php?page=Numconsulta_cadastro="+strnum+"&totalRows_consulta_cadastro=3372&empresa=&cidade=&atividade=&produto=&materiaprima=&classificador=RAZAOSOCIAL&dados=on&Submit=Enviar+Consulta")
num+=1
soup = BeautifulSoup(html_page)
for link in soup.findAll('a', attrs={'href': re.compile("^mailto:")}):
print link.get('href')

Comment: já tentou repetir os links em vez de usar um loop com os valores ?
Comment: Olá bigown, obrigado por sua atenção. São 68 links. Como fazer?
Comment: Conseguiu resolver seu problema?
Answer: Entendo sua "pergunta" como: "como posso generalizar o código abaixo?"
A versão abaixo simplifica a execução do seu código usando str.format(), um método dos objetos str que permite preencher uma string com qualquer valor, substituindo os pares de chaves com o parâmetro de número informado dentro do par (ex:"{0}").
Você também deveria evitar a estrutura while: counter, em que um loop WHILE é executado enquanto uma variável é incrementada. Seria o equivalente a usar uma Ferrari em um serviço de entrega de pizza: teoricamente possível, mas um belo (e caro) desperdício de recursos. No lugar, utilize a estrutura "for X in range(limit):", em que Python irá gerar todos os elementos entre 0 e limit, armazenar o elemento atual em X, e executar o bloco de codigo seguinte para cada possível valor de X, em ordem.
Por fim, você também deveria definir suas constantes no início do código, facilitando modificar as mesmas no futuro. Isso grandemente facilita a manutenção pois melhora a legibilidade.
from bs4 import BeautifulSoup
import urllib2
import re
WEBSERVICE = "http://www.fiepb.com.br/industria/pesquisa.php"
QUERY_VARIAVEL = "page=Numconsulta_cadastro="
QUERY_CONSTANTE = "&totalRows_consulta_cadastro=3372&empresa=&cidade=&atividade=&produto=&materiaprima=&classificador=RAZAOSOCIAL&dados=on&Submit=Enviar+Consulta"

for email_num in range(3):
    html_page = urllib2.urlopen("{0}?{1}{2}{3}".format(WEBSERVICE,
                                                       QUERY_VARIAVEL,
                                                       email_num,
                                                       QUERY_CONSTANTE))

    soup = BeautifulSoup(html_page)

    for link in soup.findAll('a', attrs={'href': re.compile("^mailto:")}):
        print link.get('href')

PRO tip: de uma olhada no módulo requests :)


Assembly error when Coded UI Test starts on a virtual machine

Question: I have made a Coded UI Test-project with VS 2015, which shall run on a virtual machine.
On the VM VS 2013 as well as 2015 are installed and the Test Agent from VS 2013 is online.
When i test it per vstest.console.exe on the VM, the tests are working fine.
But when i connect on my PC with VS 2013 or 2015 to the team project (it is in GIT) and start a team project-build, which starts the automated test via the Test Agent on the VM, the Agent deploys the build, calls the test case and then i receive the following error:
The component test adaptor has released the following exception: At least one type in the Assembly cannot be loaded. Call away the LoaderExceptions quality if you need further information.
When i take a look to the event protocols on the VM i see the following error message:
The description for the event-ID "0" from the spring "VSTTExecution" was not found. Either the component which releases this event not on the local computer is installed, or the installation is damaged. They can instal the component on the local computer or repair.
If the event on another computer has appeared, the announcement information with the event had to be stored.
The following information was stored with the event:
(QTAgent32_40.exe, PID 3732, Thread 14) Unit test adaptor threw exception: System. Reflection. ReflectionTypeLoadException: At least one type in the Assembly cannot be loaded. Call away the LoaderExceptions quality if you need further information.
   with system. Reflection. Run time modules. GetTypes (run time modules modules)
   with system. Reflection. Run time modules. GetTypes ()
   with system. Reflection. Assembly. GetTypes ()
   in Microsoft. VisualStudio. Test tools. TestTypes. Unit. UnitTestExecuter. GetAssemblyInfo (Assembly assembly)
   in Microsoft. VisualStudio. Test tools. TestTypes. Unit. UnitTestExecuter. GetTypeInfo (Type type, Boolean checkAlreadyExaminedType)
   in Microsoft. VisualStudio. Test tools. TestTypes. Unit. UnitTestExecuter. GetTypeInfo (Type type)
   in Microsoft. VisualStudio. Test tools. TestTypes. Unit. UnitTestExecuter. ResolveMethods ()
   in Microsoft. VisualStudio. Test tools. TestTypes. Unit. UnitTestExecuter. Initialize (UnitTestResult result, UnitTestRunner runner, ConsoleOutputRedirector redirector)
   in Microsoft. VisualStudio. Test tools. TestTypes. Unit. UnitTestRunner. Run (UnitTestElement test, ITestContext testContext, Boolean isLoadTest, Boolean useMultipleCpus)
The announcement resource exists, but the announcement was not found in the sign result and announcement table
How can i find out, what has gone wrong?
I already activated the logging in the Test Agent config files, but the logs where not much better than the other messages.
Thanks in advance,
Patrick
Answer: I've found it!
VS 2015 doesn't support test agents.
What a pity!
Test Agents Support for Visual Studio 2015


Voice resonating at the back of the mouth

Question: I have started taking singing lessons. My teacher is asking me to make my voice resonates at the back of my mouth.
My goal is to sing pop songs, so to have a way to sing that is like modern pop singers. I wonder if this technique is appropriate for this style of music? I know she sings opera, so I wonder if it's a technique that is just for opera singers?
Answer: Resonance is genre independent. The only time one might not opt for maximum or at least controlled resonance is if they have commercially valuable tone already.
Think Louis Armstrong. The techniques your teacher is going through with you will likely help you sing freely openly and easily.
However if you want to sing pop, as you get more advanced, you might want to spend time with someone who sings pop.
This is true of all instruments. The fundamentals carry across genre. Style is something that you want to learn from someone who is seasoned in the style.
Comment: Also, no opera singer I know of teaches proper microphone technique, or how to do a sound check. Unfortunately, most pop teachers don't, either, but some do, and IMO, this is an essential part of being a pop singer. How to choose a microphone that fits your voice, your style, and your usage scenarios (e.g. don't bring a condenser onto a loud stage), how to hold a microphone (you'd be surprised how many singers get this wrong), how to sing into a microphone (likewise), what is the proximity effect, how does it work, and how to use it, how to properly set up monitors (oh, how often I see that) …
Comment: how to communicate with the sound engineer / monitor engineer during sound check and during the performance, how to play with the compressor, the reverb, the delay, etc. One of the best singers I ever heard came up to me before the soundcheck and told me *exactly* which frequencies to cut and which to boost (he had them memorized for all the popular vocal microphones) and what the delay parameters should be. The whole soundcheck was done in less than 5 minutes, and it sounded amazing.


Promise do Javascript Com Erro de Execução

Question: Estou tentando resolver o seguinte exercício:
Crie uma tela com um  que deve receber o nome de um usuário no Github. Após digitar o
nome do usuário e clicar no botão buscar. A aplicação deve buscar pela API do Github (conforme
URL abaixo) os dados de repositórios do usuário e mostrá-los em tela:
URL de exemplo: https://api.github.com/users/diego3g/repos
Basta alterar "diego3g" pelo nome do usuário. Depois de preencher o input e adicionar, as informações devem preencher uma lista.
Não consigo entender o porque de rodar antes de eu clicar no enviar e ainda ir direto para o .catch.
Agradeço toda a ajuda!

var lista = " ";
var linha = " ";
var perfil = " ";
var textoLinha = " ";

var minhaPromise = function(){
    return new Promise(function(resolve, reject){
        var x = document.getElementById("user").value;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", 'https://api.github.com/users/'+x+'/repos');
        xhr.send('null');

        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4) {
                if (xhr.status === 200){
                    resolve();
               } else {
                   reject();

                }
            }
        }
    });
}

minhaPromise()
    .then(function() {
            lista = document.querySelector('#corpo ul');
            perfil = JSON.parse(xhr.responseText) || [];for(var dados of perfil){
                linha = document.createElement('li');
                textoLinha =  document.createTextNode(Object.values(dados));
                linha.appendChild(textoLinha);
                lista.appendChild(linha);
           }
           })

    .catch(function(){
        lista = document.querySelector('#corpo ul');                 linha = document.createElement('li');
        textoLinha = document.createTextNode("Não encontrado.");
        linha.appendChild(textoLinha);
        lista.appendChild(linha);
    });
<!DOCTYPE html>

        <meta charset="utf-8">

            <input type="text" name="nome" id="user" />
            <input type="submit" value="Enviar"  onclick="minhaPromise()" />

Answer:
Não consigo entender o porque de rodar antes de eu clicar

É simples... olhe bem para o código que escreveu:

criou uma funcao chamada minhaPromise
mas a seguir, está a chamar essa funcao com minhaPromise()

mas tem mais :)

se por alguma razao o xhr.readyState não for 4 nunca resolvera nada
a sua promessa deve de passar os dados que recebeu resolve(xhr.responseText)
a sua rejeicao deve passar um novo object Error: reject(new Error('texto a passar'))
e um erro é chamar uma funcao asyncrona em onclick="minhaPromise()"

para resolver o seu problema, tem apenas de mudar um pouco o codigo:

resolva e rejeite correctamente

xhr.onreadystatechange = function() {
    return xhr.readyState === 4 && xhr.status === 200
        ? resolve(xhr.responseText)
        : reject(new Error('Something off!'))
}

envolva a chamada minhaPromise() numa funcao, para que possa ser executada, apenas quando queremos

var onButtonClick = function() {
    minhaPromise()
        .then(function(data) {
            // "data" é o objecto com o texto do request
            // perfil = JSON.parse(data) || [];
        })
        .catch(function(err) {
            // "err.message" contem "Something off!"
        })
}

no botao, chame essa nova funcao (e nao use submitpois nao tem qualquerform`, um botao normal é suficiente)

<button onclick="onButtonClick()">Enviar</button>

já deixei de usar o XMLHttpRequest a algum tempo, desde então uso o fetch e se quiser ver o seu projecto a funcionar, com as alteracoes que expecifiquei, pode ver no CodePen


Object reference not set to an instance of an object when calling foreach loop

Question: when using @foreach in MVC 4 I get the error:Object reference not set to an instance of an object. I have called a list in outer loop and now am trying to call a list in inner loop.
@foreach (var item in Model.Users)
                        {
                           @:

                            @item.Title
                            @item.Name
                            @item.Age

                             foreach (var user in Model.Company)
                             {
                                 @user.CompanyName
                             }

                            @:

                        }

Comment: Believe it or not, there's more than one implementation of the MVC **pattern** in use in computing, in various different languages and technology stacks. I might **guess** that you're talking about ASP.Net MVC, with C# and Razor, but **I** shouldn't have to. Please edit your question and apply a few more targetted tags.
Comment: I am not 100% sure what the table is supposed to look like, but a few things. You don't need the @: near the opening and closing TR tags. Is it possible that a list of Companies was never mapped to the Model? You could try explicitly declaring it as a new list in the constructor of the Model. That would at least prevent it from blowing up. If it is always null, even when you know there is data, then im not sure what the issue would be.
Answer: Probably Model.Company is null. Check this.
How do you fill this list?
And you can remove the @: there are not needed.


Can not update drupal/core with composer

Question: Can not update drupal/core to 8.6.11
composer prohibits drupal/core:8.6.11

shows
webflo/drupal-core-require-dev  8.6.10  requires  drupal/core (8.6.10)

How can I solve it ??
Answer: The trick is, that drupal/core and webflo/drupal-core-require-dev always have to point to the very same version.
If you use composer update composer will look for this and pull the needed actual versions alone.
There are some articles recommending not to do so, but instead to update in minor parts and specify a concrete packet for better testing and reverting possibilities if something goes wrong. This means typing:
composer update drupal/core --with-dependencies
This may be true, but I often run in such errors with dependencies then I have to solve myself. You have now to specify both packets in the same command, then it will work too:
composer update drupal/core webflo/drupal-core-require-dev --with-dependencies
My private conclusion:

If I have time to go the suggested way and solve such dependencies, than I will specify the single packet to update.
If it makes problems and I have an actual backup of my codebase and my database (as you should alwas have before updating anything!) and have not so much time, I simple type composer update and mostly all will work out of the box at the first try.
Answer: Simple
composer update

did the trick by have no idea why
composer update drupal/core --with-dependencies

did not ...
final result is:
  - Updating drupal/core (8.6.10 => 8.6.11): Downloading (100%)
  - Updating webflo/drupal-core-require-dev (8.6.10 => 8.6.11)


Creating a new dask dataframe column using values from another dataframe causes "chunk sizes are unknown" error

Question: I am trying to create a new column in a dask dataframe whose values will be specific index values from another dataframe.
import pandas as pd
import numpy as np
import dask.dataframe as dd
holdings=pd.DataFrame({'cusip': ['abcd', 'efgh', 'ijkl'], 'date': ['1/1/2000', '1/1/2005', '1/1/2010']})
ratings=pd.DataFrame({'cusip':['abcd','efgh','efgh'],'date':['1/1/2001','1/1/2004','1/1/2006'],'rating':['A','AAA','B']}
dd.from_pandas(df1, npartitions=2)

The dates are all datetime.date type. The goal is that for each row in holdings, the new column will contain the index from ratings where the row contains the most recently available rating for the cusip on the date in holdings. For example, the second row of the new column in holdings should contain the index that points to the second row of ratings.
I've written the following code that does what I'm looking for when holdings and ratings are just pandas data frames (not dask):
def get_rating_index(cusip,date,ratings):
    if cusip in ratings['cusip'].values:
        temp=ratings[ratings['cusip']==cusip]
        avail_ratings=temp[temp['date'].apply(lambda x: x<date)]
        if avail_ratings.shape[0]>0:
            final=avail_ratings[avail_ratings['date']==max(avail_ratings['date'].values)]
            return final.index[0]
        else:
            return np.nan
    else:
        return np.nan
holdings['ratings_match']=pd.Series(get_rating_index(holdings['cusip'][i],holdings['date'][i],ratings) for i in holdings.index)

This post was helpful for a simpler function that I needed to apply to this same data, but when I tried to use it for this task, I got the error: "Arrays chunk sizes are unknown: %s', (nan,), 'occurred at index 0".
This was the exact code I used with dask (slight modification from the function I was using with pandas):
def get_rating_index(row):
    if row['cusip'] in ratings['cusip'].values:
        temp=ratings[ratings['cusip']==row['cusip']]
        avail_ratings=temp[temp['date'].apply(lambda x: x<row['date'])]
        if avail_ratings.shape[0]>0:
            final=avail_ratings[avail_ratings['date']==max(avail_ratings['date'].values)]
            return final.index[0]
        else:
            return -1
    else:
        return -1

holdings['ratings_match'] = holdings.apply(get_rating_index,meta='int', axis=1)

Any idea about how to do this without getting this error? I should note that the error occurs once when I try to see the data (eg. with holdings.head()), not immediately when I create the column.
Answer: This is not a complete answer yet, but may get you started:
holdings.apply(get_rating_index, meta='int', axis=1)

It is extremely likely that you actually want map or map_partition here. They allow you to generalise from Pandas in a much more straight-forward way, and are usually much more efficient.
Indeed the function you are running, get_rating_index feels a lot like a single map or where operation, although it is hard to tell what the intent is. On the other hand, temp=ratings[ratings['cusip']==row['cusip']] looks like a groupby operation.
Comment: Thanks! The issue is that in addition to the simple grouping (```temp=ratings[ratings['cusip']==row['cusip']]```) I also need to ensure that the date from the ratings data frame occurs before the date from the holdings data frame (and then also ensure it is the most recent of the dates occuring before). If there is a simpler way to do this than my unnecessarily long function, that would be extremely helpful
Comment: I'm sure there is, pandas is magic. Dask dataframes make it hard to compare a row against all other rows, because they are not meant to be a single piece in memory at once by design.


Wait for data update in realm-java between threads

Question: I am having trouble with waiting for fresh data on a worker thread. The data object is copied to realm on a main thread, but almost immediately after that I need to access this object from a worker thread, which then reports that no such object exists in realm right now ( its newly opened realm instance ) . I remember that there was a method load() that would block execution to the point of next update, but it was removed in newer versions. And I can't use change notification for this as this is not a Looper thread..
The only way I can think of right now is to sleep the thread for some magic period of time and pray to god that it has updated already, but that approach is imho wildly indeterministic.
Can anybody advise here, how can I ensure that I read the most current data at the time ?
Comment: On a worker-thread opening and closing your Realm for each unit of work should do the trick. If you see old data it is because your Realm wasn't properly closed from last time.
Comment: Yes, I think that was exactly the case .. I forgot to close the instance, which is pretty weird that I didn't run out of memory as this is a request interceptor, so instances were created very rapidly...
Answer: A possible hack would be to create a transaction that you cancel at the end.
realm.beginTransaction(); // blocks while there are other transactions
... // you always see the latest version of the Realm here
realm.cancelTransaction();

This works if the thread is started after the UI thread saves the object into the Realm.
You can also try this workaround: https://stackoverflow.com/a/38839808/2413303 (although it doesn't really help with waiting)
Comment: (but yes, you should always close Realm instance in `finally {` on background threads)
Answer: try using QueryListener, which is trigger whenewer object, satisfying certain criteria is updated
Comment: How exactly can QueryListener be set up ? I can't find anything on it within the documentation or RealmQuery object methods. Is this somehow different from regular change notifications set up on RealmResults or RealmObject and if so, do they deliver on non-Looper threads ?
Comment: Listeners doesn't work on non-looper threads. If you know for sure that something has changed, you can use `realm.waitForChange()`. However your first statement indicate you don't control your events as good as you would like as if a write happened on the UI thread it would 100% be available on a background thread if that thread was started after the write on the UI thread.
Comment: @AlexShutov because I don't have control over the created threads by the library...
Comment: @ChristianMelchior that is true, the worker threads are coming from Rx library ... More specifically they are returned by an `io` scheduler, which I believe keeps a thread pool..
Answer: using realm.beginTransaction() and realm.commitTransaction() instead of realm.executeTransaction(Realm.Transaction)
The problem with this is that executeTransaction() automatically handles calling realm.cancelTransaction() in case an exception is thrown, while the other alternative typically neglects the try-catch.
Yes, you're supposed to call cancel on transactions that aren't going to end up being committed.
For example, on background threads:
    // SAY NO TO THIS
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction(); // NO
realm.copyToRealm(dog)
realm.commitTransaction(); // NO NO NO NO NO
    // YOU NEED TO CLOSE THE REALM

// ----------------------

// SAY YES TO THIS
Realm realm = null;
try { // I could use try-with-resources here
    realm = Realm.getDefaultInstance();
    realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            realm.insertOrUpdate(dog);
        }
    });
} finally {
  if(realm != null) {
    realm.close();
  }
}

// OR IN SHORT (Retrolambda)

try(Realm realmInstance = Realm.getDefaultInstance()) {
    realmInstance.executeTransaction((realm) -> realm.insertOrUpdate(dog));
}

The problem with this is that on background threads, having an open Realm instance that you don't close even when the thread execution is over is very costly, and can cause strange errors. As such, it's recommended to close the Realm on your background thread when the execution is done in a finally block. This includes IntentServices.


How to pass multiple variables as SUDS data in python?

Question: Usually, I use dicts to call soap methods:
  SoapData = {'id':'1', 'nya':'meow'}
  Check ('SoapMethodName', SoapData)

It creates something like this:
<data:id>1</data:id>

<data:nya>meow</data:nya>

That works fine. But sometimes I need something like this in request:
<arg1>12<arg1>

<arg2>meow<arg1>

That means I can not use dictionaries. So I need a new function, which gets 2 data arguments:
  Check2 ('SoapMethodName', id, nya)

What if 20 data arguments are needed? How do I pass them? Arrays do not seem to work, is there a workaround?
Answer: args = [id, nya]
Check2('SoapMethodName', *args)


Se eu posso fazer tudo com programação estrutural, por que criaram a orientada a objetos?

Question: Na pergunta sobre - Tudo que consigo fazer em POO eu consigo fazer em PE? - a resposta aceita e mais bem votada diz que:

Sim, qualquer linguagem de programação pode fazer tudo. Agora, cada paradigma tem seu jeito de organizar, então nem sempre pode-se fazer do mesmo jeito. Mais ainda, com algumas linguagens e uso de determinados paradigmas é possível que tarefas específicas sejam mais fáceis de fazer em um paradigma do que em outro.

Ou seja, afirma que é possível, e que qualquer linguagem de programação pode fazer tudo, seja estrutural ou orientada à objetos.
Pensando nisso, gostaria de saber: se "qualquer linguagem de programação pode fazer tudo",

Por que criaram a orientação a objetos?
Foi uma necessidade de incrementar a linguagem / melhorá-la? Ou foi simplesmente para seguir a "modinha"?

P.S.: Visões mais gerais das linguagens, ao meu ponto de vista podem ser respondidas, mas gostaria de saber em específico a linguagem PHP.
Comment: "*é possível que tarefas específicas sejam mais fáceis de fazer em um paradigma do que em outro*" já não responde essa pergunta?
Comment: Pelo mesmo motivo que com cavalos se ia a qualquer lugar, mas mesmo assim houve quem quisesse inventar carros e trens.
Comment: Long story short: OO foca muito o encapsulamento, podendo ser usado até em C; suporte a OO na linguagem permite usar as coisas boas de OO numa sintaxe mais enxuta
Answer: Para organizar melhor códigos complexos, para tratar melhor domínios extensos. Sim, fazer OOP em scripts, aplicações fugazes, simples, não é vantajoso. Mas por sorte muitas pessoas não fazem OOP nessas coisas, ainda que dizem que fazem.
OOP é modinha se considerar que as pessoas usam onde não deve. Modinha não é algo passageiro, é algo que só está sendo usado porque as pessoas usam, sem um motivo claro. Não é modinha quando usado onde é útil. É muito modinha quando a pessoa fala que está fazendo e nem está, ela só quer fazer parte do grupo que está "bombando". E como eu disse em resposta anterior, é sexo de adolescente.
A criação de OOP não tem nada de modinha. A maioria das tecnologias não são modinhas. O mesmo não se pode dizer de várias metodologias que até foram criadas para atender uma necessidade, mas não cumprem o prometido.
É como porte de arma, só para pegar um exemplo. Ele é útil, mas defender que todo mundo deve poder ter uma arma é modinha. Não atende uma necessidade real, mas sim uma inventada.
Em PHP de forma geral é modinha. Tem caso que não é, mas é raro. E sinceramente quando é adequado, normalmente é a linguagem errada para aquele problema. PHP é umas linguagens mais de script que existe, até a forma de nomear variável indica isso. Colocar OOP em PHP foi e ainda é modinha. Claro que a definição mais precisa disto é sobrevivência. Hoje poucas coisas precisam de scripts (ou até tem várias, mas que você cria em um estalar de dedos e encerra, não gera trabalho), o grosso do desenvolvimento são em cima de coisas complexas. Sem OOP a linguagem definharia a um nicho muito pequeno, o que aconteceu com Perl. Mas aí a linguagem ficou inconsistente.
OOP é muito mais difícil de entender e fazer certo, tanto que quase todo mundo faz errado. É muito comum as pessoas complicarem seu design para tentar ser OOP sem trazer vantagem alguma.
OOP é ótima nesses casos de muitas relações entre objetos, quando os objetos são muito complexos, quando há relações de subtipo, hierarquias. GUI se beneficia muito disso. Jogos costumam se beneficiar, alguns tipos de negócios, mas bem mais raros. Frameworks e bibliotecas mais complexas podem ser beneficiar muito.
Reforço que a resposta fala que OOP e PE são coisas muito distintas. Gostaria que todo mundo lesse os links lá para entender um pouco mais sobre OOP (eu sei que não respondi totalmente) e entender que programação estruturada é algo muito simples e foca em outro aspecto da programação que OOP não foca. Programação estruturada não é sobre organização de código, é sobre o fluxo do algoritmo.
Coloquei no GitHub para referência futura.
Answer: Cada tipo de paradigma de programação serve um propósito, mas como dissestes, estrutural pode fazer as funções de uma Orientada a Objetos, porém quando se trata única e exclusivamente de Objetos, as linguagens de POO são bem mais fáceis de se trabalhar e gerenciam (na maioria) a memória de uma melhor maneira para esse propósito.
POO tem conceitos de herança, classes Abstratas(Java) e encapsulamento, o que é o foco desse paradigma, que salva o programador de muitas linhas de código.
Se fossemos seguir a lógica de que uma única linguagem é fundamental estaríamos programando em Assembly até hoje, ou até mesmo em Binário, o que não parece muito convidativo, certo?
Então a resposta do porque outras linguagens são criadas é simples: Cada uma serve um propósito, mas com a evolução natural a linguagem ela vem abrangendo um maior conteúdo.
Vale a leitura de Paradigmas de programação e suas diferenças
Comment: A impressão que eu tive que não foi isso que foi perguntado.


DropDownList OnSelectedIndexChanged event stops working when seemingly unrelated User Control is added

Question: I have a page with a repeater. Inside each item of that repeater are update panels, each containing a control:
<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("Property1") %>' />
            </ContentTemplate>
        </asp:UpdatePanel>
        <asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server" AutoPostback="true"
                    OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
                    <asp:ListItem Text="1" Value="1" />
                    <asp:ListItem Text="2" Value="2" />
                    <asp:ListItem Text="3" Value="3" />
                    <asp:ListItem Text="4" Value="4" />
                </asp:DropDownList>
            </ContentTemplate>
        </asp:UpdatePanel>
    </ItemTemplate>
</asp:Repeater>

The code behind supplies the data source:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            List<Class1> Source = new List<Class1>();
            Source.Add(new Class1("Test1"));
            Source.Add(new Class1("Test2"));
            Source.Add(new Class1("Test3"));
            Repeater1.DataSource = Source;
            Repeater1.DataBind();
        }
    }

And here is the class being bound:
public class Class1
{
    public string Property1 { get; set; }
    public string Property2 { get { return "Property 2"; } }
    public Class1() { Property1 = string.Empty; }
    public Class1(string P1) { Property1 = P1; }
}

And when the drop down list selected index is changed, this is the event that fires in the code behind:
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        RepeaterItem ri = (RepeaterItem)ddl.NamingContainer;
        Label l = (Label)ri.FindControl("Label1");

        l.Text = ddl.SelectedValue;

        UpdatePanel up = (UpdatePanel)ri.FindControl("UpdatePanel1");
        up.Update();
    }

All of this code works just fine. When the selected index is changed, the label text is updated to match, and everything is happy.
The problem is when I add a user control to the repeater. It doesn't seem to matter what the user control does, but here is a simple example I used to break this sample code:
Front:
<asp:Label ID="Label1" runat="server" />

Back:
public partial class WebUserControl1 : System.Web.UI.UserControl
{
    private Class1 _Item = null;
    public Class1 Item { get { return _Item; } set { _Item = value; } }

    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = Item.Property1;
    }
}

When I register this user control on the page:
<%@ Register Src="WebUserControl1.ascx" TagName="Control1" TagPrefix="uc1" %>

And place it inside the repeater in its own update panel:
<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("Property1") %>' />
            </ContentTemplate>
        </asp:UpdatePanel>
        <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <uc1:Control1 ID="Control1" runat="server" Item='<%# ((IDataItemContainer)Container).DataItem %>' />
            </ContentTemplate>
        </asp:UpdatePanel>
        <asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server" AutoPostback="true"
                    OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
                    <asp:ListItem Text="1" Value="1" />
                    <asp:ListItem Text="2" Value="2" />
                    <asp:ListItem Text="3" Value="3" />
                    <asp:ListItem Text="4" Value="4" />
                </asp:DropDownList>
            </ContentTemplate>
        </asp:UpdatePanel>
    </ItemTemplate>
</asp:Repeater>

The user control paints correctly (suggesting it is working), but the OnSelectedIndexChanged event stops firing. Even inserting System.Diagnostics.Debugger.Break() inside the event doesn't fire. Everything else (the event code, the page load, the class) all remain the same. The only difference is adding this user control to the page and repeater.
Can anyone tell me why the introduction of this (seemingly unrelated) user control seems to break the DropDownList behavior?
Thanks for any help!
EDIT: Answered. I was just missing a Page.IsPostBack test in the Page_Load event of WebUserControl1. Silly mistake.
Comment: Solved. Silly mistake. This was caused by the Page_Load event in WebUserControl1 not having a Page.IsPostBack test. Adding that solved this issue.
Answer: Yeah I had similar exact issue, if you dont check the !IsPostback property on the page load , then the control is rebound again and there fore the other controls inside like the dropdownlist is also rebound and reinitialized and thus the event is not fired


Windows Network - Can't refer to \\Server

Question: We're setting up a small network, 2 or 3 computers. We designated one computer as Server1. Computer2 can access Server1 like so: \\Server1\Folder1
However because of an application configuration issue, on Server1, it needs to reference itself in the same way. But on Server1, windows doesn't recognize \\Server1\Folder1 for some reason.
I'm having trouble getting that working.
Comment: Please tell us what is the problem you are having?
Comment: Thanks! From Computer2, I can enter \\Server1\Folder1 in the Windows Explorer and it works. But from Server1 itself, when I enter that into the Windows folder I get: Windows can not access \\Server1 ...
Comment: If you try to access to the folder by IP does it works?
What happen if you try to ping your server from itself?
It looks like he can't resolve his hostname.
Comment: Please post the output of `ipconfig /all` and `nslookup server1`, both run from Server1.
Comment: Thankyou both. By IP Address, now why didn't I think of that. It should work, I hope. I will try to run ipconfig /all and nslookup server1 and post the result. This place is remote to me, so next time I can arrange to connect...
Answer: Silly question but can you Ping Server1 from Server1 just to make sure DNS is working fine.
Also, check the Share and NTFS Permissions...can you get to \Server1\C$ ? If you can then it's a Share permission issue if not then you'll need to check Share and NTFS permissions.
Let me know how you get on and if I can help further.


sectioned table view animation

Question: I see this quite often, where you have sections view on top and then when you scroll up and the next section view reaches/overlap with the section view on top then it merges. How do I do something like this? Is there a library for doing this?
Comment: That sounds like the default behavior for a UITableView as sections, in which case you don't have to to anything. Can you point to an example that illustrates the type of animation you're seeking?
Comment: Are you referring to the behavior you see in the Contacts app?
Comment: Yes! Where the Alphabet scrolls up
Answer: This is default behavior supported by all UITableViews (you don't need a custom library for this). You have to implement the sectionIndexTitlesForTableView method of your UITableView:
<code>- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
}
</code>

sectioned table view animation


Why is there no solution with radicals for the quintic equation $x^5-x+1=0$?

Question: I'm looking for solution for this equation
$$
x^5-x+1=0.
$$
I know that there is no solution with radicals. But, I can not find possible solutions (in MSE  or  internet resource).
I know Abel-Ruffini theorem. But, this is so hard for general form.

Question: Can you please show me in this particular case why there is not solution with radicals?
Comment: [Even wolframalpha](http://www.wolframalpha.com/input/?i=x%5E5-x%2B1%3D0) doesn't know the exact forms for the solutions, only approximations.
Comment: I know wolfram alpha..
Comment: To see why there are no solutions with radicals, see [this answer](https://math.stackexchange.com/questions/837948/proving-that-a-polynomial-is-not-solvable-by-radicals) (for a slightly different polynomial).
Comment: In general, if the polynomial has rational roots we can apply https://en.wikipedia.org/wiki/Rational_root_theorem. But other than that, you would need numerical methods to find them.
Comment: That is strange: [Bring radical](https://en.wikipedia.org/wiki/Bring_radical) has not been mentioned yet.
Answer: If you are familiar with the use of Galois theory, then this particular polynomial can be handled as follows. Let $G$ be the Galois group of this polynomial.

It is irreducible over $\Bbb{Z}$ (hence over $\Bbb{Q}$) because it is irreducible over $\Bbb{Z}_5$. See this thread for many ways of seeing that. Consequently we can view $G$ as a transitive subgroup of $S_5$. In particular $G$ contains an element $\tau$ of order five which obviously must be a $5$-cycle.
Modulo two it factors as $$x^5-x+1\equiv(x^2+x+1)(x^3+x^2+1)$$ a product of an irreducible quadratic and an irreducible cubic. By Dedekind's theorem the group $G$ thus contains an element $\sigma$ with cycle type $(2,3)$.
The permutation $\sigma$ is odd, and it has order six. Therefore $|G|$ is divisible by $30$, and $G$ is not subgroup of $A_5$. It follows (from a census of subgroups of $S_5$) that $G$ must be all of $S_5$.
The group $G$ is not solvable, so by one of the main results of Galois theory the zeros of your polynomial cannot come from a field gotten as a root tower extension of $\Bbb{Q}$.
Comment: @Arthur. No, not all transitive subgroups of $S_n$ contain an $n$-cycle. The smallest example is that copy of (a transitive) Klein four as a  subgroup of $A_4$. But, when $n$ is a prime, $n=p$, then a transitive subgroup $G$ of $S_p$ does contain a $p$-cycle. This is because by orbit-stabilizer we have $p\mid |G|$, so by Cauchy there is an element of order $p$ in $G$. But such an element is necessarily a $p$-cycle. Sorry about leaving the answer a bit too sketchy at that point :-/
Comment: Wow... Thank you for amazing answer.
Comment: Dedekind's theorem with modulo 5 seems to prove that there is a $5$-cycle in $G$. However, I don't see how it follows from $G$ being transitive. Is it a general fact that all transitive subgroups of $S_n$ contains an $n$-cycle, or is there something else at work here?
Answer: There are solutions in terms of hypergeometric functions: for example,
$${\mbox{$_4$F$_3$}(1/5,2/5,3/5,4/5;\,1/2,3/4,5/4;\,{3125}/{256})}$$
See e.g. this article.
Comment: No: theorems never get repealed.
Comment: This is one root.  There are ways to express the others.
Comment: maybe, after 1000 years, can radical solutions be found?
Comment: Teacher,Can you explain me, is this function express all $5$ roots? Or 1$ root?


Put each equation in self-adjoint form (Sturm-Liouvulle)

Question: Put each equation in self -adjoint form
$x^{2}{y}''-x{y}'+\lambda y=0$
If I want to put it in the self-attached form of Sturm Liouvulle, I first do this:
$x{y}''-{y}'+\frac{\lambda }{x}y=0$
$e^{-\int \frac{dx}{x}}$
$e^{-ln(x)}=\frac{1}{x}$
$\frac{1}{x}\left [x{y}''-{y}'+\frac{\lambda }{x}y  \right ]=0$
${y}''-\frac{1}{x}{y}'+\frac{\lambda }{x^{2}}y=0$
but I don't know if what I did is good, you can help me
Answer: If you want to multiply by $a$ to put in self-adjoint form,
$$
              x^2 a(x) y''(x)-x a(x)y'(x)+\lambda a(x)y=0,
$$
then you must arrange it so that $(x^2 a)'=-xa$, or
$$
                2x a + x^2 a'=-xa \\
                  x^2 a' = -3xa \\
                  \frac{a'}{a} = -\frac{3}{x} \\
                a= Cx^{-3}
$$
$C=1$ is good enough. Then the original equation becomes
$$
              \frac{1}{x}y''-\frac{1}{x^2}y'+\frac{\lambda}{x^3}y=0 \\
           \left(\frac{1}{x}y'\right)'+\frac{\lambda}{x^3}y=0
$$


Unit normal vector to the curve of a function at a point

Question: How can I derive the formula for the normal unit-vector to the curve of a function at a given point $p$?
Answer: If curve is represented by $f(x,y)=0$, then $\nabla f_{(x_0,y_0)}$ is normal vector to curve at point $(x_0,y_0)$
Comment: 'nabla', it is.
Comment: What's the name for that reflected $\Delta$?