How to create a 3x3 grid with sub child grids 2x2 and 1x1?

Question: Currently i am using nested linearlayouts and nested weightsum and layout weight to achieve what i wanted in the screenshots below.
I did notice however that as the lint-warning suggests, that my one of my out-dated phone is slightly slow. As nested weight sums seems to hinder the performance of a device.
This is my linearlayout code currently. And I would like to achieve the screenshot attached. Are there any other way that i could achieve it without using extensively nested weightsums? I have seen constraintLayout that does similar things, but how do i actually use it?
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/title_layout"
    android:weightSum="3"
    android:orientation="vertical"
    android:layout_above="@id/next">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="horizontal"
        android:weightSum="3"
        android:layout_weight="2">

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:background="#345678"
            android:layout_weight="2">

        </RelativeLayout>

        <LinearLayout
            android:layout_weight="1"
            android:layout_width="0dp"
            android:weightSum="2"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <RelativeLayout
                android:background="#3bcad5"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1">
            </RelativeLayout>

            <RelativeLayout
                android:background="#3ca3d2"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1">
            </RelativeLayout>

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="horizontal"
        android:weightSum="3"
        android:layout_weight="1">

        <RelativeLayout
            android:background="#123456"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

        </RelativeLayout>

        <RelativeLayout
            android:background="#310911"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

        </RelativeLayout>

        <RelativeLayout
            android:background="#92F358"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

        </RelativeLayout>

    </LinearLayout>
</LinearLayout>

Answer: you can set above layout using ConstraintLayout like below :
my_file.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/darker_gray"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0">

        <android.support.constraint.Guideline
            android:id="@+id/guideline"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.6666667" />

        <View
            android:id="@+id/view_white"
            app:layout_constraintStart_toEndOf="@id/guideline"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintDimensionRatio="1"
            android:background="@android:color/white"/>

        <View
            android:id="@+id/view_green"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintDimensionRatio="1"
            android:background="@android:color/holo_green_dark"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@id/guideline"
        />

        <View
            android:id="@+id/view_orange"
            app:layout_constraintTop_toBottomOf="@+id/view_white"
            app:layout_constraintStart_toEndOf="@id/guideline"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintDimensionRatio="1"
            android:background="@android:color/holo_orange_dark"/>

        <View
            android:id="@+id/view_red"
            app:layout_constraintTop_toBottomOf="@+id/view_orange"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintDimensionRatio="1"
            android:background="@android:color/holo_red_dark"/>

        <View
            android:id="@+id/view_purple"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="@android:color/holo_purple"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintDimensionRatio="1"
            app:layout_constraintEnd_toStartOf="@+id/view_red"
            app:layout_constraintTop_toBottomOf="@+id/view_green" />

        <View
            android:id="@+id/view_blue"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="@android:color/holo_blue_light"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintDimensionRatio="1"
            app:layout_constraintTop_toBottomOf="@+id/view_green" />

    </android.support.constraint.ConstraintLayout>

</android.support.constraint.ConstraintLayout>

main Constraint-Layout is set square and second Constraint-Layout create all other view. this is exactly become like your screen shot.


TCP Balancer active/standby active/passive

Question: I have two Servers, Server A,ServerB. running as TCP socket server.
I want to a active/standby or /active/passive failover.
that means:
1:Server A and Server B Running, route ALL connection to Server A.
2:Server A down, route ALL connection to Server B.
3:Server A back, still route ALL connection to Server B.
4:Server B down, then route ALL connection to Server A.
ONLY will be one server handle all the connections at a time.
I have search a lot.
it seems that HAProxy have a trick to do like this.
Prevent HAProxy from toggling back from fallback to master
but it have a problem, in the case 4, when Server B down, Server A is running, the HAPRoxy still do not route connection to Server A.
is there a way to reolve it?
I also have try Nginx, did not work at all.
listen  sql-cluster 0.0.0.0:1433
        balance roundrobin
        server  sql01 192.168.100.109:1433 check backup
        server  sql02 192.168.100.180:1433 check inter 5s fall 3 rise 99999999
Comment: Did you try to solve this on your own? If so, could you show your config(s)?
Comment: I have try, can not resolve.
Comment: Which config did you use?
Comment: same as here http://serverfault.com/questions/220681/prevent-haproxy-from-toggling-back-from-fallback-to-master
Comment: like rise 99999999, sorry, I dunno how to format the code.
Answer: Try with Keepalived.
 vrrp_instance v_http {
  smtp_alert
  state MASTER
  nopreempt
  interface eth0
  virtual_router_id 51
  advert_int 1
  priority 101
  unicast_src_ip 126.96.36.199

  unicast_peer {
   22.214.171.124
  }
  authentication {
   auth_type AH
   auth_pass myPassword
  }
  virtual_ipaddress {
   x.x.x.x # virtual ip address
  }
 track_script {
  chk_http_port
 }
}


Print name of test function in nose_parametrized

Question: I have test classes that extend unittest.TestCase, and use nose_parameterized for parameterization. I'm using nosetests -v to run the tests. I have nosetests version 1.3.7.
I'd like the test runner to print the name of each test. Instead it just prints the parameters passed into the test.
Here's an example of my actual output:
[with sentence='Put it on the top shelf of the bookshelf'] ... ok
[with **None={'world': [<WorldObject table>, ...'basic', 'language': 'Pick cup'}] ... ERROR
[with **None={'name': 'first action', 'langua...'' ... ERROR
[with **None={'name': 'two pointing choices',...'' ... ERROR

Based on examples from the documentation for nose_parameterized, I think the output should incorporate the name of my test method and its class, approximately like this.
language_analyzer_test (md.LangaugeAnalyzerTest) ... ok
language_test (md.ReferenceResolverTest) ... ERROR
reference_resolver_test (md.ReferenceResolverTest) ... ERROR
reference_resolver_test (md.ReferenceResolverTest) ... ERROR

But it doesn't.
The documentation further states:

If the first parameter is a string, that string will be added to the end of the method name.

So based on the strings I'm passing in as the first parameter to each tests, the output should look like this:
language_analyzer_test_Pick_cup (md.LangaugeAnalyzerTest) ... ok
language_test_basic (md.ReferenceResolverTest) ... ERROR
reference_resolver_test_first_action (md.ReferenceResolverTest) ... ERROR
reference_resolver_test_two_pointing_choices (md.ReferenceResolverTest) ... ERROR

But alas.
Based on the actual output, it's hard to tell which test method is being run or even which test class it's from.
How can I get nose to print the test name for each test case?
Answer: If the method under test has a docstring, nose-parameterized will add the parameters (the [with …], above) to the docstring, and nose will print the docstring along with each test.
If you remove the docstring from the tests, you should get the method name as shown in the documentation.


Cocoa ITLibrary - ITLibMediaItem.location always nil/NULL

Question: I am getting always nil ITLibMediaItem.location attribute.
<code>    //            let library: ITLibrary = try ITLibrary(APIVersion: "1.0")
    //            library.reloadData()
    if let mediaItem = iTuneMediaItem {
        if let location = mediaItem.location{
            return location.path
        }else{
            print("nil location")
        }
    }else{
        print("nil mediaItem")
    }
</code>
If i enable commented line to reload library before get location it is working, but i don't want to reload library every time because it takes time if we have large iTunes playlist.
can please anyone explain how we can fix without reloading library every time?
EDIT :
I am using ITLibMediaItem from ITLibPlaylist.items[]
Answer: I figure the fix is need to make static app level attribute of ITLibrary and reload once at init.


Testing GUIs with GoogleTest & QTest

Question: I have a GUI and I want to test the many functionalities of this GUI.  The issue is that the sub-widgets are all private members of this main GUI class.  How can I test my main GUI when I can't populate any of these sub-widgets since they are private to me in the test class?
For example, I have multiple line edits as fields in the ui object.  These line edits are scraped and dumped into a QVariant object type specific to this GUI.  I can't populate these edits from my test functions since they are inaccessible due to privacy issues.  Therefore, I can't test the QVariant object matches the data supplied by the GUI.
I also can not call any of the QTest functions on specific widgets to trigger events.
For example, I can't call
QTest::mouseClick(testGUI.ui->pushButton1, ...)
because ui is private and pushButton1 would be private whether it was part of the UI or not.  Therefore, I can't simulate mouse click events on these buttons either.  I also tried to use
QTest::mouseClick(testGUI, ..., ..., ..., QPoint(70, 180));
Where the QPoint is the absolute position of the button with respect to the widget, but even this doesn't trigger the button clicked.
How can I test these widgets when so much of the widget is private and inaccessible to the user?
Comment: GUI is not good subject for unit-testing. It is really important to see how it looks - UT will not replace your eyes. But - you should extract/separate all business logic from your GUI and unit-test this business logic code.
Comment: I use friend declaration to grant test code access to protected and private members of code under test. For GoogleTest there is a macro FRIEND_TEST to declare test functions as friend. Maybe not the most elegant method but works for me for simple test scenarios.
Answer: You can try to create shared library which includes the directory build-xxx-desktop-debug.
Then in the test.pro you do the libs.
Hope it works.

Testing GUIs with GoogleTest & QTest


Best way to normalise to remove the effect of a variable

Question: I have a forward citation column that gives me the number of times a patent is cited. However, it is obvious that it is affected by age since the older the patent is, the probability that it will be cited more compared to a newer patent that is granted years later. Hence, I would like to normalise the forward citation column by age. I decided that I should divide the forward citation count by the patent's age. Is that the best way? . I have read somewhere that we can use log transformation but I am not sure. The pdf of forward citation is shown if that is useful. The forward citation generally follows a lognormal distribution.
Can anyone help?
Comment: This looks like a Poisson distribution. When you have a variable you want to scale by, this is called an offset in Poisson regression.
Comment: Hello, I wan to normalise by patent age. I have tried using this formula (normalised = forward citations/patent age).
Comment: You should be doing a Poisson distribution with an offset (IMHO). How to do this depends on the software you are using.
Comment: Have you plotted the age and the citation count in a scatterplot? How does it look? Can you post the graph here?
Answer: Since you have only the total number of citations at time T (for example, as of today), it makes sense to adjust by the age of the patent to account for the fact that older patents had more time to receive citations. One complication is that the number of citations a patent receives is not a linear function of time. Some patents might receive a lot of citations right from the start, others might receive very few citations in the beginning yet gain more citations later. So, ideally you would need citation information for each year since publication to be able to compare these two patents. Granted, if this information is not available, then dividing by age is a reasonable approach. This division by age is a conceptual adjustment given your expert knowledge that the number of citations depends on age. So, it is unrelated to taking logs. You can take logs if you want, depending on your regression specification.


Recover stashes that were accidentally cleared

Question: This morning while moving quickly from branch to branch, I had to stash my changes.  In my haste, I issued a
git stash clear

-- as my stash list was rather long. In the list of stashes that I cleared was some work I need to recover.  Is there a way to recover it?  The stash in question was saved using:
git stash save "my notes here"

Not sure that really helps. Is there any hope?
Comment: Does this help? http://stackoverflow.com/questions/89332/recover-dropped-stash-in-git?rq=1
Answer: As any stash is like a commit, but handled differently, you'll find them in the reflog. You can access the reflog via git reflog, where you get a list of all commit objects recently made.
Comment: I am finding that I need to use `git reflog --all` to see anything regarding stashes.  Sadly, what I get back is only the very last stash that was created (or 'pop').  When I navigate to the '/.git/refs' folder and examine the 'stash'  file in Textmate, indeed -- it only show that single (and lonely SHA1).  It would seem to me that `git stash clear` is destructive, and unrecoverable.
Comment: That's unfortunate. Did you check the link in the comment on your question? That might help.
Comment: thanks @Femaref -- it also did not help (thanks @Ashfame). Turns out my files were not tracked -- and I believe that was the crux of my problem.


SapUi5 data binding on the radio button group is not working

Question: can some one please advise on the two-way data binding of the radio buttons with SAP UI5. In the data model I have an attribute called textType, it can return "Y" or "N", based on that I have to select the correspondent radio button
 <m:RadioButton text="yes" selected="{path:'/textType',formatter: function(val){ if(textType== 'Y') return true; }else{ return false} }"/><m:RadioButton text="No" selected="{Selected}"/>

however I am not able to set the value. I tried using the radiobutton group however no success
 <RadioButtonGroup buttons="{/Type}" >
<RadioButton text="YES" selected = "{Selected}" />
<RadioButton text="No" selected = "{Selected}" />
</RadioButtonGroup>

can some one pls advise on this .
Updating the model data code .
    var stermType = this.getView().byId("rbgTermType").getSelectedButton().getText(),
    sElecReg = this.getView().byId("rbgElecReg").getSelectedButton().getText(),
    sOpenReg = this.getView().byId("rbgOpenReg").getSelectedButton().getText(),
    sConfirmgdpr = this.getView().byId("idConfirmgdpr").getSelected(),
    oData = {};
    oData = {
    Term_Type: stermType,
    Electoral_Reg: sElecReg,
    Open_Reg: sOpenReg,
    Data_Protection_Confirm: sConfirmgdpr,
    };

    this.getView().setBusy(true);
    var that = this;
    var mParams = {
    success: function () {
    that.getView().setBusy(false);
    }.bind(),
    error: function (err) {
    that.getView().setBusy(false);
that.fnShowErrorMessage(jQuery.parseJSON(err.responseText).error.message.value)
    }.bind()
};
this.getOwnerComponent().getModel().update(  "/PassportVisaBankCitizenshipDetailsSet(StudentObjid='',PassportNumber='',AccountNumber='')", oData, mParams);
this.getOwnerComponent().getModel().refresh(true);

Comment: Formatters and Expression Binding destroy Two-way data binding. Maybe you need to rework your odata backend. Instead of Y or N return boolean values.
Answer: the closest thing that you can do it treat 0 as Y and 1 as N.
here is a working example. https://jsbin.com/hutuvo/edit?html,output
<!DOCTYPE HTML>

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta charset="UTF-8">
    <title>MVC</title>

Answer: Well, if the property textType has either value Y or N, you will need to use expression binding:
 <RadioButtonGroup >
   <RadioButton text="YES" selected = "{= ${textType}==='Y'}" />
   <RadioButton text="No"  selected = "{= ${textType}==='N'}" />
 </RadioButtonGroup>

The disadvantage is that you lose two-way when using expression binding. So you will need an onSelect Event handler (check event name in api docs)
If your property would be a Boolean, then you could just use
 <RadioButtonGroup >
   <RadioButton text="YES" selected = "{textType}" />
   <RadioButton text="No"  selected = "{=!${textType}}" />
 </RadioButtonGroup>

and be done
UPDATE: Here is a working example: https://jsfiddle.net/iPirat/yhj3eabv/
I have put the thwo above Radio Button Groups in place, using the sample model with content
        {
          textType1: 'N',
          textType2: true
        }

The first {RadioButtonGroup} is working with {textType1} and an event handler is necessary
The second {RadioButtonGroup} is working with the boolean {textType2} and no event handler is needed. Binding does everything for you.
Comment: thanks it worked.  I have not tried the two way binding, changed my data type to boolean and will try saving the data and will check ..
Comment: thank you, the code is not working with the two way binding. any other advise ? I am using the above lines of code for two way binding on press event of my save button. edited my question with the code..
Comment: I added a jsfiddle example to demonstrate when you need an event handler, and when the two-way-binding is working without any event handlers


How to prove that $b_{2008}\neq 0$

Question: Let the polynomial $f$ be defined as
$$f(x)=a_{m}x^m+a_{m-1}x^{m-1}+\cdots+a_{1}x+a_{0}, \qquad a_{i}\in \Bbb Z \ (i=0,1,2,\cdots,m), \ a_{i}\neq 0.$$
Define the sequence $\{b_{n}\}$ as
$$b_{1}=0,b_{n+1}=f(b_{n}).$$
Show that
$$b_{2008}\neq 0.$$
My try: let $x_{i},i=1,2,\dots,m$ be the complex roots of the polynomial $f(x)$, then
$$f(x)=a_{m}(x-x_{1})(x-x_{2})\cdots(x-x_{m})$$
Maybe this is Olympic math exam question, this is a problem my frend asked me.
Comment: @math110 Please try not to make trivial edits to questions!
Comment: Some thoughts: Suppose that $b_{2008} = 0$. Then $g(x) = f^{(2007)}(x)$ is a polynomial with integer coefficients satisfying $g(0) = 0$ and $g(b_i) = b_i$ for $1 \leq i \leq 2007$. From $g(0) = 0$ it follows that the constant term of $g$ must be $0$, while $g(b_1) = b_1$ (and $b_1 \neq 0$) implies that the linear term of $g$ must be $1$.
Comment: @TMM but $b_1 = 0$...
Comment: Ah, the sequence starts at $b_1$. Make that a $b_2$ then.
Comment: I've gone like: since $b_{2007}$ is an integer and a root, it divides $a_0$, so $k \cdot b_{2007}  = a_0$. But $b_{2007}$ is itself a multiple of $a_0$, so $k \cdot n \cdot a_0 = a_0 $ and thus $a_0 = 0$, which is not the case, or $n \cdot k = 1$, i.e. $n=k=1$ or $n=k=-1$. I don't guarantee this works totally but I have ruled out the case $n=k=1$ :)
Comment: $f(x) = x^2 - 2x + 1$ has $b_2 = 1, b_3 = 0, \cdots$ so it is at least important that $2008$ is even.
Comment: Check Putnam 2000 problem 6: http://mks.mff.cuni.cz/kalva/putnam/psoln/psol006.html
Answer: We know that for integers $a$ and $b$ and a polynomial $P$ that $a-b|P(a)-P(b)$. Say that
$$b_i=P^i(0)=\underbrace{P(P(\dots P(0)\dots ))}_{P \text{ applied $i$ times}}$$
and $b_1=0$. Now, we know that
$$
b_1-b_0|P(b_1)-P(b_0)=b_2-b_1\\
b_{n+1}-b_{n}|P(b_{n+1})-P(b_{n})=b_{n+2}-b_{n+1}
$$
Thus, we see that
$$
b_1-b_0|b_2-b_1|b_3-b_2|\dots |b_{2008}-b_{2007}
$$
Because $a_0\neq 0$, we know that $P(0)\neq 0$, thus $P(0)-0=b_1-b_0\neq 0$. We know now that all differences are $0$ or a multiple of $P(0)=a_0$. Now, suppose $b_{2007}=0$. (I accidently assumed $b_0=0$, so we have to take $2007$ instead, which is odd (and it turns out that is a sufficient condition).)  Then, we get $b_{2008}=P(b_{2007})=P(0)=a_0$. Thus:
$$
a_0=P(0)-0=b_1-b_0|b_2-b_2|\dots|b_{2008}-b_{2007}=P(0)-0=a_0
$$
We now conclude that the absolute values of all differences $|b_{n+1}-b_n|$ must be equal to $P(0)=a_0$. We now get $b_{n+1}=b_n+\pm a_0$. From this, it follows that $2a_0|b_{2n}$ and $2a_0|b_{2n+1}+a_0$. We know that $2007$ is odd, so $2a_0|b_{2007}+a_0$. Therefore, $b_{2007}$ can't be $0$.
This is indeed a typical Math Olympiad question, as I have solve some very similar exercises during my training for the IMO.
Answer: Observe that $f(p a_0) = a_0 ( p(\text{integer}) + 1)$ and in particular $b_j = p_j a_0$ for some integers $p_j$.
Now $p_{j+1} = p_j(a_m p_j^{m-1} a_0 ^{m-1} + \cdots + a_1) + 1$.
Work modulo 2. Then this maps $0 \mapsto 1$. Also, either $1 \mapsto 0 \mapsto 1$ or $1 \mapsto 1 \mapsto 1$ under two applications. As such, $p_1 \equiv 0 \implies p_2 \equiv 1 \implies p_{2k} \equiv 1$ for all $k$. In particular, $b_{2k} \neq 0$.

How to prove that $b_{2008}\neq 0$


Converting HTML to markdown in jodit

Question: In the below link i'm using jodit editor with react. On changing the text it returns html with the styles we have selected.On typing, below you can  see the value that it returns. I need some help in printing them in markdown language, is it possible to do in it.
https://codesandbox.io/s/lively-haze-yfbug
Tried converting the returned html to markdown using https://www.npmjs.com/package/turndown,
For example
ME typing

while trying the convert the above using turndown service it just returns ME typing styles are not present.
Thanks in advance
Answer: just use

.
it should load it in the right way
Comment: I want to converted that html to markdown language. dangerouslySetInnerHTML just gives the value.
Answer: import dompurify from 'dompurify';
import { marked } from 'marked';

marked.setOptions({
    breaks: true,
    gfm: true,
    pedantic: false,
    renderer: new marked.Renderer(),
    smartLists: false,
    smartypants: false,
    xhtml: false,
});

export const convertMarkedDownToHtml = (content: string): string => {
    const parsedHTML = dompurify.sanitize(marked.parse(content));
    return parsedHTML;
};

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Converting HTML to markdown in jodit


WYSIWYG do not make url when pasted in a hyperlink

Question: When I paste a URL into a TinyMCE editor using WYWIWYG it converts the text into a  link.
So http://vimeo.com/18150336 would be come http://vimeo.com/18150336. I would like to keep the plain text. Is their a way to configure TinyMCE to keep the link as plain text.
I do not want to strip out  tags as adding a hyperlinks should be an option on the toolbar. It should just not happen by default.
Comment: Also in drupal 7 i try this module TinyMCE and there is this problem, i try to modify the settings of WYSIWYG , and i set "Unlink" then when i write the links in the editor I unlinked the links but don't right.
Answer: This is the solution--
On drupal administration:
Administration » Configuration » Content authoring » Text formats
you must remove "Converts URL into links" and then all it's Right!!
Comment: That is Drupal 7. Also I don't think that will solve the issue. I can strip a tags out on the input filter on submit. That is fine. But I dont want to. I want to strip them out when you paste them in. Only in the WYSIWYG if you click th link button should something become a hyperlink. As I am allowing the link button I can not strip the tags out.
Comment: If you want to write with the editor the text:http://vimeo.com/18150336 you must disable the option "Converts URL into links" and you will make it.
Comment: The WYSIWYG still inserts is as a link. When I save it will be stripped out but that is not what I want. I don't want it to go in as a link.
Answer:
In Drupal 6, go to admin/settings/filters/list
Click "configure" for the type of input filter being used
Uncheck "URL filter", then Save Configuration


ComboBOX qual melhor método: OnSelectedIndexChanged via autopostback ou Jquery?

Question: Tenho o seguinte DropDownList em asp.net Webform
<asp:DropDownList ID="DDL_Categoria" runat="server" CssClass="form-control" AppendDataBoundItems="true" >
<asp:ListItem Value="" Selected="True">Selecione</asp:ListItem>
</asp:DropDownList>

Ao selecionar esse campo, automáticamente um outro DropDownList deve ser completado no rodapé do formulário.
Qual melhor método? Mais rápido, politicamente correto?

Método 01
Code Behind + autopostback
<asp:DropDownList ... OnSelectedIndexChanged="DDL_Categoria_SelectedIndexChanged" AutoPostBack="True"

e no code-behind faço a lógica.
Desvantagem: Ele carrega a página, se ele estiver digitando em outro campo pode causar algum atraso?

Método 02:
Javascript chamando em iframe. Criaria uma nova página .aspx para receber esse valor
<asp:DropDownList ... onchange="nome_functionJS(this.value)"


Image inside HTML div block won't resize

Question: Please look at the "About" tab of this website, and lines 51 to 55 of the source code.
https://lwymarie.github.io/
I intend that the three images float to the right of the text, all occupying 30% of the window's width. It seems that html code for resizing these images does not work, and the images are as big as their original sizes. I'm not sure what's wrong, since my html and css codes are rather simple.
For reference I'm copying the relevant source code.

Comment: Just add `width: 100%` to each `style` element in `img` tag.
Comment: use !Important, if you have any priority cdn
Comment: #About > div > img {
    width: 100%;
}
Answer: You will need something like that in your CSS:
img{
   width: 100%;
}

Otherwise, your images will overflow their container.
Or you can use inline CSS, as you have been doing:


How to decide whether a number is inside of wrapped (modular) interval

Question: I am having a problem a finding a suitable formula for deciding whether a number falls inside of modular interval. Example:
Let's use $mod$ $100$ and the interval $\langle 90, 10\rangle$. How would you compute if the number $95$ or $0$ falls into the interval or not? In other words is there an expression that would be true for all the numbers in the interval?
Comment: If I have interpreted the term "wrapped" correctly, $\langle90,10\rangle$ is the same as $\langle -10,10\rangle$ which doesn't require any wrapping.

Check whether the number modulo $100$ falls in this interval.
Comment: Is this what you want? If it is I'll upgrade that to an answer, I made it a comment because I wasn't sure.
Comment: @Sabyasachi Yeah you're right, I guess that's the right approach. Please make it an answer, and I'll gladly accept that. Thanks!
Comment: Done.${}{}{}{}{}{}{}$
Answer: If I have interpreted the term "wrapped" correctly, $\langle90,10\rangle$ is the same as $\langle−10,10\rangle$ which doesn't require any wrapping. Check whether the number modulo $100$ falls in this interval.


The ratio of two Bayes factors for two opposite one-tailed hypotheses

Question: I am trying to understand how Bayesian inference works, so this might be a very simple question. I have an experiment where I test two hypotheses predicting opposite results. Let's say, hypothesis 1 (H1) predicts that x > 0, and hypothesis 2 (H2) predicts that x < 0.
I calculated Bayes factor with informed priors (positive and negative half-normals for H1 and H2 respectively) for two hypotheses. BF10 for the H1 was 0.04, and BF10 for the H2 was 0.13. In other words, both results indicate that I have to believe more in H0 than in any of two alternative hypotheses.
However, if I still want to make some inference on H1 and H2, can I just
divide BF10(for H2) by BF10(for H1)? This ratio (it will Bayes Factor too, right?) will be 0.13 / 0.04 = 3.25. Does this result tell me that I have to increase my belief in H2 compared to H1?
Comment: No this is not correct, the likelihood is integrated against the prior, check eg the [Wikipedia page](https://en.wikipedia.org/wiki/Bayes_factor#Example)
Comment: If I understand correctly, Bayes factor for H1 is (prior(H1) * likelihood) / (prior(H0) * likelihood). H0 (x=0) is the same for H1 and H2.
Comment: Now, after you asked, i started thinking about it, and it seems that what i did (BF(H1)/BF(H2)) is basically a Bayes factor for these two hypotheses, because the common denominator in two Bayes factors (prior(H0)*lokelihood) is cancelled in division. Would be great if somebody could confirm this.
Comment: Thanks @Xi'an !
Answer: In short, yes, but your comments indicate you might have gotten the right answer for the wrong reasons.
A Bayes Factor is the ratio of the marginal likelihoods of the data under two different hypotheses.
Let's say $L_i$ is the marginal likelihood of the data under hypothesis $H_i$,
and $H_0: x = 0$, $H_1: x > 0$, and $H_2: x < 0$, where for $H_1$ and $H_2$ you have some prior over possible values of $x$ (positive and negative values, respectively).
Your Bayes Factors are then the following ratios:

$BF_{10} = \frac{L_1}{L_0}$
$BF_{20} = \frac{L_2}{L_0}$
$BF_{21} = \frac{L_2}{L_1}$

If you know $BF_{20}$ and $BF_{10}$, their ratio is
$$
\begin{align}
\frac{BF_{20}}{BF_{10}}
 &= \frac{\frac{L_2}{L_0}}{\frac{L_1}{L_0}} \\
 &= \frac{L_2}{L_0} \times \frac{L_0}{L_1} \\
 &= \frac{L_2}{L_1} \\
 &= BF_{21}
\end{align}
$$
Comment: Indeed, I did not understand Bayes factor calculation well (i.e. marginal likelihood), but I didn't do the calculation myself (I used a script from elsewhere), therefore, the results should be right. So, it's just a BF21. Great, thank you!


How can $\lim_{x\to3}\left(\frac{\sqrt[3]{32x-96}}{x^{2}-2x-3}\right)$ be shown to equal $2$?

Question: The question given in my textbook is "Compute the limit $\lim\limits_{x\to3}\left(\frac{\sqrt[3]{32x-96}}{x^{2}-2x-3}\right)$." The solution given is merely the answer $2$, but I'm not sure how this is obtained, especially after looking at a graph. How can this be shown to equal $2$? This question is in the context of the introductory chapter to limits, so some of the more advanced tools are not (I imagine) supposed to be used. Thank you in advance for any help!
Edit: Appreciate the help from everyone, it is obvious now that the book didn't format the root correctly. Also thank you to the user that fixed my Latex code.
Answer: Factor the quantity inside the cube root, and factor the denominator:
$$\frac{\sqrt[3]{32x-96}}{x^2-2x-3} = \frac{\sqrt[3]{32(x-3)}}{(x+1)(x-3)} = \frac{\sqrt[3]{32}}{(x+1)(x-3)^{\frac23}}$$
Take the limit as $x\to 3$, and we get $\frac{\sqrt[3]{32}}{4}=\frac1{\sqrt[3]{2}}$ times a $\frac1{0}$ form. The quantity $(x-3)^{\frac23}$ we're dividing by is positive on both sides, so the limit is $\infty$. Uh, oops. There's a mistake here, and it looks like it's the textbook's statement of the problem.
Comment: Infinity as the limit is what the graph would suggest. Thanks for your confirmation, must be a typo.
Answer: Either you or the book made a mistake.  The limit should probably be:
$$
\lim_{x \to 3} \sqrt[3]{\frac{32x-96}{x^2 - 2x - 3}}
$$
Comment: And with this change, the book's answer of $2$ is easily obtained...
Answer: As JavaMan correctly indicates, this should be: $$\lim_{x\to 3} \bigg(\frac{32x-96}{x^2-2x-3}\bigg)^\frac13$$
We use two properties. Firstly that when $B(x)=A(x)\cdot \frac{x-t}{x-t}$ for any function $A(x)$ is that function with a discontinuity at $x=t$,  and it holds that $$\lim_{x\to t} B(x)=A(t)$$
The second property is the algebra of limits. Namely; $$\lim_{x\to a}(B(x))^K =\bigg(\lim_{x\to a} B(x) \bigg)^K$$
Use $B(x)=\frac{32x-96}{x^2-2x-3}=\frac{32(x-3)}{(x+1)(x-3)}$ then $K=\frac 13$ to see what I'm driving at.


Prove $\sum_{k=0}^{n-1} {n-1 \choose k}cos(\frac{2\pi k}{n}+\frac{2\pi}{n})(-1)^k \neq 0$

Question: Let $f(x)$ be a polynomial such that $f(N)=cos((N-1)\frac{2\pi}{n})$ and $N\in\{1,2,3,...n\}$. I am interested in finding the degree of $f(x)$. Using the method of successive differences, I found the $n-1$ difference to be $$D_{n-1}=\sum_{k=0}^{n-1} {n-1 \choose k}cos(\frac{2\pi k}{n}+\frac{2\pi}{n})(-1)^k$$
I am attempting to prove $D_{n-1}\neq 0$ for $n=1,2,3,...$.
So far I have attempted to take the limit as $n\rightarrow\infty$ and checked $n$ values up to $30$. Neither of these have been useful.
Comment: What about writing $\cos\theta$ as $\text{Re}(e^{i\theta})$ and computing the binomial sum?
Answer: Let's abbreviate $\omega_n = e^{2\pi i/n}$, so that $D_{n-1}$ is the real part of $$A_{n-1} = \sum_{k=0}^{n-1} \binom{n-1}{k} \omega_n^{k+1} (-1)^k = \omega_n \sum_{k=0}^{n-1} \binom{n-1}{k} (-\omega_n)^k.$$
Now by the binomial theorem, this is just $\omega_n (1-\omega_n)^{n-1}$.
For any number $t$ we have $(1 + e^{it})^2 = (2 + 2 \cos t) e^{it} = 4 \cos^2 (t/2) e^{it}$, so if $-\pi \le t \le \pi$ you get $1 + e^{it} = 2 \cos(t/2)  e^{it/2} $. In particular, $-\omega_n = e^{i(2\pi/n-\pi)}$, so
$$ 1 - \omega_n = 2 \sin \frac{\pi}{n} \exp\left[ \left(\frac{1}{n} - \frac{1}{2} \right) \pi i \right]. $$
Thus,
\begin{align}
A_{n-1}
&= \left (2 \sin \frac{\pi}{n} \right)^{n-1} \exp\left[ \frac{2\pi i}{n} + (n-1) \left( \frac{1}{n} - \frac{1}{2} \right) \pi i \right] \\
&= \left (2 \sin \frac{\pi}{n} \right)^{n-1} \exp\left[ \left( \frac{3-n}{2} + \frac{1}{n} \right) \pi i \right]. \\
\end{align}
Finally,
$$ D_{n-1} = \operatorname{Re} A_{n-1} = \left (2 \sin \frac{\pi}{n} \right)^{n-1} \cos \left[ \left( \frac{3-n}{2} + \frac{1}{n} \right) \pi \right] $$
which is always nonzero.
Comment: I just checked some values of this, it seems you are missing a $(-1)^n$ term somewhere in your answer. But since I only asked about equality to zero, it's fine.
Comment: @NickGuerrero Thanks, I fixed it.


Reading a geometry problem

Question:
Prove that the angle between the segments from the incenter to two vertices of a triangle has a radian measure equal $\pi/2$ plus one-half the measure of the angle of the triangle at the third vertex

Can someone tell me why we have to show $b = \pi/2 + z/2$? When it says the angle between the segments from the incenter to two vertices... why can't that angle be w? Isn't that also between the segments joining the incenter to the vertices of the triangle?
This may seem like a dumb question, but I am trying to get myself more familiar with reading these geoemtry problems. Please don't solve the problem
Comment: Hard to know how one learns it. Presumably like one learns most conventions: by seeing it often enough implicitly in use. Like in any other natural language, there are many conventions in mathematics, such as typographical conventions, that are rarely explicitly pointed out.
Comment: Where are you supposed to have learn this convention...? Should I have learned this in high school? I didn't get that training...(feeling so bad now lol)
Answer: There is a convention that "the" angle between two intersecting non-coincident lines means the angle in the interval $(0,\pi)$.

Reading a geometry problem


Why should write like this?

Question: Other Module Notes in requirejs.org. we can write a module like this:
define(["require", "./relative/name"], function(require) {
    var mod = require("./relative/name");
});

or:
define(function(require) {
    var mod = require("./relative/name");
});

but why i can't write like this:
define(["./relative/name"], function(require) {
    var mod = require("./relative/name");
});

Answer: If the first parameter is given as an array, it contains a list of modules to load, before the callback is executed. The parameters of the callback functions then hold references to those modules.
So have a look at the first example: Here 2 modules are loaded require and ./relative/name. The callback just takes on the first of them via the parameter require. The second is passed on to the arguments, but there is no named argument for it. However, since it is already loaded, you can use var mod = require("./relative/name"); to get a reference of it inside the callback.1
As for the second example the link you listed shows this

This form will use Function.prototype.toString() to find the require() calls, and add them to the dependency array, along with "require", so the code will work correctly with relative paths.

So actually require.js will parse your function and look for dependencies, which then create an array like in the first example.
Your last (not working) example, however, tries to mix both. But from require.js' point of view it looks like this: You have one dependency ./relative/name, which gets passed on to the argument named require. Inside the function you try to obtain another reference to the same module, this time under the name of mod. So for require.js everything seems fine, but just get the reference to one module and not both, as you (mistakenly) expect.

1A synchronous module loading using var mod = require("./relative/name"); only works, if the module has been loaded before by some other call (not necessarily by the current module).

Why should write like this?


What is a conjugacy class of reflection?

Question: I have a problem to do, asking to show that $D_{2n}$ has two conjugacy classes of reflections if n is even, but only one if n is odd.
My question is, what is a conjugacy class of reflection?
I have seen that there is a solution to this question on this site, but I don't want to lose the value of the question by looking up the solution.
Thanks
Comment: What is the definition you are using for the group?
Comment: $D_{2n}$ is the Dihedral group of order 2n
Answer: A reflection of the plane is a linear transformation (ok, it could be affine, but assume that the center of the regular $n$-gon is at the origin) such that it has two orthogonal eigenspaces, one belonging to eigenvalue $+1$ and the other to eigenvalue $-1$. These properties are invariant under conjugation by orthogonal transformations, so any conjugate of a reflection is another reflection.
If the eigenspace of $\lambda=+1$ (=the line that you reflect w.r.t) of a reflection $s$ intersects the polygon at the points $P$ and $Q$, and $g$ is any symmetry of the $n$-gon, then
$gsg^{-1}$ is the reflection w.r.t. the line connecting the points $g(P)$ and $g(Q)$.
If $n$ is odd, then for any reflection $r\in D_{2n}$ one of the points $P,Q$ is a vertex and the other is the midpoint of an edge opposite to that vertex. Because $D_{2n}$ acts transitively on the set of vertices, all the vertices (and hence also all the corresponding midpoints) occur as $PQ$-pairs. Thus there is only a single conjugacy class of reflections.
OTOH if $n$ is even, then both $P$ and $Q$ are either vertices or both are midpoints of an edge. The group $D_{2n}$ does not mix these two kinds of points. For example if $P$ is a vertex, then so is $g(P)$ for all $g\in D_{2n}$. But again $D_{2n}$ acts transitively on both vertices and midpoints, so we get two conjugacy classes of reflections.

As an extra let me point out that by the same line of reasoning all the reflections of $D_{2n}$ become conjugates in $D_{4n}$. See this answer for a discussion of this phenomenon in the case $n=4$.

And a very different way of looking at it:
The group $D_{2n}$ is defined by generators and relations as
$$D_{2n}=\langle a, b\mid a^2=b^2=(ab)^n=1\rangle.$$
If $n$ is even this implies that we get four homomorphisms from $D_{2n}\to C_2=\{\pm1\}$ by arbitrarily mapping $a\mapsto \pm1$, $b\mapsto \pm1$. Because $C_2$ is abelian all the conjugates are mapped to same elements in all those homomorphisms. Therefore $a^ib^j$ and
$a^kb^\ell$ can be conjugates only if $i\equiv k$ and $j\equiv\ell\pmod2$.
OTOH if $n$ is odd, then any homomorphism $D_{2n}\to C_2$ must map $ab\mapsto1$, so the images of $a$ and $b$ are equal. Thus the determinant (sending both $a,b$ to $-1$ is the only non-trivial homomorphism from $D_{2n}$ to $C_2$ in this case.
Combining this with the bit about conjugates of reflections being reflections also allows you to identify the conjugacy classes.
Answer: The elements of $D_{2n}$ are geometric transformations of the plane, leaving an $n$-gon fixed. So it makes sense for an element of $D_{2n}$ to be a reflection.
A conjugacy class of a reflection is a conjugacy class of an element which is a reflection. :-)
Comment: My main issue is that, looking at $D_{6}$ (order 6), shouldn't this have 3 conjugacy classes since there are 3 different reflections?
Comment: Well, the conjugacy classes of two different elements may well be equal!
Comment: There are 3 ways of swapping 2 vertices of a triangle by reflection, so isn't this 3 distinct ccls?
Comment: You are counting reflections, **not** conjugacy classes of reflections.
Comment: Make a list of all reflections and then for each of them write down the conlugacy class. Count how many *distinct* conjugacy classes you got.
Answer: This is a vague attempt to inspire geometric intuition, rather than a rigorous demonstration of the point.
Think about the conjugacy classes of the dihedral group as symmetries of a polygon. Thinking geometrically, you might see that conjugating a reflection with a rotation leaves the reflection altered by an even number of vertices.
If there are $2n$ vertices conjugation keeps the parity the same. If there are $2n+1$ vertices, you go twice round, hitting all the vertices.
Comment: Hm. Thinking about conjugacy classes as «symmetries of the polygon» is probably a bad idea, really. The actual elements of the group are the symmetries of the polygon, so *they* should be thought of as symmetries of the polygon, because they are! Conjugacy classes are, if you insist, classes of symmtries of the polygon: two symmetrices which are in the same class are "similar" (in a sense made precise precisely by the definition of conjugacy class!)
Comment: @MarianoSuárez-Alvarez I mentioned it because it works for me. A polygon size $2n$ has a pair of polygons size $n$ inside it. Either it works for you or it doesn't. If it does't, well find another way.
Comment: To be honest, I do not understand at all what you say in what you wrote (for example, I don't really understand what you mean by «a rotation leaves the reflection alterned by an even number of times») nor what these two polygons of size $n$ you mention in your comment are, but thinking of conjugacy classes as symmetries of a polygon will most certainly class with pretty much everything.
Comment: @MarianoSuárez-Alvarez Where there is an even number of vertices there is a parity which is preserved or exchanged by every element of the group. Conjugation exchanges parity twice (or keeps it the same both times) i.e. keeps it the same. Apologies if the original post was unclear about this.


Does an inverse function always give an identity element?

Question: So for multiplication the inverse element is 1 over the number and gives 1 which is the identity element for the multiplication operation. Are there examples of operations where there is an inverse function which gives the same result for each element in the group but said result is not an identity element (e.g. an "inverse" which when multiplied by a number gives a number not equal to 1). If these inverses don't exist then why?
Comment: The definition of an inverse relies on the existence of an identity element.
Comment: The question is a little hard for me to follow. Let's take the group of integers under addition to be our group. We can always find an $x$ to solve the equation $a + x = 2$ for any $a \in \Bbb Z$ (the inverse of $a$ solves $a + x = 0$, $0$ being the identity element). Are you asking if equations like this are always solvable?
Comment: @pjs no, I'm asking if there's ever an operation in a group where a o x = b where b is not the identity element so from addition say an inverse where a+x=1
Comment: And you want *the same* $x$ for all group elements $a$?
Comment: @pjs No, for addition x = -a to give the identity element of 0 hence all x are not the same but I do want the same b
Answer: I could be wrong, but I think the question comes from the idea that for all $g$, there's some $g^{-1}$ such that $g \circ g^{-1} = e$, where $e$ is the identity element of the group.
Maybe we could call $g^{-1}$ "the (right-)inverse of $g$ with respect to $e$" because right-multiplying $g$ by $g^{-1}$ gives $e$ (I don't know if there's a phrase for this kind of thing, since the identity element is baked into the definition of inverse elements). I think your question is asking if there are "(right-)inverses of $g$ with respect to any fixed group element $b$", that is, some $x$ with $g \circ x = b$ for any $g$ and fixed $b$.

Thus, as I understand the question:

Suppose $G$ is a group with operation $\circ$, and fix $b \in G$.
For each $g \in G$, can we find some $x$ so that $g \circ x = b?$

Yes, this is possible. If you've talked about Cayley tables, this is basically the observation that each group element shows up in each row and each column exactly once (in particular, $b$ shows up in each row exactly once).
In any group, you can solve the equation $g \circ x = b$ by left-multiplying each side by $g^{-1}$ to get the desired value $x = g^{-1} \circ b$. A similar technique will show that $x \circ g = b$ always has a solution too.
Answer: The identity element $e$ of a group $(G,\circ)$ is defined by
$$\forall\; g\in G: g\circ e = g = e\circ g$$
The inverse element $g^{-1}$ of an element $g$ of a group $(G,\circ)$ is defined by
$$g^{-1}\circ g = e = g\circ g^{-1}$$
For a group, the above statement is true for all $g\in G$. However, if given some other operation $\star\neq\circ$ on $G$, we could have $g\star g^{-1}\neq e$, because $e$ means the identity element in respect to $\circ$ and $g^{-1}$ means the inverse in respect to $\circ$. For example, $2\cdot\frac{1}{2}=1$, but $2+\frac{1}{2}=\frac{5}{2}\neq 1$.
Note that "Inverse" needs "identity element", not the other way around. A set with a binary operation that has an identity element but not an inverse for every element is no group but a monoid.
The inverse $g^{-1}$ is unique for each $g\in G$ (this can be proved). Therefore, given element $g,h,x\in G$, one can always solve the equation $h\circ x = g$ for $x$, it is $$h^{-1}\circ (h\circ x) = (h^{-1}\circ h)\circ x = e\circ x = x \stackrel{!}{=} h^{-1}\circ g$$
Comment: Is it possible for g o g^-1 = b where b is not e to be true (sorry I haven't figured out LaTeX yet)
Comment: @andrew I hope my edit clarified everything?
Comment: @andrew Also check https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference ;)
Comment: yeah thanks for the help, been trying to teach myself about groups, definitely better off after this.


How can I stop a systemd service with cron?

Question: I have a simple crontab entry that is supposed to stop a service, yet it does not work.
* * * * * systemctl stop nginx

I even tried:
* * * * * /bin/systemctl stop nginx

Since that't the location of systemctl that which command shows.
That line works with root user, yet not working with root's crontab.
And by not working, I mean the service is not shut down. I can confirm the server is still running and systemctl status nginx show it's active.
What am I doing wrong?
Comment: What do your cron logs say?
Comment: What was the output of `systemctl status nginx`?
Answer: Probably because you haven't told cron to use root.
* * * * * root /bin/systemctl stop nginx

That will execute the command every minute, regardless of the nginx status (started or not)
So that being said, if the goal is to make sure nginx is never started, why not just disable it?
systemctl disable nginx

==Edit==
Good point made by Aaron Copley in the comments, in order to make sure nginx wont be started even after boot the command should be;
systemctl mask nginx

Comment: This is not always true - if the entry is put into `/etc/crontab` or `/etc/cron.d/*`, then yes you will need to include the user in the crontab entry. However, if you add this job to root's individual crontab (such as `/var/spool/cron/root`, or `crontab -e -u root`) then there is no need to specify the user.
Comment: `systemctl disable nginx` will only prevent it from starting on boot and won't stop it from being started as a dependency of another service. You want `systemctl mask nginx` to prevent the service from being able to be started at all.
Comment: That was just an example, I could have put 10 16 * * *, this was just to illustrate that the problem is not due to time not properly being set. The point is, I am creating crontab entry with root user and the service is not shutting down.


I can't understand why components with 'connect()' are stateful in react

Question: My question is just same as the title.
Let's say I wrote the following code.
class TODOList extends Component {
  render() {
    const {todos, onClick} = this.props;
    return (

            {todos.map(todo =>
                <Todo
                    key={todo.id}
                    onClick={onClick}
                    {...todo}
                />
             )}

    );
  }
}

const mapStateToProps = (state) => {
  return {
    todos: state.todos
  }
}

const mapDispatchToProps = (dispatch) => {
    return {
        onClick(data){
          dispatch(complete(data))
        }
    }
}

export default connect(mapStateToProps,mapDispatchToProps)(TODOList);

Now, after the last line, this code will export the TODOList component with the state as props. It's not that it contains state, but just received state and will have them as 'props', just like the method name 'mapStateToProps' explains.
In the medium post(https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0) written by Dan Abramov, container component handles data as state, and presentational property do as props. Isn't it a presentational component that deals with data as props? I'm stuck with the idea that the right container should be one like below.
class CommentList extends React.Component {
  this.state = { comments: [] };

  componentDidMount() {
    fetchSomeComments(comments =>
      this.setState({ comments: comments }));
  }
  render() {
    return (

        {this.state.comments.map(c => (

{c.body}—{c.author}

        ))}

    );
  }
}

I'm not sure why react-redux named the API 'mapStateToProps', when I tried to make 'stateful'(not handling data by property) container component
Comment: "state" isn't a term specific to react, it's general to computer programming. It's a general term meaning remembered state of the system. https://en.wikipedia.org/wiki/State_(computer_science). Redux reducer state and component state are different things.
Answer: First of all these guidelines are not part of the bible
you should write code that is easy to reason about for YOU and your TEAM.
I think you are missing something, A redux Container is different than a react Container.
I mean, connect will create the container for you, it doesn't mean the wraped component is a Container.
Basically you can export both versions from the same file, the Container (connected version) and the presentation version (the none connected one).
Another thing that usually throw people off, is the name of the function and argument of mapStateToProps.
I prefer the name mapStoreToProps as in

map the redux store to the component's props.

the name state can be confusing when we are in the context of react.
Edit
As a followup to your comment:

I totally didn't know these two are actually different. Could you please tell me about more details

They are different in the way that connect is creating a "Container" for you.
connect is a High Order Component that creates the Container Component for us with all the subscription logic + functions to pass portions of the store and action-creators to its children as props (mapStateToProps & mapDispatchToProps).
A "normal" Container is usually refers to a component that you write by hand, its often doesn't deal with how things should look but instead deal with certain logic of the app.
As for the other comments like

The connect HoC of react-redux just injects the properties you can request into your component. It returns a new component that is wrapped around your component so that it can update your component whenever the state you're interested in the redux store is modified

As i mentioned above, this is partially true. It's not just injecting the properties into our component, its subscribing to the store, grabbing it from the Provider (via context) and its doing all these with optimizations in mind, so we won't have to do it by ourselves.

I'm not sure how mapStateToProps can confuse someone. We are talking about a state management library

I've seen some devs that misunderstood this because react has a state and redux has a store (at least that's how it was called in most of the tutorials and documentations).
this can be confusing to some people that are new to either react or redux.
Edit 2

It was a bit confusing due to the sentence 'it doesn't mean the wraped component is a Container.' Why is the wrapped component not a container? Isn't a component created by connect also a container?

I mean that the wrapped component that you wrote doesn't have to be a Container.
You can connect a "Presentation" component:
const Link = ({ active, children, onClick }) => {
  if (active) {
    return {children}
  }

  return (
     {
        e.preventDefault()
        onClick()
      }}
    >
      {children}

  )
}

// ...
export default connect(mapState, mapDispatch)(Link)

Comment: The `connect` HoC of `react-redux` just injects the properties you can request into your component. It returns a new component that is wrapped around your component so that it can update your component whenever the state you're interested in the redux store is modified.
Comment: I've added some more details to answer some of the comments
Comment: @Rhee I've answered you latest comment (Edit 2 section) Hope that's clarify it :)
Comment: Thank you for your answer. But I don't understand this part : 'I think you are missing something, A redux Container is different than a react Container.
I mean, connect will create the container for you, it doesn't mean the wraped component is a Container.'

Yes, I totally didn't know these two are actually different. Could you please tell me about more details?
Comment: I'm not sure how `mapStateToProps` can confuse someone. We are talking about a state management library.
Comment: @Sagivb.g Thank you for your kind explanations. But, some points are still remained obscure. Your additional explanations were about the fact that connect creates containers more than just normal containers
I can't get how this explanation can be about react container vs redux container. You were saying the redux container is actually the container created from connect() method?
Answer: mapStateToProps will be called when store data changes. It will pass the returned object as new props for the component. This will not affect the component's state. If you'd like to set a new state after the component got its new props you need to use another lifecycle method: static getDerivedStateFromProps (in earlier versions of react componentWillRecieveProps). The object returned by static getDerivedStateFromProps will be your new state.
https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class
connect() will connect your component to the redux store. Withouth the connect function (of course) your mapStateToProps will not work.

I'm not sure why react-redux named the API 'mapStateToProps'

We are talking about the store's state :)
Answer: The high level purpose is to seamlessly integrate Redux's state management into the React application. Redux revolves around the store where all the state exists. There is no way to directly modify the store except through reducers whom receive actions from action creators and for that to happen we need for an action to be dispatched from the action creator.
The connect() function directly connects our components to the Redux store by taking the state in the Redux store and mapping it into a prop.
This is power of Redux and its why we use it.
Lets say you are building a component called LaundryList and you want it to render a laundry list. After you have wired up the Provider in your "parent" component, I put it in quotes because technically Provider is a component so it becomes the parent.
You can then import the connect() function from react-redux, pass it mapStateToProps in order to get that laundry list from the Redux store into your LaundryList component.
Now that you have your list of linens inside of the LaundryList component you can start to focus on building a list of elements out of them like so:
class LaundryList extends Component {
  render() {
    console.log(this.props.linens);
    return
LaundryList
;
  }
}

That contains the list of linens object and for every list of linens inside of there we are going to return some jsx that is going to represent that linen on my list.
Back inside my laundry list component I will add a helper method inside the laundry list component called render list like so:
class LaundryList extends Component {
  renderList() {

  }

  render() {
    return
LaundryList
;
  }
}

So this purpose of this helper method is to take the list of linens, map over them and return a big blob of jsx like so:
class LaundryList extends Component {
  renderList() {
    return this.props.linens.map((linen) => {
       return (

       );
    });
  }

  render() {
    return
LaundryList
;
  }
}


FileField Database

Question: I like the idea of using a field within a database to hold a file.
Is it possible to store files within a database instead of within folders with Drupal 7?
My current setup is Drupal 7, Ubuntu Server 10.10/11.04, MySql, Apache2. I could switch to IIS if need be (I like Ubuntu for test server since it's lightweight and more flexible, but work is mainly windows servers... so I could go either way)
Comment: What specific usecases are you trying to solve by storing files in db column? There are many disadvantages to that approach:
Comment: Everything else is kept in the database. It just seems logical and easier to me to have the data kept as a "blob" field in my planned setup. That would keep all "data" in one place (files are data too). My setup will have one possible file per content type (that isn't reused elsewhere). I'm working on file management as well, but I figured I'd explore this avenue.
Answer: There is the dbfm module, but it is still only for Drupal 6.
You could try to update or improve it.
Comment: The 6 version is also a dev version and I don't see maintainers upgrading it soon.

FileField Database


Area under the curve using idl

Question: I have a curve between dff(x axis) and dc(y axis) and I calculated the area under the curve using IN_TABULATED function.
X=[-0.00205553,-0.00186668,-0.00167783,-0.00148899,-0.00130014,-0.00111129,-0.000922443,-0.000733597,-0.000450326,-0.000261480,0.000116216,0.000399487,  0.000588333,0.000777179,0.000966027,0.00115488,0.00134372,0.00153257,0.00172141,0.00181584,0.00200468]
F=[0.00000,21.0000,26.0000,57.0000,94.0000,148.000,248.000,270.000,388.000,418.000,379.000,404.000,358.000,257.000,183.000,132.000,81.0000,47.0000,23.0000,17.0000,431.000]
A=INT_TABULATED(X,F)
print, A

Now, I need to have a loop start from n,0 (from right to left) and calculate A1 which is 0.01 of A and to stop there, then print dff values which represent A1's area. How can I do this? Any suggestion will be helpful.
Answer: I'm not sure I fully understand the question, so let me begin by stating my interpretation.  You have a curve which integrates to A.  Starting from the right, you want the X-value (let's call it X1) which encloses 0.01 of A (the total area under the curve).  In other words, 0.99 of the total area under the curve F is to the left of X1, and 0.01 of the area is to the right.
Assuming this interpretation is correct, here's a solution:
First, loop through the data and calculate the integral from 0 to each point.
npoints = n_elements(x)

; Initialize a vector to hold integration results
area_cumulative = []

; Loop through each data point, calculating integrals from 0 to that point
for index = 0, npoints-1 do begin

    ; Assume area under first point is zero, otherwise, calculate integral
    if index eq 0 then area_up_to_point = 0d0 $
      else area_up_to_point = int_tabulated(x[0:index], f[0:index])

    ; Store integral value in the cumulative vector
        area_cumulative = [area_cumulative, area_up_to_point]

endfor

Then, you can interpolate to find X1:
;;; Find where cumulative distribution reaches 0.99 of A

a1 = 0.99 * a

x1 = interpol(x, area_cumulative, a1)

Here's an illustration.  The upper plot is your data, and the lower plot is the cumulative area (integral from x[0] to x).  The red dashed lines show X1 = 0.001952.  The gray shaded region contains 0.01 of the total area.

Hope this helps!

Area under the curve using idl


Proof verification on a simple set theory theorem

Question: I am working on one of How To Prove It by Velleman's exercise:
"Is the following proof of the theorem correct?
Suppose A, B, and C are sets and $A\subseteq B \cup C $. Then either $A\subseteq B$ or $A\subseteq C $.
Proof: Let $x$ be an arbitrary element of $A$. Since $A\subseteq B \cup C$, it follows that either $x \in B$ or $x\in C$.
Case 1. $x\in b$. Since x was an arbitrary element of A, it follows that $\forall x \in A (x\in B)$, which means that $A \subseteq B$.
Case 2. Similar step to case 1.
Thus, either $A \subseteq B$ or $A\subseteq C$."
Apparently it's incorrect, and a counterexample to the theorem is A={1,2}, B={1}, C={2}.
The counter example makes sense, but while I know that one counter example is enough to invalidate this proof, I don't really understand what went wrong in the proof; furthermore even if the proof is wrong I don't know why is the theorem incorrect. I drew up the logical form of this theorem: $$ \forall x((x\in A\to x \in B \lor x\in C) \to (x \in A \to x \in B) \lor (x \in A \to x \in C))    $$ Where the antecedent corresponds to the supposition of the proof as given. I managed to derive a contradiction with an indirect proof. So the only logical conclusion is that either my logical form or indirect proof is wrong (otherwise how could the theorem possibly be incorrect?), but I don't understand how is my logical form wrong either.
Would anyone mind giving me a hand please? Thank you so much!
$--------------------------------------$
Edit:The following is how my indirect proof with the logical form went.
$$ \forall x((x\in A\to x \in B \lor x\in C) \to (x \in A \to x \in B) \lor (x \in A \to x \in C))    $$
1. Let x be an arbitrary element, so that we have $(x\in A\to x \in B \lor x\in C) \to (x \in A \to x \in B) \lor (x \in A \to x \in C)$ to prove.

Assume $(x\in A\to x \in B \lor x\in C)$, and try to prove the consequence of the conditional $(x \in A \to x \in B) \lor (x \in A \to x \in C)$
Indirect proof: so let's assume the negated form of the consequence, which by DeMorgan's law becomes: $\sim(x \in A \to x \in B) \land \sim(x \in A \to x \in C) $
The left side of the conjuction, by negated conditional, becomes $x\in A \land \sim x \in B $. Likewise for the right side, $x\in A \land \sim x \in C $
We isolate $ x\in A$ from either of the conjunctions from 4, and by modus ponens onto the assumption of 2, we get $x \in B \lor x\in C$
We isolate $ \sim x\in B $ and $ \sim x \in C$ from 4, and by disjunctive syllogism onto 5 we get $x \in B$ and $x \in C$ - contradiction.
Comment: As I said in one of my comments, your logical form is almost correct. It should be $$ (\forall x (x\in A\to x \in B \lor x\in C)) \to (\forall x(x \in A \to x \in B) \lor \forall x(x \in A \to x \in C)) $$ or, in order to make it clearer: $$ (\forall x (x\in A\to x \in B \lor x\in C)) \to (\forall y(y \in A \to y \in B) \lor \forall z(z \in A \to z \in C)) $$ Then I think that your proof doesn't work on this statement, even if it could work on your statement (because it was only _almost_ correct).
Comment: Thank you! This question really bugged me big time so I am grateful for your help!
Answer:
Logically, when we want to prove $A\subset B$, we need to prove that every element of $A$ is in $B$. for this, we choose an arbitrary element of A and fix it. Then we prove that this fixed element  is in $B$.

Let $x$ be an arbitrary element of $A$. So hereafter we fix this  $x$. Since $A\subseteq B \cup C$, it follows that either $x \in B$ or $x\in C$. It means that the fixed $x$ is in $B$ or in $C$; not every $x$.
In your example the $x$ is $1$ or is $2$. if it is $1$ then it is in $B$ and if it is $2$ then it is in $C$.
Answer: You are right to notice that $$\forall x \in A\quad  x \in B \cup C$$
is not the same as
$$\forall x \in A\quad  x \in B \qquad\text{  or  }\qquad
\forall x \in A\quad  x \in C$$
For instance, you can surely say "all the days, I'm happy or I'm unhappy", but maybe you can't say "all the days, I'm happy,  or all the days I'm unhappy". (Take $A=$ set of all the people, $B=$ set of happy people, $C=$ set of unhappy people).
The problem here is that they take $x \in A$, and then sometimes $x \in B$ (case 1), and sometimes $x \in C$ (case 2). These cases depend on $x \in A$. But when you want to prove $A \subset B$, you must show that any $x \in A$ lies in $B$, you can't have $2$ cases depending on $x$.

More precisely, when they say in Case 1 : "$x\in B$. Since $x$ was an arbitrary element of A, it follows that $\forall x \in A (x\in B)$, which means that $A \subseteq B$.", the wrong part is
$$"\forall x \in A (x\in B)".$$
To see what this is wrong, consider the statement
 $$"\forall y \in A (y \in B)"$$
I just changed the $x$ into a $y$. It was confusing before because they used $x$ in the formula "$\forall x \in A (x\in B)$", but we already had a $x \in B$ at the beginning.
Then it is clearer that, just assuming that $x \in B$, won't suffice to prove that $"\forall y \in A (y \in B)"$. Pick $y \in A$. Well, you only know that $y \in B \cup C$. It is not possible to prove that $y \in B$, even if you picked an element $x \in A$ that lies in $B$. This is precisely what happens in the given counterexample.
Comment: I will edit my answer to explain precisely what is wrong in this 2 cases. Your translation into a logical form is (almost) correct, but this doesn't mean that the theorem itself is correct. The exact formulation should be $$ (\forall x (x\in A\to x \in B \lor x\in C)) \to (\forall x(x \in A \to x \in B) \lor \forall x(x \in A \to x \in C))    $$ For instance, the translation of the (wrong) statement "if $A \subset B$ then $B \subset A$" is $$ \forall x(x\in A \to x \in B) \to \forall x(x \in B \to x \in A)  $$ but this doesn't mean that the statement is true.
Comment: Do you mean that, the suppositions of case 1 and 2 are not valid, because the supposition given is that  A⊆B∪C, not x∈B or x∈C?

Would you mind also commenting on my logical form of the theorem please? This is actually where I am really confused; I am pretty sure my indirect proof is correct, so if there is anything wrong it's likely to be in how I translated the logical form of the theorem, but I don't know where the mistake is.
Comment: I am focusing on the logical form because I also did an indirect proof on it myself, and I managed to get a contradiction out of it. If the logical form is correct, then there must be something wrong with my proof - otherwise I just don't see how is the theorem wrong. Let me show it in my edit.


Problemas ao usar SelectOneMenu primefaces

Question: Estou com um problema para atualizar os dados de um SelectOneMenu no primefaces, como sugere o código abaixo, possuo um botão que ao ser clicado, traz dados de um WebService e armazena em uma variavel de Devices em back-end e logo após, joga somente seus nomes para a lista deviceNames, isso occorre pois printo o Size da lista com os nomes e está OK, acontece que nada aparece no meu SelectOneMenu. já fiz muitas alterações porém até agora nada. Parece ser algo bem bobo mas não consigo achar o problema.
Página XHTML
<h:body>

    <h:form id="mainform">

                <f:selectItem itemLabel="Selecione..." itemValue="" />
                <f:selectItems value="#{config.devicesName}" />

    </h:form>
</h:body>

Bean config
public void carregaSbcDevices() {
    if(this.devices == null) this.devices = new ArrayList<>();
    this.devices.clear();

    if(this.devicesName == null) this.devicesName = new ArrayList<>();
    this.devicesName.clear();

    session.getDevices(this.devices);
    for(SBCDevices device : this.devices) {
        this.devicesName.add(device.getTargetName());
    }

    System.out.println("Numero: " + this.devicesName.size());
}

Answer: Possivelmente o update do seu ajax não está encontrando o componente panelAU. Isso ocorre pois ao realizar a renderização na tela o primefaces adicionar o nome do form junto ao nome que foi definido.
Ou seja. Possivelmente o id do compontante panelAU está como: mainform.panelAU.
Troque esse trecho de código:

Para:

Caso mesmo assim não funcione. Inspecione o html gerado e coloque exatamente o id que foi gerado.
Comment: Boa tarde, primeiramente, obrigado pela ajuda.
Fiz a alteração agora porém com esta linha alterada recebo o seguinte erro:
**Cannot find component with expression "mainform.panelAU" referenced from "mainform:button1".**
Fiz a alteração para:

Que é como aparece o id da div no html, a página roda mas continua não atualizando...
Comment: Você  inspecionou o elemento? Como está o id do select?
Comment: Peguei o html e o id está como 'mainform:selectOne' - este 'selectOne' é o id que eu coloquei agora no componente, e mesmo colocando update='mainform:selectOne' não retorna nada. Estou fazendo alguns testes com somente id, ou com id do form + id do componente.
Comment: Faça isso... Teste também colocar @form.  Para ver se ele atualiza.
Comment: Coloquei o @form e até agora nada. Tentei também com 'mainform:selectOne_panel' pois dentro da div 'selectOne' existe outra com o id 'selectOne_panel' que é criado no html e é onde fica os ``.
Neste link abaixo possui o código HTML gerado:
**http://dontpad.com/htmlstackquestion**
Comment: Tente colocar a tag process="@form" no p:ajax
Comment: Tentei com o `@form` e `@parent` também, mas não houve mudanças também. Alterei a estrutura e agora tenho o Form, e logo abaixo o botão e o SelectOne, sem panel. Não houve melhoras, ainda estou tentando verificar o html mas aparentemente não tem nada sem ID... E está parecendo que o componente sofre o update mas não faz um get() novo na variável, constatei isso utilizando um p:commandRemote, e no onsuccess dele coloquei um alert. Será que pode ter algo a ver com a versão do JSF ou do NetBeans, etc??
Comment: Acabei de testar tb com <f:ajax ao invés de <p:ajax para ver se não era bug do primefaces ou algo assim, também usei o <h:selectOneMenu ao invés do <p:selectOneMenu. Mesmo assim o erro persistiu, me parece erro de lógica. Estranho isso não estão funcionando.
Comment: Recriei esta página do primefaces showcase: https://www.primefaces.org/showcase/ui/ajax/dropdown.xhtml
E o resultado foi este: http://tinypic.com/r/htwoxe/9 - Estranho não?? Creio que possa ser algo em meu primeface.
Comment: Estranho mesmo! qual versão você está utilizando?
Comment: Estava na 5.0 e alterei para a 6.0, esse da página era um erro de XML, alterei um parametro e funcionou, engraçado que a página da showcase funciona bem aqui. Agora fiz um teste, com um botão eu carrego tudo do webservice e deixo pronto, no outro eu jogo pra variavel da tela, seguindo o mesmo padrão do showcase. E o estranho é que ele traz 22 registros mas na hora de colocar esses registros na variável que vai pra tela, lança um NPE, como se alguma outra coisa zerasse essa variável. Amanhã posto mais, estou em semana de provas na facul. Mas obrigado por enquanto :D
Comment: Creio que achei o problema, separei o método em duas partes e dois botões, o primeiro popula a variavel `devices` que é a lista de objeto, e no outro botão, chama o método que traz os nomes dos objetos para `devicesName`. Ai é que está o problema, a variável `devices` está como nula no momento da segunda chamada. Parece que a página está como Request Scoped, mas na vdd está como ViewScoped... Creio que seja isto, só não sei como resolver, rs.
Comment: @Ricardo conseguiu achar uma solução?
Comment: Tentei diversas formas de Scopo porém, a solução, mesmo que momentânea, foi utilizar variaves `static`, mesmo sabendo que não seja a melhor forma. Após concluir boa parte da aplicação voltarei a esturar essa questão. Mas de momento é isto, ja que não obtive nenhuma outra informação em documentação. Obrigado.
Answer: Problema Corrigido!
Após pequenas tentativas diárias falhas, notei que os mesmos códigos feitos por outros desenvolvedores não apresentavam erro, ao buscar soluções nos packages que estava usando descobri o erro, os imports do SessionScoped e do Named (Utilizo este ao invés de @ManagedBean(name = 'beanName'). Portanto, solucionei fazendo as seguintes alterações:
Alias do Bean:
@Named(value = "beanAgregadorDetalhe")
E o respectivo import:
import javax.inject.Named;
Escopo de Sessão:
@SessionScoped
E o respectivo import:
import javax.enterprise.context.SessionScoped;
Dessa forma os escopos funcionam perfeitamente agora e a página conversa normalmente com o bean sem a necessidade de variáveis estáticas. Quem estiver com problema de variáveis manipuladas em determinado escopo, Cuidado com os imports!


Busca de filtro não funciona

Question: Tenho um form que passa os dados da consulta e um arquivo externo em PHP chamado busca.php
Meu problema é que não recebo nenhum erro php para saber o problema de ele não achar a busca de filtro. Quando uso a busca normal ele me retorna todos os valores do banco.
O que esta acontecendo? Segue o código do programa, onde q é pra receber o campo de texto consulta de um arquivo consulta.php:
if(isset($_POST['buscar'])){
    $q = $con->real_escape_string($_POST['consulta']);
    $query_Busca = "SELECT * FROM equipamento WHERE tombamento LIKE '%$q%'";
    $Busca = mysqli_query($con,$query_Busca) or die($con->error);
    // Check results
    if($Busca){
        //Se for um sucesso!
        $row_Busca = mysqli_fetch_assoc($Busca);
        $totalRows_Busca = $Busca->num_rows;
    }

Neste else a função esta funcionando normal dando todos os dados do banco como desejo o problema esta mesmo no código acima onde quero achar o equipamento somente pelo numero de tombamento que fica em "consulta" contudo ele não acha e não me retorna erro.
} else {
    $query = "SELECT * FROM equipamento";
    $Busca = $con->query($query) or die($con->error);
    $row_Busca = mysqli_fetch_assoc($Busca);
    $totalRows_Busca = $Busca->num_rows;
}

Comment: Veja se `$_POST['busca`] tem algum valor e verifique se a consulta retorna algo, pode dar: `print_r($row_Busca);`
Comment: eu coloquei e nao me retorno nada @perdeu, não apareceu nada, esta certo isso?
Comment: Se eu colocar desta forma no if `$row_Busca = $Busca->fetch_assoc($Busca);` funciona, mas ele me da esse erro: ` mysqli_result::fetch_assoc() expects exactly 0 parameters, 1`
Comment: Não sei se ajuda, mas o `tombamento` é do tipo INT ou seja, somente numero, esta certo o LIKE que eu coloquei? O que me deixa curioso é que não da erro nenhum.
Comment: Like não funciona com campos int.
Comment: o que uso para comparar entao?
Answer: tente padronizar o seu código, pois em uma parte você usa funções mysqli_ e em outra usa objetos, e esses detalhes acabam causando dor de cabeça e dificuldades em encontrar os problemas.
copiando do bloco que está funcionando, ficaria assim:
(obs.: se o campo tombamento é int, use (int) para converter para inteiro no lugar do like.)
if(isset($_POST['buscar'])){
    $q = $con->real_escape_string($_POST['consulta']);
    $query = "SELECT * FROM equipamento WHERE tombamento = '" . (int)$q . "'";
    $Busca = $con->query($query) or die($con->error);
    // Check results
    if($Busca){
        //Se for um sucesso!
        $row_Busca = mysqli_fetch_assoc($Busca);
        $totalRows_Busca = $Busca->num_rows;
    }

Comment: mas fiquei na duvida sobre essas variáveis `$_POST['buscar']` e `$_POST['consulta']` porque você condiciona com a 'buscar' e utiliza a 'consulta'?
Comment: Busca é um botão, o consulta é o campo com o numero. Testei e não funcionou, quero deixar tudo com MYSQLi, se souber como eu arrumo para deixar tudo MYSQLi agradeço também.
Comment: "não funcionou" é muito vago, você consegue determinar o que ele esta fazendo? adicione um `echo $query;` logo abaixo da `$query = "SELECT ...` e veja se ele vai imprimir a query corretamente com o numero que você digitou, então copie a query e teste-a no phpmyadmin... ou seja se o php não esta lhe dando as mensagens de erro, busque formas de depurar por si mesmo.
Comment: ele me imprimiu: SELECT * FROM `equipamento` WHERE `tombamento` LIKE '%458791%'
Comment: você ainda esta usando o like no campo INT, veja no código acima que eu modifique essa parte...
Comment: modifiquei isso e ele nao me da echo no resultado. imprimi o seu select todo e nada de erro. SELECT * FROM `equipamento` WHERE `tombamento` = '(int)458791' esse numero foi o valor que inseri para achar no Mysql que se encontra la.
Comment: Tentei fazer uma modificação direta e achei essa mensagem agora, o que pode ser? SELECT * FROM `equipamento` WHERE `tombamento` = `458791`Unknown column 'tombamento' in 'where clause'
Comment: O pior agora é que resolvi esse colocando assim: $row_Busca = mysqli_fetch_assoc($query_Busca); Ele acha mas me retorna com erro de PHP:  Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, string given
Comment: Não existe uma coluna chamada tombamento na sua tabela equipamento... Verifique.
Comment: eu consegui, era soh tirar essa parte do codigo: ` $row_Busca = mysqli_fetch_assoc($Busca);` que funcionou! Obrigado a todos pela ajuda.

Busca de filtro não funciona


Printing outout of a view in to a field in user profiles

Question: I have created a view which prints only usernames of registered users .
In user registration there is field named "father username" .  i want that field to be populated as a list from the above view .
i used view reference , but it just shows all the views in the site .
any clue ?
thanks :)
Comment: What do you mean by `In user registration there is field named "father username"` ? There is a field you added called `father username` on the signup form?
Comment: Yes there is a dropdown , to select father "Full Name" from already existing users .
Answer: I'll make an assumption, and answer based on the assumption. The assumption is that the field "Father username" is an entity reference field, and you want to use the view of registered users to populate the options for that field.
If that is so, you need to create an "entity reference" view display, then refer to that view display in the field settings of the "father username" field.
Comment: thanks worked perfectly , this is what i was looking for :)


Package plm random effect residuals

Question: Simply put, I'd like to know how the plm package in R calculates the residuals of a random-effect regression.
I ask this because i'm getting some "weird" outputs. Let-me reproduce them here using the Grunfeld data for four firms, like Gujarati in his Basic Econometrics do:
require(plm)
require(foreign)

Grunfeld<-read.dta("Data.dta")
Grunfeld<-pdata.frame(Grunfeld,index = c("id","t"))

grun.re <- plm(Y~X2+X3,data=Grunfeld,model="random",index="id")

#Means by id
X2M<-tapply(Grunfeld$X2,Grunfeld$id,FUN = mean)
X3M<-tapply(Grunfeld$X3,Grunfeld$id,FUN = mean)
YM<-tapply(Grunfeld$Y,Grunfeld$id,FUN = mean)

#Random Effect: Fit the model and the calculate residuals "by hand"
fit.re<-grun.re$coefficients[1]+grun.re$coefficients[2]*Grunfeld$X2+grun.re$coefficients[3]*Grunfeld$X3
calcResid.re<-(Grunfeld$Y-fit.re)

#Random Effect:
head(cbind(grun.re$residuals,Grunfeld[,11:13],calcResid.re))

  grun.re$residuals   alphaRE       eRE        uRE calcResid.re
1         99.395803 -169.9282 116.23154  -53.69666    -53.69666
2         18.023715 -169.9282  34.85946 -135.06874   -135.06874
3        -39.256625 -169.9282 -22.42089 -192.34909   -192.34908
4         -2.857048 -169.9282  13.97869 -155.94951   -155.94951
5        -28.334107 -169.9282 -11.49837 -181.42656   -181.42656
6          6.475226 -169.9282  23.31096 -146.61723   -146.61723

In this table, uRE is the overall residual of the regression provided by Stata (which is identical to Gretl's) and calcResid.re is the manually calculated residuals from the fitted model. So, Stata, Gretl and I did the same. But what plm package do?
We can se that calcResid.re and uRE are equals. But the residuals provided by the plm estimation (grun.re$residuals) completely differs.
Here is a link to the dataset and results: https://github.com/rrremedio/shared_folder/blob/master/Data.dta
Comment: Helix123, in the dataset, uFE=alphaFE+eRE. Where: uFE=overall residual from fixed effects, alphaFE=individual effect and the eFE=idyossincratic error.
Comment: Hard to tell, because we dont know what `alphaRE, eRE, uRE` from Stata or gretl are. Do the coefficents match? Stata uses a slightly different RE estimator as far as I recall, plm uses `random.method="swar"` as default. Note also, that you probably want `effect="individual"` instead of `index="id"`in the estimation.
Answer: Thank you Helix.
I expect don't breaking any code of politeness answering my own question.
In fact, this question is related to this. Yet, I wil try give an answer from the econometrician point fo view now.
After long time, I realized that in a Random effects estimates you are running a demeaned regression as is said in equation 6 of the plm package paper here. However, I think their notation a litle "unrelated" to the rest of the paper.
Folowing Cameron and Trivedi, Microeconometrics Methods, the feasible GLS estimator can be implemented making OLS in the demeaned equation. That is Cameron & Trivedi 21.43 demeaned equation (which is the same as the cited above).
$$ y_{it}-\widehat{\theta}{\overline{y}_{it}}=(1-\widehat{\theta})\mu+(x_{it}-\widehat{\theta}{\overline{x}_{i}})'\beta+\upsilon_{it}$$
Where:
$$\widehat{\theta}=1-\frac{\sigma_\epsilon}{(T\sigma_\alpha^2+\sigma_\epsilon^2)^{1/2}}$$
The plm package calculates theta and stores it in the regression object.
And where,
$$\upsilon=(1-\widehat{\theta})\alpha_i+(\epsilon_{it}-\widehat{\theta}{\overline{\epsilon}_{i}})$$
In a Random Effects model, the plm regression residuals are, in fact, the upsilon as above.
However, if we calculate the residuals by hand, u=Y-XB, we will obtain what Stata calls the overall error of the model. In a fixed effect model it is $$u_{it}=\alpha_{i}+\epsilon_{it}$$.
Where alpha is the individual especif effect and epsilon the idiosyncratic error. Once we obtain alpha of random effects by the shrinkage factor (as the cited related question does), we can recover the idiosyncratic error.
In summary, what plm package returns as the residuals from random effets model are the residuals of the OLS demeaned regression.
Wooldridge,  Hsiao and Baltagi books about econometrics panel data derive the same result for the feseable GLS.
Answer: As you describe in your own answer above, plm gives the residuals of the (quasi-)demeaned model. To get the "outer"/"overall" residuals of the random effects model, use:
X <- model.matrix(grun.re, model = "pooling")
y <- pmodel.response(grun.re, model = "pooling")
est <-  X %*% coef(grun.re)
res <- y - est
head(res)
       [,1]
1  -53.69666
2 -135.06874
3 -192.34908
4 -155.94951
5 -181.42656
6 -146.61723

This matches Stata's uRE.

Package plm random effect residuals


How do the pegs on Sitar neck work?

Question: I just saw a picture of a sitar (an Indian stringed instrument) with pegs throughout its neck. I searched a few websites, but I couldn't understand them well.
Can you please explain to me about these pegs? How do they work? Are they attached to strings?
Answer: Yes, they are for tuning strings that are not directly played. These additional strings are sympathetic resonators. They vibrate in resonance with the primary strings and add to the sound.
The pegs don't use gears, their stability comes from friction between the peg itself and the hole. Essentially the same as violin pegs.
Comment: I'd just add that unlike the violin, the strings do not go over a nut and then to the pegs, but rather go through holes into the hollow neck, where they are wound around the pegs.
Answer:
The inside of the neck is empty. Each peg goes in and out through two holes on opposite sides of the neck and is held in place by friction.

In the middle of the "fretboard" (below the frets) are little holes from where the sympathetic strings go into the neck and around the tuning peg. The little holes in the fretboard are lined with a bone ring, so the strings don't touch the wood and can play freely.

The sitar has two bridges, a high one for the main playable strings, and a second smaller one below the high one for the sympathetic strings.  The latter go from the small bridge on one side to the small holes in the fretboard on the other side.

The sympathetic strings are all the same gauge, and their different lengths allows them to be tuned in the desired scale and still have more or less the same tension.

These strings run BELOW the frets and resonate when the main string is played. Sometimes players also play all the sympathetic strings directly, with a single motion, using the little finger just in front of the bridge.  This sounds like when you run a finger all over the piano keyboard from right to left (high to low). Many sitar players maintain a long nail on their right hand's little finger just for this purpose, while all other nails are kept short. That long nail is also useful to play individual sympathetic strings when you tune them.

Tuning those strings takes some practice but if the pegs and the holes are well matched, and you learn how much force to apply, and when to stop turning, then it works quite well. Note that you typically have to retune those strings before each new piece you play, to fit the raga (scale) of the next piece. (Usually only a few strings have to be retuned, e.g. the thirds, to fit the new scale, but at the same time the player will also check all the other strings so they are all well tuned)

The frets above are kept in place by a tight string that goes around the back of neck. This allows you to move the frets to fit the raga (scale) you want to play. For example, there is only one fret in the position of the minor and major 3rd, so you can move the fret to have either a minor or major 3rd in the scale.(*) The peg holes are placed strategically in between the places where the frets will be tied (because otherwise you cannot move the fret string over a peg)

The material for the bridges and the rings around the sympathetic strings is often deer horn, sometimes perhaps other hard animal bone.

There can be up to a dozen sympathetic strings, and they will be tuned to the scale you want to use, with a few extra notes above and below. For example, if you're playing a C major scale, the strings may be tuned like this (Low to high): C B C D E F G A B C D C

(*) Q: But what if sometimes I want to play a note that doesn't have the fret? A: You use the previous fret and pull the string sideways, just like bending strings on a guitar. It's common on the sitar to bend notes up to a fourth or a fifth above the pitch of the fret.
P.S. I lived a few years in India and I had a few professional sitars custom made, including two experimental ones, made entirely in wood and using guitar tuning pegs instead of the traditional ones. Unlike many other instruments that get better with age, the pumpkin gradually loses strength and brightness as it ages. Sitars are awesome and there is a world of enjoyment awaiting if you go into it even only half seriously...

How do the pegs on Sitar neck work?


Sprockets::EncodingError in javascript files in Ruby on Rails3.2

Question: I have a Ruby On Rails(Ruby 1.9; Rails 3.2.13) application. I am trying to create charts using Highcharts. But i am getting an error on browser as Sprockets::EncodingError in Product#index
sample/app/assets/javascripts/highcharts.js has a invalid UTF-8 byte sequence .The code files are as below. I have added the files rails.js, highcharts.js and jquery 1.4.2.min.js inside assets/javascript folder.
application.html.erb
<code>  <!DOCTYPE html>
  <html>
    <head>
     <title>Sample</title>
      <%= stylesheet_link_tag    "application", :media => "all" %>
      <%= javascript_include_tag "jquery-1.4.2.min", "rails", "highcharts" %>
      <%= csrf_meta_tags %>
     </head>
    <body>

 <%= yield %>
 </body>
</html>
</code>
The index.html.erb file is as below.
<code> <script type ="text/javascript" charset="UTF-8">
  </script>
  $(function() {
   new Highcharts.Chart({
    chart:{
     renderTo:"products_chart"
     type: 'column'
    }

   title: {
    text: 'Number of Patents Granted',
   },

 credits: {
  position: {
  align: 'left',
  x: 20
  },
      href: 'http://www.uspto.gov',
  text: 'Source: U.S. Patent & Trademark Office'
  },

 xAxis: {
  categories: [
   '2001', '2002', '2003', '2004', '2005',
   '2006', '2007', '2008', '2009', '2010',
   '2011' ]
   },

 yAxis: {
    title: {
   text: 'No. of Patents'
    }
 },

 plotOptions: {
 },
   series: [{
    name: 'UK',
    data: [ 4351, 4190, 4028, 3895, 3553,4323, 4029, 3834, 4009, 5038, 4924 ]
    }]

   });
});
</code>
Can anyone help to resolve this error ?
Thanks
Comment: Quick question: is there any particular reason, the JS is in the tempalte and the Js code in the template is not within the `script`-Tags? My first advice would be to separate the JS and or correct the script tags.
Comment: I advice to update ot the newset jquery, secondly which version of Highcharts do you use? Please replace new Highcharts.Chart() with var chart = new Highcharts.Chart();
Comment: I tried that.. but its still not working. It gives the same error.
Comment: Thanks for the comments. The issue is resolved. We need to add the javascript code inside the head section of view and remove
     <%= javascript_include_tag "jquery-1.4.2.min", "rails", "highcharts" %> from the application.html.erb file
Answer: Go to "Save with Encoding" menu and choose "UTF-8".
In the Sublime Text 2 this is in File > Save with Encoding > UTF-8.


Tirar efeito parallax do celular

Question: Tenho um efeito parallax no meu site que aparece em desktop. Só que o mesmo efeito está aparecendo em dispositivos mobile, mas não está legal.
Tem como fazer para não aparecer o parallax no mobile ou pelo menos aparecer somente a imagem parada sem o efeito?
Agradeço se alguém puder me ajudar. Obrigada!
Meus códigos são esses:
index.html

Conheça nossa loja!

custom.css
.parallax-container {
    max-width: 160px;
    margin: 0 auto;
  }

  section.module:last-child {
    margin-bottom: 0;
  }
  section.module h2 {
    margin-bottom: 40px;
    font-family: "Roboto Slab", serif;
    font-size: 30px;
  }
  section.module p {
    margin-bottom: 40px;
    font-size: 16px;
    font-weight: 300;
  }
  section.module p:last-child {
    margin-bottom: 0;
  }
  section.module.content {
    padding: 40px 0;
    background-color: rgba(207,216,220,0.5);
  }
  section.module.content:last-child {
    margin-bottom: 60px;
  }
  section.module.parallax {
    padding: 75px 0;
    background-position: 0 0;
  }

  section.module.parallax-1 {
    background-image: url('../img/parallax1.jpg');
    background-position: 50% 0;
    background-repeat: repeat;
    background-attachment: fixed;
    background-size: cover;
    background-color: rgba(0,123,255,0.1);
    background-blend-mode: screen;
  }

  section.module.parallax-3 {
    background-image: url('../img/parallax2.jpg');
    background-position: 50% 0;
    background-repeat: repeat;
    background-attachment: fixed;
    background-size: cover;
    background-color: rgba(0,123,255,0.1);
    background-blend-mode: screen;
  }

  @media all and (min-width: 600px) {
    section.module h2 {
      font-size: 42px;
    }
    section.module p {
      font-size: 20px;
    }
    section.module.parallax {
      padding: 90px 0;
    }
    section.module.parallax h1 {
      font-size: 96px;
    }
  }
  @media all and (min-width: 960px) {
    section.module.parallax h1 {
      font-size: 160px;
    }
  }

custom.js
    $(document).ready(function(){
  var $window = $(window);
    $('section[data-type="background"]').each(function(){
        var $bgobj = $(this); // assigning the object

        $(window).scroll(function() {
            var yPos = -($window.scrollTop() / $bgobj.data('speed'));

            // Put together our final background position
            var coords = '50% '+ yPos + 'px';

            // Move the background
            $bgobj.css({ backgroundPosition: coords });
        });
    });
});

//menu transition js
$(document).ready(function(){
  $(window).scroll(function(){
    var scroll = $(window).scrollTop();
          if (scroll > 0) {
        $(".navbar").addClass("navbar-scroll");
        }
          else{
          $(".navbar").removeClass("navbar-scroll");
      }
      if (scroll > 200) {
        $(".navbar").addClass("bg-primary");
      }

      else{
          $(".navbar").removeClass("bg-primary");
      }
  })
})

Answer: Você pode usar uma media rule para desabilitar o fundo fixo (background-attachment: fixed) em resoluções de até 1024px. Coloque no fim do seu CSS:
@media all and (max-width: 1024px) {
  section.module.parallax-1{
     background-attachment: scroll;
  }
}

Estou me baseando nesta tabela de dispositivos móveis, onde o maior viewport mostrado é do iPad Pro com 1024x1366 pixels (na vertical). Se você girar o tablet, o viewport horizontal vai virar 1366, o que é uma resolução comum em desktops.
Mas você pode pegar a resolução do iPhone XS Max, que possui 414x896 (o maior da tabela) e colocar 896px em vez de 1024px:
@media all and (max-width: 896px) {
  section.module.parallax-1{
     background-attachment: scroll;
  }
}

Tem o Samsung Galaxy Tab 10, com 800x1280, só que 1280px ainda pode ser considerado uma resolução de desktop (em monitores pequenos, por exemplo), então eu não consideraria 1280px como mobile.
Comment: Obrigada pela ajuda.

Tirar efeito parallax do celular