Abrir Modal pelo code-behind

Question: Possuo um modal, #myModal, e gostaria que ao clicar no button, tivesse uma condição e que caso ela entrasse no else, abriria o modal.
Criei esse código no javascript:

  if (cbquitado.Checked == true)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Contas a Pagar já quitada!');location='" + url + "';", true);
                    return;
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "myModal", "openModal();", true);
                }

E esse código na condição, porém nada acontece, segue o código do modal:

                            <button type="button" class="close" data-dismiss="modal">×</button>

Pagamento

                            <asp:Label ID="lblDetalhe" runat="server" Text="Detalhes Conta a Pagar" Font-Bold="True"></asp:Label>
                            <asp:Panel ID="PainelContasaPagar" runat="server">
                                <asp:Label ID="Label5" runat="server" Text="Vencimento:" Font-Bold="True"></asp:Label>
                                <asp:Label ID="Label6" runat="server" Text="Label" Font-Bold="False"></asp:Label>

                                <asp:Label ID="Label7" runat="server" Text="Observações:" Font-Bold="True"></asp:Label>
                                <asp:Label ID="Label8" runat="server" Text="Label"></asp:Label>

                                <asp:Label ID="Label9" runat="server" Text="Valor:" Font-Bold="True"></asp:Label>
                                <asp:Label ID="Label10" runat="server" Text="Label"></asp:Label>
                            </asp:Panel>

                            <asp:Label ID="lblFormaPg" runat="server" Text="Forma de Pgto" Font-Bold="True"></asp:Label>
                            <asp:DropDownList ID="cbforma" runat="server">
                                <asp:ListItem>Dinheiro</asp:ListItem>
                                <asp:ListItem>Cheque</asp:ListItem>
                                <asp:ListItem>Depósito</asp:ListItem>
                            </asp:DropDownList>

                            <asp:UpdatePanel ID="UpdatePanel7" runat="server">
                                <ContentTemplate>
                                    <asp:Label ID="lblValoraPagar" runat="server" Text="Valor a Pagar"></asp:Label>
                                    <asp:TextBox ID="txtValoraPagar" runat="server" onKeyPress="return(MascaraMoeda(this,'.',',',event))" placeholder="R$" Enabled="False"></asp:TextBox>
                                    <asp:Label ID="lblDesconto" runat="server" Text="Desconto"></asp:Label>
                                    <asp:TextBox ID="txtDesconto" runat="server" onKeyPress="return(MascaraMoeda(this,'.',',',event))" placeholder="R$0,00"></asp:TextBox>
                                    <asp:Label ID="lblJuros" runat="server" Text="Juros"></asp:Label>
                                    <asp:TextBox ID="txtJuros" runat="server" onKeyPress="return(MascaraMoeda(this,'.',',',event))" placeholder="R$0,00"></asp:TextBox>

                                    <asp:Button ID="btnCalcular" runat="server" Text="Calcular" Font-Bold="True" OnClick="btnCalcular_Click" />
                                </ContentTemplate>
                            </asp:UpdatePanel>

                            <asp:UpdatePanel ID="UpdatePanel9" runat="server">
                                <ContentTemplate>
                                    <asp:RadioButton ID="rb1" runat="server" Text="Retirar da Conta" AutoPostBack="True" OnCheckedChanged="rbConta_CheckedChanged" />
                                    <asp:DropDownList ID="cbContas" runat="server"></asp:DropDownList>
                                    <asp:RadioButton ID="rb2" runat="server" Text="Retirar do Caixa" AutoPostBack="True" OnCheckedChanged="rbCaixa_CheckedChanged" />

                                </ContentTemplate>
                            </asp:UpdatePanel>

                            <asp:UpdatePanel ID="UpdatePanel8" runat="server">
                                <ContentTemplate>
                                    <asp:Label ID="lblTotalPagar" runat="server" Text="Total" Font-Bold="True"></asp:Label>
                                    <asp:TextBox ID="txtTotalPagar" runat="server"></asp:TextBox>
                                </ContentTemplate>
                            </asp:UpdatePanel>

                            <asp:Button ID="Button1" runat="server" Text="Concluir" CssClass="radiusInput" OnClick="Button1_Click" />

Comment: Você está usando o modal do bootstrap? Se sim, seria legal informar a versão.
Comment:
    Sim, estou usando, segue a referência que utilizo.
Answer: Consegui resolver o problema, que estava acontecendo devido a referência ao jquery depois do bootstrap, fiz ao contrário e deu certo.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

Comment: Boaa!!!!!!!!!!!!!!!!!!!!!!!!!

Abrir Modal pelo code-behind


R Time Series Analysis forecast result always remains same

Question: I am trying to do time series analysis in R.
I have data time series data set like this.
    Month       Year    Value
    December    2013    5300
    January     2014    289329.8
    February    2014    596518
    March       2014    328457
    April       2014    459600
    May         2014    391356
    June        2014    406288
    July        2014    644339
    August      2014    251238
    September   2014    386466.5
    October     2014    459792
    November    2014    641724
    December    2014    399831
    January     2015    210759
    February    2015    121690
    March       2015    280070
    April       2015    41336

Googling I found I can use auto.arima function to forecast the result.
I managed to write R code to do forecast using auto.arima function
    data <- c(5300,289329.8,596518,328457,459600,391356,406288,644339,251238,386466.5,459792,641724,399831,210759,121690,280070,41336)
    data.ts <- ts(data, start=c(2013, 12), end=c(2015, 4), frequency=12)
    plot(data.ts)
    fit <- auto.arima(data.ts)
    forec <- forecast(fit)
    plot(forec)

Problem is my forecast result always remain same.

Could  any tell me what is going wrong. or help me to correct my forecast result. Thanks
Comment: You specified a `frequency` of 12, but you don't have even two complete periods, how is `auto.arima` supposed to capture that?
Answer: auto.arima() believes the best model (as per its default criterion, AICc) is an ARIMA(0,0,0) model with non-zero mean. That is, a pure intercept model with no autoregressive terms, no moving average terms and no integration. So your forecast is simply the historical average.
Looking at your historical data, it is hard to say anything else should do a better job. You don't have enough data to assess seasonality. You don't have a trend. You don't have obvious AR or MA behavior. (If you want to, you can look at ACF and PACF plots, but I doubt that will show anything auto.arima() did not pick up on.)
And yes, a constant mean forecast can certainly outperform a (nonconstant) ARIMA forecast, and frequently will do so.


How to set a field for every document in a Cosmos db?

Question: What would a Cosmos stored procedure look like that would set the PumperID field for every record to a default value?
We are needing to do this to repair some data, so the procedure would visit every record that has a PumperID field (not all docs have this), and set it to a default value.
Comment: Any reason this wouldn't be set by the client creating the titem?
Comment: I updated my question to further clarify why we want to do this.
Answer: Assuming a one-time data maintenance task, arguably the simplest solution is to create a single purpose .NET Core console app and use the SDK to query for the items that require changes, and perform the updates. I've used this approach to rename properties, for example. This works for any Cosmos database and doesn't require deploying any stored procs or otherwise.
Ideally, it is designed to be idempotent so it can be run multiple times if several passes are required to catch new data coming in. If the item count is large, one could optionally use the SDK operations to scale up throughput on start and scale back down when finished. For performance run it close to the endpoint on an Azure Virtual Machine or Function.
Answer: For scenarios where you want to iterate through every item in a container and update a property, the best means to accomplish this is to use the Change Feed Processor and run the operation in an Azure function or VM. See Change Feed Processor to learn more and examples to start with.
With Change Feed you will want to start it to read from the beginning of the container. To do this see Reading Change Feed from the beginning.
Then within your delegate you will read each item off the change feed, check it's value and then call ReplaceItemAsync() to write back if it needed to be updated.
<code>static async Task HandleChangesAsync(IReadOnlyCollection<MyType> changes, CancellationToken cancellationToken)
{
    Console.WriteLine("Started handling changes...");
    foreach (MyType item in changes)
    {
        if(item.PumperID == null)
        {
            item.PumperID = "some value"
            //call ReplaceItemAsync(), etc.
        }
    }

    Console.WriteLine("Finished handling changes.");
}
</code>
Comment: thx! I updated my question to further clarify why we want to do this.  We are needing the stored procedure.
Comment: Got it. In this scenario where you want to update every instance of this property you should use ChangeFeed. I'll update the answer.


Moore-Penrose Pseudoinverse of a matrix product

Question: $X_{n \times p}$ is a real, thin ($n>p$) rectangular matrix of rank $p$, so $X^T X$ is full rank. The Moore-Penrose pseudoinverse of $X$ is given by $X^+=(X^TX)^{-1}X^T$.
Let's now define
$W=XA$
($X$ is linearly transformed by $A_{p \times k}$ to produce a $W_{n \times k}$). $W$ is of rank $k$ (so $W^TW$ is full rank).
I need to compute the Moore-Penrose Pseudoinverse of $W$ for many different $A$ matrices efficiently. Is there an identity or a decomposition that allows expressing $W^+$ as some function of $X^+$ or $(X^TX)^{-1}$?
Answer: due to distributive order reversal rule for transposing multiple and associativity of multiplication ,
$$W^+=(A^T       (X^TX)     A)^{-1} A^T X^T$$
not too much opportunity for pre-calculation it seems


Viterbi and forward-backward algorithm in HMM

Question: I am learning HMM recently and got confused with the training problem (training model parameters and hidden state given outcome sequence).
As far as I know, both Viterbi learning and Baum-Welch (forward-backward algorithm ) are used to estimate model parameters and hidden state in an EM fashion. the forward-backward algorithm is used in E step to estimate transition / emmision probability. What about estimaing hidden state seuquence in E step? is it estimated using forward-backward algorithm as well or using Viterbi algorithm?
Really appreciate if anyone can share some insight.
Answer: The HMM parameters are estimated using a forward-backward algorithm also called the Baum-Welch algorithm.
The Viterbi algorithm is used to get the most likely states sequnce for a given observation sequence.
Therefore, the two algorithms you mentioned are used to solve different problems. Classically there are 3 problems for HMMs:

Given an observation sequence and a model, finding the
likelihood of the sequence with respect to the model. This problem
is solved using a forward algorithm.
Given an observation sequence and a model, find the optimal state sequence of the model for this observation sequence. This problem is solved with the Viterbi algorithm.
Adjust the model parameters to maximal the likelihood so some
        observation sequence. This is basically training a model from
        initial values. This problem is solved using the Baum-Welch
        algorithm.

I suggest the following reading: An introduction to Hidden Markov Models by L.R. Rabiner and B.H. Juang (1986) which can be found here: http://ai.stanford.edu/~pabbeel/depth_qual/Rabiner_Juang_hmms.pdf


Kalman Filtering, Smoothing and Parameter Estimation for State Space Models in R and C#

Question: I am in the process of writing an open source State Space Analysis suite in C# (for fun). I have implemented a number of different Kalman-Based Filters (Kalman Filter, Information Filter and the Square Root Filter) and the State and Disturbance Smoothers that work with these implementations. My tests on these filters (using the Nile data from Durban and Koopman's (DK) book "Time Series Analysis by State Space Methods" and other more complex data) show that the filters and smoothers work and they produce very similar results (as you would expect for a local univariate model). The smoothed output for the basic Kalman Filter for the Nile data looks like (because everyone likes a graphic or two :])

The dotted line is the 90% confidence interval.
Now, my problem; I am now attempting to write the first part of the parameter estimation code and for the parameter estimation of the covariances $\mathbf{H}_{1}$ and $\mathbf{Q}_{1}$ in the linear Gaussian State Space model
$$y_t = \mathbf{Z}_{t}\alpha_{t} + \epsilon_{t},$$
$$\alpha_{t + 1} = \mathbf{T}_{t}\alpha_{t} + \mathbf{R}_{t}\eta_{t},$$
where $y_{t}$ is our observation vector, $\alpha_{t}$ our state vector at time step $t$ and
$$\epsilon_{t} \sim NID(0, \mathbf{H}_{t}),$$
$$\eta_{t} \sim NID(0, \mathbf{Q}_{t}),$$
$$\alpha_{1} \sim NID(a_{1}, \mathbf{P}_{1}).$$
where $t = 1,\ldots, n$.
We have an implementation of the Expectation Maximisation (EM) algorithm and this is estimating $\mathbf{H} = 19550.37$ and $\mathbf{Q} = 7411.44$ with the loglikelihood converging in 32 iterations to -683.1 with a convergence tolerence of $10^-6$.
The DK book quotes $\mathbf{H} = 15099$ and $\mathbf{Q} = 1469.1$ and from Tusell's paper and this walkthrough using R he matches this prediction getting $\mathbf{H} = 15102$ and $\mathbf{Q} = 1468$. I have debugged my code and it really seems like my implementation of the EM algorithm is correct. So get to the bottom of what is going on I want to run the same data set using R and KFAS...
Using R and the R Package KFAS, I have attempted to reproduce these estimates for $\mathbf{H}$ and $\mathbf{Q}$, but my R knowledge is weak. My current R script is as follows
install.packages('KFAS')
require(KFAS)

# Example of local level model for Nile series
modelNile<-SSModel(Nile~SSMtrend(1,Q=list(matrix(NA))),H=matrix(NA))
modelNile
modelNile<-fitSSM(inits=c(log(var(Nile)),log(var(Nile))),model=modelNile,
method='BFGS',control=list(REPORT=1,trace=1))$model

# Can use different optimisation:
# should be one of "Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN", "Brent"
modelNile<-SSModel(Nile~SSMtrend(1,Q=list(matrix(NA))),H=matrix(NA))
modelNile
modelNile<-fitSSM(inits=c(log(var(Nile)),log(var(Nile))),model=modelNile,
method='L-BFGS-B',control=list(REPORT=1,trace=1))$model

# Filtering and state smoothing
out<-KFS(modelNile,filtering='state',smoothing='state')
out

How can I extend this R script using KFAS in order to estimate the parameters $\mathbf{H}$ and $\mathbf{Q}$? and Should each method of parameter estimation be hitting the same values for $\mathbf{H}$ and $\mathbf{Q}$?
Thanks for your time.
Answer: Afer perusing the documentation for KFAS, it seems to me that KFS() will return
what you want in components V_eta and V_eps of the object you name out. (This is the case because you are dealing with a univariate time series, so
the only diagonal term of V_eps is the variance you want.)
You should expect about the same values from your code and any of the packages. Discrepancies may crop up, however, on account of: i) Different initial conditions (exactly diffuse, as KFAS implements, or setting the variance of the initial state to a very large number, as you probably have done), and ii) Different criteria to stop the likelihood climbing.
Discrepancies due to different algorithms (like plain Kalman filter iteration versus square root algorithms, either covariance or information filters) may also appear with longer series and/or more complicated models, but with not the Nile data.
Please note my name's spelling: Tusell.
Comment: Sorry, I did not have a chance to connect until now. Perhaps what KFS returns depend on the values you pass to filtering= and smoothing= . In the mean time, I see that @SteinarV has provided an alternative way to obtain the matrices you are after.
Comment: Thanks for your reply and sorry about the spelling of your name; I was typing very quickly. I have attempted to check the variables `out$V_eta`/`out$V_eps` but they both return `NULL`. I have also attempted this after running `modelNile<-fitSSM(...)` by using `modelNile$V_eta`/`modelNile$V_eps` but this also returns `NULL`. Again, thanks for your time...
Answer: Im not sure why KFS does not return V_eta or V_eps, but why not use modelNile$H and modelNile$Q? They are also kept in the return object from KFS, out$model$H and out$model$Q. You will find what the objects contains by using the names() function as in names(modelNile) or names(out$model).


Find Similar Strings In Two Python Lists

Question: I have a list of words I'm trying to find in another list. I'm wanting to find the match_words in my main_list and return their values in a new list.
match_words = ['reports', 'users']
main_list = ['reports_data', 'users_accounts', 'backups', 'logs']

The correct value returned should be
returned_list = ['reports_data', 'users_accounts']

I've tried using
returned_list = filter(lambda x:x in main_list,match_words)

I'm assuming they aren't matching because they aren't exact matched keywords?
Comment: perhaps you could use [difflib](https://docs.python.org/3/library/difflib.html#module-difflib)
Answer: A bit verbose, but it does the job
match_words = ['reports', 'users']
main_list = ['reports_data', 'users_accounts', 'backups', 'logs']

returned_list = []

for i in match_words:
    for j in main_list:
        if i in j:
            returned_list.append(j)

Answer: It is unclear what is your similarity measure, but, assuming you only need a matching prefix, you can use the following list comprehension
returned_list = [word for pre in match_words for word in main_list if word.startswith(pre)]

Edit:
If you need to check if a string is a part of another string, you can use in operator
returned_list = [word for part in match_words for word in main_list if part in word]

Comment: Will this work if the match_word is "reports" and the main_list word is "data_reports". I need it to check the entire string in the main list, not just the beginning.


Does the old Druid song, Les Series, have an ancient melody as Villemarque charted it?

Question: This may be too long and specialized for many, but I'll put it up and see what kind of interest or reaction there is:
Some of you may have heard of the old Druid number tutorial, Les Series or Ar Rannou, that was charted by Viscount Theodore Villemarque. In 1845 Villemarque publishd his Barzaz-Breizh collection of old Breton songs. He laboriously recorded by hand in notebooks the oral tradition songs in very obscure Old Breton dialects he heard from the local peasants in Brittany. This was an old Celtic region, sharing tradition and people with Cornwall, across the English Channel.
Villemarque got the melody and lyrics for one of these Druid songs, known variously as "Les Series" or "Ar Rannou," from a young peasant of the parish of Nizon whose mother had taught it to him ("to form his memory"). My gut feeling as a musician about the score he wrote after hearing the young peasant sing it to him makes me believe the melody he published in 1845 is probably close to the old Celtic melody that would have originally been known pre-Christian era in Brittany/Wales/Cornwall. It is given in the key of Bb, appearing to be used as the G minor scale (the relative minor of Bb) in the song melody given.
Here is the score Villemarque wrote after hearing the young peasant sing the song:

Towards the end of this long post is a link to me roughing out the melody charted above, as well as a link to a modern fusion jazz band interpreting it.]
I know the lyrics/thoughts have survived the 20 odd centuries embedded in a number chant, a not uncommon way for the common people to keep alive complex history and thought without writing, i.e., the lyrics given do seem to be Druid era thoughts and memories (I'll include a link to the lyrics translated below).
I'm thinking that c. 100 BC, for example, there may have been Druid singing accompanied by ancient Celtic harp or lyre, something with 6 strings (like the one found at the 600 AD Anglo Saxon burial site at Sutton Hoo) or maybe a few more, likely tuned to a G pentatonic scale, G A B D E, with a melody being free to hit a C or Bb to make the Ar Rannou melody alongside, or with those strings or tunings added, etc. Here is a link to a good discussion of the Sutton Hoo harp, which is within a few centuries of the Druid period I am discussing:
http://www.tha-engliscan-gesithas.org.uk/archives/the-sound-of-the-sutton-hoo-harp
So, my question is does the Les Series melody seem like one that might have been sung by Celtic Druids around Brittany/Wales/Cornwall 2 thousand years ago and if they accompanied with harps of that era, what were its likely tunings (and that goes to the question of how ancient the melody charted is). Here is a link to an excellent translation and discussion of Ar Rannou:
http://tempietto2.blogspot.com/2009_01_01_archive.html
And finally, here is a brief ad hoc run through I did June 2015 on a six string guitar (croaking like an old Druid vocally), offered as an audio sample of the charted melody. I have no idea if the chords I added were used in ancient times. I alternated D and C in the first portion (verse) and then transitioned to Gm - Bb - C - F ascending behind the melody of the refrain. It seemed natural to me, but I grew up with Western diatonic scales. I suspect the ancient Celts may have used more diatonic accompaniment (say a third or a fifth) than is generally acknowledged, since the likely string tones included those possibilities, and the songs we have from 1200 or so (for example, Sumer Is Icumen In) demonstrate long-time familiarity with diatonic melody and harmony.
Link to me roughing out Ar Rannou/Les Series (just a couple of verses):

Here is an interesting link, off the topic, but very cool, the French fusion jazz band doing their interpretation of Les Seris/Ar Rannou live 2011:
Answer: If you accept some form of the celto-scythian hypothesis, then we can establish some parameters that a Celtic liturgical tradition might have followed. It would be approximately that of the classical Greco-Egyptian tradition of several hundred years earlier. This would put us somewhere around the time of Pythagoras or between him and Plato.
So the music would IMO be confined to Church Modes, specifically the Aeolian and the Ionian. So that would rule-out effects like the raised 7th shown here.
There would also be a tendency to conceive melodies "upside-down" from our point of view. This is because the root or tonic of the scale is the highest pitch. (I imagine this would arise naturally from the lack of a concept of a *reference pitch* when tuning a lyre. If you don't want to snap your high string when you get to it, you must *start* with the high string and then *descend* to the longer/lower-tension strings.) This example does seem to follow this conception.
There would also be a tendency not to complete the octave, as this was a later invention. Octaves (and double-octaves) would be used for part-doubling, to allow male and female voices to sing together. Polyphony as such was a later development (according to legend it was developed by the Celts and brought to the court of Charlemagne by a Hyperborean Monk (Druid?)).


Passing values to formmail.cgi without refresh (HTML form PHP handling)

Question: My host has a formmail.cgi script to send html form data to emails (http://formmail.dreamhost.com/), but I dont understand how to pass it values that it understands.
Ive tried using this method to pass form values:
HTML:
<form  id="contact_form" action="http://formmail.dreamhost.com/cgi-bin/formmail.cgi" method="POST">

 <input type=hidden name="recipient" value="info#raphaelguilleminot.com">
 <input type="hidden" name="subject" value="Message from Raphael's portfolio site" />
 <input type=text id="email" class="email default-value" name="email" value="Your email">
 your email is required
 <textarea id="message" class="contact_message default-value" name="message" value="your message">Tell me whats on your mind!</textarea>

 <input class="submit button" type="submit" value="Send" />

</form>

Jquery:
$(".button").click(function() {

var dataString = 'recipient=info#raphaelguilleminot.com' + 'name='+ name + '&email=' + email + '&message=' + message;

$.ajax({
 type: "POST",
 url: "http://formmail.dreamhost.com/cgi-bin/formmail.cgi",
 data: dataString,
 success: function() {
  $('#contact_form').hide().fadeIn(1500)
  }
  });
  return false;
  });
 });

Any ideas?
Answer: In order for it not to refresh the page, you need to add
$('#contact_form').submit(function(){ return false; });
One thing I noticed is that you didn't prefix & for the name attribute, while constructing your own url encoded string is nice, you could use jquery to do it for you automatically.
Set Id's for each form input, then get the values by using:
msg = $('#message').val();
replyto = $('#email').val();
and for the data section:
data:({
   recipient:info#raphaelguilleimnot.com,
   subject:'Message from Raphael's portfolio site',
   email:replyto,
   message:msg
})
Answer: The way you defined your dataString is not correct.
var dataString = 'recipient=info#raphaelguilleminot.com' + 'name=' (...)

should actually be
var dataString = 'recipient=info#raphaelguilleminot.com' + '&name=' (...)

Also, you should rather use an array or an object to pass your data parameters, such as
var data = {
  recipient: 'info#raphaelguilleminot.com',
  name: name,
  (...)
}

jQuery would ensure automatically that your parameters are escaped correctly.
Finally, you should prevent the default behavior of the submit button so that your ajax call can be made. Otherwise, your page will load the CGI script, actually sending the data twice (if the ajax call has been lucky to get by).
$('#contact_form').submit(function(){
  return false;
});

Should do the trick.


Ho to maintain space between grid in GridLayoutManager when itemview is gone?

Question: In activity
recyclerview.setLayoutManager(new GridLayoutManager(this, 3));

inAdapter onBindViewHolder
holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                holder.itemView.setVisibility(GONE);
            }
        });

After itemview gone grid layout not arranged properly
Comment: The screenshot is from your output or the desired output?
Comment: no its current output
Comment: Then, you need to remove the item from the list.
Answer: You have to remove the item from your list which you bind in your GridLayout.
holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                yourlist.remove(position);
                notifyDataSetChanged();
            }
        });

If you gone particular item then space is always there in view...
Update
// Gets linearlayout
LinearLayout layout = findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 0;
params.width = 0;
layout.setLayoutParams(params);

Comment: by the removing there are new problems are raised which are not maintain here, i already tried it , and its work perfect, but i want to go through GONE method
Comment: "If you gone particular item then space is always there in view.." thats i want to remove
Comment: is any option for itemview width set 0?
Comment: @Vora can you mention the problems that you face when you remove the item?
Comment: that is very length and i removed before few hours, so i changed my stratagy
Comment: visit my previous question  these are my problem
https://stackoverflow.com/questions/61452776/how-to-maintain-uploading-task-in-adapter-when-notifyitemremoved-or-notifydatase
Comment: @Vora You have to remove the item from the list. And if you don't want then you have to dynamically set the height of your view as 0.
Comment: "dynamically set the height of your view as 0." and width also 0
but how to do it ?
Comment: Check updated answer : not working space remain constant after set param
Comment: @Vora : the only thing you need to do is you have to remove item from list. That' it.


Can someone explain the difference between app server/web server/web services?

Question: I know that with web server, the html pages are transfered from server to client, with web services, a xml file is sent, but still ... I don't understand them; not even the difference between them.
Can someone explain as simple as possible this terms ?
Platform: java,python,php
Thank you
Answer: There is no really precise definition of these terms, but very roughly speaking:

a web server is a program that serves content (HTML, images, etc) to browsers, i.e. to be read by humans
a web service is a service that can be accessed via HTTP (the same protocol a web server uses), typically an API to be used by programs

So the difference is the "audience": a web server serves pages for people to read in a browser; a web service provides data to some program (which may itself be a web server ;-)).
To make the confusion complete, most web servers (the program) can be used to implement a web service (as the technical basis is the same). So it's not really a technical distinction, but one of which purpose the server has.
Answer: A web server is something that serves you contents using the HTTP(S) protocol; it receives requests in the form "give me http://some.site.com/some/page?some=parameter" and sends back an answer that can be an HTML page or anything else that can be transferred over HTTP(S); that is, pretty much anything (see MIME for details).
More often than not, web pages will not be only static text files, but will be generated on-the-fly by the server using some server-side code developed by programmers; when a web site (or part of it) gets complex enough, it's common to define it as a "web application"; the term is very vague, and actually means "a web site with a dynamic-generated content". Sometimes, the web server and the application server are actually the same program (see IIS, or Apache with modules); other times, the application server is a full-blown different program (maybe even running on a different machine), which communicates with the web server to feed it dynamic contents while the web server manages HTTP requests and static contents; this is the standard practice for Java web sites.
A web service is a web application which follows some standards defined for exchanging requests and responses using XML; the idea here is that the web service is not going to be used by humans, but will be called by other programs (possibly being web applications themselves) and so it doesn't need to do fancy graphics or anything else, but just to provide the requested informations in a standardized way.
Answer: A simple way is to run through a couple of scenarios:
A web-server has the files you want to give to the client. (client can be a browser, an application or another web-server, or another server)
A web-service is the mechanism through which the web-server understands a request from a client and in turn reacts to it. The reaction could be serving up the results of a query, doing an internal command and other similar items.
Generally, when you hear "webservices" in web 2.0 speak, like an API, you're talking about a programming language that is listening on the web-server waiting for commands or queries.
Take for example Twitter. Twitter itself is served by a web-server, but when a client clicks on "followers" the browser sends a web-services command to the webserver asking who the followers are.
A web-server serves files by definition, but it must run some type of web-service in order for it interact with clients. Also, in sysadmin circles, a webservice can be any service that can be exposed as it relates to the webserver. For example if you have a website with 4 customer facing applications (mysql, tomcat, apache, netbeans) you could loosely refer to those as "webservices" even though they technically are webservers and database services, but this isn't what you were looking for I don't think. Stick to webservices as to it relates to APIs.
Also this should expand well - http://en.wikipedia.org/wiki/Web_server and http://en.wikipedia.org/wiki/Web_service
HTH


Por que .dat e não .txt?

Question: Estou realizando um trabalho para a minha faculdade na linguagem C, seria basicamente o sistema inteiro de uma sapataria, com manipulação de arquivos. Procurando alguns exemplos de CRUD na internet eu encontrei vários que fazem uso de arquivos .dat, e nenhum que faz uso de um .txt.
O .Dat é melhor para manipular os arquivos? Por que não txt (tudo que me ensinaram até agora foi apenas em txt)?
Teria algum jeito de eu melhor visualizar o que está escrito em um arquivo .dat?
Answer: .dat é só um nome qualquer, isso indica nada sobre o que ele tem dentro, não existe sequer especificação que diz que um .dat deve ser de um jeito ou de outro, assim como um `.txt também não, embora costuma-se usar um texto sem formatação alguma.
Costumam usar isso para dizer que tem dados lá dentro, nada mais que isto, cada uso pode ser de um jeito. Obviamente que é mais comum algo que tenha dados binários (codificados assim, aceitando a faixa inteira de um byte e não apenas um subconjunto, porque tecnicamente só texto também não deixa de ter uma forma binária) enquanto que um .txt espera-se que tenha só textos simples.
Para você visualizar apenas pode abrir em qualquer editor, alguns vão mostrar dados binários melhor que outros, mas eles serão essencialmente ilegíveis. Alguns editores foram feitos para ler binários e possuem ferramentas específicas para isto.
Fora isto você pode criar um código que abra e leia todos os dados de forma livre, ou seja, byte por byte sem se importar com o conteúdo.

Por que .dat e não .txt?


Html DIV ID definida com echo

Question: Estou com um problema que não consigo descobrir, não consigo entender porque a ID da DIV não recebe o o valor vindo do php, utilizando o valor da constante $i, ele sempre recebe o ultimo valor do laço.
a proposta é mostrar/esconder a DIV selecionada por ID quando clicado no href do Nome.

<?php
//classe
class Clientes{
    public $id;
    public $nome;
    public $cpf;
    public $endereco;

    public function __construct($id,$nome,$cpf,$endereco){
        $this->id = $id;
        $this->nome = $nome;
        $this->cpf = $cpf;
        $this->endereco = $endereco;
    }
};

    $cliente1 = new Clientes("0","Bruno","550","rua protasio");
    $cliente2 = new Clientes("1","Thiago","4400", "rua barao");
    $cliente3 = new Clientes("2","Ana","650","rua nova");
    $cliente4 = new Clientes("3","Beatriz","840","rua velha");
    $cliente5 = new Clientes("4","Gustavo","960","rua brasil");
    $cliente6 = new Clientes("5","Alberto","123255","rua jovem");
    $cliente7 = new Clientes("6","Jose","466897","rua normal");
    $cliente8 = new Clientes("7","Andre","44699", "rua das petalas");
    $cliente9 = new Clientes("8","Vinicius","87750", "rua irmao");
    $cliente10 = new Clientes("9","Bruna","4890", "rua bolao magico");

    $arrayclientes = array($cliente1, $cliente2,$cliente3,$cliente4,$cliente5,$cliente6,$cliente7,
                            $cliente8,$cliente9,$cliente10);

    for($i=0;$i<10;$i++){
    $arrayclientes[$i]->id;
    $arrayclientes[$i]->nome;
    $arrayclientes[$i]->cpf;
    $arrayclientes[$i]->endereco;
    include("thumbimg.php");
    }

    ?>

Segundo Codigo:

<?php
echo "disp" .$arrayclientes[$i]->id;
?>

 Nome:<?php echo $arrayclientes[$i]->nome; ?>

    <div id=" <?php echo "disp" .$arrayclientes[$i]->id; ?> ">

Cpf:<?php echo $arrayclientes[$i]->cpf; ?>

Endereco: <?php echo $arrayclientes[$i]->endereco; ?>

Comment: olhe se esta resposta pode te ajudar.
http://pt.stackoverflow.com/questions/22726/como-esconder-mostrar-uma-div-em-html
Comment: o problema que eu percebi está com a  que não recebe o valor, o javascript funciona normalmente
Comment: O segundo código é o que vai no include?
Comment: sim, isso mesmo
Comment: Então veja se a resposta ajuda.
Answer: Acredito que o Segundo Codigo vai dentro do arquivo include("thumbimg.php");.
Problemas do código:

A cada loop você está repetindo o function display() {...} e em var elem = document.getElementById("disp2"); você só está chamando o elemento com disp2, indepentende do link que você clicar.
No id de cada elemento você adicionou espaços no começo e fim, <div id=" <?php echo "disp" .$arrayclientes[$i]->id; ?> ">, os espaços são considerados caracteres válidos para o ID, portanto se você chamar document.getElementById("disp2"); ele vai retornar NULL, pois está procurando um ID sem espaço
Você abre a tag
, depois a tag e fechaprimeiro e depois fecha a tag`, isto está errado:

 Nome:<?php echo $arrayclientes[$i]->nome; ?>

o correto seria assim:

Nome:<?php echo $arrayclientes[$i]->nome; ?>

Você resolver o problema, movendo a função para um lugar isolado, fora do arquivo thumbimg.php e passar um paramentro no display() com o id, veja como pode ser o seu código:

<?php
    class Clientes {
        public $id;
        public $nome;
        public $cpf;
        public $endereco;

        public function __construct($id,$nome,$cpf,$endereco) {
            $this->id = $id;
            $this->nome = $nome;
            $this->cpf = $cpf;
            $this->endereco = $endereco;
        }
    }

    $cliente1 = new Clientes("0","Bruno","550","rua protasio");
    $cliente2 = new Clientes("1","Thiago","4400", "rua barao");
    $cliente3 = new Clientes("2","Ana","650","rua nova");
    $cliente4 = new Clientes("3","Beatriz","840","rua velha");
    $cliente5 = new Clientes("4","Gustavo","960","rua brasil");
    $cliente6 = new Clientes("5","Alberto","123255","rua jovem");
    $cliente7 = new Clientes("6","Jose","466897","rua normal");
    $cliente8 = new Clientes("7","Andre","44699", "rua das petalas");
    $cliente9 = new Clientes("8","Vinicius","87750", "rua irmao");
    $cliente10 = new Clientes("9","Bruna","4890", "rua bolao magico");

    $arrayclientes = array($cliente1, $cliente2,$cliente3,$cliente4,$cliente5,$cliente6,$cliente7,
                            $cliente8,$cliente9,$cliente10);

    for ($i=0;$i<10;$i++) {
        $arrayclientes[$i]->id;
        $arrayclientes[$i]->nome;
        $arrayclientes[$i]->cpf;
        $arrayclientes[$i]->endereco;

        include("thumbimg.php");
    }
?>

e o segundo código:
<?php
echo 'disp', $arrayclientes[$i]->id;
?>

        <a onclick="display('<?php echo 'disp', $arrayclientes[$i]->id; ?>)">
            Nome: <?php echo $arrayclientes[$i]->nome; ?>

    <div id="<?php echo 'disp', $arrayclientes[$i]->id; ?>">

Cpf:<?php echo $arrayclientes[$i]->cpf; ?>

Endereco: <?php echo $arrayclientes[$i]->endereco; ?>

Comment: já havia testado a questão de espaços, o div id tem que ser dinamica, ou irei esconder TODAS as entradas a moral era esconder apenas uma
Comment: @ThiagoFreitas Então apenas edite a parte do
Comment: eu coloquei aquele valor para verificar se o laço estava atribuindo valor correto para as DIV(por sinal não está), bobeira minha acabei colando o codigo aqui com aquilo.
Answer: Retire a função display do loop e altere para receber o id por parâmetro.

E dentro do loop, passe o ID para função no onclick.

<a onclick="display('<?php echo "disp" .$i; ?>')"> Nome:<?php echo $arrayclientes[$i]->nome; ?>

    <div id="<?php echo "disp" .$i; ?>">

Cpf:<?php echo $arrayclientes[$i]->cpf; ?>

Endereco: <?php echo $arrayclientes[$i]->endereco; ?>

Answer: Olha essas mudanças, só funciona a DIV que ficou com ultimo valor a "DIV 9";

<?php
echo "disp".$i;
?>

 Nome:<?php echo $arrayclientes[$i]->nome; ?>

    <div id="<?php echo "disp" .$i; ?>">

Cpf:<?php echo $arrayclientes[$i]->cpf; ?>

Endereco: <?php echo $arrayclientes[$i]->endereco; ?>

retirei o o ID nos atributos e etc..
Comment: Somente a ultima DIV que mostra/esconde independente de onde eu clicar
Answer: Acredito que isso deve resolver o problema:

<?php  for($i=0;$i<10;$i++):?>
    <?php
    echo "disp" . $arrayclientes[$i]->id;
    ?>

        <a href="javascript:void(0);" onclick="display(<?php echo $arrayclientes[$i]->id;?>)"> Nome: <?php echo $arrayclientes[$i]->nome; ?>

     <div id="<?php echo "disp" .$arrayclientes[$i]->id; ?>">

Cpf:<?php echo $arrayclientes[$i]->cpf; ?>

Endereco: <?php echo $arrayclientes[$i]->endereco; ?>

<?php endfor; ?>

Html DIV ID definida com echo


Which algorithm is used for the H2O AutoML metalearner

Question: We know that h2o.automl() uses GBMs, Random Forest, DNNs, GLMs, and Extremely-Randomized Forest as base-learners, but what algorithm is used as the metalearner to combine base-learners?
Answer: There are two Stacked Ensembles in H2O AutoML (v3.16), both use a GLM (with a non-negative weight constraint).  Other than the non-negative constraint, all the other hyperparameters for the GLM are the standard H2O GLM defaults.
In future iterations, we will introduce additional ensembles that use different algorithms for the metalearner (e.g. GBM).
Comment: The theoretical results of Super Learner rely on cross-validation, but you can still get an ensemble that's better than the best base learner using the hold-out method, it just won't be as good as the Super Learner.  If you are concerned about computation time, then a decent compromise is to use Super Learner with 2-fold CV (but if you have time-series, then you should still use the hold-out approach).
Comment: @AndreaM We have a bespoke ordering for the algorithms (based on a number of optimizations) and the order is listed here: http://docs.h2o.ai/h2o/latest-stable/h2o-docs/automl.html#faq
Comment: Very thanks for your reply. However, there is one problem that  I don't clear. I saw you said in another question " metalearner is trained on (usually) cross-validated predicted values generated by the base learners", why "usually"? If my study object is time series data, could I divide my data into 3 parts:training, validation, and testing and use predictions of validation to train meta-learner? not cross-validation.
Comment: Yes, the time when you would not want to use cross-validated predictions is when you have time-series data.  If you have IID data, then CV preds will give the best results (which is why its most used) but you can also use a hold-out set to create the predictions which are used to train the metalearner if you want to save computation time.
Comment: but, I wonder that does this approach still meet the theoretical requirements of super-learning(stacking)  and ensure our results performs essentially as well as or better than any of the candidate learners?
Comment: This approach is called Blending?
Comment: Yes "blending" is probably the most common name for this technique (the ensemble technique of using a hold-out set instead of cross-validated predictions).
Comment: how the AutoML process decide which is the next model to train? Is it used a Random Grid Search or some other kink of algos (I think that the meta-learner has a huge impact in this stage of the training)


Show full image path D8

Question: I have set a Drupal 8 project into another server with some child directory. This D8 project is working good, But images are not showing due to path missing. E.g
My project is setup:- http://abc.xyz.com/client/development/project-name/
but when I was inspecting element then I got image URL:-http://abc.xyz.com/sites/default/files/images.png
I know client/develoment/project-name/ path is missing into the image path. May you let me know how to get full image path display?
Full path must show:-http://abc.xyz.com/client/development/project-name/sites/default/files/images.png
Thanks
Comment: In what context you want image url? Are you in custom module ? Twig template?
Comment: Want to display image in the browser.Bcoz project already is done but images are not displayed.
Comment: Do anything change in default/settings.php page?
Comment: Images are inside the body or part of fields, you have to give more information otherwise the question is very broad.
Comment: Images are inside into the body.
Comment: If images are inside body then they already have a path. Drupal is not generating the path, so you can't change the path. You should edit your content or solve it in the webserver level.
Answer: Images are hardlinked inside the body field.
One way to correct it is to do a search and replace inside the database.
Perhaps also pathologic can help correct the problem with broken images.

add pathologic support to your desired text formats (congig > content authoring > text formats)
make sure you check  Correct URLs with Pathologic

when visiting a page pathologic should correct those broken images

Show full image path D8


Find the eigenvalues of $A^{3}$

Question: Given the matrix
\begin{bmatrix}
    4       & 0 & 1 \\
    -2       & 1 & 0 \\
    -2       & 0 & 1
\end{bmatrix}
I have found the eigenvalues to be $\lambda_{1} = 1$, $\lambda_{2} = 2$, $\lambda_{3} = 3$. How do I find the eigenvalues of $A^{3}$?
Answer: Hint: for an eigenvector $x$ of A
$A^3 x=AAAx=AA\lambda x =\dots = \lambda^3 x$.

Find the eigenvalues of $A^{3}$


How do we apply chain rule to a function of two variables, which are also functions.

Question: Let $f$ and $g$ be differentiable functions.
$$
\frac{\partial}{\partial z}(g(f(x+y),f(z))
$$
How do we apply the chain rule here correctly? Do we just treat $f(x+y)$ and $f(z)$ as some variables $u$ and $v$?
Comment: Look in the index of your calculus book: "chain rule for partial derivatives"
Answer: Yes.  Think of $g = g(u,v)$.  Then, you have $$\frac{\partial}{\partial z}(g(f(x+y),f(z)) = \frac{\partial g}{\partial v}(f(x+y),f(z))f'(z).$$
Comment: Assuming $x,y$ are not functions of $z$.
Comment: @DMcMor Yes of course, thank you so much!
Comment: Then would $\frac{\partial g}{\partial u} \frac{\partial u}{\partial z} + \frac{\partial g}{\partial v} \frac{\partial v}{\partial z}$ also be correct?
Comment: @MilošRadoman yes, but notice here that $\frac{\partial u}{\partial z} = 0$ unless either $x$ or $y$ are non-constant functions of $z$.
Answer: We consider:
\begin{align*}
g=g(u,v)\qquad\qquad &u=u(x,y,z)\\
&v=v(x,y,z)
\end{align*}
In the current situation we have:
\begin{align*}
&u(x,y,z)=f(x+y)\qquad\qquad v(x,y,z)=f(z)\\
&\qquad\ \,\frac{\partial u}{\partial z}=0\qquad\qquad\qquad\qquad\quad\ \  \frac{\partial v}{\partial z}=f^\prime(z)
\end{align*}

Application of the chain rule gives
\begin{align*}
\frac{\partial}{\partial z}g(u(x,y,z),v(x,y,z))&=
\frac{\partial g}{\partial u}\,\frac{\partial u}{\partial z}
+\frac{\partial g}{\partial v}\,\frac{\partial v}{\partial z}\\
\color{blue}{\frac{\partial}{\partial z}g(f(x+y),f(z))}&\color{blue}{=}
\frac{\partial g}{\partial u}\, \cdot 0
+\color{blue}{\frac{\partial g}{\partial v}\,f^{\prime}(z)}
\end{align*}
in accordance with the already given answer.


position: sticky junto com overflow;

Question: existe uma forma de fazer com que position: sticky e overflow-x: auto funcionem juntos, sem setar valores de height?
 Nessa estrutura que fiz ao setar overflow-x: auto na minha class .scroll, meu position: sticky da tag th para de funcionar, porém ao remover o overflow o mesmo funciona normalmente. Pesquisei sobre e achei que só funcionam junto com valor de height setado.
 Existe alguma outra forma de fazer com que as duas propriedades funcionem juntas? Se sim somente com css é possível? ou preciso de uma ajuda com javascript? estou usando Angular7, se precisar de javascript, é possível sem ser com Jquery?

table {
    min-width: 250px;
    border-collapse: separate;
    border-spacing: 0;
    margin-right: 5px;
}

thead th {
    position: sticky;
    top: 0;
    background-color: #c3ac6c;
}

th {
    border-top: 1px solid;
    border-bottom: 1px solid;
    border-right: 1px solid;
    text-align: center;
    padding: 4.5px;
}

tbody tr:nth-child(even) {
    background: #efefef;
    overflow: hidden;
}

tbody tr:nth-child(even):hover {
    background-color: #ffff99;
}

td {
    border-bottom: 1px solid;
    border-right: 1px solid;
    padding: 4.5px;
    text-align: center;
}

tr{
    min-height: 25px;
}

th:first-child,
td:first-child {
    border-left: 1px solid;
}

tr:hover {
    background-color: #ffff99;
}

.fixed{
    position: sticky;
    left: 0;
    padding: 0 5px 0 5px;
    background-color: #fafafa;
    z-index: 3;
  width: 100%
}

.scroll {
  display: flex;
  justify-content: space-between;
  width: 800px;
  overflow-x: auto;
}

          1
          2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1
          2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1
          2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1
          2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

          1	 2

Comment: Cara eu não entendi direito, vc quer isso? https://imgur.com/JDxZvSW ?  Fiquei meio confuso com qual resultado final vc espera...
Comment: Isso mesmo, porem não consigo chegar nesse resultado sem setar `height`, preciso que minha tabela tenha o tamanho de linhas que vier do banco, com tabela da esquerda fixa, e os headers fixos na horizontal e vertical.
Answer: Cara mas se vc não que definir um tamanho para sua tabela como vc quer que ela tenha scroll? Se vc não vai definir o tamanho da tabela vc precisa definir a altura de algum elemento que a tabela vai estar dentro, mesmo que seja o body.

Fiz esse exemplo onde a div.scroll tem 100% da altura e da largura do body. Usei max-width e max-heigt, então o scroll só vai aparecer se o conteúdo for maior que o container pai, se for meno não aparece scroll
Aqui eu diminui o número de elementos por causa da limitação de caracteres do Snippet do Stackoverflow, mas vc pode testar ai com mais conteúdo para ver como fica

<!DOCTYPE html>

<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                        1
                        2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

                    1
                    2

position: sticky junto com overflow;


Dynamic select list in the form (dependent dropdown)

Question: I'm using Drupal seven. I want to make the options in a select list be dependent on the value chosen in another select list in a form.  I'm sure this has been asked many times before, but I am having difficulty finding a clear answer for how to do this.
The form is for users to enter a work history.  They need to select a squadron which is a node reference to the squadron field type, and this is in a drop-down list.  However, the squadron, is dependent upon a city drop-down list.  Users first need to select a city which will then filter the options for the squadron.  In the squadron content type, I created a taxonomy for city which gets tagged to the squadron.
I would be very grateful for any pointers as to the best way (simplest?) to go about this, or for any useful resources online which would help.
Comment: Simple example: https://api.drupal.org/api/examples/ajax_example%21ajax_example.module/function/ajax_example_dependent_dropdown/7.x-1.x
Answer: You can use Ajax to accomplish this. Drupal 7 has good Ajax support now. On your first select list (city) you'll need to add Ajax information. Then, the second select list can be populated based on the information in the first. You can also even hide the second select list until an option in the first is selected, and I'll explain how to do that in a bit.
First, to set up the basic form:
$form['city'] = array(
  '#type' => 'select',
  '#title' => t('City'),
  '#options' => $options,
  '#ajax' => array(
    'event' => 'change',
    'wrapper' => 'squadron-wrapper',
    'callback' => 'mymodule_ajax_callback',
    'method' => 'replace',
  ),
);
$form['squadron_wrapper'] = array('#prefix' => '
', '#suffix' => '
');
$form['squadron_wrapper']['squadron'] = array(
  '#type' => 'select',
  '#title' => t('Squadron'),
  '#options' => $squadron_options,
);

This is just the basic setup of the elements. Now you'll need a way to determine what options should go in squadron. First you need to make your Ajax callback identified in 'city' select list. In most cases you can just return the element that wraps the ajax element, in this case $form.
function mymodule_ajax_callback($form, $form_state) {
  return $form;
}

Now, when the 'city' select list changes it will rebuild the squadron-wrapper part of the form. Your 'city' value will now be in $form_state['values']. So, when the form is rebuilt we need to determine what options to give to the select list based on the value of 'city'.
// Get the value of the 'city' field.
$city = isset($form_state['values']['city']) ? $form_state['values']['city'] : 'default';
switch ($city) {
  case 'default':
    // Set default options.
    break;
  case 'losangeles':
    // Set up $squadron_options for los angeles.
    break;
}

// If you want to hide the squadron select list until a city is
// selected then you can do another conditional.
if ($city !== 'default') {
  $form['squadron_wrapper']['squadron'] = array(
    '#type' => 'select',
    '#title' => t('Squadron'),
    '#options' => $squadron_options,
  );
}

Comment: Examples can be found in the [Examples](http://drupal.org/project/examples) module ("AJAX Examples" → "Dependent dropdown"). You can also see at [Hierarchical Select](http://drupal.org/project/hierarchical_select) module.
Comment: By the way, alternatively you can do this in a multi-step form, but I didn't think that sounded like what you were looking for. Also ^ good call! Examples modules are *great* for learning this kind of thing.
Comment: @jordojuice Thank you very much for your answer. I am working on it now. In the third example of the code you give above (beginning //Get the value...) which function do I put this part of the code in? Does it go in the _ajax_callback function? Thanks
Comment: I followed the example module for this but i got an error everytime i select an item in the first drop down:Warning: array_values() expects parameter 1 to be array, string given in _field_filter_items() (line 525 of I:\My Documents\web\xampp\htdocs\mysite\modules\field\field.module). I'm using a multi step form in conjunction with this ajax dependent drop down that i wrote in a custom override module.... Although the values get changed for the second dd based on the first. It's just a warning showing up though but irritating... can someone please help me remove that warning? thanks!
Comment: 2 Important differences between this code and what ended up working for @Ben. Note that the #suffix uses an id, and the ajax callback returns the form element, not the entire form. Other than that this was super helpful!
Comment: In addition, consider using "`return $form['squadron_wrapper']`" in the callback to make the AJAX response even smaller (and with that faster).
Answer: Many thanks to jordojuice above. With his help I managed to find a solution. I also refered to the example at http://public-action.org/content/drupal-7-form-api-dependent-lists-and-ajax-form-submission. I eventually used the code below which worked in a custom module. For some reason I couldn't find any of my values in the $form_state values, but was able to find them in $form. Finally, when I tested, I was getting an error message that Drupal had detected an illegal choice in the drop-down.  I got round this by commenting out line 1290 in form.inc:
form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
The final code I used was:
<?php

function sappers_squadron_form_work_history_node_form_alter(&$form, &$form_state) {
        //echo '
';
        //print_r ($form);
        //echo '
';

        $squadron_options = array();

        if(isset($form['field_wkhist_city']['und']['#default_value'][0])) {
            $city = $form['field_wkhist_city']['und']['#default_value'][0];
        }
        else {
            $city = 0;
        }

        $squadron_options = sappers_squadron_squadrons($city);

        $form['field_wkhist_city']['und']['#ajax'] = array(
            'event' => 'change',
            'wrapper' => 'squadron-wrapper',
            'callback' => 'sappers_squadron_ajax_callback',
            'method' => 'replace',
        );

        $form['field_squadron']['und']['#prefix'] = '
';
        $form['field_squadron']['und']['#suffix'] = '
';
        $form['field_squadron']['und']['#options'] = $squadron_options;
}

function sappers_squadron_ajax_callback($form, $form_state) {
    $city = $form['field_wkhist_city']['und']['#value'];

    $form['field_squadron']['und']['#options'] = sappers_squadron_squadrons($city);

    return $form['field_squadron'];
}

function sappers_squadron_squadrons($city) {
    $nodes = array();

    $select = db_query("SELECT node.title AS node_title, node.nid AS nid FROM  {node} node INNER JOIN {taxonomy_index} taxonomy_index ON node.nid = taxonomy_index.nid WHERE (( (node.status = '1') AND (node.type IN  ('squadron')) AND (taxonomy_index.tid = $city) )) ORDER BY node_title ASC");

    $nodes[]="";

    foreach ($select as $node) {
            $nodes[$node->nid] = $node->node_title;
    }

    return $nodes;
}

?>

Comment: I get an An illegal choice has been detected. Please contact the site administrator.
 error when I tried implementing above. Can u help?
Comment: @harshal - I had the same problem and got round it by implementing the solution I give in my answer, please see above (altering form.inc). This is a bit of a hack but it worked for me.
Comment: @harshal - Probably a better solution is that one given by Hacker below.
Answer: put the line of code i.e
$nodes[''] = '- None -';  after
 $nodes = array();

in ur
sappers_squadron_squadrons function
and that will solve your error
form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
Answer: The root cause of "An illegal choice has been detected. Please contact the site administrator." is that the empty string with the value of 0 added by $nodes[]=""; is invalid for the field_squadron field.
See Advance PHP Programming and Development, but keep in mind that the DANGEROUS_SKIP_CHECK and validated flags are deprecated in D7.
After I removed that line, the error was gone.
Answer: Use the Reference field option limit module

This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.
Comment: Is it an alternative to conditional fields module?


Como ter acesso ao banco de dados de outra máquina

Question: Galera, boa noite.
É o seguinte:
Estou com um projeto de PHP com MySQL para ser entregue. Porém, estou fazendo desta maneira: Criei 3 máquinas virtuais no VMWare Workstation Pro, a do Cliente é Windows, a que fica somente o PHP é Ubuntu, e a que fica o banco de dados também é Ubuntu. A ideia é que seja uma simulação. Da máquina do Cliente, eu consigo acessar o site na máquina do PHP através do IP da máquina/nome_do_arquivo.php, consigo fazer isso sem problemas. O negócio é que eu fiz um formulário nesse site PHP para inserir dados no banco de dados que está em outra máquina.
Resumo da ópera: não estou conseguindo obter conexão com o banco de dados, ou seja, não consigo ter acesso remoto ao banco, mesmo tendo configurado o arquivo de conexão da maneira certa. Jà pesquisei em vários lugares, tanto nacionais como na gringa, e não achei nada.
Se puderem me ajudar, ficarei muito grato!!!!!!
Answer: Para permitir o acesso externo ao banco de dados mysql em um servidor remoto, é configurar-lo para acessos externos.

Acessar o arquivo my.cnf e modificar o parâmetro IP bind-address  =  127.0.0.1 para 0.0.0.0
Reiniciar o mysql
Acessar o mysql de dentro do servidor e dar as permissões de acesso a partir de qualquer IP. mysql> GRANT ALL ON . TO 'root'@'%' IDENTIFIED BY '[senha]' WITH GRANT OPTION;
Para finalizar atualizar os privilégios mysql> FLUSH PRIVILEGES;
Comment: Não deu certo :/ ja desabilitei o firewall, ja configurei o GRANT no mysql, ja configurei o arquivo do mysql mas não conecta.. quando eu carrego a pagina de conexao.php nem aparece erro, fica em branco
Answer: Você consegue se conectar ao MySQL a partir do seu próprio host? Se não, veja se ele está rodando.
sudo service mysql status

Se o status estiver como 'active', verifique se o arquivo /etc/mysql/my.cnf contém a linha bind-address 127.0.0.1 . Se sim, comente-a com # ou remova-a.
Verifique também se o seu firewall está ativo:
sudo ufw status verbose

Se estiver, pode ser necessário desbloquear a porta 3306 - ou outra definida como padrão.
sudo ufw allow from 192.168.* to any port 3306

Espero ter ajudado! Valeu!
Comment: Não deu certo :/ ja desabilitei o firewall, ja configurei o GRANT no mysql, ja configurei o arquivo do mysql mas não conecta.. quando eu carrego a pagina de conexao.php nem aparece erro, fica em branco
Comment: Alex, em qual parte não deu certo? Funciona localmente? Se funciona, utilize o heidisql (ou outro cliente) pra conectar remotamente. Há chances tbém de que seja problemas de configuração dos caminhos de rede. Somente depois utilize a sua aplicação ou página pra tentar o acesso. Vai reportando aí, quem sabe não encontramos o problema.


Inference in Logistic regression with feature cross/non-linear terms

Question: I would like to perform inference on a binary classification problem.
I have a logistic regression with a mix of binary and continuous inputs. I would like to perform a feature cross (e.g. add some non-linear terms) in my regression and then infer how these variables increase or decrease the probability of observing a positive result. So, I would like to be able to make a statement about my predictors when taking into consideration non-linear interactions between the two.
So if I have binary variable x1 and continuous variable x2 (ranges from 0 to 1) and perform a simple logistic regression using statsmodels for example, I might get back something along the lines of...

variable
coef
other columns such as std error, p-value, etc.

constant
-4
~

x1
-2
~

x2
-0.2
~

From this, assuming everything is significant, I might conclude that increases in x1 and x2 are both associated with decreased probability of observing a positive result. But if I also believed there might be a non-linear effect and wanted to test a logistic regression with the following argument, instead: ~ ax1+bx2+cx1x2
I would get the following output from statsmodels

variable
coef
other columns such as std error, p-value, etc.

constant
-4
~

x1
-3
~

x2
-0.2
~

x1*x2
6
~

I can see that the non-linear term increases the probability of a positive result, but the coefficient for x2 has also changed, which is expected, but the inference is no longer simple. If there was no error on the estimates of the coefficients, it might be easy to say that when x2 is above the value of 3/5.8 and x1 is 1, that the probability of a positive result increases. I come to this conclusion since -3*(x1)-0.2*(x2)+6*(x1)(x2)>0 simplifies to -3+5.8(x2)>0 when x1 = 1. But since my coefficients have a range of values, I can't perform this simple algebra.
Ultimately, is there some way to gauge whether or not variables like x1 and x2 in fact increase the probability of observing a positive result when factoring in non-linear interactions like the one I outlined? Is there perhaps a more simple way to perform such an analysis that I have overlooked (maybe logistic regression is not the way to go)? Finally, would such an approach change if x1 and x2 were both continuous, or both binary?
I am usually more interested in the construction of classifiers as opposed to inferences that one can make based off of the classifier model that gets fit, so I apologize if this question comes across naïve.
Comment: These kinds of marginal effects are supported in Stata by the `margins`. However, the corresponding `margeff` in statsmodels only supports single column terms but not multicolumn terms like interacted effects. The marginal effect in nonlinear models depends on the values of explanatory variables and the effect might not be monotonic over the space of explanatory variables.
Answer:
is there some way to gauge whether or not variables like x1 and x2 in fact increase the probability of observing a positive result when factoring in non-linear interactions

When there's a significant interaction, there's no simple way to evaluate the overall associations between single predictors and outcome. The association between x1 and outcome depends of the values of x2, and vice-versa. Even the single-predictor coefficients become tricky to interpret, as each represents the association with outcome only when its interacting predictors are at reference levels (interacting categorical predictors) or at 0 (interacting continuous predictors). Just centering a predictor can change the single-predictor coefficients of all the other predictors it interacts with.
For inference on particular combinations of predictor values as you propose, you can use the formula for the variance of a sum of correlated variables to get standard errors and confidence intervals, based on the assumption of asymptotic normality of the coefficient estimates in logistic regression. That handles the "range of values" of the coefficient estimates. For inference on the overall association between outcome and a predictor involved in interactions or other nonlinear terms, you can perform a multiple-parameter Wald test on the set of coefficients involving the predictor. For those analyses you need to use the covariance matrix of the coefficient estimates, which is typically hidden from standard model summaries but is contained in the model object.
There are many tools available for this type of post-modeling analysis in R, for example in the rms, emmeans, and car packages. I don't use statsmodels but I imagine that there is some similar functionality provided by Python packages.
Comment: Out of curiosity, if I had instead 10 predictors, would I have to test all 45 different possible interaction terms at once in a given model, or could I still make a statement about statistically significant interactions by testing pairs of 2 predictors at a time in a logistic model with a single interaction term (similar to what I outlined in my original post) and focus on interaction terms with the largest magnitude, and statistically significant coefficients?
Comment: @delsaber8 logistic regression has a problem with [omitted variable bias](https://stats.stackexchange.com/q/113766/28500). Any restriction to subsets of predictors is likely to lead to bias. After fitting a full model you can get post-modeling Wald chi-square statistics for any sets of coefficients, whether for individual predictors or interaction terms, that can be used (after subtracting the number of degrees of freedom, the mean under the null hypothesis) for evaluating relative contributions to a model. See [this answer](https://stats.stackexchange.com/a/591213/28500) and its links.


Where are the best places to post Drupal 7 RFP?

Question: Do you have any thought on the best places to post an RFP for Drupal 7 development and theme work?
I have posted on drupal.org and groups.drupal.org but someone mentioned odesk, but I wasn't sure if that would be fruitful or just overkill.
Answer: drupal.org reaches a wide audience, and is a good venue.  That said, please be aware that widely distributing an RFP can be harmful to your project.  Many of the best shops don't respond to RFPs.  Advomatic has published an interesting presentation on this topic.
Comment: Hey, unfortunately I watched that video by Advomatic after we had committed to this process. Still it was not my decision and it might have turned out the same either way. Anyway, thanks for your answer.
Answer: There is the paid services forum on drupal.org and there is also the #drupal-consultants channel on chat.freenode.net, wher you can find consultants to discuss the project in real time.


Não consigo retornar todos os dados nos inputs com o PDO?

Question: Criei uma pagina pra colocar o cpf e logo depois faz uma busca no banco, e traz os dados de acordo com o cpf digitado. mas tem alguns inputs que não estão voltando como <radio> (sexo M ou F), os <select> também não estão voltando, os <textarea> e os <input type="checkbox">.
aqui e o codigo php que faz a busca com o cpf digitado:
<?php  include("php/conexao.php"); $pdo=conectar();
       $cpf = $_POST['cpf'];
       if(isset($cpf)){
         $consulta= $pdo->prepare("SELECT * FROM paciente where cpf = :cpf");
         $consulta->bindParam(":cpf",$cpf);
         $consulta->execute(); $resultado = $consulta->fetchAll(); print_r($resultado);
       }
       if(!$resultado){
        echo "";
       }
?>

aqui e onde os dados devem retornar em cada input conforme o banco de dados tb:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>NutricLIFE</title>
        <link rel="stylesheet" type="text/css" href="css/style.css">
        <link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet">
        <link rel="shortcut icon" href="imagens/favicon.png" />

                PDF

        voltar

                <form action="#.php" method="get">

Dados do Paciente

                          <input class="campo-form-c" type="text" name="nome" placeholder="Nome" value=<?php print_r($resultado[0]['nome']); ?>>

                          <input class="campo-form-c" type="text" name="cpf" placeholder="CPF" value=<?php print_r($resultado[0]['cpf']); ?> >

                            <input class="campo-form-c" type="text" name="ultimopeso" placeholder="Ultimo peso" value=<?php print_r($resultado[0]['ultimopeso']); ?>>

                          <input class="campo-form-c" type="text" name="pesoatual" placeholder="Peso Atual" value=<?php print_r($resultado[0]['pesoatual']); ?>>

                        <input class="campo-form-c" type="text" name="altura" placeholder="Altura" value=<?php print_r($resultado[0]['altura']); ?>>

                        <input class="campo-form-c" type="number" name="idade" placeholder="Idade" value=<?php print_r($resultado[0]['idade']); ?>>

                        <input class="campo-form-c" type="text" name="datan" placeholder="Data de nascimento" value=<?php print_r($resultado[0]['datan']); ?>>

                            Sexo:

                                    <input type="radio" name="sexo" value=<?php print_r($resultado[0]['sexo']); ?>>Masculino

                                    <input type="radio" name="Sexo" value=<?php print_r($resultado[0]['sexo']); ?>>Feminino

            <input class="campo-form-c" type="text" name="medidab" placeholder="Medida do Braço" maxlength="5" value=<?php print_r($resultado[0]['medidab']); ?>>

            <input class="campo-form-c" type="text" name="medidat" placeholder="Medida Tricipital" maxlength="5" value=<?php print_r($resultado[0]['medidat']); ?>>

            <input class="campo-form-c" type="text" name="medidaabd" placeholder="Medida Abdominal" maxlength="5" value=<?php print_r($resultado[0]['medidaabd']); ?>>

            <input class="campo-form-c" type="text" name="imc" placeholder="IMC" maxlength="4" value=<?php print_r($resultado[0]['imc']); ?>>

            <input class="campo-form-c" type="text" name="gorduratricpital" placeholder="Gordura Tricipital" maxlength="5" value=<?php print_r($resultado[0]['gorduratricpital']); ?>>

            <input class="campo-form-c" type="text" name="circunferenciabraco" placeholder="Circunferência do Braço" maxlength="5" value=<?php print_r($resultado[0]['circunferenciabraco']); ?>>

            <input class="campo-form-c" type="text" name="circunferenciambraco" placeholder="Circunferência Muscular do Braço" maxlength="5" value=<?php print_r($resultado[0]['circunferenciambraco']); ?>>

            <input class="campo-form-c" type="text" name="gorduracorporal" placeholder="Gordura Corporal" maxlength="5" value=<?php print_r($resultado[0]['gorduracorporal']); ?>>

              Alguma alergia a medicamentos?
                <select class="select-form" name="alergiamedicamento" value=<?php print_r($resultado[0]['alergiamedicamento']); ?>>
                  <option>Sim</option>
                  <option>Não</option>
              </select>

                    Utiliza algum medicamento?
                        <select class="select-form" name="algummedicamento" value=<?php print_r($resultado[0]['algummedicamento']); ?>>
                            <option>Sim</option>
                            <option>Não</option>
                    </select>

                    Quais?
                        <textarea class="areat" name="quaismedicamentos" placeholder="Rascunho" value=<?php print_r($resultado[0]['quaismedicamentos']); ?>></textarea>

                        <input class="campo-form-c" type="text" name="tempomedicamento" placeholder="Tempo de medicamento" value=<?php print_r($resultado[0]['tempomedicamento']); ?>>

                    Bebe Água?
                        <select class="select-form" name="bebeagua" id="inputindex" value=<?php print_r($resultado[0]['bebeagua']); ?>>
                            <option>Sim</option>
                            <option>Não</option>
                        </select>

              Quantos copos?
                            <input class="select-form" type="number" name="quantoscopos" placeholder="Quantos Copos" value=<?php print_r($resultado[0]['quantoscopos']); ?>>

                    Frequência intestinal ?
                        <select class="select-form" name="intestinal" value=<?php print_r($resultado[0]['intestinal']); ?>>
                            <option>Todos dos dias</option>
                            <option>Há cada dois dias</option>
                            <option>Há cada três dias</option>
                        </select>

                    Urina com Frequência ?
                        <select class="select-form" name="urina" value=<?php print_r($resultado[0]['urina']); ?>>
                            <option>Sim, todos os dias</option>
                            <option>Poucas vezes por dia</option>
                            <option>Quase não urino durante o dia</option>
                        </select>

                    Fuma ?
                        <select class="select-form" name="fuma" value=<?php print_r($resultado[0]['fuma']); ?>>
                            <option>Sim</option>
                            <option>Não</option>
                        </select>

                    Ingere Bebida alcoólica ?
                        <select class="select-form"" name="alcool" value=<?php print_r($resultado[0]['alcool']); ?>>
                            <option>Sim</option>
                            <option>Não</option>
                        </select>

                    Pratica alguma atividade física ?
                        <select class="select-form" name="atividadefisica" value=<?php print_r($resultado[0]['atividadefisica']); ?>>
                            <option>Sim</option>
                            <option>Não</option>
                        </select>

                        <input class="campo-form-c" type="text" name="pratica" placeholder="Qual atividade física ?" value=<?php print_r($resultado[0]['pratica']); ?>>

                    Quantas vezes por semana ?
                        <select class="select-form" name="vezes" value=<?php print_r($resultado[0]['vezes']); ?>>
                            <option>0</option>
                            <option>1</option>
                            <option>2</option>
                            <option>3</option>
                            <option>4</option>
                            <option>5</option>
                            <option>6</option>
                            <option>7</option>
                        </select>

                    Intenção da Consulta ?
                        <textarea class="areat" name="consulta" placeholder="Rascunho" value=<?php print_r($resultado[0]['consulta']); ?>></textarea>

                    Problemas de Saúde ?
                        <select class="select-form" name="saude" value=<?php print_r($resultado[0]['saude']); ?>>
                            <option>Sim</option>
                            <option>Não</option>
                        </select>

                    Histórico familiar ?
                        <textarea class="areat" name="familiar" placeholder="Rascunho" value=<?php print_r($resultado[0]['familiar']); ?>></textarea>

                    Possui alergia a algum alimento ?
                         <textarea class="areat" name="comment" name="alergia" placeholder="Rascunho" value=<?php print_r($resultado[0]['alergia']); ?>></textarea>

                    Anamnese Alimentar: O que o paciente costuma comer de segunda a sexta ?
                        <textarea class="areat" name="anamnese" placeholder="Rascunho" value=<?php print_r($resultado[0]['anamnese']); ?>></textarea>

                    E sábado e domingo ?
                        <textarea class="areat" name="sabadoedomingo" placeholder="Rascunho" value=<?php print_r($resultado[0]['sabadoedomingo']); ?>></textarea>

                            Tem exames recentes de Sangue? Urina ? Fezes? (Menos de 3 meses)

                                <input type="checkbox" name="examesf" value=<?php print_r($resultado[0]['examesf']); ?> >Sangue |

                                <input type="checkbox" name="examesf" value=<?php print_r($resultado[0]['examesf']); ?>>Urina |

                                <input type="checkbox" name="examesf" value=<?php print_r($resultado[0]['examesf']); ?>>Fezes |

                                <input type="checkbox" name="examesf" value=<?php print_r($resultado[0]['examesf']); ?>>Sem examesf

                            <textarea class="areat" name="examesfr" placeholder="Rascunho" value=<?php print_r($resultado[0]['examesfr']); ?>></textarea>

                            Solicitar exames :

                                <input type="checkbox" name="examess" value=<?php print_r($resultado[0]['examess']); ?>>Sangue |

                                <input type="checkbox" name="examess" value=<?php print_r($resultado[0]['examess']); ?>>Urina |

                                <input type="checkbox" name="examess" value=<?php print_r($resultado[0]['examess']); ?>>Fezes

                            <textarea class="areat" name="examessr" placeholder="Rascunho" value=<?php print_r($resultado[0]['examessr']); ?>></textarea>

                </form>

usando o print_r no codigo php ele retorna o array:

Array ( [0] => Array ( [id_paciente] => 1004 [0] => 1004 [nome] => fulano [1] => fulano [cpf] => 111.111.111-11 [2] => 111.111.111-11 [ultimopeso] => 90 [3] => 90 [pesoatual] => 75 [4] => 75 [altura] => 1.93 [5] => 1.93 [idade] => 20 [6] => 20 [datan] => 11-11-2000 [7] => 11-11-2000 [sexo] => M [8] => M [medidab] => 12.34 [9] => 12.34 [medidat] => 12.54 [10] => 12.54 [medidaabd] => 32.54 [11] => 32.54 [imc] => 12.3 [12] => 12.3 [gorduratricpital] => 50.32 [13] => 50.32 [circunferenciabraco] => 12 [14] => 12 [circunferenciambraco] => 12 [15] => 12 [gorduracorporal] => 12 [16] => 12 [alergiamedicamento] => Sim [17] => Sim [algummedicamento] => Sim [18] => Sim [quaismedicamentos] => exemplo. [19] => exemplo. [tempomedicamento] => exemplo. [20] => exemplo. [bebeagua] => Sim [21] => Sim [quantoscopos] => 10 [22] => 10 [intestinal] => Todos dos dias [23] => Todos dos dias [urina] => Quase n�o urino durante o dia [24] => Quase n�o urino durante o dia [fuma] => Sim [25] => Sim [alcool] => Sim [26] => Sim [atividadefisica] => Sim [27] => Sim [pratica] => exemplo. [28] => exemplo. [vezes] => 7 [29] => 7 [consulta] => exemplo. [30] => exemplo. [saude] => Sim [31] => Sim [familiar] => exemplo. [32] => exemplo. [alergia] => exemplo. [33] => exemplo. [anamnese] => exemplo. [34] => exemplo. [sabadoedomingo] => exemplo. [35] => exemplo. [examesf] => Fezes [36] => Fezes [examesfr] => exemplo. [37] => exemplo. [examess] => Sangue [38] => Sangue [examessr] => exemplo. [39] => exemplo. ) )

mas os input que comentei no começo ainda não chegam. <radio> (sexo M ou F), os <select> também não estão voltando, os <textarea> e os <input type="checkbox">.
Answer: Os inputs do tipo checkbox, radio e select tem o valor padrão setado de forma diferente de inputs do tipo text.
Para checkbox e radio funciona da mesma forma. Você deve adicionar o atributo checked. Que pode ser ele sozinho ou checked="checked" (do xHTML):
<?php

$isMale = $resultado[0]['sexo'] == "M" ? 'checked="checked"' : '';
$isFemale = $resultado[0]['sexo'] == "F" ? 'checked="checked"' : '';

?>

<input type="radio" name="sexo" value="M" <?= $isMale; ?> />Masculino
<input type="radio" name="Sexo" value="F" <?= $isFemale; ?> />Feminino

Essa disposição funciona tanto para radio quanto checkbox.
Quanto ao select, você deve definir qual option do select é que está selecionado. É similar ao checkbox, só que, ao invés de checked será selected.
Como você utiliza valores fixos no HTML, pode ser feito de forma parecida com o checkbox.
<?php

$isTrue = $resultado[0]['saude'] == "S" ? 'selected="selected"' : '';
$isFalse = $resultado[0]['saude'] == "N" ? 'selected="selected"' : '';

?>

<select class="select-form" name="saude">
    <option value="S" <?= $isTrue; ?> />Sim</option>
    <option value="N" <?= $isFalse; ?> />Não</option>
 </select>

Outro ponto, select não possui o atributo value, quem possui esse atributo é o option que está dentro do select.
Por último, mas não menos importante, o textarea também não possui o atributo value. Diferente dos inputs, que é uma tag sem fechamento, o textarea precisa de tag de abertura e fechamento. O conteúdo/valor do textarea deve ser inserido entre as tags:
<textarea class="areat" name="quaismedicamentos" placeholder="Rascunho"><?=  $resultado[0]['quaismedicamentos']; ?></textarea>

Outras considerações
Em todo o seu código, você está utilizando print_r, print_r não é para output do valor da variável, e sim para exibir as informações, com uma fácil leitura (human-readable), de uma variável. No seu caso, você deve usar apenas print ou echo.
O seu HTML também está com alguns problemas, por isso não há o retorno certo para salvar no banco de dados.
O radio está com nomes diferentes. O primeiro está Sexo e o segundo sexo. Ele é case sensitive, deve manter sempre o mesmo case.
Já no caso do checkbox, ele deve ser tratado como array. Nesse caso, todos os seus inputs do tipo checkbox devem ter o name com a simbologia do array (name="examesf[]").
Então, seus checkbox seriam:
<input type="checkbox" name="examesf[]"/>

Lá no PHP, você pode iterar sobre os valores selecionados:
foreach($_POST['examesf'] as $value)
{
    echo $value;
}

Somente para explicação. Se o checkbox possuir um valor setado (value), somente valores selecionados serão enviados ao PHP. Se o checkbox for de name único e não possuir valor, o PHP receberá o valor (On/Off).
Comment: ajudou bastante, porem estou com dificuldade no 'selected' naõ estou consigo passar os valores do 'option', queria saber se essa e a unica maneira, ou se que estou fazendo errado então. Outra coisa no 'checkbox' estou com dificuldade mas isso deve ser pq não estou salvado certo no banco, pq no check tem 5 ou 3 opções e no banco só salva 1 mesmo marcando todas as opções juntas, apenas salva 1 opção. no no html com os checkbox te esta assim so 'name=exames' 'value=sangue', 'value=urina', 'value=sem exame',
Comment: @BrunoD.assis Qual está sendo o problema com o `select`? Atualize sua questão com a dificuldade. Quanto a questão do `checkbox` é porque sua modelagem está errada. Precisa ter uma segunda tabela para salvar os dados dos `checkbox` e relacionar com o registro que você salva. De uma olhada [nesse artigo](http://rberaldo.com.br/usando-campos-multivalorados/). De qualquer forma, essa última questão seria interessante ser uma outra pergunta (pois, o foco dessa aqui é outro).