How to get the value from Text Editor in React Js? [Snippet attached]

Question: I am making a simple app that makes a JSON form and I have already included the basic details and employment details as two sections.
Basic details section has two inputs such as First Name and Last Name.
Now I am given the requirement to implement the Profile Summary control that should be a text editor and the values entered needs to be stored in JSON format.
Please look at the JSON format in the given codesandbox link.
File that forms JSON: https://codesandbox.io/s/nextjs-css-only-carousel-forked-8grpo?file=/components/form_context.js
{
    basicDetails: {
      firstName: "",
      lastName: "",
      profileSummary: "" --------> This is where I need to fetch the text editor entered values
    },
    companyDetails: [
      {
        companyName: "",
        designation: "",
        startDate: ""
      }
    ]
  }

Text Editor file: https://codesandbox.io/s/nextjs-css-only-carousel-forked-8grpo?file=/components/text_editor.js
Requirement:
The requirement is that the text editor value needs to be stored inside the JSON format.
Eg: If the the text is made bold or bullet list in the editor then the value of the key profileSummary needs to be added with respective tags.
I am trying to achieve the text editor field value like here: https://www.ippy.io/
As I am trying to build a resume like structure, Unable to get the point of how should I need to make the text editor value into JSON key profileSummary.
Complete working example:

https://codesandbox.io/s/nextjs-css-only-carousel-forked-8grpo

Any help is much appreciated.
Answer: Everytime editorState change, you need to get its plain HTML equivalent and pass that to your BasicDetails component.
onEditorStateChange = (editorState) => {
  // console.log(editorState);

  this.setState({ editorState }, () => {
    // state updated

    // convert editorState to plain HTML
    const contentRaw = convertToRaw(editorState.getCurrentContent());
    const contentHTML = draftToHtml(contentRaw);

    const fakeEvent = {
      target: {
        name: this.props.name,
        value: contentHTML
      }
    };

    // call onChange function from Parent passing the
    // fakeEvent object
    this.props.onChange(fakeEvent);
  });
};

On your BasicDetails you pass onChange and name prop to EditorContainer component.
...

<EditorContainer
  name="profileSummary"
  onChange={(event) => handleInputChange(event)}
/>

Unfortunately, converting DraftJS Editor content to plain HTML is not built-in on draft-js library, in fact they only support the following functions for data convertions

convertFromRaw
convertToRaw
convertFromHTML

So you are required to use another library, in my code above I'm using draftjs-to-html - the same person who created react-draft-wysiwyg.
Edit We can avoid setting the profileSummary with empty p tag by checking if editorState has some text.
this.setState({ editorState }, () => {
  const currentContent = editorState.getCurrentContent();
  const contentRaw = convertToRaw(currentContent);
  const value = currentContent.hasText() ? draftToHtml(contentRaw) : "";

  const fakeEvent = {
    target: {
      name: this.props.name,
      value
    }
  };

  this.props.onChange(fakeEvent);
});

Comment: Bro, Could you help here https://stackoverflow.com/questions/63717261/how-to-make-step-wizard-form-in-reactjs ?
Answer: You need write a funtion  hangleEditorChange in  BasicDetails.
Then,
# basic_detail.js
  ...

        Profile Summary
        <EditorContainer  onChnage ={hangleEditorChange}/>

...

```js
# text_editor.js

  onEditorStateChange = (editorState) => {
    this.setState({
      editorState
    });
   this.props.onChange(editorState)
  };


select repeat visitors given two time periods

Question: I would like to find the percent of repeat visitors to my site. Currently I am selecting users for one month and dividing that month by the following month. to calculate those that have returned. Is this the best way to write that query?
it is yielding results that seem to be accurate, but wondering if there is a more elegant solution.
SELECT (
SELECT COUNT(table.user) as Total
FROM table
WHERE table.event IN ('event1','event2','event3')
AND table.month IN ('october')
) /
(
SELECT COUNT(table.user) as newTotal
FROM table
WHERE table.event IN ('event1','event2','event3')
AND (table.month IN ('october') OR table.month IN ('november'))
) AS percent_return

table structure looks like this, you have the same user purchasing multiple events for the same month or the same time period.
 order_number user month event gross

   1 jack october event2 30
   2 jack november event3 20
   3 jack november event3 20
   4 jack november event2 30
   5 sam november event2 30
   6 john october event3 20
   7 john october non_event 20

Comment: What is the tables' sturcture?
Comment: how do you define a "repeat visitor"? your calculation doesn't seem to explain this. when you say you want a % of repeat visitors, what is it a % of? % of repeat visitors compared to total visitors? or % of visitors who came back?
Comment: sorry by repeat visitor I meant that I will run this query multiple times substituting the month each time. like here I am running against october/november. I can run it on january/february etc.
Answer: You don't need two subqueries to do what you want.  Just use conditional aggregation:
SELECT (SUM(s.month IN (october)) / SUM(s.month IN (october, november))
       ) as percent_return
FROM sales s
WHERE s.event IN ('event1', 'event2', 'event3') AND
      s.gross > 0;

Also, there is no need for single quotes around numeric constants.
Comment: just realized this does not work because it does not select the user
Comment: @alex_b . . . What do you mean "does not select the user"?  It should be producing the same results as your original query.
Comment: the first query selects the user count, SELECT COUNT(table.user)
Comment: Does `table.user` take on `NULL` values?  That seems unlikely, but it is easy enough to add `and s.user is not null` to each of the sums.
Comment: I figured it out it was http://stackoverflow.com/questions/23985854/calculating-percent-return-users-using-with-sql thanks for everything.


I have a problem with treeview

Question: I'm struggling with the wpf treeview.
 I need to load a list, but it is coming out the name of each object in the list, not that I'm doing wrong.
 I need a simple treeview example, carrying a ItemsSource.
My code is :
<my:WpfTreeView Name="tvInteracciones" Margin="10,10,10,105">
                        <TreeViewItem Header="Principios activos" ItemsSource="{Binding V_VistaInteraccionPrincipioActivo}">
                            <TreeViewItem.ItemTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding CFG_CAT_FAR_Interaccion_descripcion}"></TextBlock>
                                </DataTemplate>
                            </TreeViewItem.ItemTemplate>
                        </TreeViewItem>
  </my:WpfTreeView>

And:
public void LoadInteraccionesPF(List<V_VistaInteraccionPrincipioActivo> lista){
     tvInteracciones.ItemsSource = null;
                    tvInteracciones.Items.Clear();

                    tvInteracciones.ItemsSource = lista;
}

With the above code, I get the names of objects, not the content I want the attribute description.
What is my problem?
![This is the result scrren][1]
![enter image description here][2]
The problem remains the same then your solution which can be?
News code pics
   https://i.stack.imgur.com/AVJPV.jpg
https://i.stack.imgur.com/BkBIz.jpg
Comment: If you don't specify a datatemplate, it will use the ToString() of the datacontext.
Answer: You have to use item template
<TreeView Name="tvInteracciones" Margin="10,10,10,105">
            <TreeViewItem Header="Principios activos" ItemsSource="{Binding Path=CFG_CAT_FAR_Interaccion}">
                <TreeViewItem.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Name}"></TextBlock>
                    </DataTemplate>
                </TreeViewItem.ItemTemplate>
            </TreeViewItem>
        </TreeView>

Try this way...
Don't specify any itemssource to treeview item.... an itemssource should always be a collection..
<my:WpfTreeView Name="tvInteracciones" Margin="10,10,10,105">
                        <TreeViewItem Header="Principios activos">
                            <TreeViewItem.ItemTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding CFG_CAT_FAR_Interaccion_descripcion}"></TextBlock>
                                </DataTemplate>
                            </TreeViewItem.ItemTemplate>
                        </TreeViewItem>
  </my:WpfTreeView>

I have updated the xaml....
try this one
<my:WpfTreeView Margin="10,10,10,105">
                        <TreeViewItem Header="Principios activos"  Name="tvInteracciones">
                            <TreeViewItem.ItemTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding CFG_CAT_FAR_Interaccion_descripcion}"></TextBlock>
                                </DataTemplate>
                            </TreeViewItem.ItemTemplate>
                        </TreeViewItem>
  </my:WpfTreeView>

in the above code instead of giving itemssource to wpftreeview... i am giving items source to treeviewitem... just by changing the name give to wpftreeview item.....
Comment: Hello, thank you for sample, but i have an error. I have a List list;  tvInteracciones.ItemsSource = list; And i want see atribute V_VistaInteraccionPrincipioActivo.CFG_CAT_FAR_Interaccion_descripcion on screen. In above code, i'm use ItemsSource="{Binding Path="V_VistaInteraccionPrincipioActivo} and the text in textblock Text="{Binding CFG_CAT_FAR_Interaccion_descripcion}"
Comment: is it possible to post "V_VistaInteraccionPrincipioActivo" class structure and what do you want to display from that...?
Comment: i want display N descriptions the List, the problem is the code above display the structure...
Comment: i got it by seeing your image. it is very clear that binding is happening what we have to take care is to do proper binding to show description.... that's why i am asking for full class structure..
Comment: i have do a new screen shoots, You want this?  in post CHGUV.Guia.Farmacoterapeutica.Business.HGUVHis.CFG_CAT_FAR_Interaccion is the object class
Comment: Thanks for everything, now if that works, by name failed ...
 thanks again
Comment: as I can select an item from the treeview
Comment: If that works please accept this as answer.... that will improve your acceptance percentage and i will get few credits....

I have a problem with treeview


hook for maintenance mode

Question: I would like to send an email to some users, when i put my Drupal-7 website in maintenance mode. Are there any hooks that allow me to do this? I could not figure it out for myself.
Comment: If you're enabling maintenance mode through the UI you can use `hook_form_alter` and add a submit handler which sends the email. If by drush/something else, you'd probably need to script it as part of that op
Answer: As @Clive said you can use hook_form_alter() or hook_form_FORM_ID_alter() and add extra submit handler to send email notifications.
<code>function YOURMODULE_form_system_site_maintenance_mode_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'email_system_settings_form_submit';
}

function email_system_settings_form_submit($form, &$form_state) {
  // Add your email code here
}
</code>

hook for maintenance mode


Google Map Marker not displaying

Question: I've tried adding a marker variable to my Google Map API and it will not show. Any ideas why?
The website: http://www.franhaines.co.uk/paddlethewye/
function initialize() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 12,
        center: new google.maps.LatLng(51.843143, -2.643555),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    $("#findButton").click(findMe);}

function errorCallback() {
    alert("I'm afraid your browser does not support geolocation.");
}

function successCallback(position) {
  var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  var myOptions = {
    zoom: 15,
    center: latlng,
    mapTypeControl: false,
    navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
var map = new google.maps.Map(document.getElementById('map'), myOptions);
}

var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title:"We are here!"
});

function findMe()
{
    if (navigator.geolocation)
        {
             console.log(navigator.geolocation.getCurrentPosition(successCallback,errorCallback,{timeout:10000}));
        }
    else
    {
        alert("I'm afraid your browser does not support geolocation.");
    }
}

Comment: Try adding the marker inside `successCallback`.  You're doing it outside, where `map` is undefined
Comment: You are calling `successCallback` function but actually not passing `position` parameter and `latlng` depends on `position` parameter.
Comment: I've now added the position parameter in and it is still not working. :(
Comment: `ReferenceError: myLatlng is not defined`
Comment: Try this `if(navigator.geolocation) {

  navigator.geolocation.getCurrentPosition(function(position) {
   successCallback(position);
  }
}` .. Other thing is you are using `myLatlng` and you saved Latitude and Longitude in `latlng` So you need to change this as well
Comment: Hi @Rohil_PHPBeginner thanks for your reply. I've tried adding the if statement but it has now thrown up more errors and the map has stopped working completely.
Comment: See @Dr.Molle 's answer ..it will solve your issue ..
Answer: the issues

myLatlng is not defined
you create the marker before the map has been created
even when the map already has been created the Map-instance(map) wouldn't be accessible in the scope where you create the marker
the geolocation-callback creates a new Map-instance, the marker will not be drawn in this instance

Fixed issues:
function initialize() {

    var myLatlng = new google.maps.LatLng(51.843143, -2.643555),
        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 12,
            center: myLatlng
        }),
        marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: "We are here!"
        });

    //use the button as control when you want to
    map.controls[google.maps.ControlPosition.TOP_CENTER].push($("#findButton")[0]);

    function successCallback(position) {
        var latlng = new google.maps.LatLng(position.coords.latitude,
                                            position.coords.longitude),

            myOptions = {
                zoom: 15,
                center: latlng,
                mapTypeControl: false,
                navigationControlOptions: {
                    style: google.maps.NavigationControlStyle.SMALL
                },
                mapTypeId: google.maps.MapTypeId.ROADMAP
            },
            bounds = new google.maps.LatLngBounds(latlng);

        bounds.extend(marker.getPosition());

        //only set new options for the map
        //instead of creating a new instance
        map.setOptions(myOptions);

        //when you want to
        //set the viewport  of the map so that it diplays both locations
        map.fitBounds(bounds);

        //marker for the user-location when you want to
        new google.maps.Marker({
            position: latlng,
            map: map,
            title: "You are here!",
            icon: 'http://maps.gstatic.com/mapfiles/markers2/boost-marker-mapview.png'
        });
    }

    function errorCallback() {
        alert("I'm afraid your browser does not support geolocation.");
    }

    function findMe() {
        //hide the button, no need for further clicks
        $(this).hide();

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {
                timeout: 10000
            });
        } else {
            alert("I'm afraid your browser does not support geolocation.");
        }
    }

    $("#findButton").click(findMe);
}

Demo: http://jsfiddle.net/doktormolle/eb6kwkwg/
There is another, CSS-related issue(you may have noticed that the apperenance of the controls is distorted). For a fix see: Google Map Infowindow not showing properly
Comment: Thanks so much for this! I knew about the CSS issue just have not got round to fixing it yet. Thank you once again.
Comment: add this to style.css : `#map img {
    max-width: none;
}`

Google Map Marker not displaying


Properly using SVN & CI

Question: I am setting up the development environment for my start-up just now. I use Hudson for continuous integration of source code. It polls the SVN repository for changes every 10 minutes and if there are any deploys them to the LIVE servers from our DEV servers.
What I would like though is to have another Hudson job which deploys from DEV to TEST. I want to be able to commit code to SVN and then manually deploy to TEST, do a manual QA check and then it to be transferred to LIVE.
Is there a way I can do this with branches and the trunks in SVN? I would like it to still poll every 10 minutes as there are plenty of occasions when it should go straight from DEV to LIVE. I thought maybe I could commit to a branch then have hudson automate the deployment to TEST and then if it works out fine commit the branch to the trunk. Am I right??
Thanks in advance
Answer: I don't understand why you want a separate test step if there are still "plenty of occasions when it should go straight from DEV to LIVE" - which, as @Hightechrider says, sounds risky.  The way I would do it is:

Have Hudson detect changes every 10 minutes and deploy to TEST
Carry out your manual testing
Write another Hudson job which deploys the SVN revision you just tested from TEST to LIVE based on a trigger, for example sending an email to your Hudson server, if the tests pass (see the Hudson Wiki for details)

If your manual tests fail in step 2, I'm assuming you'll want to have your developers fix the code and repeat steps 1 and 2 before deploying to production.
I'm wondering if we're misunderstanding your scenario - if so, please add some more details on why you sometimes want to deploy to TEST and other times straight to LIVE.
Comment: You can also check into the promotion Plugin. With this you can promote certain builds to prod. This will save you the hassle of sending out emails to Hudson.
Answer: What we do using TeamCity is to build and then check in the binaries to a separate BINARY SVN for TEST using SVN LOAD_DIRS.  Deploy those bits to TEST servers.  If they look good, fire off another CI task manually that uses SVN LOAD_DIRS a second time to copy the bits over to a PRODUCTION SVN  repository and then deploy those bits to production.
The advantage of this is that you have a copy of the exact bits you deployed to each server and can roll back easily, or can check out any specific version (say, last friday's) and test against that.  You can also make changes to configuration files in the binary version and deploy those to production whilst still having a track record of who changed what, and when they did it.
This also gives you a deployment system with atomic properties - i.e. you get all or nothing when you try to update your servers to the new version, and never a partial / failed deployment.
Another advantage is that you can surgically replace individual content files in production with the latest version by checking out just those individual changed files - a handy feature at 4PM on Friday when you'd rather not risk a full deployment just in case some other change sneaked in to the binaries.
I can't see a scenario where we would ever want a direct deployment to LIVE - sounds risky.
Comment: I might be being completely stupid but I haven't heard of SVNs LOAD_DIRS command before. Can you explain?
Thanks
Comment: svn_load_dirs.pl is a script that was supplied with SVN until recently but is still available if you hunt around.  It can be used to load a directory into SVN on top of an existing copy of that code and it will correctly leave files unchanged that are unchanged, will  record updates for changed files and will add new files.  If you use this to load your binaries into the binary tree you preserve file-level version history (better than deleting a directory and adding a replacement for it) and can see exactly which files have changed or been added with each revision.

Properly using SVN & CI


Why do we assume Gaussian margins in Gaussian mixture models

Question: A Gaussian mixture model is a weighted sum of Gaussian densities, i.e.,
$L(\theta) = \sum_{i=1}^{m} \pi_{i} f(x_i)$
where $m$ is the number of the mixture component.
Hence, Gaussian mixture models is a sum of a finite mixture Gaussian distribution with unknown parameters. I read that, in Gaussian mixture models, each univariate margins are assumed to be normal. Is that correct and why?
Any help, please?
Comment: The false premise of this question was comprehensively pointed out the last several times you posted it. Please do not post it again.
Answer: We do not (need to) assume anything on the margins. Generally, in a mixture model setting we start with a single density $f(\cdot;\theta)$ and then we assume that we have random variables $(X_1, ..., X_N, Z_1, ..., Z_N)$ such that $(X_i, Z_i)$ are independent and for a parameter $\Theta = (\tau_1, ..., \tau_K, \theta_1, ..., \theta_k)$ we have that $X = (X_1, ..., X_N)$ and $Z = (Z_1, ..., Z_N)$ have a common density $p(x,z)$ and that
  $$p(x|z) = \prod_{i=1}^N p(x_i|z_i) = \prod_{i=1}^N f(x_i;\theta_{z_i})$$
and
  $$p(z) = \prod_{i=1}^N p(z_i) = \prod_{i=1}^N \tau_{z_i}$$
Let us assume that $N=1$ then we simply compute
  $$p(x) = \int_{\mathcal{Z}} p(x,z) dz = \int_{\mathcal{Z}} p(x|z)p(z) dz = \sum_{k=1}^K f(x;\theta_{k}) \tau_k$$
i.e. the marginal of each and every data variable $X_i$ is the same and it is this mixture expression that you have written above and not a single Gaussian!
Comment: thank you so much for your answer. Hence, the margin of each variable is a mixture of Gaussian in the case of the Gaussian mixture model. Is that what you meant by "e. the marginal of each and every data variable Xi
X

 is the same and it is this mixture expression that you have written above and not a single Gaussian!"?
Comment: In addition, the margin of each component will be a Gaussian distribution.


Validate Phone number textbox

Question: I want to know how I can validate a phone number in a textbox using this code:
System.Text.RegularExpressions.Regex rphone = new System.Text.RegularExpressions.Regex(@"^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$");

Answer: try:
\+[0-9]{3}\s+[0-9]{3}\s+[0-9]{5}\s+[0-9]{3}

heres a little explaination of pattern above .
\+ -------------|> +sign
[0-9]{3} -------|> matches 0-9 max of 3digit
\s+ ------------|> a whitespace

matches with your sample:
+020 111 94546 333
if you want to validate if the number was completed lets say you got a button then textbox do something like:
private void button1_Click(object sender, EventArgs e)
{
    Regex phoneNumpattern = new Regex(@"\+[0-9]{3}\s+[0-9]{3}\s+[0-9]{5}\s+[0-9]{3}");
    if (phoneNumpattern.IsMatch(textBox1.Text))
    {
        MessageBox.Show("OK");
    }
    else
    {
        MessageBox.Show("Invalid phone number");
    }
}

Answer: private void myTextBox_Leave(object sender, EventArgs e)
{
    Regex pattern = new Regex(@"^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$");
    if (pattern.IsMatch(myTextBox.Text))
    {
        MessageBox.Show("OK");
    }
    else
    {
        MessageBox.Show("Invalid phone number");
    }
}

Comment: please tell me the output of this string Regex pattern = new Regex(@"^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$");
Comment: I'm not sure I understand your question. The input is a valid phone number in the textbox named myTextBox. The output from the `pattern.IsMatch()` is a boolean value indicating if the phone number passes the regEx.
Comment: yes i know that but i need to know how the number will input +020 111 94546 333
Comment: Yeah I am confused about what you're asking. A user would type the number into the textbox, when the textbox lost focus (ie the `Leave` event) is fired the validation would occur.
Comment: i want to know the rigth form should be written in the textbox
Comment: Well thats a different question entirely. You will need a `masked textbox` to do that.

Validate Phone number textbox


mysql get latest records by order by desc without subquery

Question: Im trying to get result with below query but its taking around 2min to retrieve
SELECT *
FROM customer e
WHERE e.id=324
AND e.g_id IN('x133fv','be6544','e992170','93611c')
and e.enrol_id =
(
 select e1.enrol_id
 from customer e1
 WHERE e1.id=324
 AND e1.g_id=e.g_id
 ORDER BY update_time DESC, posted_time DESC, enrol_id DESC
 LIMIT 1
)

I have index on (g_id,id)
Is there any other way to get the result via JOIN?
Comment: I'm with Gordon on this. Don't look for another way. This query looks good and reads well. If it takes too long, then you should look at the EXPLAIN plan and try to see if it can be made efficient by adding an index. Since you have 2 equality conditions on id and g_id and an order by on another 3 columns, Gordon's suggestion of adding a composite 5 column index may very well solve your problems.
Comment: Frazz, gordon index just helped me gain 6 seconds from total 2min output time. :(
Answer: This is your query:
SELECT *
FROM customer e
WHERE e.id = 324 AND
      e.g_id IN ('x133fv','be6544','e992170','93611c') and
      e.enrol_id = (select e1.enrol_id
                    from customer e1
                    WHERE e1.id=324 AND e1.g_id=e.g_id
                    ORDER BY update_time DESC, posted_time DESC, enrol_id DESC
                    LIMIT 1
                   )

You can improve the performance with indexes.  I would suggest: customer(id, g_id, update_time, posted_time, enrol_id).
Comment: Thanks for the response... But is it possible to get a JOIN rather than subquery?
Comment: I added this index but still its using the old index (g_id,id). Did analyze table several times also and did FORCE INDEX too but still took same time..
Comment: @user3752021 . . . As I look at the query, only one index is necessary.
Comment: The new index of customer(id, g_id, update_time, posted_time, enrol_id) helped to gain only 6seconds from original 2min output time. :(  any other option  to reduce the time.
Comment: @user3752021 . . . Try making that:  `customer(g_id, id, update_time, posted_time, enrol_id)`
Comment: I did try that option but same 6second gain.
Comment: @user3752021 . . . If you replace the `in` with a comparison to just one value, does the performance improve dramatically?
Comment: Bascially if i just have 1 group ID and if I remove subquery Link from e1.g_id=e.g_id to e1.g_id IN (1groupid). This performs the best. But i cant do that since i have multi groupid in play. Thats why i was asking if rewrite JOIN can help here.
Comment: Try moving the "g_id IN(...)" condition into the SUBSELECT... or replicating it (like you did the "id =" condition). Just to see if this works better with the index.


How to run experiments in such a way to understand the underlying sources of variation?

Question: Suppose I have some outcome variable $Y$ that depends on several factors $F_1, \ldots, F_m$, which I assume to be binary for simplicity. Each time I conduct an experiment on levels of the factors, I get a result of $Y$. I would like to understand how much of the sampling variation on $Y$ is attributable to each of $F_1, \ldots, F_m$. For example, 20% of variation when I sample $Y$ is due to $F_1$, etc. What are some general methods for inferring the variance that can be attributable to various underlying factors?
Comment: It might be helpful to construct an orthogonal design (https://support.minitab.com/en-us/minitab/18/help-and-how-to/modeling-statistics/doe/supporting-topics/basics/orthogonal-designs/).  An orthogonal design will allow you to attribute a "proportion of variance explained" for each predictor (https://stats.stackexchange.com/questions/60872/how-to-split-r-squared-between-predictor-variables-in-multiple-regression) which sums to the full model r squared.
Comment: @DemetriPananos: This looks like an answer, can you make it into one?
Comment: @kjetilbhalvorsen  I've copy and pasted my comment as an answer.
Answer: It might be helpful to construct an orthogonal design (https://support.minitab.com/en-us/minitab/18/help-and-how-to/modeling-statistics/doe/supporting-topics/basics/orthogonal-designs/). An orthogonal design will allow you to attribute a "proportion of variance explained" for each predictor (How to split r-squared between predictor variables in multiple regression?) which sums to the full model r squared.


Django button to send emails

Question: How would you go about creating a button in your templates of an app in Django. I have a script in my views.py:
def my_python_script(request):
    if request.is_ajax:
        # stuff here
    else:
        return HttpRequest(status=400)

But how do I actually turn this into a button? Is there some html or css I need to put somewhere? I saw some things about a templates directory in the application but I'm unsure on what things to put there and in what formats.
Comment: You need to start at the beginning of the django tutorial and work through it.
Answer: You would do like the following:
<button type='button' id="my_button">Click me</button>

And with a js (jquery):
$("#my_button").click(){
     $.get("url_to_view",{data:"data",function(response){
          // response to do something after the request
     });
});

Django button to send emails


Rudin's RCA $2.20$ theorem $(c)$.

Question: There are the definitions which we need for the theorem:

There are the theorem $2.20$ and proof of its part $(a)$ and $(b)$:

There are the proofs of part $(c)$, $(d)$ and $(e)$:
The proofs of $(c)$, $(d)$, and $(e)$ will use the following observation: If $\lambda$ is a positive Borel measure on $R^k$ and $\lambda(E)$ $=$ $m(E)$ for all boxes $E$, then the same equality holds for all open sets $E$, by property $2.19(d)$, and therefore for all Borel sets $E$, since $\lambda$ and $m$ are regular (Theorem $2.18$).
To prove $(c)$, fix $x$ $\in$ $R^k$ and define $\lambda(E)$ $=$ $m(E+x)$.
It is clear that $\lambda$ is then a measure; by $(a)$, $\lambda(E)$ $=$ $m(E)$ for all boxes, hence $m(E+x)$ $=$ $m(E)$ for all Borel sets $E$.
The same equality holds for every $E$ $\in$ $\mathfrak M$, because of $(b)$.
I don't understand why is it clear in $(c)$ that $\lambda$ is a measure.
I also don't understand how does $(a)$ imply, that $\lambda(E)$ $=$ $m(E)$ for all boxes?
Any help would be appreciated.
Comment: This might get closed as the other one did. There are too many pictures and it's quite hard to follow. I recommend making the question more focused, and if you have to, feel free to leave out further details such as other lemmas and prerequisite theorems as it's likely that many readers know them.
Answer: We can demonstrate this using the second part of (e), that is, when $T$ is invertible, $\Delta(T) = |\det T|$ (this is not obvious, but it can be proven by proving it for $T$ that generate $GL(n, \mathbb{R})$, e.g. $T$ being each of the three elementary row operations).
Suppose $Y \subset \mathbb{R}^n$ is a linear subspace of dimension $k < n$. By basic linear algebra, there is an orthogonal matrix $A$ such that $A(Y) = \mathbb{R}^{k} \times \{0\}^{n - k}$. In particular, $A : \mathbb{R}^n \to \mathbb{R}^n$ is an isometric isomorphism, so $A$ and $A^{-1}$ are both continuous, hence measurable. Thus $Y = A^{-1}AY = A^{-1}(\mathbb{R}^{k} \times \{0\}^{n - k})$ is Borel measurable. Since $\det A = \pm 1$, we get
$$m(Y) = m(A(Y)) = m(\mathbb{R}^{k} \times \{0\}^{n - k}) = m(\mathbb{R}^k) \cdot m(\{0\}^{n - k}) = \infty \cdot
0 = 0.$$
Comment: @Obito Why is $\Delta(T)$ equal of $|detT|$ when T is invertible? I also don't understand how does the fact that det $A$ $=$ $1$, or $-1$ guarantees that $Y$ is Borel-measurable?
Comment: @JohnNash I've fixed my answer to elaborate those points.
Comment: Great job on gaining your first bounty!

Rudin's RCA $2.20$ theorem $(c)$.


javax.el.CompositeELResolver class not found in Tomcat

Question: When I am developing a JSF project in Tomcat 7, the server keep arguing this class not found. May I know which jar am I missing?
Caused by: java.lang.ClassNotFoundException: javax.el.CompositeELResolver

I have already put this jar in the Tomcat lib folder:

jsf-api-2.0.1.jar
jsf-impl-2.0.1.jar
javax.servlet-api-3.0.1.jar

Beside this, I also have servlet-api-2.5.jar and servlet-api.jar, not sure which one is currently using by Tomcat 7.
Answer: Tomcat 7 is a Servlet 3.0 container. It already comes along with JSP/Servlet/EL libraries by itself. You can find them all in /lib folder of the default (and untouched) Tomcat installation.
You should not add libraries of a different servletcontainer make/version in there. You should only add libraries which are not already provided by Tomcat itself. So the following statements

javax.servlet-api-3.0.1.jar

Beside this, I also have servlet-api-2.5.jar and servlet-api.jar,

are not a good indication that you understood it. You should remove all Servlet API libraries which you explicitly added yourself. This would only conflict with Tomcat's own ones and result in this kind of classpath troubles.
See also

How do I import the javax.servlet API in my Eclipse project?


programmatically create one bean block to the default theme

Question: I am trying to programmatically create beans in a custom module using entity_metadata_wrapper. This is creating a bean for each installed theme. (In Drupal 7)
Is there a way I can create only one instance of the bean block?
for example in my database it creates a bean block for

my subtheme
omega
seven

I would like to only create one block/bean for my subtheme. I am then using mymodule_beans_block_info_alter(&$blocks, $theme, $code_blocks) {} to then change region location and other block parameters.
function bean_ctas_enable(){
    foreach(bean_ctas_info() as $bean_content){
        $bean_ids = array();
        $bean = bean_create(array('type' => 'block_cta'));
        $bean_wrap = entity_metadata_wrapper('bean', $bean);
        $bean_wrap->label->set($bean_content['label']);
        $bean_wrap->title->set($bean_content['title']);
        $bean_wrap->field_text->set(array(
            'value' => ($bean_content['field_text']),
            'format' => ('full_html'),
            ));
        $bean_wrap->field_link->set(array(
            'url' => ($bean_content['link_url']),
            'title' => 'Read More',
        ));
        $bean_wrap->save();
        $bean_ids[] = $bean_wrap->bid->value();
        //set variable to store bean ids
        variable_set('bean_ctas_bean_ids', $bean_ids);
    }
}

Answer: I used hook_block_info_alter(&$blocks, $theme, $code_blocks) to alter the blocks in my custom modules .module file
inside of my  hook_block_info_alter i wrote an if statment
if($blocks['bean'][$key]['theme'] == variable_get('theme_default', '0')){}

to make sure I was only altering regions only for my default theme


Passing Method as a Character String

Question: I need to allow the user to create an object with one of several classes. The object will require further analysis so will be passed to one of numerous S3 methods downstream.
My thought is to have them provide the class as a character string on the creation function call, but I'm not sure the best way to use useMethod to select the proper S3 method, since the different objects will be created with different algorithms.
The create_thing() function will return an object with class set, so graph_thing() and report_thing() will take the output of create_thing() and have a class to work with.
create_thing <- function(model = 'strange', foo, bar){
  tmp <- ""
  class(tmp)<-model
  UseMethod("create_thing", tmp)
}

create_thing.strange <- function(model, foo = 1, bar = 2){
  ## stuff
  print("strange")
  return(structure(list(data=runif(5)), class = c("list", "strange")))
}

create_thing.normal <- function(model, foo = 3, bar = 4){
  ## stuff
  print("normal")
  return(structure(list(data=rnorm(5)), class = c("list", "normal")))
}

graph_thing <- function(athing){
  UseMethod("graph_thing")
}

graph_thing.normal <- function(athing){
  print("normal")
  plot(athing$data)
}

graph_thing.strange <- function(athing){
  print("strange")
  plot(athing$data)
}

report_thing <- function(athing){
  UseMethod("report_thing")
}

report_thing.normal <- function(athing){
  print("normal")
  print(mean(athing$data))
}

report_thing.strange <- function(athing){
  print("strange")
  print(median(athing$data))
}

Comment: There seems to be serious object/function confusion here.  The last call in a function determines what is returned. `UseMethod("thing", tmp)` returns ....  a function. And it's unclear what `thing.strange` and `thing.normal` are supposed to be doing because they coded as empty, return a character object and _most_ _importantly_ are not described in natural language. Please improve the question.
Comment: The proper way to use `UseMethod` is via standard `S3` dispatch, which is handled under the hood if the object class is set correctly. I'm not entirely clear on the reasons for your example to exist, can you give more details on what you are trying to do? What objects might someone pass in?
Comment: I *think* what you're trying to do could be accomplished if you defined a standard generic `thing = function(foo, bar) {UseMethod("thing")}` and then did whatever weird things you are currently doing in your version of `thing` in `thing.default` instead, with it's last line being to call `thing()` on it... assuming you've changed the class to something with a different `thing` method. But it does seem like you're running yourself in circles.
Comment: Maybe you just need to define an `as.strange` and expect users to use that? Y'know, like S3 classes usually work? The mentions of `graph_thing` and `report_thing` are confusing in your text since they don't seem to line up with your example code. Do you mean `graph.thing` and `report.thing`? Is `thing` your class, or are `strange` and `normal` different classes?
Comment: Sorry for the ugly question, I hope it is better now.
Answer: The UseMethod function looks up the call stack to see what was passed in to the original function. Any modifications or new objects created will not influence how dispatching works.
If you are using the create_thing functions to initilize the object, then you should create a separate generic function for that
create_thing <- function(model = 'strange', foo, bar){
  tmp <- ""
  class(tmp)<-model
  init_thing(tmp, foo, bar)
}

init_thing <- function(model, foo=0, bar=0) {
    UseMethod("init_thing")
}
init_thing.strange <- function(model, foo = 1, bar = 2){
  ## stuff
  print("strange")
  return(structure(list(data=runif(5)), class = c("list", "strange")))
}

init_thing.normal <- function(model, foo = 3, bar = 4){
  ## stuff
  print("normal")
  return(structure(list(data=rnorm(5)), class = c("list", "normal")))
}

Passing Method as a Character String


Generate in Excel 365 a matrix from rows and columns with one array function

Question: Suppose we want to make in Excel a matrix from a row of values and a column of values (or labels). For years a way to write a single formula to fill this matrix was to write an absolute column reference and an absolute row reference (e.g. =$A1+B$1 ) and fill the matrix. For example, like this.

For static matrices this works perfectly. Now with Excel 365 we have a range of array formulas that can create dynamic sequences and arrays. Suppose the matrix is defined by two dynamic sequences for rows and for columns as below, and its dimensions can change. Copy and paste a formula like before means that every time dimensions change, the formula will have to be copied and pasted manually to new location to fill the new matrix. Here is an example of such a dynamic matrix.

Is there a way to reproduce the original method of filling the matrix with sum of row and column values with one formula that uses array formulas(s) so that the formula will fill the whole matrix automatically, if either row dimension or column dimension changes?
I assume this formula will most likely not need for row and column inputs be laid out in cell, they can be fed to it as array inputs - but if not, it will still be a solution I seek.
I tried =MAKEARRAY(row, col, lambda(r, c, f(r,c)) ) but cannot figure out how I can pass arrays to lambda to iterate over.
Answer: Ok, after a few days of trying I found a solution. Not a very pretty one but working.
For math operators + - * / ^ () spill (#) reference does the trick:
=A2#*B1#

Some canned formulas can also take spill (#) inputs and generate an array:
=PMT(A2#/100,B1#,1000,0)

Some cannot. E.g. =MAX(A2#,B1#) will only return the single largest value.

However, it is still possible to produce a workaround.
=MAKEARRAY(COUNT(A2#),COUNT(B1#),LAMBDA(row,col,MAX(INDEX(A2#,row),INDEX(B1#,1,col))))

Step by step:

=COUNT(A2#) =COUNT(B1#) return length of row and column dynamic ranges
=MAKEARRAY(COUNT(A2#),COUNT(B1#),LAMBDA()) generates a rectangular dynamic array of these dimensions
LAMBDA(row,col,MAX(row,col)))) takes row index and column index as first two required inputs and passes them to MAX() formula
Finally, INDEX(A2#,row),INDEX(B1#,1,col) again take row and column array and return the values that match the indices, which MAX() processes.

E.g row=1 is converted to 1 and column=1 becomes 10. MAX(1,10) returns 10 to LAMBDA() and MAKEARRAY(1,1,LAMBDA()) populates the array at position 1,1 with 10. Repeat until all pairs of row=A2# and column=B1# are done.
Hope this helps others who may be looking for a solution to this problem.


Irregular blanks between inline list elements

Question: There is some irregular blanks in jsfiddle link. It had to be line-by-line and pictures had to be immediatly after each one. I wonder that why it is happen and how i can fix it.                               .
HTML:

.
.
.

CSS:
#content{
    width: 90%;
  margin: auto;

}
ul {
    list-style-type: none;
}
#videos{
    overflow: hidden;
    position: relative;
  padding-left: 10px;

}
#videos-wrapper{
    -moz-border-bottom-colors: none;
    -moz-border-left-colors: none;
    -moz-border-right-colors: none;
    -moz-border-top-colors: none;
    background-color: #101010;
    border-color: #222;
    border-image: none;
    border-style: solid solid none;
    border-width: 1px 1px 0;
    clear: both;
    padding-bottom: 8px;
    position: relative;
}
#videos-ul{
        left: 0;
    margin-left: 2px;
    margin-top: 6px;
    position: relative;
}
ul {
    list-style-type: none;
}
ul li.single-video-li {
    vertical-align: top;
    display: inline-block;
}
.single-video-block{
    width: 35px;
    margin-right: 10px;
    position: relative;
    height: 35px;

}
.video-thumb{
    width: 30px;
    height: 30px;
}

RESULT:
Answer: You had multiple
s within some
s
http://jsfiddle.net/s8d77r2z/1/
Answer: You are including two divs in the li element. Please see this updated Fiddle
Answer: #videos-ul {
    left: 0;
    margin-left: 2px;
    margin-top: 6px;
    position: relative;
    font-size:0; /* <======   to get rid of white spaces when inline-block element are present as child */
}

Make you repeating li similar like below

DEMO
Comment: You are not repeating similar blocks, like others pointed all your repeating li should be similar in structure.
Comment: which parts i am repeating? I really can't find out. I can not see any difference between your fiddle and my fiddle. But your's is working fine.


Erro na paginação com custom post type

Question: Eu tenho dois Custom post type criado, um para filmes e outro para series, eu tenho um loop que mostra os dois na index, só que quando eu uso a paginação, não funciona.
Ex.:
Aperto para ir para a /page/2
Só que eu recebo um erro 404, como se não existisse a pagina 2.
Procurando no github e nos fóruns da SO eu encontrei uma possível solução, quando eu adiciono essa função na functions.php e erro some, só que quando eu vou para a pagina 2, aparece o mesmo post na /page/2
add_filter( 'request' , 'pagination_request_filter' );

function pagination_request_filter( $query ) {

    // https://wpquestions.com/Trouble_with_custom_post_type_pagination/937

    if ( empty( $query['preview'] ) && empty( $query['feed'] ) ) {
        $my_post_type = $query['post_type'];
        if ( empty( $my_post_type ) ) {
            $query['post_type'] = 'any';
        }
    }
    return $query;
}

Meu loop que eu estou utilizando na index e esse, não estou usando nenhum plugin para paginação, tentei usar o wp-pagenavi mas sem sucesso.
vou deixa o código completo:

<?php $args = array('post_type'=>array('filmes', 'series')); query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php   if (has_post_thumbnail()) {
$imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'home');
$imgsrc = $imgsrc[0];
} elseif ($postimages = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0")) {
foreach($postimages as $postimage) {
$imgsrc = wp_get_attachment_image_src($postimage->ID, 'home');
$imgsrc = $imgsrc[0];
}
} elseif (preg_match('/
]*src=["|\']([^"|\']+)/i', get_the_content(), $match) != FALSE) {
$imgsrc = $match[1];
} else {
$imgsrc = get_template_directory_uri() . '/images/no-imagen.png';
} ?>
<li class="post_container" id="post-<?php the_ID(); ?>">

<?php $id = get_the_author_meta( 'ID' );
if (is_user_online($id) ) {
echo '';
} else {
echo '';
}
?>

<?php echo get_avatar( get_the_author_email(), '64' ); ?>

<div class="tooltipped tooltipped-n tooltipped-multiline" aria-label="<?php the_author_meta('description'); ?>" style="position: relative;">

<span class="tooltipped tooltipped-n qpost-cont" aria-label="Autor de <?php the_author_posts() ?> postagens"><?php the_author_posts() ?>
Postagens
<em class="userBanner <?php echo get_author_role(); ?>">
<span class="before <?php echo get_author_role(); ?>">
<strong class="tooltipped tooltipped-n befafter" aria-label="<?php echo get_author_role(); ?>"><?php echo get_author_role(); ?>
<span class="after <?php echo get_author_role(); ?>">

<?php the_author(); ?>

<a class="post_info_link tooltipped tooltipped-n" aria-label="Atualizado há <?php echo meks_time_ago(); ?> - <?php if(function_exists('the_views')) { the_views(); } ?>">Adicionado há <?php echo meks_time_ago(); ?>

<?php if($values= get_post_custom_values( '_audio_video')) { ?><?php echo $values[0]; ?><?php } ?>

<img src="<?php echo $imgsrc; $imgsrc = ''; ?>" alt="<?php the_title(); ?>">

<a href="<?php the_permalink() ?>"><?php the_title(); ?>

<?php echo get_the_term_list($post->ID, 'categoria', '', ', ', ''); ?>

<?php if($values = get_post_custom_values("_sinopse")) { ?><?php echo $values[0]; ?><?php } ?>

Elenco:
<?php if(get_the_term_list($post->ID, 'personalidade', '', ', ', '')) { ?>

<?php echo get_the_term_list($post->ID, 'personalidade', '', ', ', ''); ?>

<?php } ?>

Criador:
<?php if(get_the_term_list($post->ID, 'criador', '', ', ', '')) { ?>

<?php echo get_the_term_list($post->ID, 'criador', '', ', ', ''); ?>

<?php } ?>

Gênero:
<?php if(get_the_term_list($post->ID, 'genero', '', ', ', '')) { ?>

<?php echo get_the_term_list($post->ID, 'genero', '', ', ', ''); ?>

<?php } ?>

Duração:
<?php if($values= get_post_custom_values( '_runtime')) { ?>

<?php echo $values[0]; ?>

<?php } ?>
Publicado em <?php the_time(get_option('date_format')); ?>

<a href="https://www.imdb.com/title/<?php if($values= get_post_custom_values( '_imdb_id')) { ?><?php echo $values[0]; ?><?php } ?>" target="_blank">

<?php if($values= get_post_custom_values( '_imdb_points')) { ?><?php echo $values[0]; ?><?php } ?>

<span class="imdb_post_rating_p" style="width: <?php if($values= get_post_custom_values( '_imdb_percentage')) { ?><?php echo $values[0]; ?><?php } ?>;">

<a class="imdb_post_imdb_a" href="https://www.imdb.com/title/<?php if($values= get_post_custom_values( '_imdb_id')) { ?><?php echo $values[0]; ?><?php } ?>" rel="nofollow" target="_blank">IMDB:
<?php if($values= get_post_custom_values( '_imdb_points')) { ?><?php echo $values[0]; ?><?php } ?>/10
<?php if($values= get_post_custom_values( '_imdb_votes')) { ?><?php echo $values[0]; ?><?php } ?>
votos

<div class="tooltipped tooltipped-nw content_parental content_parental_rating-<?php if($values= get_post_custom_values( '_classification')) { ?><?php echo $values[0]; ?><?php } ?>" aria-label="<?php if($values= get_post_custom_values( '_description')) { ?><?php echo $values[0]; ?><?php } ?>"><?php if($values= get_post_custom_values( '_classification')) { ?><?php echo $values[0]; ?><?php } ?>

<a class="update tooltipped tooltipped-s" aria-label="Atualizado em <?php the_modified_date ('d \d\e F \d\e Y'); ?>">Atualizado em <?php the_modified_date ('d \d\e F \d\e Y'); ?>
<a class="download" href="<?php the_permalink() ?>">Mais Informações

<?php $activar_ads = get_option('activar-slider-footer'); if ($activar_ads == "true") { ?>
<?php $random = rand(1,6); if ($ads2 == 3) : ?>
<?php $ads = get_option('slider-footer'); if (!empty($ads)) echo stripslashes(get_option('slider-footer')); ?>
<?php endif; $ads2++; ?>
<?php } ?>

<?php endwhile; wp_reset_query(); ?>
<?php else : ?>

<?php _e('No content available', 'mundothemes'); ?>

<?php endif; ?>
<?php pagination(); ?>

Minha função de paginação:
function pagination($pages = '', $range = 2) {
    $pagn = ($range * 2)+1;
    global $paged; if(empty($paged)) $paged = 1;
    if($pages == '') {
        global $wp_query; $pages = $wp_query->max_num_pages;
        if(!$pages){ $pages = 1; }
    }
    if(1 != $pages) {
        echo "

";

        if($paged > 2 && $paged > $range+1 && $pagn < $pages)
            echo "
".__( 'First', 'mundothemes' )."
";
        if($paged > 1 && $pagn < $pages)
            echo "";
        for ($i=1; $i <= $pages; $i++){
            if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $pagn )) {
                echo ($paged == $i)? "
".$i."
":"
".$i."
";
            }
        }
        if ($paged < $pages && $pagn < $pages)

        if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $pagn < $pages)
            echo "
".__( 'Last', 'mundothemes' )."
";
            echo "

";
    }
}

Answer: Depois de dois dias procurando informações e métodos para arrumar esse erro, finalmente encontrei uma maneira.
Já estava quase desistindo, resolvi vim aqui em ultimo caso para perguntar, geralmente sempre tem a galera que sabe mais sobre o assunto, no entanto acabei por solucionando "sozinho"...
Primeiramente já vou logo dizendo que eu não sou nenhum programador, sou apenas um curioso que costuma acertar sempre que quero fazer alguma coisa rs, então não faço nem ideia de como explicar as funções, mas sei que comigo funcionou assim.
Loop (acho que e isso) que eu uso para solicitar as postagens que estão nos meus custom post type:
<?php $args = array('post_type'=>array('filmes', 'series'),'paged' => $paged,'orderby'=>'date','posts_per_page' => 2); query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

Na solicitação acima eu quero mostrar todos os post que estão nos meus custom post type, que são "filmes" e "series", onde esta escrito "'posts_per_page' => 2" e a quantidade de post que vai ser exibido na index, que no meu caso e apenas 2.
Esses são meus dois custom post type:

A função dos custom post type "filmes" e "series":
add_action( 'init', 'post_type_movies' );

function post_type_movies() {

  $labels = array(
    'name'                => __( 'Filme' ),
    'singular_name'       => __( 'Filmes' ),
    'add_new'             => __( 'Adicionar Novo' ),
    'add_new_item'        => __( 'Adicionar Novo Filme' ),
    'edit_item'           => __( 'Editar Filme' ),
    'new_item'            => __( 'Novo Filme' ),
    'all_items'           => __( 'Todos os Filmes' ),
    'view_item'           => __( 'Ver Filme' ),
    'search_items'        => __( 'Pesquisar Filme' ),
    'not_found'           => __( 'Nenhum filme encontrado' ),
    'not_found_in_trash'  => __( 'Nenhum filme na lixeira' ),
    'menu_name'           => __( 'Filmes' ),
  );

  $supports = array( 'title', 'editor', 'thumbnail', 'comments');

  $slug = get_theme_mod( 'movies_permalink' );
  $slug = ( empty( $slug ) ) ? 'filmes' : $slug;

  $args = array(
    'labels'              => $labels,
    'public'              => true,
    'publicly_queryable'  => true,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'query_var'           => true,
    //'rewrite'             => array( 'slug' => $slug ,'with_front' => false),
    'rewrite'             => array( 'slug' => $slug ),
    'capability_type'     => 'post',
    'has_archive'         => true,
    'hierarchical'        => false,
    'menu_position'       => 4,
    'supports'            => $supports,
    'menu_icon'           => 'dashicons-editor-video',
  );
  $wp_query = new WP_Query($args);
  $posts = $wp_query->posts;

  register_post_type( 'filmes', $args );

}

add_action( 'init', 'post_type_series' );

function post_type_series() {

  $labels = array(
    'name'                => __( 'Série' ),
    'singular_name'       => __( 'Séries' ),
    'add_new'             => __( 'Adicionar Novo' ),
    'add_new_item'        => __( 'Adicionar Nova Série' ),
    'edit_item'           => __( 'Editar Série' ),
    'new_item'            => __( 'Nova Série' ),
    'all_items'           => __( 'Todas as Séries' ),
    'view_item'           => __( 'Ver Série' ),
    'search_items'        => __( 'Pesquisar Série' ),
    'not_found'           => __( 'Nenhuma série encontrado' ),
    'not_found_in_trash'  => __( 'Nenhuma série na lixeira' ),
    'menu_name'           => __( 'Séries' ),
  );

  $supports = array( 'title', 'editor', 'thumbnail', 'comments');

  $slug = get_theme_mod( 'series_permalink' );
  $slug = ( empty( $slug ) ) ? 'series' : $slug;

  $args = array(
    'labels'              => $labels,
    'public'              => true,
    'publicly_queryable'  => true,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'query_var'           => true,
    //'rewrite'             => array( 'slug' => $slug ,'with_front' => false),
    'rewrite'             => array( 'slug' => $slug ),
    'capability_type'     => 'post',
    'has_archive'         => true,
    'hierarchical'        => false,
    'menu_position'       => 4,
    'supports'            => $supports,
    'menu_icon'           => 'dashicons-editor-video',
  );
  $wp_query = new WP_Query($args);
  $posts = $wp_query->posts;

  register_post_type( 'series', $args );

}

Aqui e um filtro que eu não sei ao certo o que ele faz, mas esta no meu arquivo functions.php, esta com algumas observações que eu coloquei para meu entendimento:
add_filter( 'request' , 'pagination_request_filter' );

function pagination_request_filter( $query ) {
    // https://wpquestions.com/Trouble_with_custom_post_type_pagination/937
    // https://codex.wordpress.org/Class_Reference/WP_Query
    if ( empty( $query['preview'] ) && empty( $query['feed'] ) ) {
        $my_post_type = $query['post_type'];
        if ( empty( $my_post_type ) ) {
            //$query['post_type'] = 'any';
            $query['post_type'] = array( 'filmes', 'series');
            //< ?php $args = array('post_type'=>array('filmes', 'series'),'paged' => $paged,'orderby'=>'date','posts_per_page' => 2); query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post(); ? >
            //< ?php $paged = (get_query_var('paged')) ? get_query_var('paged'):1; query_posts(array('post_type' =>array('filmes', 'series'), 'paged' => $paged, 'orderby'=>'date','posts_per_page' => 2)); if ( have_posts() ) : while ( have_posts() ) : the_post(); ? >
            // Os dois codigos funcionam, não se esquecer de deixar em: 1 post nas Configurações de leitura
        }
    }
    return $query;
}

Eu testei com o plugin wp-pagenavi e funcionou, mas se não quiser usar plugin nenhum basta adicionar a função abaixo no seu functions.php:
function post_pagination($pages = '', $range = 4) {
    $showitems = ($range * 2)+1;

    global $paged;
    if(empty($paged)) $paged = 1;

    if($pages == '')
    {
        global $wp_query;
        $pages = $wp_query->max_num_pages;
        if(!$pages)
        {
            $pages = 1;
        }
    }

    if(1 != $pages)
    {
         //echo "
Páginas";
        echo "
";
        if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "«";
        if($paged > 6 && $showitems < $pages) echo "1 ...";

        for ($i=1; $i <= $pages; $i++)
        {
            if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
            {
                echo ($paged == $i)? "".$i."":"".$i."";
            }
        }

        if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "... $pages";
        if ($paged < $pages && $showitems < $pages) echo "»";
        echo "
";
    }
}

Adicione no final da index depois de "endif;", no meu esta depois do endif:
<?php post_pagination();?>

Até agora não achei nenhum problema, pelo menos comigo esta funcionando liso, se alguém tiver alguma sugestão de como melhorar a função ou algum método melhor, basta comentar.

Erro na paginação com custom post type


Banco Sqlite não funciona em Unity Games compilados para Android

Question: Estou usando o Sqlite como banco de dados de um jogo feito em Unity que funciona perfeitamente no Unity Editor, porém quando realizo o build para Android o jogo simplesmente não acessa o banco (nada é informado ou lançado).
O que posso fazer para que o banco sqlite seja acessível através do Android assim como no Unity Editor?

Programas/Versões usadas:- Unity 5.3.1f1-Sqlite Precompiled Binaries for Windows 64 (sqlite-dll-win64-x64-3100200.zip
  (688.01 KiB))

Folder Structure:
-- Assets/Database/MyDataBase.db
-- Assets/Scripts/PerguntaScript.cs
-- Assets/Plugins/Mono.Data.Sqlite.dll
-- Assets/Plugins/sqlite3.def
-- Assets/Plugins/sqlite3.dll
-- Assets/Plugins/System.Data.dll

PerguntaScript.cs (Script que acessa o banco de dados Sqlite)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using System.Data;
using Mono.Data.Sqlite;

public class PerguntaScript : MonoBehaviour {

    private string connectionString;

    void Start () {
        connectionString = "URI=file:" + Application.dataPath + "/Database/DoencasDB.db";
    }

    private void GetPergunta(){
        using(IDbConnection dbConnection = new SqliteConnection(connectionString)){
            dbConnection.Open();

            using(IDbCommand dbCommand = dbConnection.CreateCommand()){
                string sqlQuery = "SELECT * FROM " + sqliteTabelasPerguntas[sqliteIndexTabelaPergunta] + " WHERE doenca_id=@id LIMIT 1";
                dbCommand.Parameters.Add(new SqliteParameter("@id", doencaId));
                dbCommand.CommandText = sqlQuery;

                using(IDataReader reader = dbCommand.ExecuteReader()){
                    while(reader.Read()){
                        pergunta = reader.GetString(1);
                        alternativasId[0] = reader.GetInt32(3);
                        alternativasId[1] = reader.GetInt32(4);
                        alternativasId[2] = reader.GetInt32(5);
                        alternativasId[3] = reader.GetInt32(6);
                        alternativaCorretaId = reader.GetInt32(7);
                    }
                    dbConnection.Close();
                    reader.Close();
                }
            }
        }
    }

OBS: Testado em Android: 4.4 e 5.0
Answer: Para fazer com que funcione fora do ambiente de edição (neste caso no ambiente mobile) tive de fazer as seguintes alterações:
1) verificar qual o ambiente estou (através dos comentários de compilação determino qual código irá para o compilado).
2) verifico se o arquivo já foi aberto e armazenado pelo aplicativo (descompactado do jar (verificar a documentação da unity)) se não é necessário abrir o banco de dados e armazena-lo no local adequado (expresso por: Application.persistentDataPath)
public void GenerateConnectionString(string DatabaseName)
{
    #if UNITY_EDITOR
        string dbPath = Application.dataPath + "/StreamingAssets/" + DatabaseName;
    #else
        //check if file exists in Application.persistentDataPath
        string filepath = Application.persistentDataPath + "/" + DatabaseName;

        if (!File.Exists(filepath) || new System.IO.FileInfo(filepath).Length == 0)
        {
            // if it doesn't ->
            // open StreamingAssets directory and load the db ->
            #if UNITY_ANDROID
                WWW loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName);  // this is the path to your StreamingAssets in android
                while (!loadDb.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
                // then save to Application.persistentDataPath
                File.WriteAllBytes(filepath, loadDb.bytes);
            #elif UNITY_IOS
                var loadDb = Application.dataPath + "/Raw/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
                // then save to Application.persistentDataPath
                File.Copy(loadDb, filepath);
            #elif UNITY_WP8
                var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
                // then save to Application.persistentDataPath
                File.Copy(loadDb, filepath);
            #elif UNITY_WINRT
                var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName;  // this is the path to your StreamingAssets in iOS
                // then save to Application.persistentDataPath
                File.Copy(loadDb, filepath);
            #endif
        }
        var dbPath = filepath;
    #endif
    connectionString = "URI=file:" + dbPath;
}

Answer: Você precisa adicionar as bibliotecas de conexão do SQLite a seu projeto, o arquivo acredito que não é disponibilizado atualmente no site oficial do SQLite (mas você encontra facilmente por ai), trata-se de um arquivo com a extensão .so.
Você deve adiciona-lo em /Assets/Plugins/Android
Diferente de muitas bibliotecas que usamos como as .dll o Android usa as .so.
Fonte: Documentação Unity.
Aqui no SOen um problema idêntico ao seu.
Comment: Mesmo adicionado esta este arquivo `.so` não funcionou.


A homomorphism that extends to a place or an embedding

Question: I tried to learn commutative algebra and I found a problem to do the following:
Consider an integral domain $R$ and an algebraically closed field $M$. Let $\varphi_0$ be a homomorphism from $R$ to $M$, and let $F$ be a field that contains $R$. In this context, we can explore two possibilities for extending $\varphi_0$: either as an embedding $\varphi$ of $F$ into $M$, or as a place $\varphi$ of $F$ into $M\cup \{\infty\}$.
In this context, a place is defined as follows:
A place of a field $F$ is a map $\varphi$ into a set $M\cup \{\infty\}$, where $M$ is a field satisfying:

$\varphi(a+b)=\varphi(a)+\varphi(b)$
$\varphi(ab)=\varphi(a)\varphi(b)$
There are $a,b\in F$ such that $\varphi (a)=\infty$ and $\varphi(b)\ne 0,\infty$.

Also, the symbol $\infty$ has the following properties:

$x+\infty=\infty+x=\infty$ for all $x\in M$.
$x\cdot\infty=\infty\cdot x=\infty\cdot\infty=\infty$ for all $x\in M^\times$.
Neither $\infty+\infty$, nor $0\cdot\infty$ are defined.

Now, I try to figure out the following:

What is an example where $\varphi_0$ extends to an embedding?
How to prove the theorem that the extension leads always to an embedding or to a place?

I already found that if $\varphi(1)=1$ then $\varphi$ can be extended to a place of $F$. (S. Lang, Introduction to algebraic geometry (1973) Theorem 1, page 8) that was suggested by M. D. Fried and M. Jarden, Field Arithmetic (2008), third edition, Proposition 2.3.1, page 24.
Comment: what does it mean for a place exactly?
Comment: @FedericoFallucca I updated the problem statement.
Answer: Addressing the first question one can say the following (I assume that $\phi_0(1)=1$): The field $F$ contains the field $K$ of fractions of $R$. A necessary condition for $\phi_0$ to extend to an embedding of $F$ into $M$ is that $\phi_0$ be injective. In that case $\phi_0$ naturally extends to an embedding $\phi_1$ of $K$ into $M$. Now if the cardinality of a transcendence basis $T$ of the field extension $F/K$ is not bigger than the cardinality of a transcendence basis of the field extension $M/\phi(K)$ the homomorphism $\phi_1$ extends to a homomorphism $\phi_2$ of the rational function field $K(T)\subseteq F$ into $M$. Since the field extension $F/K(T)$ is algebraic and $M$ is algebraically closed the homomorphism $\phi_2$ extends to a homomorphism $\phi$ of $F$ into $M$.


Pouchdb. How to verify a doc is replicated

Question: Im using poychdb basically to let a mobile user create sales orders offline, then later replicate them to central couchdb server, then process them there on a cron job basis.
As replication can sync some docs...then stop (lost Internet. ..) i need a way to block the mobile user from editing those already synced orders. But hd can still edit other non-yet-uploaded orders
There is some way to do that?
Answer: The replicate() function returns an event emitter which emits a 'change' event: http://pouchdb.com/api.html#replication.
So you can listen for 'change' events, which will tell you how many documents were written and the seq (update sequence #) of the last written document. Using the changes feed and the since parameter, you can figure out which documents were already written to the remote database.
E.g. if the last_seq is 50, then changes({since: 50}) will give you all documents that haven't been synced yet.
Comment: The `last_seq` from the `complete` event, is saved somewhere to be queried, or should i save it for later use it as the `since` parameter on the `changes` call?

BTW, i'm not using live replication, so i can safely use just the `complete` event, not the `change`, right?
Comment: Maybe i'm wrong, but both `changes` and `complete` return...

`{ pull { ... }, push: { ... } }`

Which one last_seq should i use on this case? `info.pull.last_seq` ? or `info.push.last_seq`?
Comment: I added a longer comment in the GH issue you opened: https://github.com/pouchdb/pouchdb/issues/2521


Is there offside if the ball is deflected from a teammate?

Question: This just happened in our soccer game.
A defender gets possession of the ball and attempts to clear it out of the penalty box but it deflects off an opponent, who is onside and goes straight to another opponent who is standing in an offside position. Is this player offside?
Answer: Yes, this player is offside.
See Law 11 - Offside Offence of the IFAB Laws of the Game (emphasis mine):

A player in an offside position at the moment the ball is played or
  touched by a team-mate is only penalised on becoming involved in
  active play by [...]

He would be onside if the ball was played directly to him by the defender.


drupal views images with different sizes

Question: i want create a views show last news with image and title.
first image news must be 300px * 300px and other news images 150px * 150px .
something like this :
Comment: This question appears to be off-topic because it is about Implementing a functionality, or a layout seen in a site, for which only a screenshot or a site URL is provided. Please read through the links in the [help] to understand what types of question we answer here. Thanks
Answer: Try the Image Matrix  module

Image Matrix module provides Views style plugin and content field formatter for displaying any number of images in magazine-like layout, arranging them at different sizes so that all images fit within a defined "square box".

Sample Image from module page


How do I add the Anaconda path to the PATH environment on a Mac?

Question: I have a macbook and I can't find any solutions to add the Anaconda path to the PATH environemnt online on my laptop. On Windows, you execute the installer file and this screen should show up. enter image description here
Then, I have to click the Anaconda distribution folder when I click on "choose from list" button on Eclipse but I don't have that option displayed. Supposed to look like pt. 12
What my screen looks like
Answer: On mac/linux, you need to add env path by yourself.
Find your anaconda installed path and add commands in .zshrc or .bashrc
export PATH=~/anaconda3/bin:$PATH
export PATH="/anaconda3/bin:$PATH"

Then, execute command source ~/.zshrc if you are using zsh.
Or, execute command source ~/.bashrc by default.
Comment: Can you explain how to find my anaconda installed path? I tried to execute the commands and nothing happened.
Comment: In mac, it might be installed in `/Users/{Your username}/opt/anaconda3` or `~/anaconda3`. Since everyone has different install environment, you need to find it by your own. I can only give you some tips, it might not be accurate.
Comment: I figured out my anaconda installed path, thank you!! When I executed the command source ~/.zshrc, it said __add_sys_prefix_to_path:6: command not found: dirname
__add_sys_prefix_to_path:7: command not found: dirname
Comment: Sorry, I didn't describe clearly. For me, I use zsh for my terminal, so I modify the .zshrc file. And execute `source ~/.zshrc` for command activated.
If you are not using zsh, you may modify the `.bash_profile` or `.bashrc` file.
The file may not exist, just create one.
Comment: For more information about .bashrc, please refer [stackoverflow.com/questions/19662713/where-do-i-find-the-bashrc-file-on-mac](https://stackoverflow.com/questions/19662713/where-do-i-find-the-bashrc-file-on-mac)
Comment: done worry too much about the source ~./zshrc command just close and reopen your terminal it should work


Train/test split that resembles original dataset and each other

Question: I'm modelling a continuous variable (say, the average amount of smth per client). The variable has some asymmetric distribution: for example Gamma/Tweedie/ etc.
Suppose that I'm not able to do cross validation after building a model: All I can do is to select train/test subsets once (80%/20%) from initial dataset and then train model using train set.
The problem is that when generating 80% using pseudo random variable it might happen that my train test does not correctly resemble original dataset. Also the problem is that train and test set could not resemble each other.
Does anyone know how to correctly split data into train/test so that each part of train/test would resemble each other and initial distribution?
I understand that usually I should use cross-validation while selecting model parameters to overcome such type of problems, but is there anything one could do without it? I found some information about
KLIEP algorithm but I'm not sure that it is applicable to the case mentioned above.
I would appreciate any comments/links to read.
Comment: You can always stratify your sample so that the distribution of the underlying variables is similar between the two sets. There are techniques such we do precise [covariate balancing between control and treatment groups](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2656533/) that could also be applicable but they are almost certainly an over-kill to use in this setting.
Comment: @usεr11852 could you provide a reference how to do it in case of continuous response, please? Or maybe expand your comment a bit
Comment: I was actually doing that as I realised it was a bit too scarce! :) Please see my answer below.
Answer: We can always stratify our sample so that the distribution of the underlying variables is similar between the two sets; stratified sampling is quite standard approach to ensure random subgroups have similar statistical properties.
If we are using R they are multiple packages offering stratified sampling; e.g. the packages splitstackshape and stratification have a lot of readily available functionality.
Most of stratified sampling methodology originates from survey statistics and ecology, so one might want to see a paper like Shao's (2003) "Impact of the Bootstrap on Sample Surveys", to get a better idea about potential implications of bootstrapping a (survey) sample. I have also found the UN's FAO (Food and Agriculture Organisation of the United Nations) Fisheries Technical Paper 434 on Sampling methods applied to fisheries science: a manual extremely readible and to the point (see in particular section 4 "Stratified random sampling")
There are techniques that allows precise covariate balancing between control and treatment groups that could also be applicable but they are almost certainly an over-kill to use for picking a hold-out set. They might be useful as diagnostic tools nevertheless.
Comment: Correct me if I misunderstood smth please. So, Basically the idea is following: I should bin my continuous variable (into large enough amount of bins), call the stratified sampling function on my response and thats it? The nature of stratification guarantees that empirical distributions will be similar?
Comment: 1. Generally we would like to avoid the binning of a continuous variable as it may create discretisation artefacts; that said, it is a quick-and-dirty solution for what you want (a proper solution would be a moment-matching sampling approach). 2. Yes, you are correct; the idea of stratification is to guarantee that the empirical distributions will be similar.
Comment: @ usεr11852 Would you be so kind also to give a hint/reference to method how could I ensure that two sets are belong to same distribution? Is there any statistical test? Maybe I should somehow compare distributions via Kolmogorov-Smirnov test? Or maybe is it just enough to compare means and variances (I personally don't think that it is sufficient)?
Comment: @ usεr11852 I had two ideas: 1) We can compare means and variances of Empirical Distribution Functions (or smith similar) for each of 3 sets: original/train/test 2) We can calculate empirical distribution for original set and use KS to make sure that it fits our train/test. Is any of these makes sense? Or maybe there is any other  "state of art" solution to question? Sorry if I'm "statistically" incorrect, I'm very new to this field.
Comment: Your ideas are perfectly fine. I would suggest you look into the article: [*Reporting of covariate selection and balance assessment in propensity
score analysis is suboptimal: a systematic review*] by Ali et al. as it has a full list of methods assessing covariate balance. In general, for a large original set, one would not expect massive differences between a randomly chosen split unless dealing with pathological cases, or very imbalanced data.
Answer: In addition to @usεr11852's answer:

if you can do train/test splits that are random but have the desired distribution matching properties, you can repeat/iterate this: this is a resampling technique called set validation and in this is similar to cross validation and out-of-bootstrap validation.
For a single continuous variable of interest, there are non-random cross validation schemes like venetian blinds splitting where you sort your samples according to the continuous variable and then assign groups with equal sample no. modulo $k$. That leaves a slight systematic difference between the groups.
For multiple such covariates, clustering methods like k-means (using what is otherwise mostly considered a weakness: that k-means tends to produce similar-sized spherical clusters) or Kohonen maps have been used for the stratification.
The Duplex algorithm (Snee: Validation of Regression Models: Methods and Examples, Technometrics 1977  (a variant of the Kennard-Stone algorithm) gives a single split into train and test sets.
This algorithm is particularly interesting if you need to select a subset of a larger number of data points for training and testing (e.g. lots of measurements available, but reference values are expensive).
Comment: +1  Nice resources, I will definitely look at that article!


Grafana histogram displays wrong values (Datasource: Prometheus)

Question: I'm using Grafana 4.3.2 with Prometheus 2.0 as the datasource.
I'm trying to display a Prometheus histogram on Grafana. The values I retrieve from Prometheus is like the following:
<code>http_request_duration_seconds_bucket{<other_labels>, le="+Inf"}     146
http_request_duration_seconds_bucket{<other_labels>, le="0.005"}    33
http_request_duration_seconds_bucket{<other_labels>, le="0.01"}     61
http_request_duration_seconds_bucket{<other_labels>, le="0.025"}    90
http_request_duration_seconds_bucket{<other_labels>, le="0.05"}     98
http_request_duration_seconds_bucket{<other_labels>, le="0.1"}      108
http_request_duration_seconds_bucket{<other_labels>, le="0.25"}     131
http_request_duration_seconds_bucket{<other_labels>, le="0.5"}      141
http_request_duration_seconds_bucket{<other_labels>, le="1"}        146
http_request_duration_seconds_bucket{<other_labels>, le="10"}       146
http_request_duration_seconds_bucket{<other_labels>, le="2.5"}      146
http_request_duration_seconds_bucket{<other_labels>, le="5"}        146
</code>
So what I expect to see is 12 buckets, with the values which is specified on the right. However, Grafana shows completely different values as you can see below:

Is there anything I'm missing, or does Grafana simply not support Prometheus histograms (discards "le" label)?
Comment: See [How can I visualize a histogram with Promdash or Grafana?](https://stackoverflow.com/a/51543885/11934850).
Answer: You need to set the legend formater to "{{le}}"


Determine the largest possible value of $|f(1/2)|$ and give an example of a function $f$ that attains your upper bound.

Question: Edited because I need more help than the linked "duplicate" provides.
ORIGINAL QUESTION:
This is a problem from a past complex analysis qualifying exam and I'm studying for my own qual next month. I'm not quite sure how to approach this one.
Problem:
Suppose $f(z)$ is an analytic function that maps the unit disc into itself and has zeros at $\frac{i}{2}$ and $-\frac{i}{2}$. Determine the largest possible value of $|f(1/2)|$ and give an example of a function $f$ that attains your upper bound.
What I've tried/considered:
We know by the maximum modulus principle that the function attains its maximum on the boundary, thus since it maps from the unit disc to the unit disc, the max on the boundary is 1. But what we need is the maximum at $|z| = 1/2$.
I thought about using the Schwarz Lemma, but it doesn't seem like we have $f(0)=0$ here. I considered using the argument principle, but there are zeros on the circle of radius ½.
I think I can use the Schwarz-Pick Theorem (though I'm not sure how I'd remember this specific one on a qual?) to get a bound such that $|f(1/2)|<= \sqrt{8/17}$ but I'm not sure if that is right, and if it is right, I haven't been able to figure out a function that attains this value?
EDIT TO REQUEST ADDITIONAL HELP:
The question was closed, stating that itt is simply a special case of this. However, I do not understand how to apply it. Perhaps the suggestion is that the bound I'm looking for can be found using the zeros at $z_1 = \frac{i}{2}$ and $z_2 = -\frac{i}{2}$ by
$$
|f(z)| \leq \prod_{k=1}^n \left\vert \frac{z-z_k}{1-\bar{z_k}z} \right\vert = \left\vert \frac{z-i/2}{1+(i/2)z} \right\vert \left\vert \frac{z+i/2}{1-(i/2)z} \right\vert = \left\vert \frac{4z^2+1}{z^2+4} \right\vert
$$
and thus
$$
\left\vert f\left(\frac{1}{2}\right)\right\vert \leq \frac{8}{17}.
$$
Is this correct? If this is the case, two questions remain for me:
(1) Is this inequality found in some lemma or theorem that I should know to use? As stated in my question, I was struggling to find which theorem applies and why.
(2) If this is the correct maximum, how do I find an example of a function $f(z)$ which attains this value at $f(1/2)$? I am new to this kind of problem, so would really appreciate a clear and complete answer if possible.
Comment: I'm not sure you can use Schwarz-Pick since $f$ isn't guaranteed to be a bijection.
Comment: @Serafina Sure, $f(z) = z^2$. Observe that $|z| \leq 1$ implies $|f(z)| \leq 1$. To see that $f$ is a surjection, suppose $w = re^{i\theta}$. Take $z = \sqrt{r} e^{i\theta / 2}$, then clearly $f(z) = w$.
Comment: @CharlesHudgins Good point. Can a function map the unit disk into itself and not be a bijection?
Comment: This is a special case of the more general estimate https://math.stackexchange.com/q/94122/42969, therefore I closed the question as a duplicate.
Comment: @MartinR I would have found it more helpful if you could have linked to this other answer and helped me see how to apply it here in my specific case, while perhaps leaving the opportunity for others to answer as well. Sometimes one person's way of explaining things is clearer than another's.
Comment: As for a function that attains the maximum, what about $\frac{4z^2 + 1}{z^2 + 4}$?
Comment: The argument is exactly as in the more general question. You define $ g(z) = \frac{f(z)}{ \left ( \frac{z-i/2}{1+(i/2)z} \right ) \left ( \frac{z+i/2}{1-(i/2)z} \right ) } $ and use the  maximum modulus principle to show that $|g(z)| \le 1$ in the unit disk. Equality holds if $g \equiv 1$, that is for $f(z) = \left ( \frac{z-i/2}{1+(i/2)z} \right ) \left ( \frac{z+i/2}{1-(i/2)z} \right )$.
Comment: @MartinR Several questions still remain for me. (1) I have no idea *why* I would use this approach and what theorems/lemmas I'm not aware of or understanding in order to know to do that. (2) How does this answer the actual question of the bound of $|f(1/2)|$ AND a function where it could attain that? I'm really not trying to be annoying, but I need to understand. To me, the maximum modulus principle just states that a maximum can only occur on the boundary of a region. Defining a new function and then defining its max on the boundary doesn't yet make sense to me as an answer to my question.
Answer: The topic here is finite Blaschke products which are the analog for the unit disc of polynomials in the plane; these are holomorphic on the closed unit disc (meaning on a slightly bigger open disc depending on the particular Blaschke product of course), have modulus $1$ on the unit circle and you can specify their finitely many zeroes in the unit disc, so if the zeroes are $z_1,...z_n, |z_k| <1$ (with repeats for multiplicities), one can define for example $$B(z)=\Pi_{k=1}^n\frac{z-z_k}{1-\bar z_k z}$$ and then if some $f$ holomorphic in the disc has finitely many zeroes, there is a finite Blaschke product $B$ (unique up to multiplication by $|\alpha|=1$ and one can take $B=1$ if there are no zeroes) st $f=Bg$ with $g$ holomorphic in the unit disc, and having no zeroes, while $|f|, |g|$ behave the same on the unit circle.
In this case, since $|f| \le 1$ we have $|g| \le 1$ so $|f(z)| \le |B(z)|$ for any $z$ in the unit disc; however since now $g$ has no zeroes, one, of course, can take $g=1$ to attain the maximum, so we solved the extremal problem in the OP, or more generally, the extremal problem where $f$ is a holomorphic self-map of the unit disc to itself, taking zeroes at prescribed finitely many points $z_1,...z_k$ (including repeats for multiplicity here) and one asks for the maximum of $|f(y)|$ for some $y$ in the unit disc, the answer being precisely $|B(y)|$ where $B$ is the Blaschke product above, with the extremal functions being any $\alpha B, |\alpha|=1$
Comment: THANK YOU. I was really having trouble with this because I had never even heard of Blaschke products before.
Comment: Happy to be of help


Problemas para criar Child no Firebase

Question: Estou tentando add pratos no meu banco de dados do firebase porém estou tendo alguns problemas que até agora não sei o por que não funciona. e chega a dar este erro:
Process: meals.com.meals, PID: 1585
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
   at com.google.android.gms.internal.zg.zzar(Unknown Source)
   at com.google.android.gms.internal.zh.zzas(Unknown Source)
   at com.google.android.gms.internal.zg.zzao(Unknown Source)
at com.google.android.gms.in

Para vocês verem o que eu estou fazendo vou postar também o código da activity e da classe prato.
public class CriarPrato extends AppCompatActivity {

private Spinner NomeRestaurante;
private EditText NomePrato1;
private EditText PrecoPrato1;
private Button GerarPrato;
private String IDrestaurante;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_criar_prato);

    NomeRestaurante = (Spinner) findViewById(R.id.spinnerNomeRestaurantePrato);
    NomePrato1 = (EditText) findViewById(R.id.editTextNomePrato);
    PrecoPrato1 = (EditText) findViewById(R.id.editTextPrecoPrato);
    GerarPrato = (Button) findViewById(R.id.buttonPrato);

    Query queryPrato = ConfiguracaoFirebase.getReferencia().child("Restaurante").orderByChild("localRestaurante");

    queryPrato.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //  final List<String> localRest = new ArrayList<String>();
            final List<String> NomeRestauranteList = new ArrayList<String>();

            for (DataSnapshot data : dataSnapshot.getChildren()) {
                Restaurante restaurante = data.getValue(Restaurante.class);
                //   localRest.add(restaurante.getLocalRestaurante().toString());
                NomeRestauranteList.add(restaurante.getNome().toString());
            }

            //LocalRestaurante = (Spinner) findViewById(R.id.SpinerLocalPrato);
            // ArrayAdapter<String> areas = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, localRest);
            // areas.setDropDownViewResource(R.layout.spinner_item);
            // LocalRestaurante.setAdapter(areas);

            NomeRestaurante = (Spinner) findViewById(R.id.spinnerNomeRestaurantePrato);
            ArrayAdapter<String> NomeRestAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, NomeRestauranteList);
            NomeRestAdapter.setDropDownViewResource(R.layout.spinner_item);
            NomeRestaurante.setAdapter(NomeRestAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    Query query = ConfiguracaoFirebase.getReferencia().child("Restaurante").orderByChild("nome").equalTo("McDonald's");

    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot data : dataSnapshot.getChildren()) {
                IDrestaurante = data.getKey();
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    GerarPrato.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Prato prato = new Prato();
            prato.setID(IDrestaurante);
            prato.setNomePrato(NomePrato1.getText().toString());
            prato.setPrecoPrato(PrecoPrato1.getText().toString());

            prato.Salvar(IDrestaurante);
        }
    });
}

Obs.: Eu sei que eu não estou ainda utilizando o spinner, tive alguns problemas para pegar o valor dele portanto coloquei na mão o valor, para fazer alguns testes.
public class Prato {

    private String ID;
    private String NomePrato;
    private String PrecoPrato;

    public Prato() {
    }

    public void Salvar(String key){
        DatabaseReference reference = ConfiguracaoFirebase.getReferencia();
        reference.child("Restaurante").child(key).child("Cardapio").child(getID()).setValue(this);
    }
    @Exclude
    public String getID() {
        return ID;
    }

    public void setID(String key) {
        reference = ConfiguracaoFirebase.getReferencia().child("Restaurante").child(key).child("Cardapio");
        this.ID = reference.push().getKey();
    }

    public String getNomePrato() {
        return NomePrato;
    }

    public void setNomePrato(String nomePrato) {
        NomePrato = nomePrato;
    }

    public String getPrecoPrato() {
        return PrecoPrato;
    }

    public void setPrecoPrato(String precoPrato) {
        PrecoPrato = precoPrato;
    }

    public DatabaseReference getReference() {
        return reference;
    }

    public void setReference(DatabaseReference reference) {
        this.reference = reference;
    }

    private DatabaseReference reference;

}

Segue uma imagem da organização do banco de dados para melhor compreensão

Eu quero adicionar em cada restaurante um nó chamado Cardápio e dentro deste nó Cardápio vou colocar meu produtos criando nós Com os id's e dentro deste id's vai ter as variáveis: nome do prato e valor no prato.
Comment: Você pode nos mostrar um print do firebase RealtimeDatabase no console ? Assim fica um pouco mais fácil entendermos as estrutura dos nós filhos do seu banco
Comment: Concerteza vou editar e colocar
Comment: @EduardoRafaelMoraes fiz a alteração!!! Tks
Answer: Não sei se eu entendi direito mas pelo que percebi da sua história, eu faria o banco com essa estrutura:

....
no salvar da sua classe modelo ficaria assim:
public void Salvar(String key){
    DatabaseReference reference = ConfiguracaoFirebase.getReferencia();
    reference.child("Restaurante")
          .child("Iguatemi")
          .child("cardapio")
          .child(nomeLoja)
          .push()
          .child(prato.getNomeRestaurante)//opcional, assim vc teria o nome do bobs seguido de nós com o nome do prato e o valor
          .setValue(this)
}

Isso, pensando que o Iguatemi é um shopping e tem algumas lojas nele, caso ele seja um restaurante você poderia eliminar o .child(nomeLoja), e para retornar os dados:
Query queryPrato = ConfiguracaoFirebase.getReferencia().child("Restaurante").child(nomeRestaurante);

Acredito que assim fique mais facil de receber os nós no valueEventListener.
Comment: Eduardo eu entendi a sua resposta, é um boa ideia porem eu queria entender o por que o meu salvar não ta funcionando. No que eu vi o problema esta em salvar mesmo parece que ele estoura a quantidade mb que se pode passar para salvar. Porem não faz sentido pois são info TXT.

Problemas para criar Child no Firebase


Ajuda - Modificar fórmula ao mudar de radiobutton

Question: Olá, desenvolvedores!
Preciso de ajuda para meu programa de cálculo do MRU.
Quando eu insiro os dados com o radiobutton metros/segundos ativo, e depois seleciono no radiobutton km/h ele converte os dados corretamente.
Já quando estou em km/h, e clico no radiobutton metros/segundos, ele não está fazendo a conversão...

private void radMetrosSegundos_CheckedChanged(object sender, EventArgs e)
{
    lblEspacoInicialMedida.Text = "metros";
    lblVelocidadeMedida.Text = "metros/segundos";
    lblTempoMedida.Text = "segundos";
    lblEspacoFinalTipo.Text = "metros";
    /* Essa é a formula mais não funciona quando eu clico em metros /segundos.
    numEspacoInicial.Value = numEspacoInicial.Value * 1000; // KM para metro
    numTempo.Value = numTempo.Value * 3600; // hora para segundos
    numVelocidade.Value = numVelocidade.Value / Convert.ToDecimal(3.6); //segundos para hora
    */
}

private void radKMH_CheckedChanged(object sender, EventArgs e)
{
    lblEspacoInicialMedida.Text = "Km";
    lblVelocidadeMedida.Text = "Km/h";
    lblTempoMedida.Text = "Horas";
    lblEspacoFinalTipo.Text = "Km";

    //Aqui funciona corretamente
    numEspacoInicial.Value = numEspacoInicial.Value / 1000; // Metro para KM
    numTempo.Value = numTempo.Value / 3600; // segundos para hora
    numVelocidade.Value = numVelocidade.Value * Convert.ToDecimal(3.6); // m/s para km/h
}

Desde já agradeço!
Comment: A princípio a função está correta. Verifique se o evento '**radMetrosSegundos_CheckedChanged**' está relacionado ao RadioButton.
Answer: Voce pode fazer a verificação de qual radioButton que está checado e dependendo do radioButton faz as alterações e isso tudo apenas em uma void, utilizando um radioButton.Checked, esqueça a void radMetrosSegundos_CheckedChange deixe ela sem valor, mas não a exclua pois acarretará em erros.
private void radKMH_CheckedChanged(object sender, EventArgs e)
{
    if(radKMH.Checked)
    {
        lblEspacoInicialMedida.Text = "Km";
        lblVelocidadeMedida.Text = "Km/h";
        lblTempoMedida.Text = "Horas";
        lblEspacoFinalTipo.Text = "Km";

        //Aqui funciona corretamente
        numEspacoInicial.Value = numEspacoInicial.Value / 1000; // Metro para KM
        numTempo.Value = numTempo.Value / 3600; // segundos para hora
        numVelocidade.Value = numVelocidade.Value * Convert.ToDecimal(3.6); // m/s para km/h
    }
    else if(radMetrosSegundos.Checked)
    {
        lblEspacoInicialMedida.Text = "metros";
        lblVelocidadeMedida.Text = "metros/segundos";
        lblTempoMedida.Text = "segundos";
        lblEspacoFinalTipo.Text = "metros";
        numEspacoInicial.Value = numEspacoInicial.Value * 1000; // KM para metro
        numTempo.Value = numTempo.Value * 3600; // hora para segundos
        numVelocidade.Value = numVelocidade.Value / Convert.ToDecimal(3.6); //segundos para hora
    }
}