Practical significance, especially with percents: "standard" measure and threshold

Question: I, like many people, dislike statistical significance testing. I would much rather measure "practical significance" / effect size.
The problem is that I do not know of a "standard" way of doing so. Many people say that there is no standard way to measure practical significance -- it all depends on the problem. I completely agree, but I need to be able to cite someone authoritative to back up what I am doing. I think this is the reason that statistical significance testing is so prevalent -- there is a standard way of doing it: p < .05. So anyone can do it with little thinking. The way to get practical significance testing to be more popular might be to take a similar approach.
More specifically, I often need to see if two percents are practically different from each other. What is a good way of doing so -- something with an authoritative citation and which is easy to explain intuitively?
Odds ratio? What's a good citation for using it to measure practical significance? In health / social sciences would be a plus. Odds ratios are difficult to present intuitively though. Ideas on that?
Going one step further, what is a good "standard" / "magical" threshold for an OR (or whatever measure you like)? Like .05 for statistical significance testing. I know, I know, it depends on the problem. But is there a "standard" one with a good citation?
Comment: practical significance is a vague term. please indicate its relevance to statistical significance.
Answer: I do a lot of statistical consulting and am commonly ask the question "How many subjects do I need to recruit?"  I always address the sample size question in terms of "clinical" or "practical" significance.  To address that I ask them to describe how large a difference "effect size" would they want to have to claim a difference between the groups.  What you call a test of "statistical" significance is really a test of practical significance because even though the critical value is set based on a standard statistical significance level such as 0.05, the sample size is dictated by the power to detect a clinically or practically significant difference.  There is no standar way to do this because the level that is called clinically significant is subjective and rightfully so.
Comment: @SubhashC.Davar Sadly Michael R. Chernick passed away 2 years ago. You can read obituaries here: https://magazine.amstat.org/blog/2021/03/01/obituary-michael-ross-chernick/ and here https://www.fluehr.com/obituary-detail.php?obitid=4630 . Maybe you should ask a new separate question; someone else might be able to offer you the information or clarification you're looking for in a detailed answer.
Comment: What you call a test of "statistical" significance is really a test of practical significance because even though the critical value is set based on a standard statistical significance level such as 0.05, the sample size is dictated by the power to detect a clinically or practically. " - quite confusing.  Validation and statistical methods do not have same genesis? How the two :statistical significance and practical or clinical significance can be equated?
Answer: I don't think there is any kind of test for practical significance because it really depends on the field or the problem. Sorry.
For example, if you find that implementing a certain policy increases revenue by $0.0000001, (some negligibly small amount) even though this might be statistically significant, i.e, p-value < 0.05, practically the policy has negligible effect, so it is not practically significant. But the only way to tell about whether results are practically significant is too have good understanding of the problem. In some other cases coefficient of 0.0000001 could be very practically significant.
So basically, first you use statistical tools to see if something is statistically significant, and then use your knowledge of the field to see if something is practically significant. That's ideal case of course. Very often people try to pretend that their results are practically significant if they are statistically significant.
Comment: @Jessica Though I like your measure, I kind of agree with Akavall. A finding with a Q equal to 2 in personal psychology (where it is very difficult to find high correlations) is going to be viewed as more significant than if you find that kind of correlation in a gene expression study (where it is often easy to find correlations between members of the same signaling pathway). Not saying it can't be done, but I think you might want to look into some way of comparing effects to other known ones in the field.
Comment: In the context of $y = a+bx$, I think a good measure of practical significance is $Q = b\sigma_x/\sigma_y$ (is there a name for this?). It measures the change (in SD's) in $y$ for a 1 SD change in $x$. Thus, you could say something like:

Q < 1/3: very low effect;
Q < 1/2: low effect;
Q 1/2 to 2: medium effect;
Q > 2: high effect;
Q > 3: very high effect.

In your example, all I need to know is that $b = 0.0000001$ and the SD's of $y$ and $x$.
Comment: If you standardize your $x$-values by subtracting the mean & dividing by the SD, & standardize $Y$ similarly, you get the measure I think you're going for here. Namely, the slope becomes $r$, Pearson's correlation coefficient.
Answer: More than likely, if you're writing a paper, you're well on your way to what you need for practical significance.  You've reviewed the literature and studied the subject matter and people have said, either explicitly or implicitly, what a practically significant amount is.  All you need to do is cite that literature and use it in your article.  If you want something just on the utility of effect sizes just google search effect size and your field (and perhaps cohen, 1962).  Often there are effect size promotion papers specific to various disciplines.  You could also look at Cohen 1962 as an example of how this kind of problem is approached (but not an example of what effect size is practically significant in your case-- it's unfortunate typical use).
There is no odds ratio that's a gold standard but I'm a bit surprised you're having a hard to explaining one.  I suppose it's not surprising giving most textbook treatments.  Betting uses odds ratios all of the time and people are familiar with it.  If you need to explain it use that analogy.  The odds of "Come by Chance" winning the race is 3:1 (or 3).  Most people know what that means in payout.  And they can see it's the number of times the horse is expected to lose the race (3) against the number of times it would win (1), or 75% of the time.
Of course, if this isn't just some proportion but something like a diagnostic odds ratio it's probably best to also be expressing things in specificity and sensitivity as well.  Odds ratios alone miss bias in that case (and other similar ones where it is important).
Answer: To add to most other answers, as you were looking for references, below you'll find some saying that you should avoid using arbitrary thresholds.
Note that there are various standardized effect sizes established by Jacob Cohen on a "small/medium/large" scale; you can find some specific examples on the wikipedia article about effect size. These thresholds or standards  seem to be quoted in the documentation of some statistical software too. But if you dig a bit, you'll realize that even Cohen advised against using this "small/medium/large" standard -or any arbitrary standard, for that matter. See several of his quotes at the end of this answer, taken from the book where he established this "small/medium/large" standard.
Here are some reliable references about the problems caused by using standardized effect sizes:
Glass, G.V., B. McGaw, and M.L. Smith, in Meta-Analysis in Social Research (1981):

There is no wisdom whatsoever in attempting to associate regions of
the effect size metric with descriptive adjectives such as "small,"
"moderate," "large," and the like. Dissociated from a context of
decision and comparative value, there is little inherent value to an
effect size of 3.5 or .2. Depending on what benefits can be achieved
at what cost, an effect size of 2.0 might be "poor" and one of .1
might be "good."

Kelley, K. and Preacher, K.J., On Effect Size (2012), https://doi.org/10.1037/a0028086:

Consequently, as tempting as it may be, the idea of linking universal
descriptive terms (e.g., "small," "moderate," or "large") to specific
effect sizes is largely unnecessary and at times misleading (e.g.,
Baguley, 2009; Lenth, 2001; Robinson et al., 2003; B. Thompson, 2002).
Our view is that the meaningfulness of an effect is inextricably tied
to the particular area, research design, population of interest, and
research goal, and it would be inappropriate to wed effect size to
some necessarily arbitrary suggestion of substantive significance

Harrell, F., Statistical Problems to Document and to Avoid:  Checklist for Authors (2020):

Many researchers use Cohen's standardized effect sizes in planning a
study. This has the advantage of not requiring pilot data. But such
effect sizes are not biologically meaningful and may hide important
issues as discussed by Lenth. Studies should be designed on the
basis of effects that are relevant to the investigator and human
subjects. [...]

Even Jacob Cohen, who established the "small/medium/large" thresholds in his book Statistical Power Analysis for the Behavioral Sciences (1988, second edition), repeatedly and unequivocally warned against their use, and considered them as a last resort. In other words, even if you consider they might have some value (which may be debated, as seen in previous quotes), Cohen considered that you should avoid them as much as possible. For example, page 25 of his book, about the effect size $d$:

The terms "small," "medium," and "large" are relative, not only to
each other, but to the area of behavioral science or even more
particularly to the specific content and research method being
employed in any given investigation (see Sections 1.4 and 11.1). In
the face of this relativity, there is a certain risk inherent in
offering conventional operational definitions for these terms for use
in power analysis in as diverse a field of inquiry as behavioral
science. This risk is nevertheless accepted in the belief that more is
to be gained than lost by supplying a common conventional frame of
reference which is recommended for use only when no better basis for
estimating the ES index is available.

p.113, about the effect size $q$:

Again, the reader is urged to avoid the use of these conventions, if
he can, in favor of exact values provided by theory.

p.147, about the effect size $g$:

It must be reiterated, however, that a basis for positing $g$ which
comes from theory or experience should automatically take precedence
over these conventions.

p.184, about Cohen's $h$:

As before, the reader is counseled to avoid the use of these
conventions, if he can, in favor of exact values provided by theory or
experience in the specific area in which he is working.

p.224, about the effect size $\omega$:

The best guide here, as always, is the development of some sense of
magnitude ad hoc, for a particular problem or a particular field.

and so on.
Answer: After further reading, here is one possible answer to my own question. If you have other answers along the same lines, please post them as well.
Cohen's h from Cohen (1988).
$h = |2\arcsin\sqrt{p_1}-2\arcsin\sqrt{p_2}|$
Qualification of effect sizes, with the disclaimer that they might be different in other disciplines,

$h = 0.2$: "small"
$h = 0.5$: "medium"
$h = 0.8$: "large"

In R, http://rss.acs.unt.edu/Rdoc/library/pwr/html/ES.h.html
Comment: [tag:effect-size] is a very broad class of statistical estimation. It's not a bad potential answer to your question though.


How to set a dynamic url on blueimp/jQuery-File-Upload

Question: I'm trying to implement this plugin, and i can't make it work with change dynamically the url,
Example, once i have init the plugin:
$('#image').fileupload({...})

I call the following method to set id:
function setUrl(id) {
    var uploadUrl = '/api/products/' + id + '/images';
    // config upload url
    $('#image').fileupload("option", "url", uploadUrl);
}

but i've these error line:
"Uncaught Error: cannot call methods on fileupload prior to initialization; attempted to call method 'option'"

How can I solve it?
Comment: Overwriting the initialization $('#image').fileupload() on the method and setting url param inside, doesn't works, its always the same url param
Answer: you could set the url in add callback, as:
fileupload({
   add: function(e, data) {
      data.url = '/api/products/' + id + '/images';
      ...
   },
   ...
}

Comment: Make sure to do a `data.submit();` inside your function, else the file won't be submitted to the server.
Comment: Hi DemoUser, I probably making a big mistake... i've put that code inside the method setURL, that gets and id and sets the new URL. But **id** param is always the same inside data.url, before that i've checked the id and its the right one, but it seems that is keeping on fileupload config


How to connect a virtual NIC in one QEMU-KVM instance to a virtual NIC in another QEMU-KVM instance without a bridge

Question: Is there a way to connect a Virtual NIC one QEMU-KVM instance to a Virtual NIC on another QEMU-KVM instance. I want to be able to do this efficiently and it may be possible that the 2 instances could be on local or remote machines.
I understand the use of TAP interfaces tied a bridge. But I am trying to create point to point connections between Virtual NICs in different QEMU-KVM instances
Answer: Qemu simply maps the v-NIC to a tap, whatever you plug the tap into is up to you. Bridge is the obvious choice, but there's also openvswitch, for example.
Comment: what is wrong with using a bridge between the two? It doesn't have to also use a physical NIC, unless you need to get out of the host
Comment: I really want to to connect the TAP1(connected to vNIC1/VM1) to TAP2(connected to vNIC2/VM2) back to back. Locally and possibly remotely. Can't figure out how to do that.


Routing error for create action

Question: Iam new to rails ,Iam getting the above error don't know why.i have a link from where Iam getting values and storing in controller
    <%= link_to "Add Stocks " ,userstocks_path(user:
    current_user,short_code: @stock.short_code,stock_id: @stock.id ?
    @stock.id : '' ),class: "btn btn-primary"%>

my controller create action
 def create
     if params[:stock_id].present?
     @userstock = Userstock.new(stock_id: params[:stock_id],user: current_user)
      end
   respond_to do |format|
   if @userstock.save
    format.html { redirect_to users_my_portfolio_path   , notice: 'Userstock was successfully created.' }
    format.json { render :show, status: :created, location: @userstock }
  end
 end
end

my routes
    resources :userstocks,except: [:show,:edit,:update,:index]

Instead of going to post request in userstocks_path its going to index of userstocks_path .and if the remove "except: :index" from routes its giving me template error in console .any solutions
Comment: Did you try with `new_userstock_path` instead `userstocks_path`, or to what method do you want to make a request?
Comment: actually userstock is a scaffold in which I dont require form.just wanna use create action in userstocks controller.
Answer: Reason being you need to define method type with link_to as per REST index(method type is 'get') and create(method type is 'post') action both has same routes but the difference is their method type. your can see it by command rake routes | grep userstocks
try this -
<%= link_to "Add Stocks " ,userstocks_path(user:
    current_user,short_code: @stock.short_code,stock_id: @stock.id ?
    @stock.id : '' ),:method=> :post, class: "btn btn-primary"%>

thank you.

Routing error for create action


NBA rule - how far does the ball have to go in the hoop to count for points?

Question: Say the ball goes in halfway past the rim, and an opponent knocks the ball back upwards and out. Does this count for points? How far does the ball have to pass the rim to count as a successful score?
Comment: Another interesting question, if the ball goes partially in the hoop, then somehow rolls out on it's own, is this a bucket, or no?
Comment: @New-To-IT Even more interesting to hear how that could happen? Laws of physics is hard to beat.
Comment: @New-To-IT I'm imagining the ball is rotating clockwise, falling down and to the right, then hitting the right edge of the rim so that its rotation would push the ball up. If the ball is spinning fast enough it could get out of the hoop
Answer: That would be illegal and considered interference.
From NBA rule 11, section I

A player should not :
  b. Touch any ball from within the playing area when it is above the basket ring and within the imaginary cylinder.
g. Touch the ball at any time with a hand which is through the basket ring.
i. Touch the rim, net or ball while the ball is in the net, preventing it from clearing the basket.
PENALTY: If the violation is at the opponent's basket, the offended team is awarded two points, if the attempt is from the two point zone and three points if it is from the three point zone. The crediting of the score and subsequent procedure is the same as if the awarded score has resulted from the ball having gone through the basket, except that the official shall hand the ball to a player of the team entitled to the throw-in. If the violation is at a team's own basket, no points can be scored and the ball is awarded to the offended team at the free throw line extended on either sideline. If there is a violation by both teams, no points can be scored, play shall be resumed by a jump ball between any two opponents in the game at the center circle.

NBA rules 2014-2015
Comment: What is the punishment for interference in this case? Does the shooter get the points, or is it a free throw or something else?
Comment: @Fillet It depends on where it happens. I edited in the penalty


Is $(function () {}) same to $(document).ready(function(){});

Question: As title says, I am not sure about  $(function () {})
Test:
$(function () {console.log("one")});

And at the bottom of body:
 console.log("two");

the console prints two , one
Does it mean $(function () {})  is the same as $(document).ready(function(){}); ?
Comment: This question appears to be off-topic because it is easily answered by [*reading the fine manual*](http://api.jquery.com/jQuery/#jQuery3)
Comment: thank you , I am a newer. and I want to post a question , but it always says "It looks like your post is mostly code; please add some more details.", could you help me , thank you
Answer: Yes, just $(function(){ }) is short-hand.
See the jQuery(callback) overload documentation.


Mini-SAS Connector Puzzle

Question: Can anyone clearly define the difference between the Mini-SAS HD SFF-8644 and SFF-8614 connectors please?
The SFF-8644 seems to be the more widely recognised 'male' connector but SFF-8614 seems also to be in use. I cannot find if there is any discernible difference between the two but I don't want to order cables with the wrong type of connector.
The one possibility I have come across is that the 8614 is the 4-lane version and the 8644 is the 8-lane version although it does specify "8-lane with dual connector" which muddies the water somewhat. I would appreciate confirmation of this if anyone knows for sure as this is from Wikipedia (Serial-Attached SCSI).
Thanks
Answer: An interesting question which I thought I would have a go at answering.
Seagate provide a list of the SFF specifications but all of the links direct you to the current host, the Storage Networking Industry Association (SNIA). Here we can search for each specification which yields the following.

SFF-8613 / SFF-8643
SFF-8614 / SFF-8644

If we take a look inside SFF-8614 there is the following note:

Update History:
The content of this specification was formerly contained in SFF-8644, and it was
  broken out into a separate specification so that it could be referenced by higher
  speed variations.

Reading the two specifications my interpretation follows.
The content which was moved to SFF-8614 discusses the physical form of the connectors; both the "fixed" part (socket) and the "free" part (plug). There's even a heat sink specification for a socket (!).
The content of SFF-8644 which remains is almost nothing. The only purpose I can see to this document now is a link between the physical form (which the document refers to as the "Connector Mechanical") with the SAS-3 PCIe 3.0 Application Interface (what I tend to think of as the electrical specification, or signal specification).
I haven't had time to digest the details but SFF-8644 contains an illustration taken from SFF-8614 and it looks like an SFF-8644 connector may be x4 or x8 and I would assume the cable assembly should specify which (although perhaps x4 is 'normal enough' to go unspecified, with x8 being explicitly stated). I've uploaded a copy of Figure 4-1 General View of Configurations below from SFF-8644 to illustrate.
The SFF-8614 spec also states:

2.1 Industry Documents
The following interface standards and specifications are relevant to this
  Specification.

INCITS 519 SAS-3 (Serial Attached SCSI 3)
INCITS 534 SAS-4 (Serial Attached SCSI 4)
SFF-8410 High Speed Serial Testing for Copper Links
SFF-8643 Mini Multilane 4/8X 12 Gb/s Unshielded Connector (HD12un)
SFF-8644 Mini Multilane 4/8X 12 Gb/s Shielded Connector (HD12sh)
SFF-8673 Mini Multilane 4/8X 24 Gb/s Unshielded Connector (HD24un)
SFF-8674 Mini Multilane 4/8X 24 Gb/s Shielded Connector (HD24sh)

This makes it slightly more clear that you probably want to buy SFF-864{3,4} or SFF-867{3,4} cables, rather than SFF-861{3,4}. With the 3 variants being un-shielded (presumably internal) and 4 variants being shielded (presumably external).
I hope this helps your understanding. It has certainly helped mine!

Mini-SAS Connector Puzzle


Find the number of ways giving name tags such that there exist a student who don't exit the table after 4 operations.

Question: Question:

There are $n$ students sitting at a round table. You collect all $ n $ name tags and give them back arbitrarily. Each student gets one of the $n$ name tags. Now the $n$ students repeat following operation:

The students who have their own name tags leave the table. The other students give their name tags to the student who is sitting to their right.

Find the number of ways of giving out the name tags such that there is a student who doesn't leave the table after $4$ repetitions of the operation.

I see some discussion that it is not true, but I think their result is true (because my English is not very good, so I only use Chinese say, that's you know what I mean). And I think this is an interesting problem. Now I can't have important key idea for this problem:Final Korean Mathematical Olympiad 2014, #3, and can see
mathlinks:
Answer: This doesn't get as far as you probably want, but it may help somebody.  Let the number of students after one round be $p$, after two rounds be $q$, three rounds be $r$, and four rounds be $s$.  At the end of round three we have $r-s$ students with their own nametags and $s$ students with a derangement of theirs.  The derangement can be chosen in (the closest natural to) $\frac {s!}e=\lfloor \frac {s!}e+\frac 12 \rfloor$ ways.  We can select the students that leave in ${n \choose p}{p \choose q}{q \choose r}{r \choose s}$ ways, so the final result is $$\sum_{p=2}^n\sum_{q=2}^p\sum_{r=2}^q\sum_{s=2}^r {n \choose p}{p \choose q}{q \choose r}{r \choose s}\left \lfloor \frac {s!}e+\frac 12 \right \rfloor$$ where the sum starts from $2$ because you can't have just one student left.  The last term in the sum is zero for $s=1$


Definir CMD como terminal padrão do VSCode

Question: Eu tenho usado o terminal no VSCode bastante esses últimos dias, porém toda vez que eu abro o terminal ele muda de CMD para o PowerShell.

Queria saber se a uma forma de definir o CMD como padrão.
Pra ficar sempre assim:
Answer: Basta clicar na setinha :

Depois clicar em Selecionar o Perfil Padrão:

E aí seleciona o CMD:


Space between FlatButton in flutter

Question: enter image description hereHello I am making an application where i need to maximize and minimise the screen.But i want to reduce space between 'A+'(i.e. maximising the screen) and 'A-'(i.e. minimising).I am attaching an image for better understanding.Thank you.

Here is the code:

return Scaffold(
      appBar: AppBar(
        title: Text(''),
        backgroundColor: Color(0xFF125688),
        actions: <Widget>[
           FlatButton(
                padding: EdgeInsets.all(0),
                onPressed: null,
                child: Text('A+',style: TextStyle(
                  fontSize: 22.0,fontWeight: FontWeight.bold,color: Colors.white
                ),)),

          FlatButton(
            padding: EdgeInsets.all(0),
            onPressed: null,
            child: Text('A-',style: TextStyle(
                fontSize: 15.0,fontWeight: FontWeight.bold,color: Colors.white
            ),),

          )

        ],
      ),

Answer: Use SizedBox
Scaffold(
      appBar: AppBar(
        title: Text(''),
        titleSpacing: 10,
        backgroundColor: Color(0xFF125688),
        actions: <Widget>[
           SizedBox(
             width: 30,
             child: FlatButton(
                padding: EdgeInsets.all(0),
                onPressed: null,
                child: Text('A+',style: TextStyle(
                  fontSize: 22.0,fontWeight: FontWeight.bold,color: Colors.white
                ),))),

          SizedBox(
             width: 30,
             child:FlatButton(
            padding: EdgeInsets.all(0),
            onPressed: null,
            child: Text('A-',style: TextStyle(
                fontSize: 15.0,fontWeight: FontWeight.bold,color: Colors.white
            ),),

          ))

        ],
      ))

Comment: @Chinmay use a variable for the fontsize of your content, then when tapping on A+, change your variable value with the SetState function.
Comment: It worked thank you.How can i maximize the content when i tap on A+.In  android i did using set.textsize.
Answer: Image of the Flatbutton:

Container(
        decoration: new BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Colors.blue, width: 1.0),
          borderRadius: new BorderRadius.all(Radius.circular(3.0)),
        ),
        width: double.infinity,
        child: FlatButton(
          padding: EdgeInsets.all(8.0),
          onPressed: () {
            // Write the function
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text("Add a Note"),
              Icon(
                Icons.note_add,
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ),

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask).

Space between FlatButton in flutter


how can I implement a Unity fps sprinting animation?

Question: I'm currently working on an FPS game and I have these hand models as well as weapons. But I want it so that if I press the W key (move forward) it plays the sprinting animation with the arms. I initially thought of coding it like, if(Input.getkeydown(keycode.w))animation.play or something like that. But I'm using the character controller which doesn't use that. It uses the  Input.getaxisraw. How should I implement this with the character controller?
Thank you a ton in advance
Comment: @AmirHashempour Please don't put things like "FPS" inside `code blocks`. They are not code and so it is not an improvement.
Answer: You will need to implement a basic animator controller. You can define all your states (Idle, Crouch, Jump, Sprint, Aim) and define the transitions between them. You may then add parameters like floats, triggers and booleans as conditions to transition between these states.

In the above example, if you want to move to a crouch state, you would use
GetComponent<Animator>().SetBool("Crouch", true);

Or for another example, if you want to move from Run to Walk. The transition (The blue lines indicating the movement from one state to another) will have a condition to move from walk to run and back based on the float parameter "Speed". if Speed>x, move from walk to run. else move from run to walk. In this case you would set
GetComponent<Animator>().SetFloat("Speed", floatValueHere)

and the controller will take care of the animation transitions.
This is just a pointing to the right direction. you will need to watch a couple of videos on animator controllers Check Unity's simple 8 minute explanation here Hope this helps!
Comment: Yeah but how would that work with the character controller? My current movement code is, (float x = Input.getaxisraw("horizontal");  how would work with the animator? Because it's just one line of code. Thank you very much!
Comment: Once you get the value of x in the update loop, right under it you would check for the value of x. let's say x<=0.4 means walk and x>0.4 means run. so you would do:

float x = Input.getaxisraw("horizontal");
GetComponent().SetFloat("Speed", x)

if you're using a bool for a parameter instead,

float x = Input.getaxisraw("horizontal");
if(x<=0.4)
GetComponent().SetBool("run", false)
else
GetComponent().SetBool("run", true)

and your animator would make the transition simply based on what parameters you set. Make sure the transitions are defined well.


retrieve data from localstorage to be able to publish a post

Question: Hello I would like to retrieve the user in my users table (id) so that the user can publish a post because it retrieves the userid and the token for me while I would like the userid
export default function Share() {
    const [publier, setPublier] = useState('')

    const handlePublier = (e) => {
        setPublier(e.target.value)
      }
    const register = () => {
        const posterId = localStorage.getItem('users')
        let objSo = JSON.parse(posterId)
        const poster = objSo.user
        axios.post('http://localhost:4200/api/post/',
         { posterId: posterId, message: publier }).then((response) =>{ console.log(response) })

    }

  return (

            <input placeholder='Que veux-tu publier ?' className='shareInput' onChange={handlePublier} />

                    <PermMedia htmlColor='tomato' className='shareIcon' />
                    Photo ou Vidèo

                <button className='shareButton' onClick={register}>Publier</button>

  )
}

Comment: can you be more clear what's the issue is ?
Comment: @AmanSadhwani sorry is it better this way? I would like to retrieve the user in the users table and only the user, not the token
Answer: Well, it seems that you aren't passing the const poster = objSo.user to axios at all.
See if this works:
const register = () => {
    const posterId = localStorage.getItem('users')
    let objSo = JSON.parse(posterId)
    const poster = objSo.user

    axios.post('http://localhost:4200/api/post/',
     // Passing `poster` which I assume is the `user` id that you want
     { posterId: poster, message: publier }).then((response) =>{ console.log(response) })

}


Proving $A_1^c,A_2, ... ,A_n$ are independent.

Question: Let $A_1,\ldots, A_n$ be independent events. Prove $A_1^c,A_2,\ldots, A_n$ are independent as well.

So I wish to reference a question posted by Jeffrey Anders: How can I prove that $A_1^c, A_2,A_3,A_4,\dots,A_n$ are independent events and more specifically an answer given by BCLC.

I've proven the base of my induction and am now stuck in the step. I assume $A_1^c,A_2,\ldots, A_{n-1}$ are independent, knowing $A_1,\ldots, A_n$ are independent from the datum.
Now from the assumption: $$\forall I \in [n-1]: P(\cap_{i\in I}A_i)=P(\Pi_{i \in I}A_i)$$
Therefore assume $I \in [n]$. Now I have:$$P(\cap_{i\in I}A_i)=P(\cap_{i \in I \setminus\{n,1\}}A_i \cap A_n \cap A_1^c)$$
I want to say: $\cap_{i \in I \setminus\{n,1\}}A_i \cap A_n$ is independent from the datum, and $\cap_{i \in I \setminus\{n,1\}}A_i \cap A_1^c$ is independent form the assumption of the induction.
Now denote:
$$P(A_1^c \cap A_n) = P(A_n)-P(A_1 \cap A_n)=P(A_n)-P(A_1)P(A_n)=P(A_n)(1-P(A_1))=P(A_n)P(A_1^c)$$
$\implies \cap_{i \in I \setminus\{n,1\}}A_i \cap A_n \cap A_1^c$ is independent and:
$$P(\cap_{i \in I \setminus\{n,1\}}A_i \cap A_n \cap A_1^c) = \Pi_{i \in I} \cap_{i \in I \setminus\{n,1\}}A_i \cap A_n \cap A_1^c$$
Now is this the way to prove my induction or did I just babble nonsense?
Thanks in advance!
Answer: $P(n)$: Let $A_1,...A_n$ be independent events, then $A_1',A_2,...,A_n$ are also independent.
$P(1)$ is trivial. Let $P(n-1)$ hold. To show that $B_1=A_1',B_2=A_2,...,B_n=A_n$ are independent, we need to prove for any subset $I$ of $[n]$:
$$P(\cap_{i\in I}B_i)=\Pi_{i \in I}P(B_i).$$
As $P(n-1)$ holds and consideting the assupmtion, for all $|I| \le n-1$, the above holds. Hence, we need to prove it only for $I=[n]$, which is shown below:
$$P(A_1'\cap_{i=2}^nA_i)=P(\cap_{i=2}^nA_i)-P(A_1\cap_{i=2}^nA_i)=(1-P(A_1))P(\cap_{i=2}^nA_i)
=P(A'_1)\Pi_{i=2}^{n}P(A_i).$$


Paypal DonationForm not passing dropdown option name item to paypal

Question: This code is not passing the dropdown item name to paypal. I don't know what is wrong with it.
    <form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">

    <input type="hidden" name="cmd" value="_donations">

    <input type="hidden" name="business" value="firstname.lastname@example.com">
    <input type="hidden" name="item_name">
    <input type="hidden" name="item_number" value="WF-1001">
    <input type="hidden" name="tax" value="0">
    <input type="hidden" name="no_shipping" value="2">
    <input type="hidden" name="lc" value="AU">
    <input type="hidden" name="currency_code" value="AUD">

    <input type="hidden" name="return" value="https://mullumseed.org.au/thankyou">

    <input type="hidden" name="cancel_return"
value="https://mullumseed.org.au/cancel">
    <input type="hidden" name="bn" value="PP-DonationsBF:btn_donateCC_LG.gif:NonHosted">
    <input type="hidden" name="button_subtype" value="products">
    <input type="hidden" name="no_note" value="0">
    <input type="hidden" name="cn" value="Add special instructions to the seller:">
Please enter your donation amount: (Example - 10.00)

    <input type="text" name="amount" size="5">

Choose Your Organization:
    <select name="item_name">
    <option value="Widget Fund Donation - Byron Shire Chemical Free Landcare" selected>Byron Shire Chemical Free Landcare</option>
    <option value="Widget Fund Donation - Corem">Corem</option>
    <option value="Widget Fund Donation - Mullum Seed Inc">Mullum Seed Inc</option>
    <option value="Widget Fund Donation - Mullum Community Garden">Mullum Community Garden</option>
    <option value="Widget Fund Donation - Mullum Cares">Mullum Cares</option>
    <option value="Widget Fund Donation - Mullum Mens Shed">Mullum Mens Shed</option>
    <option value="Widget Fund Donation - Mullum Food Coop">Mullum Food Coop</option>
    <option value="Widget Fund Donation - Shara Community Gardens">Shara Community Gardens</option>
    <option value="Widget Fund Donation - Reforest Now">Reforest Now</option>
    <option value="Widget Fund Donation - Mullumbimbees">Reforest Now</option>
   </select>

    <input type="hidden" name="on1" value="Tax Deductable Email Receipt Requested">Would you like a Tax Deductable Email Receipt?
    <INPUT NAME="os1" type="radio" value="Yes" checked>Yes

    <INPUT NAME="os1" type="radio" value="No Thanks">No Thanks

    <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">

</form>

Answer: Remove the leftover line 6
<input type="hidden" name="item_name">

Comment: you are the best :-)


How to make program return ID after the button will be pressed?

Question:
This program return 0, need to stop/pause program, press button and then return ID.

static int ID=0;
static String log="";
static String pass="";
static SessionFactory factory;

public static int enterStudent(JPanel panel){

    panel.setLayout(null);
    JLabel jLabel=new JLabel("Login");
    panel.add(jLabel);
    jLabel.setBounds(10,10,100,30);
    JLabel jLabel1=new JLabel("Password");
    panel.add(jLabel1);
    jLabel1.setBounds(110,10,100,30);
    final JTextArea textArea=new JTextArea();
    textArea.setBounds(10,50,100,50);
    panel.add(textArea);
    final JTextArea textArea2=new JTextArea();
    textArea2.setBounds(110,50,100,50);
    panel.add(textArea2);
    JButton enterButton=new JButton("Enter");
    enterButton.setBounds(10,100,200,50);
    panel.add(enterButton);
    try {
        factory = new Configuration().configure().buildSessionFactory();
    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex);
    }

ActionListener

    enterButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e2) {
            log=textArea.getText();
            pass=textArea2.getText();
            Session session = factory.openSession();
            Transaction tx = null;
            try{
                tx = session.beginTransaction();
                List students = session.createQuery("FROM Student").list();
                for (Iterator iterator =
                             students.iterator(); iterator.hasNext();){
                    Student student = (Student) iterator.next();
                    if((student.getLogin().equals(log))&&(student.getPassword().equals(pass))){
                        ID=student.getId();//this should be returned
                        JOptionPane.showMessageDialog(null,"return="+ID);
                        break;
                    }
                }
                tx.commit();

            }catch (HibernateException e) {
                if (tx!=null) tx.rollback();
                e.printStackTrace();
            }finally {
                session.close();
            }
        }
    });

    return ID; //returns 0
}

This is function for LogIn, check login and pass in DATABASE. Need return ID of student, but program returns 0
Answer: You can't return anything from an ActionListener since its method, actionPerformed(...) is defined to return void, nothing. But fortunately you don't need to. This is a Swing GUI, and inside of your  ActionListener, display the ID within a JLabel by calling myLabel.setText(...) or display it elsewhere where it needs to be displayed. Or if you don't want to display it, then call some class's setId(...) method.
Note that the true canonical answer to this question would be to use an M-V-C or Model-View-Control type design pattern, and in your ActionListener (part of the control), set the model's id field to the value found in the database. The GUI should have listeners attached to the model that would update the GUI's state (the data it displays) if the model's state changes. But for your simple program this would probably be a bit of over-kill.
Other side recommendations:

Your code shows a significant over-use of static modifier, and doing this can make it hard to extend or enhance your program, or get it to easily work with other classes.
Your code does not follow Java naming rules, and you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.

Edit: I now see that you're trying to return an int from the enterStudent method via the JButton's ActionListener. This won't work as written because you're returning the id field before the ActionListener has completed. Solutions include use a callback method of some sort, one that is perhaps passed into your enterStudent's method parameter, or else if you use a modal dialog such as is available with a JOptionPane. Otherwise, based on this increase in complexity, then yes, you're best off using an M-V-C structure which itself is based on use of listeners (callbacks).
Comment: Thanks for the idea "display the ID ".
Answer: That means program control is not reaching this block hence your ID is getting the default defined value which is 0.
if((student.getLogin().equals(log))&&(student.getPassword().equals(pass))){
                        ID=student.getId();//this should be returned
                        JOptionPane.showMessageDialog(null,"return="+ID);
                        break;
                    }

here the if condition is not getting true which means either of getLogin() and getPassword is not having values as "".


Dominated convergence with $g$ depending on $n$

Question: I have a question about dominated convergence. Suppose I have a functions $f_n(x)$ which converge pointwise to $f(x)$. Furthermore, I know that $|f_n(x)|\leq g_n(x)$ for all $n$ and $x$, where $g_n(x)$ has limit $g(x)$.  If I also know that
$$\lim_{n\to\infty}\int g_n(x)dx=\int g(x)dx,$$ can I conclude that
$$\lim_{n\to\infty}\int f_n(x)dx=\int f(x)dx?$$
(This is basically the dominated convergence theorem, with $g$ replaced by $g_n$.)
Answer: Yes, that's the General Lebesgue Dominated Convergence Theorem except you give the additional assumption that $\lim g_n$ exists:
Answer: You can show that the following generalization of Lebesgue's dominated convergence theorem holds:
Let $\{f_n\}_{n\in\mathbb{N}}$ be a sequence of $\mu$-measurable functions $f_n:(E,\mathcal{E},\mu)\to \bar{\mathbb{R}}$. Suppose $f_n\to f$, point-wise a.e. on $E$ and there is a sequence $\{g_n\}_{n\in\mathbb{N}}$ of $\mu$-integrable functions that converge pointwise a.e. to $g$ and
$$|f_n| \leq g_n$$
for all $n \in \mathbb{N}$.
If $\int_E g_n \to \int_E g$, then $\int_E f_n \to \int_E f$.


Just starting Piano and Theory is confusing and interesting to me at the same time. Anyway resources or tips to learn?

Question: The title is basically what it is. Piano is fascinating to me and I'd like to be able to understand and play it. Theory really gets confusing for me so are there any resources or places where I can learn more theory? Right now I barely can grasp a basic understanding.
Thanks for any help!
Answer: Learn to play. Learn notation.   When you've got your fingers round some pieces, then's the time to look into how they're put together!
Answer: Music theory is a complicated topic that involves a lot of practice to truly understand. If you have a private teacher, ask them for help with anything you don't understand. And take the time to look for online resources like musictheory.net.
You can also use music theory method books like the Hal Leonard ones, Keith Snell, etc. But overall, I would suggest you play a lot of different pieces and study them carefully. Look at the way the composer modulates, how they use scales and arpeggios and chord progressions.


How to workaround a memory leak in a vendor's DLL being used in Python?

Question: I'm using a vendor's C API for a piece of business software by loading their library using Python's ctypes module.
After deploying the software I wrote, I found that the vendor's library leaks memory on a consistent and predictable basis, according to the number of calls of a certain function that's part of their API.
I even duplicated the leak in a C program that uses no heap allocations.
I contacted the vendor about the issue, and they said they're working on it, but I probably can't realistically expect a fix until the next version of the software.
I had the idea of reloading the vendor's dll after a certain threshold of calls to the leaking function, but this did not release the leaked memory.
I found that I could force the library to unload like so:
<code>_ctypes.FreeLibrary(vendor_dll._handle)
</code>
This frees the memory, but causes the interpreter to crash seemingly randomly after a number of minutes of using the vendor's API.
I found this issue in the Python bug tracker that describes my situation:
https://bugs.python.org/issue14597
It seems that if there's still an open reference to the library, forcing it to unload will inevitably crash the Python interpreter.
Worst case scenario, I'm thinking I could load the vendor's library in a separate process, proxy requests using a multiprocessing Queue, and setup a watchdog to recreate the process if the interpreter dies.
Is there a better way to work around this?
Comment: I suppose a more elegant solution to my above workaround would be to exit and relaunch the worker process on a regular interval. This would allow the memory leaked by the vendor's library to free, but wouldn't crash the interpreter.
Comment: If freeing the library works, then it's not really a memory leak. The library must be tracking these allocations to free them on `DLL_PROCESS_DETACH`. As to unloading `vendor_dll`, you should first remove all references to the current instance and ensure nothing executes its code again, including outstanding asynchronous callbacks. Then you can unload and reload the DLL. Shared libraries are reference counted, so to ensure it's actually unloaded, call `FreeLibrary` until it raises an `OSError`.
Answer: In the end, I fixed the issue by loading the vendor's library in a separate process, and accessing it through Pyro4, like so:
<code>class LibraryWorker(multiprocessing.Process):
    def __init__(self):
        super().__init__()

    def run(self):
        self.library = ctypes.windll.LoadLibrary(
            'vendor_library.dll')

        Pyro4.serveSimple(
            {self, 'library'},
            ns=False)

    def lib_func(self):
        res = self.library.func()
        return res
</code>
It was a bit of extra work to massage the old code to not pass ctypes pointers between the two processes, but it works.
With the library loaded in a separate process, I can keep track of the memory usage. When it gets too high, I can terminate and recreate the process to free the memory.
Comment: Sorry, do you have a full example of using pyro for communication between processes in one app? Somehow, I can't make it work.


.htaccess - only one referral allowed; fastcgi

Question: I am creating .htaccess file first time and it doesn't work for me.
My htaccess looks as following:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^https://(www\.)?mysite.net/.*$ [NC]
RewriteRule .* - [F]

.htaccess file is in directory that corresponds to subdomain support.somesite.com
I want to allow access only for https://www.mysite.net domain (https://www.mysite.net/qa/test.aspx and other has links to support.somesite.com)
However, above .htacess doesn't work. I ran phpinfo and see that Server API is cgi/fastcgi and not Apache. I do not know if this is an issue.
Is this something with mod_rewrite module? Can I use above htaccess with fastcgi Server API?
Answer: HTTP_REFERER does not work with https.
Comment: So what you suggest then?I have found the followign link - http://stackoverflow.com/questions/1390862/http-referer-lost-using-https This is almost my case. So I have two pages. One is https://www.mysite.net and https://www.mysite.net/qa, it is hosted on IIS and there are ASPNET pages. Another is support.somesite.com which is hosted on Apache server, but currently the client uses only html pages. I need support.somesite.com allow only https://www.mysite.net as referel. It is just for reduce traffic a bit, but it is not so important security issue. So what should I use?
Comment: I want to add that first site is https, second site is http, so I am linking from https to http.
Comment: That's it. When you're from an https page, the HTTP_REFERER header is not available. I don't have anything else to suggest, just follow what was suggested in that SO question. Basically, add a secret into the url (so that the url linked from mysite.net/qa changes every time) and verify it in your 2nd site, a secret is like (REMOTE_ADDR, hmac(REMOTE_ADDR)) where hmac is just like a hash function. However, IMHO traffic is cheap and in this case you should not do anything.


minifying js & css with one min file for each jsp page

Question: I have around 5 major JSPs in my website. Each jsp includes multiple js and css files. I want to minify both the js and css, with one js&css per JSP.
All the plugins which are available speaks about one js & css for entire website, but I would rather want is to have one js/css per JSP. Otherwise on home page loading itself, it would download the full js/css which I donot want.
Can any one please suggest any solution for the same.
Thanks,
Harish
Answer: If those files are just static, then it's better to just pack them into one CSS and one JS. That way, the next few pages will only load the cached versions. But yes, you can still do packing per JSP for ligher pages especially for mobile.
As for tools, there are a lot. YUI Compressor and Google Closure Compiler are usually top picks.


Como separar HTML do PHP

Question: Li em vários lugares que não se deve misturar PHP com HTML e vice-versa,
Como então poderia separar esse código por exemplo:
<?php include 'C:\xampp\htdocs\trabweb\sessaoBD.php' ?>

<!DOCTYPE html>

  <title>Trabalho web</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="http://localhost/trabweb/css/style_hashbase.css">

<?php include 'C:\xampp\htdocs\trabweb\header.html' ?>

  <?php if ($login === true and $_SESSION["user_name"] === "lucas"): ?>
    *NEW POST*

    <?php endif; ?>

          <?php
          $sql =  "select titulo,id from POSTS";
          //$sql = "DELETE FROM POSTS" ;
          $result = $conn->query($sql);
          if ($conn->query($sql) === false) {
              echo "Error: " . $sql . "
" . $conn->error;
          }
          if ($result->num_rows > 0) {
              // output data of each row
              while ($row = $result->fetch_assoc()) {
                  echo  ''.$row["titulo"].'
'; //cada post é um link para o seu conteudo
              }
          } else {
              echo "0 results";
          }
          ?>

Comment: Já eu recomendaria ficar bem longe de frameworks por hora. Se não domina o básico, não tem sentido querer dominar o *avançado*. Como sempre digo: frameworks são soluções para problemas específicos. Usá-los para uma finalidade diferente é um erro que traz mais prejuízos que benefícios.
Comment: Se você quer montar o HTML com o PHP, essencialmente terá que *misturar* os dois. O que você pode fazer aí é separar as coisas: PHP que define layout de PHP que define lógica, como por exemplo a execução da SQL.
Comment: estuda sobre MVC uma boa seria utilizar uma framework chamada Phalcon a estrutura dela ja permite criação de layouts e a performance dela é a melhor
Comment: Lucas a melhor forma de separar o php do html é usando algum framework de templates.
Atualmente o Twig (template engine) ou blade atende bastante essa necessidade. Se você você estiver usando o php sem framework o twig pode cair muito bem...
Answer: Primeiro, usando caminhos fixos vão complicar para você publicar. No servidor não será esse caminho.
Segundo, quase tudo o que você vê por aí sobre programação é escrito por gente que não entende do que está falando, são pessoas que também leram em algum lugar e ficam repetindo sem entender o motivador e contexto. Vira um "telefone sem fio". Só acredite em coisas que expliquem o porquê.
Não dá para separar totalmente em páginas que precisam ser construídas dinamicamente (e é um erros as pessoas tentarem fazer tudo ser dinâmico). Dá para minimizar o uso e separar a lógica mais complexa em outro arquivo. Mas só faz sentido como uma forma de organizar tudo coerentemente, só fazer uma separação simples não ajuda muito, é só pra "cumprir tabela".
Se precisa de comentários é porque o código está confuso demais. Não vou consertar vários problemas nele, só mostrar o que foi perguntado.
Para fazer certo seria complicado mostrar aqui, mas a grosso modo basicamente é abstração do que precisa separar.
<?php include 'sessaoBD.php' ?>
<!DOCTYPE html>

  <title>Trabalho web</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="css/style_hashbase.css">

<?php include 'header.html' ?>

         <?php if ($login and $_SESSION["user_name"] === "lucas"): ?>
             *NEW POST*

         <?php endif;
         getPosts();
         ?>

Postagens.php
<?php
function getPosts() {
    $sql =  "select titulo, id from POSTS";
    $result = $conn->query($sql);
    if ($conn->query($sql) === false) echo "Error: " . $sql . "
" . $conn->error;
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo  ''.$row["titulo"].'
';
        }
    } else echo "0 results";
}
?>

Coloquei no GitHub para referência futura.
Ao contrário do que está sendo dito por outros, eu não recomendo estudar MVC. Primeiro porque é mais complicado para um iniciante e que está tendo dificuldade bem básicas ainda. Segundo porque há uma corrente que já percebeu que MVC é canhão para matar passarinho na maioria dos cenários web. Ele serve para projetos grandes com muita lógica, onde realmente precisa gerenciar complexidade, mas para pequenos projetos, que é a esmagadora maioria dos casos ele só adiciona complexidade sem trazer vantagens, por isso frameworks mais recentes tem preferido uma abordagem mais simples (e não estou recomendando o uso deles, antigos ou modernos).
Comment: É apenas um trabalho da universidade, então não vou precisar publicar.

"Quase tudo o que você vê por aí sobre programação é escrito por gente que não entende do que está falando", anotado : ) .

os comentários são porque o professor pediu mesmo.

Agradeceria se me falasse algum desses erros.

"E não estou recomendando o uso deles, antigos ou modernos" anotado.

Vou deixar como está então, obrigado.
Comment: A lista é grande demais pra listar :) O modelo básico que está seguindo funciona, o erro é como organizar isso da maneira como se faz em situações reais de mercado.
Comment: (T_T) , : D , vou perguntar ao professor quando tiver a opurtunidade.
Answer: Cara, um pouco de PHP e HTML sempre acaba misturando, por exemplo os includes e o IF podem ficar ai tranquilamente, o que você poderia separar é essa parte:
<?php
   $sql =  "select titulo,id from POSTS";
   //$sql = "DELETE FROM POSTS" ;
   $result = $conn->query($sql);
   if ($conn->query($sql) === false) {
       echo "Error: " . $sql . "
" . $conn->error;
   }
   if ($result->num_rows > 0) {
       // output data of each row
       while ($row = $result->fetch_assoc()) {
           echo  ''.$row["titulo"].'
'; //cada post é um link para o seu conteudo
       }
   } else {
       echo "0 results";
   }
?>

Ai você tem duas opções, ou colocar esse código em um arquivo separado e simplesmente incluir ele ai, ou criar um arquivo e transformar esse código em uma função, então no código HTML você só chama essa função.
Answer: Eu acredito que um primeiro passo para você poder entender isso melhor, seria estudando a arquitetura MVC, que é uma das arquiteturas de software mais comuns. Já vai lhe abrir vários horizontes de como seu projeto pode ser bem dividido e organizado.
No seu caso, como está trabalhando com PHP, também recomendaria que desse uma olhada no framework CodeIgniter, assim como vários outros frameworks, o CodeIgniter trabalha com a arquitetura MVC, "obrigando" o desenvolvedor a trabalhar em cima dela.
Há várias outras opções de framework em PHP, como Zend, Laravel, etc. Mas acredito que dentre a maioria o CodeIgniter é um dos que possui a menor curva de aprendizado, melhor para iniciantes.
Comment: E realmente nunca vai ser regra, cada caso é um caso, então pode ser sim que você tenha que misturar PHP com HTML, não se sinta culpado por isso.
Comment: Meu professor disse que não deveria ser usado essas frameworks (esqueci de ter comentado) , mas não custa estudalas.
Comment: @lucaspelepek compreendo, acredito que a resposta do Maniero está bem de acordo na verdade, espero que tenha conseguido sanar suas dúvidas.

Como separar HTML do PHP


QML QVariantMap as ComboBox model

Question: I have this class:
//main_model.hpp
#ifndef MAIN_MODEL_H
#define MAIN_MODEL_H

#include <QObject>
#include <QVariantMap>

class MainModel : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QVariantMap map READ map NOTIFY mapChanged)

  public:
    MainModel();

    const QVariantMap& map() const { return m_map; }

  signals:
    void mapChanged();

  private:
    QVariantMap m_map;
};

#endif // MAIN_MODEL_H

And in main_model.cpp:
#include "main_model.hpp"

MainModel::MainModel()
{
  m_map.insert("KEY1", "VALUE1");
  m_map.insert("KEY2", "VALUE2");
  m_map.insert("KEY3", "VALUE3");
  emit mapChanged();
}

I have registered the MainModel class as mainModel through the QML engine, then in main.qml
Window {
    height: 640
    width: 360
    visible: true

    ComboBox {
        height: parent.height * 0.1
        width: parent.width * 0.5
        anchors.centerIn: parent
        model: mainModel.map // This is not working
    }
}

I would like to show in the ComboBox the values of the map -> ["VALUE1","VALUE2","VALUE3"], and when the ComboBox selection changes I would like to log which key was chosen. Is this possible?
Answer: ComboBox really needs something a list such as QQmlListProperty, QAbstractListModel (including QML ListModel), or a QList (e.g. QVariantList). Because you're using a QVariantMap it doesn't work because it is not list-like or array-like. QVariantMap behaves like a JavaScript object, so a quick fix would be to convert the JavaScript object to an JavaScript array using one of the following: Object.values(), Object.keys() or Object.entries. For example:
    ComboBox {
         height: parent.height * 0.1
         width: parent.width * 0.5
         anchors.centerIn: parent
         // model: mainModel.map // This is not working
         model: Object.values(mainModel.map)
    }

I know you're instantiating MainModel and assigning it directly to the context property, but, in general, the constructor of a QObject component should also support a QObject* parent property, e.g.
class MainModel : public QObject
{
  //...
  public:
    // MainModel();
    MainModel(QObject* parent = nullptr);
  //...

And the implementation, of course, should also do something with that parameter, e.g.
// MainModel::MainModel()
MainModel::MainModel(QObject* parent) : QObject(parent)
{
  m_map.insert("KEY1", "VALUE1");
  m_map.insert("KEY2", "VALUE2");
  m_map.insert("KEY3", "VALUE3");
  emit mapChanged();
}

Another quick fix would be to replace QVariantMap with QVariantList. In the following example, I also updated the Q_PROPERTY to use the default getter by using MEMBER instead of READ thus reducing the need to implement a custom getter.
// MainModel.h
#ifndef MAIN_MODEL_H
#define MAIN_MODEL_H

#include <QObject>
#include <QVariantMap>

class MainModel : public QObject
{
    Q_OBJECT
    // Q_PROPERTY(QVariantMap map READ map NOTIFY mapChanged)
    Q_PROPERTY(QVariantList list MEMBER m_list NOTIFY listChanged)

  public:
    MainModel(QObject* parent = nullptr);

    // const QVariantMap& map() const { return m_map; }

  signals:
    void listChanged();

  private:
    // QVariantMap m_map;
    QVariantList m_list;
};

#endif // MAIN_MODEL_H

// MainModel.cpp
#include "MainModel.h"

MainModel::MainModel(QObject* parent) : QObject(parent)
{
    QVariantMap map;
    map["key"] = "KEY1";
    map["value"] = "VALUE1";
    m_list.append(map);
    map["key"] = "KEY2";
    map["value"] = "VALUE2";
    m_list.append(map);
    map["key"] = "KEY3";
    map["value"] = "VALUE3";
    m_list.append(map);
    emit listChanged();
}

// main.qml
import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")
    ComboBox {
         height: parent.height * 0.1
         width: parent.width * 0.5
         anchors.centerIn: parent
         model: mainModel.list
         textRole: "key"
         valueRole: "value"
    }
}

Answer: As an addition to the great answere of @StephenQuan here the answere to your question, how to log the selection:
You can use the property change signals onCurrentIndexChanged, onCurrentTextChanged and onCurrentValueChanged
Here a small example:
ComboBox {
    textRole: "text"
    valueRole: "value"

    model: [
        { value: 1, text: "Key 1" },
        { value: 2, text: "Key 2" },
        { value: 3, text: "Key 3" }
    ]

    onCurrentIndexChanged: {
        console.log("index: " + currentIndex);
    }

    onCurrentTextChanged: {
        console.log("text:" + currentText);
    }

    onCurrentValueChanged: {
        console.log("value:" + currentValue);
    }

}

QML QVariantMap as ComboBox model


Enumerate Windows DNS Server Zone attributes via shell

Question: I'd like to use a command-line tool to list a (primary) zone's configured secondary servers, if any.
Dnscmd comes close with:
dnscmd server /ZoneResetSecondaries:[list of secondaries]

But, I don't want to clobber any current settings, I just want to review them.  PowerShell (even on Server 2012) doesn't seem to help.
Thanks.
Comment: Ah, I just found it.

Use `dnscmd server /EnumZones`

then parse the list of zones to get zonenames run `dnscmd server /ZoneInfo zonename` and finally parse the output for `Zone Secondaries`
Answer: You are most correct in that you can:

Enumerate the zones and look for the "Primary" ones
Retrieve zone info for each zone

I've previously written about parsing dnscmd output using PowerShell, and this should accomplish step 1:
function Get-DNSZones
{
    param(
    [String]$ComputerName = "."
    )

    $enumZonesExpression = "dnscmd $ComputerName /enumzones"
    $dnscmdOut = Invoke-Expression $enumZonesExpression
    if(-not($dnscmdOut[$dnscmdOut.Count - 2] -match "Command completed successfully."))
    {
        Write-Error "Failed to enumerate zones"
        return $false
    }
    else
    {
        # The output header can be found on the fifth line:
        $zoneHeader = $dnscmdOut[4]

        # Let's define the the index, or starting point, of each attribute:
        $d1 = $zoneHeader.IndexOf("Zone name")
        $d2 = $zoneHeader.IndexOf("Type")
        $d3 = $zoneHeader.IndexOf("Storage")
        $d4 = $zoneHeader.IndexOf("Properties")

        # Finally, let's put all the rows in a new array:
        $zoneList = $dnscmdOut[6..($dnscmdOut.Count - 5)]

        # This will store the zone objects when we are done:
        $zones = @()

        # Let's go through all the rows and extrapolate the information we need:
        foreach($zoneString in $zoneList)
        {
            $zoneInfo = @{
                Name       =   $zoneString.SubString($d1,$d2-$d1).Trim();
                ZoneType   =   $zoneString.SubString($d2,$d3-$d2).Trim();
                Storage    =   $zoneString.SubString($d3,$d4-$d3).Trim();
                Properties = @($zoneString.SubString($d4).Trim() -split " ")
                }
            $zoneObject = New-Object PSObject -Property $zoneInfo
            $zones += $zoneObject
        }

        return $zones
    }
}

Now you can list all Primary zones with:
Get-DNSZones|Where-Object {$_.ZoneType -eq 'Primary'}

You could then use the Zone array to automate the lookup for all the primary zones:
$PrimaryZones = Get-DNSZones|Where-Object {$_.ZoneType -eq 'Primary'}
$PrimaryZones |% {$out = iex "dnscmd . /ZoneInfo $($_.ZoneName) |find `"Zone Secondaries`" "; "$($_.ZoneName) = $out"}

Answer: Just to leave an alternative to Mathias's already great answer, here's a one-liner that works with any version of Powershell:
PS C:\> Get-WmiObject MicrosoftDNS_Zone -Namespace Root\MicrosoftDNS `
          -ComputerName DC01 | Where ZoneType -EQ 1 | `
          Select ContainerName, SecondaryServers

(ZoneType values for reference: http://msdn.microsoft.com/en-us/library/cc448936.aspx)
Edit: Duh, if using an older version of PS < 3, change the second element in the pipeline to
| Where { $_.ZoneType -EQ 1 } |
Comment: Simplicity at its best :-)


How to set photo field as not mandatory

Question: Iam new to rails, I have an image field in my form. But i did not make it as mandatory field. But when i try to bypass it and submit the form it shows an error. I am posting my error below.
When i add if params[:contact] && params[:contact][:photo] iam getting error, that is because it is trying to access the hash which is empty to avoid that i have added params[:contact][:photo].original_filename = "empty.jpg" but it also throws error
NoMethodError in ContactsController#create
undefined method `original_filename' for nil:NilClass
private
def func
    name=params[:contact][:photo].original_filename
    directory= "public/data"
    return path = File.join(directory,name)                                             end

TypeError in  ContactsController#create
no implicit conversion of nil into String
def contact_params
    File.open(func,"wb") { |f| f.write(params[:contact][:photo].read) }
    params.require(:contact).permit(:firstname, :lastname, :gender, :email_id, :mobile_number, :address)
end

Thanks for your patience.
Comment: inspect your params to see what is passed to the controller
Answer: Check if params[:contact][:photo] was actually passed to your controller before trying to access it.
private
def func
  if params[:contact] && params[:contact][:photo]
    name=params[:contact][:photo].original_filename
    directory= "public/data"
    return path = File.join(directory,name)
  else
    return nil # or whatever you'd like to return if no filename is passed
  end
end

end
I'd suggest checking out the Action Controller Rails Guide (and the Rails Guides in general) for more information.
Comment: Thanks for your reply, i have tried using the if loop as you mentioned, but it throws an error. Posting my error below and i want to use an blank contact image incase the image is not provided, i have tried it but its not working                                        TypeError in ContactsController#create
no implicit conversion of nil into String

    def contact_params
  File.open(func,"wb") { |f| f.write(params[:contact][:photo].read) }
  params.require(:contact).permit(:firstname, :lastname, :gender, :email_id, :mobile_number, :address)
 end
end
Comment: This is an entirely different issue, because it seems like the error is in your `create` method. Could you please add your `create` and `contact_params` methods to your question?
Comment: Iam posting that below
def create
  contact = Contact.new(contact_params)
  name=params[:contact][:photo].original_filename
  if contact.save
   contact.update(:photo => name )
   redirect_to @contact
  else
   render 'new'
  end
 end

def contact_params
  File.open(func,"wb") { |f| f.write(params[:contact][:photo].read) }
  params.require(:contact).permit(:firstname, :lastname, :gender, :email_id, :mobile_number, :address)
 end
Comment: A couple of things. First, when you're adding a function, please add it to your question. A function in a comment is unreadable. Second, you're doing the exact same thing that you were doing in `func`. Every time you try to call a function, method, attribute, etc. on `params[:contact][:photo]`, you need to make sure that the photo exists. Please make the change I suggested above every time you try to get the original filename of a contact's photo.
Comment: @suganyasangith any luck?
Comment: I could n't fix it iam trying, still its returning the same error message. Will you please tell how to set an empty profile image in case the image is not provided.
Comment: This line checks if the image is present: `if params[:contact] && params[:contact][:photo]`. Could you please edit your question and add any errors you're still finding?

How to set photo field as not mandatory


What happens if you reject normality of residuals when estimating with least squares?

Question: What happens if you reject normality of residuals when estimating with least squares?
Is it too important to have normality on the residuals?
Comment: in what way are the residuals non-normal?
Comment: and how did you decide to reject normality?
Comment: And how many observations do you have?
Answer: The $t$-statistic is assumed to be distributed asymptotically normally for hypothesis tests. If your residuals are severely non-normal, your $t$-statistics, $p$-values, and hypothesis tests will be meaningless.
Your $\hat{\beta}$ estimates are still okay, but you cannot express confidence in the $\beta$s.
You can try and use some form of robust standard error that controls for non-normality. Alternatively, if your dataset is very large and your $\hat{\beta}$ estimates are very far from zero, you might be able to get away with it.
Comment: I believe that statistic inference is destroyed more than implied above.  And non-normality of residuals is sometimes indicative of not having the best transformation of $Y$.
Comment: gmacfarlane, the t-test (the unequal variance version) is actually equivalent to use of robust standard errors. In samples of at least modest size and with independent observations, the property that actually matters is constant variance; if the observations in your two groups have it, the equal variance t-test will be fine. If they don't, the unequal variance t-test will _still_ be fine. Normality (or non-Normality) of the residuals is just not very important; the Central Limit Theorem takes care of the distribution of the t-statistic.
Comment: What if the error distribution is not normal by any normality test, but is symmetric and majority of the residuals are near to zero? Something like a t distribution? Assumption satisfied?


Uncaught TypeError: Cannot read property 'show' of undefined

Question: I'm making a simple brick breaker game using Java Script, and my console is showing me error while displaying blocks on to the canvas, they are being drawn onto the canvas but all the other objects are not working and console is showing

index.js:173 Uncaught TypeError: Cannot read property 'show' of undefined
at update (index.js:173)
at index.js:177

if you comment out from line no:172 and 173, which is a for loop that tells the canvas to draw them on it
everything's is working fine.

one more thing: that canvasRendering...rundedRectangle is a function that draws rounded edge rectangles
someone please find a solution!

CanvasRenderingContext2D.prototype.roundedRectangle = function(x, y, width, height, rounded) {
    const radiansInCircle = 2 * Math.PI
    const halfRadians = (2 * Math.PI)/2
    const quarterRadians = (2 * Math.PI)/4

    // top left arc
    this.arc(rounded + x, rounded + y, rounded, -quarterRadians, halfRadians, true)

    // line from top left to bottom left
    this.lineTo(x, y + height - rounded)

    // bottom left arc
    this.arc(rounded + x, height - rounded + y, rounded, halfRadians, quarterRadians, true)

    // line from bottom left to bottom right
    this.lineTo(x + width - rounded, y + height)

    // bottom right arc
    this.arc(x + width - rounded, y + height - rounded, rounded, quarterRadians, 0, true)

    // line from bottom right to top right
    this.lineTo(x + width, y + rounded)

    // top right arc
    this.arc(x + width - rounded, y + rounded, rounded, 0, -quarterRadians, true)

    // line from top right to top left
    this.lineTo(x + rounded, y)
}

var canvas= document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");

function Player(x,y,w,h){
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.show = function(){
        ctx.beginPath();
        ctx.rect(this.x, this.y, this.w, this.h);
        ctx.fillStyle = "#ffff";
        ctx.fill();
        ctx.closePath();
    }
    this.move = function(speed){
        this.x += speed;
    }
}

function Ball(x,y,r){
    this.x = x;
    this.y = y;
    this.r = r;
    this.show = function(){
        ctx.beginPath();
        ctx.arc(this.x,this.y,this.r,0,2* Math.PI);
        ctx.fillStyle = "tomato";
        ctx.fill();
        ctx.closePath();
    }
    this.move= function(speedX,speedY){
        this.show();
        this.speed = 2;
        this.x += speedX;
        this.y += speedY;
    }

}

function Block(x,y,w,h){
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.show= function(color){
        ctx.beginPath();
        ctx.roundedRectangle(this.x,this.y,this.w,this.h,7);
        ctx.fillStyle = color;
        ctx.fill();
        ctx.closePath();
    };
};

var player = new Player(canvas.width/2-50,canvas.height*0.95,100,20);
var ball = new Ball(canvas.width/2-5, player.y-20,15);
var rigthPressed = false;
var leftPressed = false;

var blocks = [];
var rowCount = 5;
var columnCount = 6;
var noInRow = 6;
var blockCount = (rowCount*columnCount)+1;
var blockRow = 0;
var blockCol = 0;

var ballSpeedX = 5;
var ballSpeedY = -10;
for(let i = 1; i < blockCount; i++){
    blocks.push(new Block(blockCol*60+25,blockRow*60+30,50,50));
    blockCol++;
    if(i % noInRow == 0){
        blockRow++;
        blockCol = 0;
    }
}

window.addEventListener("keydown", function(e){
    if(e.keyCode == 39){
        rigthPressed = true;
    }
    if(e.keyCode == 37){
        leftPressed = true;
    }
});
window.addEventListener("keyup", function(e){
    if(e.keyCode == 39){
        rigthPressed = false;
    }
    if(e.keyCode == 37){
        leftPressed = false;
    }
});

function objMovement(){
    if(rigthPressed){
        player.move(5);
        if (player.x > canvas.width-player.w){
            player.x = canvas.width-player.w;
        }
    }
    if(leftPressed){
        player.move(-5);
        if(player.x < 0){
            player.x = 0;
        }
    }

    if(ball.x > canvas.width-ball.r || ball.x < 0+ball.r){
        ballSpeedX = -ballSpeedX;
    }
    if (ball.y > canvas.height-ball.r || ball.y < 0+ball.r){
        ballSpeedY = -ballSpeedY;
    }
    if(ball.x<player.x+player.w &&ball.x>player.x && ball.y>player.y){
        ballSpeedY = -ballSpeedY;
        ballSpeedX= ballSpeedX;
    }
    function Bump(){
        if (ball.x>player.x && ball.x<player.x+player.w/2){
            if (ball.y >= player.y){
                ballSpeedX = -5;
            }
        }
        if(ball.x>player.x+player.w/2 && ball.x<player.x+player.w){
            if(ball.y >= player.y){
                ballSpeedX = 5;
            }
        }
    }
    //Bump();
}

function update(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ball.show();
    ball.move(ballSpeedX,ballSpeedY);
    player.show();
    objMovement();
    for(let i=0;i<blockCount;i++){
        blocks[i].show("violet");
    }
    window.requestAnimationFrame(update);
}
update();
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

    <canvas id="gameCanvas" width=400 height=800></canvas>

Answer: When you create blocks you start from 1
for (let i = 1; i < blockCount; i++) {
    blocks.push(new Block(blockCol * 60 + 25, blockRow * 60 + 30, 50, 50));
    ...

so when you update you need to consider that
function update() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ball.show();
    ball.move(ballSpeedX, ballSpeedY);
    player.show();
    objMovement();
    for (let i = 0; i < blockCount -1; i++) { // or for (let i = 0; i < blocks.length; i++) {
        blocks[i].show("violet");
    }
    window.requestAnimationFrame(update);
}


My onTouch method is not doing what it is programmed to do

Question: I am making a Android app. The objective is to make circles that when touched something happens.In more detail this app will display 2 types of circles either a red or a green one. The color of the circle is stored in the lastColor variable. The purpose of the color is so that when a user "touches" a red or green circle something happens. For example if a green circle is touched a point is added to there score, or if a red circle is clicked the activity is changed, but when either of the circles are clicked nothing happens. Here is the onTouch method
public boolean onTouch(View v, MotionEvent event) {
   int x = (int) event.getX();
   int y = (int) event.getY();
   if(isInsideCircle(x, y) ==  true){
      //Do your things here
       if(redColor == lastColor){
          Intent i = new Intent(v.getContext(), YouFailed.class);
          v.getContext().startActivity(i);
       } else {
           addPoints++;
       }
   }else {

   }
   return true;
}

This part of the code is the thing that is not functioning properly. Here is the entire class below.
public class DrawingView extends View {

    public DrawingView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub

    }

    RectF rectf = new RectF(0, 0, 200, 0);

    private static final int w = 100;
    public static int lastColor = Color.BLACK;
    private final Random random = new Random();
    private final Paint paint = new Paint();
    private final int radius = 230;
    private final Handler handler = new Handler();
    public static int redColor = Color.RED;
    public static int greenColor = Color.GREEN;
    int randomWidth = 0;
    int randomHeight = 0;
    public static int addPoints = 0;

    private final Runnable updateCircle = new Runnable() {
        @Override
        public void run() {
            lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
            paint.setColor(lastColor);
            invalidate();
            handler.postDelayed(this, 1000);
        }
    };

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        handler.post(updateCircle);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        handler.removeCallbacks(updateCircle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // your other stuff here
        if (random == null) {
            randomWidth = (int) (random.nextInt(Math.abs(getWidth() - radius / 2)) + radius / 2f);
            randomHeight = (random.nextInt((int) Math.abs((getHeight() - radius / 2 + radius / 2f))));
        }
        else {
            randomWidth = (int) (random.nextInt(Math.abs(getWidth() - radius / 2)) + radius / 2f);
            randomHeight = (random.nextInt((int) Math.abs((getHeight() - radius / 2 + radius / 2f))));
        }

        canvas.drawCircle(randomWidth, randomHeight + radius / 2f, radius, paint);

        paint.setColor(Color.BLACK);
        paint.setTextSize(150);
        canvas.drawText("Score: " + addPoints, 120, 300, paint);
    }

    public boolean onTouch(View v, MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        if (isInsideCircle(x, y) == true) {
            //Do your things here
            if (redColor == lastColor) {
                Intent i = new Intent(v.getContext(), YouFailed.class);
                v.getContext().startActivity(i);
            }
            else {
                addPoints++;
            }
        }
        else {

        }
        return true;
    }

    public boolean isInsideCircle(int x, int y) {
        if ((((x - randomWidth) * (x - randomWidth)) + ((y - randomHeight) * (y - randomHeight))) < ((radius) * (radius)))
            return true;
        return false;
    }
}

Comment: *" when touched something happens."* like what? *"This part of the code is the thing that is not functioning properly"* how?
Comment: when a green or a red circle is "touched" it is suppose to do something. if its a red circle it will display another activity if its a green circle it will add a point, but of course nothing happens when i click anywhere
Comment: Is it crashing or simply doing nothing? Have you put logs and/or breakpoints to see what is/isn't getting called? As it stands, this is a pretty broad question with a lack of self-debugging which makes it difficult for others to solve.
Comment: not crashing just not doing anything when i "touch" or click something on the emulator
Comment: logs or breakpoints? logs as in logcat? there is no errors in logcat
Comment: If (randomWidth, randomHeight) is supposed to be the coordinate of your circle's center, you need to change your canvas.drawCircle line to be just canvas.drawCircle(randomWidth, randomHeight, radius, paint);
Comment: that makes sense i dont know why i had that there, but i removed and still nothing happend
Comment: You should be able to figure out what's going on using the debugger in Android Studio or Eclipse (whatever you're using).  Check out this article for a description of how to run in debug mode, breakpoint placement, etc. https://developer.android.com/tools/debugging/debugging-studio.html
Comment: @PaulTrueman I'm not talking about the logcat. I mean [setting log statements and breakpoints](https://developer.android.com/tools/debugging/debugging-studio.html) to see which lines are/aren't being hit.
Comment: yeah none of that helped
Answer: You need to override the onTouchEvent function. I tested the code and it fully works! Also, make sure to return false after addPoints++ to ensure only one point is added. Hopefully this works for you!
@Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int) event.getX();
    int y = (int) event.getY();
    if (isInsideCircle(x, y)) {
        //Do your things here
        if (redColor == lastColor) {
            Intent i = new Intent(getContext(), null);
            getContext().startActivity(i);
        }
        else {
            addPoints++;
            return false;
        }
    }
    else {

    }
    return true;
}


Import error when starting to use plotly

Question: I'm trying to use plotly, based on the tutorial here: http://nbviewer.ipython.org/github/plotly/python-user-guide/blob/master/s00_homepage/s00_homepage.ipynb
Seem to have the correct library and Python versions, although I get AttributeError while importing plotly. Wonder if anyone had the same problem, see versions and stacktrace below:
Python 2.7.5+ (default, Feb 27 2014, 19:37:08)
Type "copyright", "credits" or "license" for more information.

IPython 2.0.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import numpy

In [2]: numpy.__version__
Out[2]: '1.8.1'

In [3]: import pandas

In [4]: pandas.__version__
Out[4]: '0.13.1'

In [5]: import plotly
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-c27a4132ad2e> in <module>()
----> 1 import plotly

/usr/local/lib/python2.7/dist-packages/plotly/__init__.py in <module>()
     29 from __future__ import absolute_import
     30
---> 31 from plotly import plotly, graph_objs, tools, utils
     32 from plotly.version import __version__

/usr/local/lib/python2.7/dist-packages/plotly/plotly/__init__.py in <module>()
     10 from __future__ import absolute_import
     11
---> 12 from plotly.plotly.plotly import *
     13
     14 __all__ = ["sign_in", "update_plot_options", "get_plot_options",

/usr/local/lib/python2.7/dist-packages/plotly/plotly/plotly.py in <module>()
     27 from plotly.plotly import chunked_requests
     28 from plotly import utils
---> 29 from plotly import tools
     30 from plotly import exceptions
     31 from plotly import version

/usr/local/lib/python2.7/dist-packages/plotly/tools.py in <module>()
     18 from plotly import exceptions
     19
---> 20 from . graph_objs import graph_objs
     21
     22 # Warning format

/usr/local/lib/python2.7/dist-packages/plotly/graph_objs/__init__.py in <module>()
     10 from __future__ import absolute_import
     11
---> 12 from plotly.graph_objs.graph_objs import *
     13
     14 __all__ = ["Data",

/usr/local/lib/python2.7/dist-packages/plotly/graph_objs/graph_objs.py in <module>()
    279         return super(DictMeta, mcs).__new__(mcs, name, bases, attrs)
    280
--> 281 @six.add_metaclass(ListMeta)
    282 class PlotlyList(list):
    283     """A container for PlotlyDicts, inherits from standard list.

AttributeError: 'module' object has no attribute 'add_metaclass'

Comment: If you do `import six`, and then `six`, where does it say it's installed? It's possible that you have a `six.py` file which it's picking up instead of the [six](https://pypi.python.org/pypi/six) package.
Comment: The reason was that I missed "pip install --upgrade plotly", which has finally upgraded all necessary dependencies too.
Answer: I had a similar error and following Mark's note above, pip install --upgrade plotly worked for me.


mysql regexp two words enclosed with any special characters

Question: +-----+------+
|  A  |  B   |
+-----+------+
| gan | esh  |
| dhi | nesh |
+-----+------+

I have a table like this. I want to check this with another table has column
+----------------+
|       C        |
+----------------+
| !!dhin!!esh    |
| gan!!esh..     |
| $$$gan%%%esh.. |
+----------------+

The following query works fine
select * from table1 a, table2 b where c like concat('%',a,'%',b'%')

but what I want is starting, ending, middle should contain only non-alphanumeric. I am a newbie to regexp.
Answer: CONCAT("[^[:alnum:]]", a, "[^[:alnum:]]+", b, "[^[:alnum:]]")

Or perhaps
CONCAT("\\b", a, "[^[:alnum:]]+", b, "\\b")


Set UiWebView's minimumZoomScale and maximumZoomScale with custom value in iPhone/iPad Objective c

Question: In my App for iPhone/iPad(in Objective C), there is a UiWebView which loads any site(by typing the URL). My UiWebView loads site successfully and it can be scrolled and Zoomed successfully.
But my app requirement is that the UiWebView will ZoomIn more than the specified mimimum Zoom level of UiWebView. My code used for setting my Zoom levals is:
<code>webview.scrollView.minimumZoomScale=0.5;
webview.scrollView.maximumZoomScale=10.0;
webview.scrollView.zoomScale=webview.scrollView.minimumZoomScale;
</code>
By seeing the minimumZoomScale=0.5, it sets the Zoom level correctlt. But as soon as I started Zooming it out it Zoomed out the default minimum level and further it can not be Zoomed in at my described Zoom levels.
Please let me know if somebody has any idea or solution.
Comment: Does any body not having any idea?

Please help me I am totally stuck with this.

I have also tried to use the **Meta** tag. In this I have applied the

> maximum-scale=10.0 initial-scale=0.1 minimum-scale=0.1

This works fine for me for the web based websites but for the mobile versions......its just blurry.
Comment: Sorry that this is no help, but I tried this out (I'm having a related problem and figured I might learn something here that could help me), and verified that it is as you say: when you set your initial zoom scale to your minimum zoom scale (which is less than 1) and then zoom out, you can't zoom back down to your minimum.  I tried setting the 'scalesPagesToFit' attribute to 'NO', but that had no effect.  Like I said, this is likely no help, but at least you now have confirmation that this is happening to others as well.
Answer: I used this answer: https://stackoverflow.com/a/10699622/422338
It seems that the UIWebView's max/min zoom levels are set from the web page (and hence the settings you provide to webView.scrollView.minimumZoomScale are ignored).
If you do not have control of the HTML site being visited, you could do a "hack" to inject a meta tag via javascript (using the stringByEvaluatingJavaScriptFromString: method on UIWebView). Would this suit your needs? If you get it working, let me know :).


Rank-ordered data - dealing with increased randomness among lower ranks

Question: What is the best way to analyze rank-ordered data when there are signs that respondents were less diligent/able to assign lower ranks? Is it sufficient to introduce a dummy for lower/earlier ranks into the model or should one model this directly?
I have a set of survey data containing rank-orderings. More specifically, a large sample of respondents was asked to indicate which groups of people should first get access to a COVID-19 vaccine once it becomes available. They ranked 7 different groups from highest to lowest priority; ties were not permitted, rankings had to be complete and the initial ordering of the groups was randomized across respondents.
In my analysis so far, I followed Allison & Christakis (1994, "Logit Models for Sets of Ranked Items", Sociological Methodology). Descriptive analyses show a quite consistent rank-ordering across a number of demographics and non-parametric tests (Friedman & Wilcoxon) indicate significant differences between pairs of choices.
The problem is: It turns out that respondents seem to have been less diligent in assigning the lower ranks, or at least less able to do so (not unrealistic, IMO). Following Allison/Christakis (pp. 216-218), I created a dummy for higher (1-4) and lower (5-7) ranks and included it as an individual-specific covariate into the model. The interactions between the dummy and the alternatives were significant and the coefficient estimates for later choices also show signs of greater randomness (the standard deviation between the coefficients for early choices is 3 times the SD for late choices).
My question is: What is the best way to deal with this? If I understand Allison/Christakis correctly, I should treat later choices as ties by, it seems to me, keeping the early/late dummy in the model - or, in Stata at least, code all later choices as 0 and use the incomplete() option for rologit.
One alternative is to use models that allow for unobserved heterogeneity in ranking capabilities (Fok. et al., "A Rank-Ordered Logit Model with Unobserved Heterogeneity in Ranking Capabilities", Journal of Applied Econometrics), but I am not aware where this would be implemented (not in Stata and the gmnl package for R by Sarrias & Daziano cannot deal with ranked data, as far as I can tell). A final alternative, but hardly a great one, would be to use only the most-preferred choice as the outcome and use the regular conditional logit (or multinomial logit, as it is also known).
Any better suggestions or pointers to relevant packages would be greatly appreciated!
Answer: I think you might be well served by applying the multistage models of Plackett and Luce, later extended by Benter. Briefly, these models are constructed as sequences of conditional multinomial distributions.
In more detail, I recently proposed a method that further extends these models and so I have been doing quite a bit of reading about them. Here are the standard Plackett-Luce modeling assumptions as I write out in my paper.

For $i=1,\ldots,n$, the $i$th ranker's ordered list of $\ell_i$ items is denoted by ${\bf x_i} = \{x_{i1},x_{i2},\ldots,x_{i\ell_i}\}$, with $x_{is}\in\{1,\ldots,v\}$ and $s=1,\ldots,\ell_i$ indexing each stage. If the lists are complete, then $\ell_i\equiv v$ for all lists; if they are partial, then $\ell_i \equiv \ell < v$ for all $i$, where $\ell$ is artificially chosen and external to the modeling process; if they are ragged, then $\ell_i \leq v$ for each $i$, with potentially different values of $\ell_i$ for each $i$.

and later

The $i$th ranker generates an ordered list of length $v$ from among a pre-specified, fixed-length set of items, starting with his/her/its most-preferred item. Define $\mathcal{O}_{is}$ to be the set of items yet to be ranked just before the $s$th stage:
\begin{align}
\mathcal{O}_{is} = \begin{cases}
\{1, \ldots, v\}, & s=1\\
\{k: k \not\in \{x_{is'}\}_{s'<s}\}, & s>1
\end{cases}\Bigg\},\label{ois}
\end{align}
and let $1_{[X]}$ be 1 when the statement $X$ is true and 0 otherwise. The Plackett-Luce (PL) probability that item $k\in\{1,\ldots,v\}$, is ordered $s$th is $\Pr(x_{is} = k|\mathcal{O}_{is}) = 1_{[k\in\mathcal{O}_{is}]}\exp(\theta_k)/\sum_{j\in \mathcal{O}_{is}}\exp(\theta_j)$, i.e. proportional to $\exp(\theta_{k})$ until it gets ordered, and zero afterwards. There are $v$ parameters, $\Theta = \{\theta_1,\theta_2,\ldots,\theta_v\}$. Of these, $v-1$ are identified, and without loss of generality, we may assume that $\min_j\{\theta_j\}\equiv0$.

An important extension that I think is appropriate for your situation where rankers are more ambivalent at later stages comes from Benter, who proposed to dampen the weights towards zero so that at later stages (later ranks), differences in the log-likelihood are smaller. Let a dampening function $\delta(s)$ map the set of integers $s\in\{1,\ldots,v-1\}$ to the interval $(0,1]$, with $\delta(1)\equiv 1$ for identifiability. From my paper again:

...the  Benter-Plackett-Luce (BPL) model for the probability of selecting item $k$ at the $s$th stage conditional on the choices from the previous $s-1$ stages is $\Pr(x_{is} = k|\mathcal{O}_{is}) = 1_{[k\in\mathcal{O}_{is}]}\exp(\theta_k\delta(s))/\sum_{j\in \mathcal{O}_{is}}\exp(\theta_j\delta(s))$, for $k=1,\ldots,v$ and $s = 1,\ldots,\ell_i$. To be estimated are the $v-1$ identified parameters in $\Theta$ plus the number of parameters in the chosen functional form of $\delta(\cdot)$

I have not yet put my R code into a package, but the scripts for fitting BPL models are on my github repo, along with a few examples and vignettes, which should hopefully be useful for you.
If you're interested, what I did in my paper to extend the BPL models was equip this BPL log-likelihood with an $L_0$ variable selection penalty, so that when maximizing the penalized log-likelihood, some of the item weights ($\theta_i$) get forced to zero, and you can thus obtain a sparse consensus list that doesn't necessarily include all of the items that were ranked.
EDIT Since your data are comprised of complete rankings, you don't need the $\theta_0$ parameter that I introduce. All parameters are logged, so the way to drop $\theta_0$ from the likelihood would be to set it equal to $-\infty$, which you do by setting fixed = matrix(-Inf,dimnames = list(c("0"))) in the call to penalized_rank_path.
Comment: Yes, my code stills handles the situation where all respondents rank all alternatives; I've edited my response to indicate how precisely.
Comment: Hi Philip, many thanks for the answer, looks pretty much like the solution I was looking for! I still have to take a closer look at your R-code, but: if I read your paper correctly (I might not and may reveal some of my ignorance toward higher-level stats here!), you are modelling the case where respondents in essence give up - they rank _i_ out of _I_ alternatives and then decide that this is enough. The results is what you call "ragged" lists. In my case, we forced respondents to rank all alternatives; incomplete rankings were not permitted. Does your solution really travel to my case?
Comment: (BTW: If your response has received a downvote, then this was me and was entirely done by mistake (page jumped while loading!)
Comment: Excellent, many thanks for the additional info. I'll still have to dig through your code a bit to make sure I get everything correctly, but I'll set your answer to accepted.