which sql is better on Hbase with phoenix?

Question: I make two tables by phoenix on Hbase.
One is ORIGIN_LOG, the other ORIGIN_LOG_INDEX.
In ORIGIN_LOG, the key is info_key.
In ORIGIN_LOG_INDEX, the key is (log_t, zone)
And we save log_t, zone, info_key in ORIGIN_LOG_INDEX, so that we can search info_key very quickly by log_t and zone in ORIGIN_LOG_INDEX. Then using info_key, we can get detail log info from ORIGIN_LOG by info_key because info_key is the key for ORIGIN_LOG.
But when we explain the following sql. we find it will cost full scan on ORIGIN_LOG.
explain select "log_t", "app_ver", "device_id", "mobage_uid",     "param1","param2","param3", "param4" , "param5", "user_id", "a_typ", "a_tar", "a_rst"  from "ORIGIN_LOG" where "info_key" in (select distinct "info_key" from "ORIGIN_LOG_INDEX" where  "log_t">='1423956600' and  "log_t"<'1423956601' and  "zone" ='18')

    CLIENT 4-CHUNK PARALLEL 4-WAY FULL SCAN OVER ORIGIN_LOG
    CLIENT MERGE SORT                        |
    |     SKIP-SCAN-JOIN TABLE 0               |
    |         CLIENT 2-CHUNK PARALLEL 2-WAY SKIP SCAN ON 2 RANGES OVER
    ORIGIN_LOG_INDEX [0,'1423956600','18'] - [1,'1423956601','18'] |
    |             SERVER FILTER BY FIRST KEY ONLY |
    |             SERVER AGGREGATE INTO DISTINCT ROWS BY [info_key] |
    |         CLIENT MERGE SORT                |
    |     DYNAMIC SERVER FILTER BY info_key IN ($5.$7) |

If we only use ORIGIN_LOG with conditions log_t and zone, as following:
select "log_t", "app_ver", "device_id", "mobage_uid", "param1","param2","param3", "param4" , "param5", "user_id", "a_typ", "a_tar", "a_rst"  from "ORIGIN_LOG"  where  "log_t">='1423956600' and  "log_t"<'1423956601' and  "zone" ='18';

We also get full scan.
CLIENT 4-CHUNK PARALLEL 4-WAY FULL SCAN OVER ORIGIN_LOG |
|     SERVER FILTER BY (log_t >= '1423956600' AND log_t < '1423956601' AND  zone = '18') |
| CLIENT MERGE SORT                        |

So what the difference between two sql. And which sql is better for the performance.
Thank you.
BRs
Answer: Your first query is range base scan of HBase on ORIGIN_LOG_INDEX and then Gets on ORIGIN_LOG.
Your second query is a range based scan in HBase where you would provide a "startkey" and "endkey" for scan.
Second query is much better because you are avoiding lookup into another table and you are also not doing distinct operation.
However, it is possible that startKey and endkey range might span entire table. So, the worst case of your scan is "FULL TABLE" scan.
Hence, i think, the explain plan is showing it as a full table scan.Maybe, you can ask on the mailing list for further clarification.
Comment: thank you for your answer. But the fact is that the second sql will cause rpc timeout because the ORIGIN_LOG table is too big. Only the first sql can return the results.


App needs elevated privileges to run - why?

Question: Not as stupid as it sounds ;)
I have a third party app that I have no source for. Official support is for XP and higher - but higher only with UAC off. Which I do not want.
Now, I know the programmers and they are willing to make a change if it is not too much work and I can tell them WHAT Needs to be done.
I know that the app, which starts multiple executables, does not get network connection when I start it without elevated priviledges - but it seems no port that is open is in the loer range  (as per netstat -b
Is there any guideline on trying to find out WHY an app needs elevated priviledges? THe applicaiton is business critical - and this currently subverts secutiry as users must be local admins. If anyone has an idea - once I find the reason I am sure I can get the vendor implement a change.
Comment: I was stating you said you know the 3rd party app's programmers, so I'm wondering why they can't debug on their end and say why the app needs elevated rights.  The SO part was to see if they had any tools up their sleeves that could run in conjunction with the app running like an SDK tool that would show what calls the app was making and when it failed as a normal user...possibly?
Comment: Elevated privileges could be required if the application has to write in some protected locations, such as `Program Files` or `Windows` folder, or `[HKLM]` registry key. Maybe this tool could help you to figure out what the app actually does when it runs : http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx
Comment: I wonder if the SO folks would know quicker?  Can the programmers not step through/debug the app and look for when the app gets a deny as a standard user?
Comment: The problem is that I dont ahve source, so I am totally looking at it from an admin point. This is a totaly user level app, so it MUST be something trivial like a port number or something like that. Not even sure. SO may be an idea, but they will assume control over the app.
Comment: @TheCleaner: Absolutely. The fact they need an end user to tell them what their app requires to play nice with a modern OS doesn't exactly inspire confidence in the quality of the product.
Comment: @SvW Let me be diplomatic once and say that those assumptions have more points that are backing them up. But things are as they are and that is THE business critical application for more than half of the people working for me and I just want to try to get that solved. If it were to me I would take a FIX interface into their backend any day and write my own frontend.
Comment: File and registry virtualisation should mean that trying to write protected locations shouldn't be a game-ender - http://msdn.microsoft.com/en-us/library/windows/desktop/aa965884%28v=vs.85%29.aspx
Answer: As per one of the comments, your best bet is likely to be using Sysinternals' Process Monitor to see what is being tried and failing due UAC.
Download Process Monitor from http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx
Run process monitor, run your borked, obsolete, badly coded app, go to process monitor > filter  > if Process Name is <borkedapp> then Include and if Result is Success then Exclude which should give you a mere few thousand entries to scan for the bit that is failing.
Alternatively there is a tool linked below (I have not tried it) that will help you compare process monitor traces so you can take a trace running as standard user and another running elevated and compare them.
http://forum.sysinternals.com/tool-for-comparing-procmon-traces_topic28870.html
https://github.com/patraulea/LogDiff
Answer: tIn addition to Blue's answer, there are tools for migrating applications to Windows 7. Even though your app says it's Windows 7 compatible, running it through this ringer would tell you what is needed for your app to correctly function with UAC on. You may even be able to create a 'shim' which modifies certain settings when your app runs. I believe the tool is called the Standard User Analyzer http://technet.microsoft.com/en-us/library/cc766021(v=ws.10).aspx.
I'll also add that a lot of the times the elevated privileges can be avoided by granting the appropriate permissions, i.e., giving the user modify rights to the C:\Program Files\ folder and subfolders.


Recovering a file deleted with python

Question: So, I deleted a file using python. I can't find it in my recycling bin. Is there a way I can undo it or something. Thanks in advance.
EDIT: I used os.remove. I have tried Recuva, but it doesn't seem to find anything. I have done a deep search.
Comment: The recycling bin in something windows uses when you delete from the GUI. Using Python, you're not in Kansas any more.
Comment: Short answer: not easily. Long answer: probably, possibly.
Comment: See [Recuva](http://www.piriform.com/recuva) for example.
Comment: https://mail.python.org/pipermail/python-list/2007-February/419077.html
Comment: http://stackoverflow.com/questions/12094663/where-does-os-remove-go It uses the os's unlink. so can't recover that file.
Comment: @RaviKumar Deleted my comment since OP also edited his question. Thanks for pointing that out, though.
Comment: First step remove the drive from box and don't boot from it again.  Your file is still there, but anything you do on it can easily overwrite it now because the spot it was in is no longer allocated to your file.  Step 2 install the drive on another machine with drive recovery software pre installed like http://www.cgsecurity.org/wiki/PhotoRec.  Step 3 learn to use the software and get your data back.
Comment: @litepresence The file isn't an image.
Answer: If you used os.remove and ended up deleting a file by accident, then there's no reason for this file to be in the recycle bin. It is removed from the filesystem. There is no Python operation to get that file back.
However, a simple deletion just breaks the link to the file but does not erase the bits of the file on the filesystem. You can try file recovery softwares to get it back.
Note that

Now that the file is erased, this question is not Python specific anymore. You'd be in the same situation if you had deleted the file by any other means.
You should avoid using your system to minimize the chances of erasing the bits of the file by writing another file at the same place on the disk.
The tools you can use to recover the file are platform specific and the generic question "how to recover deleted files" has most certainly already been asked here, on Super User, Unix & Linux, or some other Stack Exchange community.
Answer: If you deleted the file using PyCharm IDE then it is possible. It says:
Restore deleted files
If you've accidentally deleted a file that was not under version control, you can restore it with Local History.

Select the node that contained the file you deleted in the Project tool window, right-click it and choose Local History | Show History from the context menu.

On the left, select the revision that contains the file you want to restore, right-click that file, and choose Revert Selection.

Recovering a file deleted with python


User Session Management with Spring (Business and Transaction Management)

Question: In my application
The web front end is done using Struts and Spring for Business and  transaction Management.
Now, Am implementing logging in the Business Logic side (beans).
The log should happen such that, every method in the Service, should have the logged in User Details
One approach would be sending the User Object to every method in Service, when it is been called from Servlet
But this would really be dirty.
Does spring/ struts2-spring support any other way to do this.??
Answer: You should use Spring AOP to do the logging. This will make code cleaner and you need not rely on developer to do the logging at each place. For printing the user details use MDC feature of SLF4J. It is like a ThreadLocal hashmap which you can access from any where. So your entry method can put the userdetails to MDC and it can be accessed in your log method.
Answer: Use Spring AOP to do your logging for you (Accompanied By a logging framework), Struts2 has nothing to do with Spring AOP. Spring AOP can work on its own regardless if its a Web Application or a Swing application with Minimal Setup.


How to actually remove a QGraphicsItem from the screen?

Question: I've got a QGraphicsItem (a map) that has some children (icons on that map). No issues so far.
However, I want to be able to remove the icons from the screen. In order to do this, I tried to just break up the parent-children relationship:
<code>foreach(QGraphicsItem* item, displayedIcons) {
    item->setParentItem(NULL);
}
</code>
In some way, the map and the icons are detached from each other, i.e. when I pan the map, the icons remain at their absolute position on the screen. But the problem is, that the icons are still displayed at all.
Is there anything I am missing in order to actually remove the icons from the screen?
Answer: Use QGraphicsScene::removeItem().


Largest box fitting inside an ellipsoid

Question: Find the volume of the largest box with sides parallel to the $xy$, $xz$, and $yz$ planes that can fit inside the ellipsoid $(x/a)^2 + (y/b)^2 + (z/c)^2 = 1$.
My answer: We want to maximize $f(x,y,z) = xyz$ subject to $(x/a)^2 + (y/b)^2 + (z/c)^2 \leq 1$. So $\nabla f $ parallel to $\nabla g$, i.e.
$$(yz, xz, xy) = \lambda \left( \frac{x}{a}, \frac{y}{b}, \frac{z}{c} \right)\\ \Rightarrow \frac{ayz}{x}=\frac{bxz}{y}= \frac{cxy}{z}\\ \Rightarrow ay^2 = bx^2 ; bz^2 = cy^2 ; az^2 = cx^2 \\  \Rightarrow (x,y,z) \text{ parallel to } \left( 1, \sqrt{\frac{a}{b}}, \sqrt{\frac{a}{c}}\right)$$
so we need to find $t$ such that $\left( t, t\sqrt{\frac{a}{b}}, t\sqrt{\frac{a}{c}}\right)$ is on the ellipsoid, i.e.
$$\left( \frac{t}{a\sqrt{a}}\right)^2 + \left( \frac{t}{b\sqrt{b}}\right)^2 + \left( \frac{t}{c\sqrt{c}}\right)^2 = 1.$$
So the volume is $$8t^3 \frac{1}{\sqrt{abc}}\\ = 8\frac{1}{\left(\sqrt{ \frac{1}{a^3} + \frac{1}{b^3} + \frac{1}{c^3} }\right)^3}\cdot \frac{1}{\sqrt{abc}}$$
But the answer which the T.A. has indicated is $\frac{8abc}{3\sqrt{3}}$ (of course there could be a mistake). Where is my error?
Comment: Have you noticed that there must be a mistake in your computation since your solution is not symmetric in $a,b,c$ whereas the problem is?
Comment: @tohecz I saw that too, now I have edited. Of course I think there is still a mistake...
Answer: It is not difficult to verify that the largest box in the unit sphere is the cube with sides $2/\sqrt3$, whence for such a sphere you get the volume $8/3\sqrt3$. Now notice that $f:\mathbb R^3\to\mathbb R^3$, $(x,y,z)\mapsto(ax,by,cz)$ maps unit sphere to your ellipsoid, and $V(f(X))=abc V(X)$ where $V$ is the volume and $X$ is any set. Moreover, $f$ brings your box to a box again. Therefore the maximum is necessarily attained for $f(X)$ where $X$ is the cube. And you get $V(f(X))=8abc/3\sqrt3$.
Your mistake is that $\partial_x (x/a)^2 = 2x/a^2$ and not $2x/a$.
Comment: Thank you so much! That is very helpful

Largest box fitting inside an ellipsoid


Is it possible to pass components as properties and add interactions to them?

Question: I am having the following class, that is supposed to handle a modal
class Modal extends React.Component {
   constructor(props){
      this.confirmBtn = props.confirmBtn || <button type="button">Confirm</button>
      this.cancelBtn = props.confirmBtn || <button type="button">Cancel</button>
   }

   render(){
       return (

       {this.props.children}

{this.confirmBtn} {this.cancelBtn}

);

   }
}

Since these buttons are components, they can do whatever they were supposed to do, but what I want to do is add the extra functionality of closing the modal.
Ideally I would like something like this:
Pseudocode
render(){
   const ConfirmBtn = this.props.confirm;
   const CancelBtn = this.props.cancel;
   return (

       {this.props.children}

          <ConfirmBtn onClick={this.close.bind(this)}/>
          <CancelBtn onClick={this.close.bind(this)}/>

);
}

I know it is possible to just keep the buttons internally and add callbacks to them, but I'm just wondering if this thing is even possible to do in React.
Answer: You code will work fine, assuming that this.props.confirm and this.props.cancel are components and not elements.  As an example, Modal would be a component but <Modal/> is an element.
That said, I'm not personally a fan of passing components in this way.  While it will work, you're not imposing any forced constraints on which kinds of Component is allowed to be passed in for confirm and cancel.  Imagine passing in a textbox component.  Or a button styled incorrectly that takes up too much space and ruins the style of the rest of the modal.
 It would render, but.... eugh.
And sure, human testing should catch those issues.  But if we need to rely on an actual human being, then we're susceptible to human error.  We all hate human error, right?
Instead, I would suggest making a prop named buttonType.  Use this prop as an enum to choose between whatever various button components you might wish to use.  Have a default.  e.g.
getButtonComponent() {
    switch( this.props.buttonType ) {
        case 'someType': return SomeType;
        case 'anotherType': return AnotherType;
        default: return DefaultType;
    }
}

render() {
    const ConfirmButton = this.getButtonComponent();
    const CancelButton = this.getButtonComponent();
    ...

Comment: Totally agree with your arguments, it's just that I'm trying to push the framework to see what it allows and what it doesn't :)


Finding mean and variance through mean and variance of subsets

Question: Suppose I have a big subset of smaller subsets where each small subset contains x amount of numbers.
How would I go about finding the mean and variance of the larger subset through the mean and variance of fragments of the smaller subsets?

For example:
Let subset A = [[1,3], [5, 7], [10, 19]]
Lets split subset A into the 2 smaller subsets -- B and C
B = [[1, 3]] and C = [[5, 7], [10, 19]]
If we know the mean and variance of B is 2 and 1 respectively,
and we know the mean and variance of C is 10.25 and 28.6875 respectively.
How would we find the mean and variance of A from the mean and variances of B and C?
Thanks!
Answer: You seem to be using the $\frac1n$ version of variance
If $n_B$ and $n_C$ are the number of elements of $B$ and $C$, and $\mu_B, \mu_C, \sigma^2_B, \sigma^2_C,$ their means and variances then:

$n_A=n_B+n_C$
$\mu_A=\frac1{n_A}(n_B \mu_B+n_C\mu_C)$
$\sigma^2_A=\frac1{n_A}(n_B (\sigma^2_B +\mu_B^2)  +n_C (\sigma^2_C +\mu_C^2)) - \mu_A^2$
Comment: I think you meant $n_C (\sigma^2_C +\mu_C^2)$ instead of $n_C (\sigma^2_B +\mu_B^2)$ for $\sigma^2_A$. That solution works like a charm. Thanks!
Comment: @Omrii - You are correct - thank you - now edited


What is causing static when I try to record directly from my guitar through a pre amp into my computer?

Question: Bare with me here as a lot of this is new to me, but here is my understanding of my problem. I have a Taylor GS mini, which I believe has an active preamp built in. When I plug my guitar into my pre amp using an XLR chord I have, and then from my preamp into my computer via USB (Using logic pro X as my DAW), I'm getting a static sound.
From the research I've done, it's because my guitar outputs an instrument level signal into the preamp, but the preamp is expecting a microphone level signal, so it's boosting an already too loud signal?
More research seems to point me towards the fact I need a DI. That's why I'm here. I want to make sure I understand what's really going on before I buy one, and also would I need a passive or active DI. I assume passive, because I want to drop the instrument level signal to a microphone level signal for my preamp.
Can you guys explain what would be causing this static? Am I way off? Is a DI a good idea to have to fix this problem?
Comment: There are two types of electronics available from Taylor for the GS Mini.  You can get the ES Go pickup made for the GS Mini, which is a passive magnetic pickup and you can buy the GS Mini "e" with an active piezo under saddle pickup.  It might be helpful to know which type of pickup your GS Mini has.  If you are not sure - the Active under saddle pickup needs batteries and the passive magnetic pickup does not.  Also, the active pickup (with pre-amp) has volume and tone controls.
Comment: Bad cords and dirty contacts also cause static. If its popping, your processor is most likely too slow, if its humming, you have bad power from the outlet.
Comment: @RockinCowboy It does have volume and tone controls, so it must be an active pickup.
Answer: It's probably not the level but the impedance, which is the ratio of voltage to current for a given level of power. A DI is mostly an impedance matcher but it also lets you do some level manipulation in many cases. The active versus passive DI question is more about tone than level. If you want a nice clean tone with a wide frequency response, active is usually a better choice. For a smoother spound with a little extra warmth, you might want a passive DI. Active DIs also require phantom power.
If I were in your shoes I would plug that into a Radial J48 or Countryman active DI, assuming I could afford it. The Radial JDI is pretty much the passive DI, but I have a couple Whirlwind passives that have nice transformers in them and are more affordable. Just don't dishonor a Taylor by plugging it into a Behringer DI. :-)
Comment: Well this is a little late, but I did end up picking up a passive DI and it solved my problem. Still wrapping my head around all of this but I'm getting there. Thanks a lot! :D
Comment: Kk. So if this is an impedance problem a DI should solve that, whether it be an active or passive one? I'm definitely going to look into those DI's you suggested. Thanks!
Answer: It may be related to your audio interface settings. If the buffer sizes are too low it can cause all kinds of weird (bad) sounds. If your computer and interface are up to the task, you should be able to adjust the buffer so you get a good clean sounds with minimal lag. Another thing I have seen is on laptops, the power saving settings sometimes cause issues. Even setting to 'Maximum' might not be enough. (look for settings relating to USB ports). Final word on the buffer size - you can rule this out by setting it to its maximum buffer size - if it clears up you know you are on the right track. It may be unplayable due to lag, but you can then shrink the buffer to your liking. If you cant shrink it enough to keep the sound clean without lag you need to upgrade your hardware.


How to solve this Differential Equation without ProductLog in Mathematica?

Question: I'm trying to solve a Differential Equation using Mathematica to check whether the result I get is equal to the result I got by solving the equation by hand.
However, Mathematica gives me an answer including ProductLog which doesn't make sense to me.
Here is my differential equation:
y'[x] == x^2 + y[x]^2)/(x*y[x] - x^2)

This is my input to Mathematica:
DSolve[y'[x] == (x^2 + y[x]^2)/(x*y[x] - x^2), y[x], x]

This is the answer I got:
{{y[x] -> -x - 2 x ProductLog[-(E^(-(1/2) - C[1]/2)/(2 Sqrt[x]))]}}

The answer I got by solving by hand is:
y = xLn|((x+y)^2)/(x)| + Cx

C is the constant of integration.
Answer: Use Mathematica to solve for y in the solution you found by hand.  The result involves ProductLog and looks very much like the soluiton Mathematica gives for your differential equation.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Add ID using JSON property

Question: I am looking to add in an ID for each row in the loop which will equal the data[i].name value. I have the data in a json structure which is reading as expected. I am struggling to find the correct place to add in the ID and also how to make sure the ID equals the data[i] name.
buildTable(myArray)

 function buildTable(data){
  var table = document.getElementById("myTable")

  for (var i = 0; i < data.length; i++){
   var row = `

                ${data[i].name}
                ${data[i].theme}
                ${data[i].level1}
                ${data[i].level2}
                ${data[i].level3}

                  <select name="levels" id="levels">
                  <option value="level1">Level 1</option>
                  <option value="level2">Level 2</option>
                  <option value="level3">Level 3</option>
                  </select>

 `
  table.innerHTML += row
             }
  $("tr").addClass("class1")
 }

Comment: Side note: Don't use `+=` with `innerHTML` in loop. When you do, each loop iteration the browser has to loop through all of the nodes in the element, build an HTML representation of them, hand that string to the JavaScript engine, get the updated string from the JavaScript engine, parse it, tear down the old elements and throw them away, build new elements, and fill in the target element with those new elements. Instead, use [`insertAdjacentHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML) and similar (or create elements and `appendChild` them).
Comment: JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON.
Comment: Did you mean ``?
Comment: Which property of `data[i]` do you want to use for the `id`? You seem to already know how to include information from `data[i]` in the HTML you're creating (that's what you're doing with `${data[i].name}` and such. Where are you stuck in relation to the `id`?
Comment: `` should do the trick then already, no? (Whether all your names actually constitute _valid_ values for an id attribute, would be a different question.)
Comment: How are you going to use the ids? Rows in a table already have "id"s, they've `rowIndex` property.
Answer: You can use something like:
buildTable(myArray)

 function buildTable(data){
  var table = document.getElementById("myTable")
  var tableContent = "";

  for (var i = 0; i < data.length; i++){
   var row = `

                ${data[i].name}
                ${data[i].theme}
                ${data[i].level1}
                ${data[i].level2}
                ${data[i].level3}

                  <select name="levels" id="levels">
                  <option value="level1">Level 1</option>
                  <option value="level2">Level 2</option>
                  <option value="level3">Level 3</option>
                  </select>

 `
  tableContent += row;
             }
  table.innerHTML = tableContent;
}

Add ID using JSON property


Find equation of a line intersecting parabola at one point only?

Question: Find equation of a line with gradient equal to $2$ which intersects the parabola $y = 6 − x − x^2$ at one point?
I tried using the equation of the line $y=2x+c$ and making it equal to $y= -x^2 - x +6$. Then finding $x$ using the quadratic formula. But I just can't find the $c$ value.
Comment: I tried using equation of line y=2x+c and make it equal to y= -x^2 - x +6. Then find x using quadratic formula. But I just can't find the c value.
Comment: Hint: let the determinant of the quadratic equation $+x^2+3x+c-6=0$ be equal to zero. Then there will be only one point of intersection, and will get the value of c.
Answer: Let's find point of intersection:
$$
2x+c=-x^2-x+6\Longrightarrow x^2+3x+(c-6)=0.
$$
These equation must have exactly one root; so,
$$
3^2=4\cdot1\cdot(c-6)\Longrightarrow c=\frac{33}{4}
$$
Answer: The equation of such a line, which passes through the point $(x_0,y_0)$ is given by $$y-2x=y_0-2x_0$$
It intersects the parabola at only one point if the abscissae equation for the intersection (which is a quadratic equation):
$$6-x-x^2=2x+y_0-2x_0\iff x^2+3x+y_0-2x_0-6=0$$
has a double root, which amounts to saying its discriminant is $0$:
$$\Delta=0\iff9=4\cdot(y_0-2x_0-6)\iff y_0-2x_0=\frac{33}4$$
Thus an equation of the line with slope $2$, tangent to the parabola, is
$$y-2x=\frac{33}4\enspace\text{or}\quad 8x-4y+33=0.$$
We then can compute the abscissa of the point of contact, solving
$$x^2+3x+\frac{33}4-6\iff4x^2+12x+9=(2x+3)^2=0\iff x=-\frac32$$
whence $y=-3+\dfrac{33}4=\dfrac{21}4$.


$x''+(x^2+2x'^2-1)x'+x=0$ has a non trivial periodic solution.

Question: I'm trying to prove that $x''+(x^2+2x'^2-1)x'+x=0$ has a non trivial periodic solution. I've written it as a 2x2 system and found that the only equilibrium point $(0,0)$ is strictly unstable. Therefore I'm trying to find a invariant set that contains the origin so I can apply Poincaré-Bendixson, but I haven't had any luck. Any suggestions? also, do you know of a better way to prove this?
Thank you!
Answer: The original equation can be rewritten as the system
$$
\dot x=y,\quad \dot y=-x-(x^2+2y^2-1)y.
$$
Consider the Lyapunov function $V(x,y)=x^2+y^2$. Its derivative is
$$
\dot V= 2xy-2yx-2y^2(x^2+2y^2-1)=-2y^2(x^2+2y^2-1).
$$
The derivative is nonpositive in the set
$$D=\left\{
(x,y):\;x^2+2y^2\ge 1
\right\}
$$
thus $V(x,y)$ is nonincreasing along the trajectories in $D$.
Hence, the level set
$$
\Omega_1=\left\{
(x,y):\;x^2+y^2\le1
\right\}
$$
is invariant since no solution can get out of it:
Comment: Any set $\left\{(x,y):\;x^2+y^2\le r\right\}$ where $r\ge 1$ would be invariant, right?
Comment: @Hans Yes, it is. We just need only one set in order to use the Poincaré-Bendixson theorem, so I didn't point this out.
Comment: I see. What tool do you use to generate this pretty graph?
Comment: @Hans I used MATLAB (the arrows are drawn manually)
Comment: I suspected it was Matlab but was not sure how the arrows were generated. Cool.


Why is overflow hidden required to make this flex layout work properly?

Question: In the following example I can't understand why I need to hide the overflow on #articles. To me, it seems that because I have article { flex: 1 1 auto; } that it should shrink & grow to the parent #articles height. Help appreciated!

html, body {
    height: 100vh;
    overflow: hidden;
}
#container {
    display: flex;
    flex-direction: column;
    align-items: stretch;
    height: 100vh;
    overflow: hidden;

    width: 50%;
    background-color: red;
}

#container header {
    background-color: gray;
    flex: 0 0 auto;
}

#articles {
  display: flex;
  flex: 1 1 auto;
  flex-direction: row;
  /* Why is this required? */
  /* overflow: hidden; */
}

article {
    flex: 1 1 auto;
    overflow-y: auto;
    min-height: 0px;
}

article + article {
  background-color: blue;
}
#container footer {
    flex: 0 0 auto;
    background-color: gray;
}

    This is a header

Short

        This is the content that

        With a lot of lines.

        With a lot of lines.

        This is the content that

        With a lot of lines.

        This is the content that

        With a lot of lines.

        This is the content that

        With a lot of lines.

    This is a footer

Comment: to be more accurate, you need `min-height:0` but overflow:hidden is doing the same
Answer: I'm not sure and this is entirely based in my own experience... but:
I made a codepen to mess around: https://codepen.io/jorgeks/pen/gOgmPgO
#articles-wrapper {
    border: 4px solid pink;
  display: flex;
  flex: 1 1 auto;
  flex-direction: row;
  /* Why is this required? */
/*   overflow: hidden; */
    /* This also works, or anything in fact */
/*  overflow: auto; */
}

I think the problem is because your blue content is actually bigger than the wrapper with overflow: hidden, so, it doesn't display but still exists. Flex would try to fit in there, but you set an overflow property, so it may ignore the height/width because you say so.

So, when you set a new overflow property to the blue block you made it fit and the scrolls appears.
There's no context, but, why use all of this overflows and fixed heights? Is not something usual...
Also, check these answers, may help:

Flexbox and overflow: hidden not working properly
How can I hide flex items when it overflows the flex parent?
Comment: There are two overflow definitions that aren't required in this example `html, body` & `#container`. There are no fixed heights defined except on `html, body` & `#container`. If you think something isn't usual, please provide a full alternative css solution that explains why it is better than what I have posted above.
Comment: I think I will try this tonight. Can you please send a wireframe/briefing of what you want to achieve. As I mentioned, I don't have any context. And yes, two overflows and fixed heights are a lot, is possible to have a very complex page with none of that. But again, the property exists for a reason, your requisites may be one of that.


Extreme Vocal Problems

Question: So I've been doing false chord vocals for a few years now, and it's become increasingly a problem that I can't get my vocal chords to 'catch', or produce a raspy sound.
I used to get the problem when I was starting after about an hour of screaming, the chords seemed like theu got fatigued and would stop catching.
Now it's every few weeks I have a period of about a week where I can't get my false chords to produce any sound.
However, my speaking and singing voice are working as normal.
The possible causes are obviously poor technique (but im not sure in which way), or medication I've been taking which causes me to he dehydrated.
Rest doesn't seem to help so I'm not sure how to fix it.
Any ideas?
Comment: Are you screaming on purpose to try to make your voice... change somehow? Dehydration has a dramatic effect on the voice, so you definitely want to stay hydrated and avoid caffeine and alcohol.
Comment: @cmp, Not sure you were answered.  Caffeine and alcohol will dehydrate you.  In short, vocalists should treat their bodies like athletes (actually all musicians benefit from this) and take care of themselves to be at peak performance level.
Comment: To the OP, you bring up an interesting issue.  The use of false chord vocal technique to create roughness.  In a nutshell most vocalists would say "Don't do it".  If you're able to "sing" in normal voice w/o trouble I would think you just lost the feeling internally that tells you your technique is on.  I'd go back to some old exercises and see if you can reconnect with the feeling.
Comment: @ToddWilcox It is surely (part of) a vocal technique.
Comment: @ToddWilcox why should you avoid caffeine Todd?
Comment: yes, medications can impact your health, hearing, voice and breathing, however all performers sing in their natural range, if one wants to expand it, he/she should train first not to injure oneself.
Answer: I decided to "answer" rather than comment.
In a nutshell most vocalists would say "Don't do it". If you're able to "sing" in normal voice w/o trouble I would think you just lost the feeling internally that tells you your technique is on. I'd go back to some old exercises and see if you can reconnect with the feeling.
In classical voice training we do things like lip trill to activate the resonance in the sinuses.  We also do exercises to control breath, the rate of flow and pressure inside the body.  Getting to correct feeling is an important part of knowing your technique is correct.  Sometimes is sound right but feels bad, other times the opposite.
An example is passing from one register to another.  I seem to be able to sing will in my upper and lower registers but the one note that defines the transition is problematic.  This causes tightening up of the muscles in the neck, etc.  The fix is not over practicing the note, but doing relaxation exercises to take your mind off your body.  Things like rubbing the back of the neck, or tilting the head down, etc.
This example is a beginner's problem but it is meant to illustrate a point.  When things aren't working correctly taking your mind off the technique can free you up.
Assuming that you are not suffering from other issues like dehydration, I'd go back to basic exercises and see if you can recapture that feel you have when false chords "catch" properly.  Are you (or have you) taking vocal lessons, or using some sort of method?  Or are you self taught?

Extreme Vocal Problems


How to make keep the active page bar highlighted?

Question:

#menu ul{
margin:0px;
padding:0px;
list-style:none
}
#menu li a{
float:left;
display:inline-block;
width:210px;
margin:0px 0px 3px 0px;
background:#0093dd;
color:#fff;
border:5px solid #dd127b;
line-height:50px;
font-size:1.3em;
font-weight:bold;
letter-spacing:.1em;
text-transform:uppercase;
text-decoration:none
}
#menu li a:hover{
background:#fff;
color:#0093dd;
text-decoration:none
}
#menu li a:active{
background:#dd127b;color:#fff;
text-decoration:none
}

...

...

...

...

...

Dear developer, please help me to make the code right (without javascript) for highlight* the active page bar.
*background:#fff;color:#0093dd;text-decoration:none
I think some part of the code Im using it is incorrect or incomplete.
Using the present css and html code every function works fine such as color change for background and text on hover, color change for background and text on click.
Highlight the active page bar is the only function that I cant make it work.
It isnt the native blogger nav page bars. It is a mini app html placed in the header just below the #header (company logo).
Comment: Hello, I would suggest adding some code to your question and you may want to check this page for improving your question quality https://stackoverflow.com/help/how-to-ask
Answer: To say in short you have to use some Javascript magic :
1. Detect active page url using window.location object
2. Find corresponding a tag with var item =document.querySelector("a[href=<found url is here>]")
3. Add active class item.classList.add("active")
4. Describe . active{...} class in yous css code


Mattooltip doesn't work in *ngFor Angular 13

Question: Mat tool tip doesn't work. Angular 13
I need mat tool tip to show expected value under following condition but it disables checkbox and doesn't show any tooltips

      <mat-checkbox
        *ngFor="let sampleAvailability of sampleAvailabilityOptions; let i = index"
        [formControlName]="sampleAvailability.id"
        [color]="'primary'"
        id="sample-availability-status-checkbox"
        [id]="'sample-availability-status-checkbox-' + i"
        #tooltip="matTooltip"
        [matTooltip]="
          sampleAvailability.name === 'Checked-in'
            ? 'This sample is available'
            : 'This sample is checked out'
        "
      >
        {{ sampleAvailability.name }}
      </mat-checkbox>

I tried to write condition according the documentation. If i remove tooltips then checkboxes work fine
Comment: it worked for me, I used angular 15 though , https://angular-ivy-rebjb4.stackblitz.io . share the package json and corresponding ts and html file.
Answer: Disabled elements don't show tooltips.
Wrap any disableable elements and put the tooltip on that instead.
E.g.

    <mat-checkbox ...>
        {{ sampleAvailability.name }}
    </mat-checkbox>


Images on react native component

Question: I created a react native component and package it for npm following:
https://www.freecodecamp.org/news/how-to-publish-a-react-native-component-to-npm-its-easier-than-you-think-51f6ae1ef850/
After this I created a new react native app and installed my new component using npm pack and npm i ...
However, every time I use Image from within this component using
<code>    const myImg = require(imagesFolder + 'Happy.jpg')
    const caller = this.props.caller;

 return(
    <View style={{height: '100%', alignItems: 'center', backgroundColor: '#ffc600'}}>

            <Text></Text>

            <Image source={myImg}
                style={{width:150, height:150, borderWidth: 1, borderColor: 'red', resizeMode: 'contain'}}
            />

            <Text></Text>
</code>
I can not see the image and the compiler does not report that it could not find the image. Any ideas? Is there a special location for image files that need to placed at?
Thanks
Answer: Try it
<code>    <Image
      source={myImg}
      style={{ height: 350, width: WIDTH }}
      resizeMethod="resize"
      resizeMode="contain"
    />
</code>
Answer: <code><Image
    style={styles.tinyLogo}
    source={require('@expo/snack-static/react-native-logo.png')}
</code>
For more infoenter link description here
Comment: It is just an example. You can access the image. The component does not change. You just have to add the image path.
Comment: Well, this is a very interesting option.... however we are not using Expo!!

Images on react native component


catalog/maven - Demoiselle

Question: Bom dia, à todos !
Executei o comando demoiselle-worspace, foi gerado a workspace, porém sem o servidor jboss somente o tomcat. Mesmo assim configurei o AS Jboss, mas no ato de escolher o catalog demoiselle não apresenta o mesmo. Instalei o linuxMint 17.1, a JVM instalada é da SUN java 7, meu arquivos source.list está sem deb http://demoiselle.c3sl.ufpr.br universal stable. Qual procedimento devo fazer? instalar o kit jdk 6 da oracle e acrescentar esse arquivo no source.list?
Answer: Welder,
Seguiu as instruções deste material? http://demoiselle.sourceforge.net/docs/infra/reference/2.0.0/html/
Para funcionamento correto do Eclipse, precisa ter uma JDK, que pode ser 6 ou 7. No Mint tem opção pela OpenJDK.
A linha  deb http://demoiselle.c3sl.ufpr.br universal stable tem que estar no source.list para poder instalar o pacote do Demoiselle: demoiselle-2-infra-3
Caso já tenha as instruções a cima, vc pode enviar o resultado da execução do comando demoiselle-workspace.
Comment: Olá Emerson, fiz algumas alterações no SO linuxMint 17.1, por ventura não está constando mais no source.list  o link: http://demoiselle.c3sl.ufpr.br/ vou adicionar o link do source.list e inserir o comando para criação da workspace.
Comment: Funcionou, antes eu tinha baixado a chaves e armazenado em um diretório, exclui as chaves e baixei novamente, gerando a workspace como root não conseguiu acessar o workspace, agora sem o super usuário consegui.
Comment: Obrigado pelo retorno, acho que vou melhorar a documentação para ficar claro que para criação do workspace não deve ser como root.

catalog/maven - Demoiselle


Averaging the linear regression coefficients

Question: Isn't it always better to make a number of linear regression models on different samples (sampled out using random sampling) of data set and then taking average of the regression coefficients for all variables?
The reason I am asking this question is that I have read somewhere that the regression coefficient of a variable is distributed normally with mean equal to the population parameter.Although , I am not very clear about this concept , so please correct me if I am wrong.
Also , if I am correct , is it necessary to make same type of model (having same features) each time I take a new sample to train with (so that the regression coefficients are distributed normally).
Comment: *"Isn't it always better to..."* Better in what sense? What sort of improvement do you have in mind? Also, better compared to what alternative?
Answer: I can spot two aspects in your question.
The first is on mixing theory and practical application. The second one is on ensemble modeling.
Mixing theory and practical application
If you are willing to impose many strict assumptions on your linear regression, indeed regression coefficients (seen as random variables) follow a multivariate normal distribution. This allows to calculate classic p values, standard errors and confidence intervals, which is often quite useful. Since these p values etc. are a result from mathematical statistical theory, in applications you don't have to run multiple linear regressions on multiple subsets by your own. You run one model and theory provides you with nice p values etc.
It is the same with the arithmetic mean: You calculate it for your random sample and thanks to the Central Limit Theorem, you know this mean is approximately normal and thus a confidence interval is immediately available without resampling.
Just as an exercise, you might split your sample into 20 parts, run a simple linear regression on each of the 20 parts and look at the distribution of the 20 slopes. It will look more like a Gaussian distribution than, say, a uniform distribution.
Ensemble modeling
You mention different ways on how to run multiple models (and then combining them). Both are typical elements of so called ensemble models. They are used as a way to reduce overfitting and eventually, increase true model performance on fresh data.

Random sampling: If you draw rows with replacement, this is called bootstrap aggregating or bagging and is one of the key features of a random forest. Sampling without replacement is also common, e.g. with gradient boosting.
Random subspace method: Each model has access only to a random subset of covariables. This is heavily used e.g. with gradient boosting methods.

Both element can be applied to linear regression as well, but it is very untypical. Why?
Firstly, linear regressions are often very simple reflections of reality and as such do not overfit in a problematic way. Secondly, it is not too simple to derive classic p values from such ensemble model.
Comment: Thanks for this thorough answer! Talking about the first part (mixing theory) you said that we don't need to run different models since we have p-values ,but then p-value just tells us if the variable is meaningful (correct me if I am wrong). So,what I was thinking was to take average of coefficients coming from different subsets so that our estimate will become more accurate (since mean of the coefficients would be equal to true estimate). And if this is correct than is it necessary to train same type of linear model ,so that coefficients are normally distributed (my 2nd question).


IPTables INPUT and ucarp

Question: What rule(s) are needed to allow ucarp traffic on IPTables?
Answer: I'm assuming you're talking about the advertisment packets between ucarp hosts. I haven't used ucarp, but a quick examination of the source makes me think that it's listening via libpcap such that it will be effectively immune to filtering by iptables.
The carp_send_ad() function in carp.c seems to be where the advertisment packets are sourced from. I'm seeing the code putting together a multicast or broadcast ethernet frame (depending on the no_mcast boolean) with the CARP advertisment inside it. The source IP appears to be the source ip specified on the command-line and the destination IP appears to be the the multicast address 220.127.116.11. As such, you could filter for these source and destination addresses on the INPUT chain, but I think you're going to find that there's no need to worry about it since the packets are being slurped off the wire with libpcap anyway.
(It would be nice if the rain here would let up a bit so that I wasn't sitting inside playing Server Fault...)

IPTables INPUT and ucarp


Need help with some surprising classifications by naiveBayes

Question: We are trying to do a POC on using NaiveBayes to classify an establishment by the category.
We loaded the following  training set in R.
NAME_1,NAME_2,CHANNEL_5
Vanilla,Bar,Bar &  Grill
Zen,Bar,Bar &  Grill
cafe,havana,Bar &  Grill
cafe,hollywood,Bar &  Grill
monaco,grill,Bar &  Grill
grill,grill,Bar &  Grill
hunai,asian,Bar &  Grill
Apple,Institute,School
devry,Institute,School
usu,College,School
suny,university,School
fashion,school,School
theater,study,School
Burger,King,Hamburger
Mighty,Burger,Hamburger
one,Burger,Hamburger
wendy,sandwich,Hamburger
Burger,Heaven,Hamburger
Burgler,Burger,Hamburger

Columns 1 & 2 make up the name of the establishment. Column 3 is the class.
library(e1071);

new_training_data <- read.table("C:/Users/test/08_jul_13_training.txt",
header=TRUE , sep="\t");

 model1<-naiveBayes(new_training_data[,1:2],new_training_data[,3],laplace
 =2);

test_data <- read.table("C:/Users/test/test1.txt", header=TRUE , sep="\t");

predict(model1, test_data[,1:2],type = c("class","raw"));

The test_set with the expected category and the actual result from NaiveBayes classifier are given below.
NAME_1,NAME_2,Expected_category,Actual_Result_from_Naive_bayes
my,Bar,Bar &  Grill, Bar &  Grill
cafe,milano,Bar &  Grill, Hamburger
Teaching,Institute,School, Bar &  Grill
devry,Institute,School, Bar &  Grill
beauty,school,School, Bar &  Grill
fashion,school,School, Bar &  Grill
theater,school,School, Bar &  Grill
Burger,Baja,Hamburger, Hamburger
Burger,Big,Hamburger, Hamburger
Pepsi,Cola,Hamburger, Bar &  Grill
Burger,Supreme,Hamburger, Hamburger
Burger,King,Hamburger, Hamburger

my bar is correctly classified as Bar & grill. However  Cafe Milano is classified as Hamburger instead of Bar & Grill.
statistically speaking the probability of Bar in my Bar is no different from Cafe in Cafe Milano.
Any pointers in how NaiveBayes is coming up with these results will be greatly appreciated.
Comment: Does it really make sense to classify on the _name_ of an establishment?
Comment: Unfortunately this is the only option we have.
Answer: I think this is related to factors, which are a data type in R which often behave unexpectedly.
I don't have your test data, but when you use the classifier to predict from a new data point, you have to make sure that the possible levels of NAME_1 and NAME_2 are exactly the levels which appear in the training data. If the training and test data come from different text files, then this is very unlikely to be the case.
Your first three lines of code work fine for me.
Let's just suppose you want to classify a single new data point with NAME_1 = n1 and NAME_2 = n2. Here is how you could do it.
    pred <- function(model, n1, n2, type){
      n1 <- factor(n1, levels = levels(new_training_data[,1]))
      n2 <- factor(n2, levels = levels(new_training_data[,2]))
      predict(model, data.frame(NAME_1 = n1, NAME_2 = n2), type)
   }

Now it should work with your model. The following behave for me as expected:
pred(model1, "Teaching", "Institute", "class")
pred(model1, "cafe", "milano", "class")
pred(model1, "beauty", "school", "class")

You could extend this to data frames so you could classify all of your test data at once. I hope it helps!
Comment: Thank you. The approach suggested by you is working. Can you suggest how this can be extended to classify all test data at once without using a loop.
Comment: After loading your `test_data`, do this: `for (i in 1:2) test_data[,i] <- factor(test_data[,i], levels=levels(new_training_data[,i]))`. Words in `test_data` which did not appear in the training data will now appear as `NA`. Then your `predict` should work.
Answer: it looks to me like you're doing a multinomial naive bayes.  If you look at the tables component of the model object, you should (according to the docs) see tables of conditional probabilities given the target class.
How many classes are you attempting to predict?  Have you tried 1-3 grams on the incoming words?  It kind of looks like you're using up to two 1-grams; is that correct?
Also, please put your data into tables so we can see which text goes in which column?


Find a Linear Fractional Transformations (LFT) $w(z)$

Question:
I have absulotly no idea how to approach this question, Can anyone please provide with a hint or any kinda information so I can solve this question.
Thank you very much for you help
Comment: What's a LFT? ${}{}$
Comment: Linear Fractional Transformations (LFT)
Answer: So by definition, a fractional linear transformation (a.k.a. a Möbius transformation) is a complex function of the form $w(z) = \frac{az + b}{cz + d}$, where $a,b,c,d \in \mathbb{C}$ satisfy $ad - bc \neq 0$.
In this particular example, we are looking for a fractional linear transformation $w(z)$ that satisfies $w(1) = 1+i$, $w(i) = 1-i$, and $w(-i) = 2$.
Let's start off by arbitrarily picking a value for one of the four unknowns. (If we have the bad fortune of picking a value that makes the rest of the problem impossible, then we'll need to start over and pick a different arbitrary value.) I'll choose to set $a = 1$.
So $w(z) = \frac{az + b}{cz + d} = \frac{z + b}{cz + d}$.
Now we apply our constraints:

Plugging in $w(1) = 1+i$ gives us $\frac{1 + b}{c + d} = 1+i.$ Rearranging gives us $-b + (1+i)c + (1+i)d = 1$.
Plugging in $w(i) = 1-i$ gives us $\frac{i + b}{ci + d} = 1-i.$ Rearranging gives us $-b + (1+i)c + (1-i)d = i$.
Plugging in $w(-i) = 2$ gives us $\frac{-i + b}{-ci + d} = 2.$ Rearranging gives us $-b -2ic +2d = -i$.

So now we have 3 linear equations in 3 unknowns, namely:

$-b + (1+i)c + (1+i)d = 1$
$-b + (1+i)c + (1-i)d = i$
$-b -2ic +2d = -i$

You can solve this using any of the same techniques you would use to solve a 3-by-3 system of linear equations with real coefficients.
When I solved this system, I found $b=-\frac{4}{5}-\frac{3 i}{5}$, $c=\frac{3}{10}+\frac{i}{10}$, and $d=-\frac{1}{2}-\frac{i}{2}$. You should solve the system yourself and make sure you get the same result.
Comment: Okay I get everything you are saying, but now I'm stuck on the solving the equations part. I'm not sure if I'm solving them right
Comment: that is perfect! thank you very very much!!


Scheme what does #= as output mean?

Question: Hi I'm trying to learn Scheme and I was working on an example from a university website:
https://courses.cs.washington.edu/courses/cse341/05au/lectures/scheme-side-effects.html
The example is something along these lines:

(define circ '(a b))
(set-cdr! (cdr circ) circ)

and this is the output:
=> #0=(a b . #0#)
I don't understand what this means.  The code defines a variable called circ as a list with 2 elements (a b).
set-cdr! mutates the cdr of this list [which is (b '())] and changes it to circ (which is (a b)).
So the output I expected here was (a (a b)) but I got this weird hashtag thing instead.
I'm using DrRacket IDE with R5RS scheme set as the language.
What does this hashtag stuff mean?  Is it maybe creating a pointer to itself like (a [pointer to circ]) in which case it would be like some kind of infinite loop or something?
I mean if I do this:

(define x '(a b))
(set-cdr! x 'c)
x

=>(a . c) ; is the output
this is easy to understand as set-cdr! replaces the (b '()) with 'c and getting rid of the '() at the end is why I get a dotted pair back instead of a list.  But this isn't in-line with the earlier example.
anyway if anybody cares to fill me in, let me know.  Thanks in advance.
Answer: You are correct in thinking that the operation is the creation of a circular list.
Drawing a list through its cons cells, this is the situation after the define:

and this is the situation after the set-cdr!:

Note that the modification is on the cdr of the cdr of circ (so on the cdr of the second cell). The notation #0=(a b . #0#) in lisp languages describes an improper list where the last cdr is equal to the list itself, producing a circular data structure (i.e. a data structure with a "loop").
Comment: ahh this is even more helpful than I thought because I wasn't getting in general that each element of a list is a cons cell with 2 values.  The first is the actual value and the second is a link to the next cons cell.  I guess that should have been obvious but it just sank in looking at these drawings you posted and it's why I couldn't understand what is going on.  So the tail of the list is a cons cell with the value as the car and instead of a link it has the null or '() empty list symbol as the cdr.  I was thinking of each element of a list as a single value.  Thanks again.
Comment: Thanks.  I guess I'm thinking also from this (and other examples) that #something is what Scheme is going to output when the symbol being evaluated doesn't have a printed representation like a string or a number would.

Scheme what does #= as output mean?


I want to set some error message at one method and display it at another method

Question: I have a method , here I set some message .
function doSomeAction(){

$messenger = \Drupal::Messenger();
$messenger->addMessage('error msg',$messenger::TYPE_ERROR,true);
 $response = new RedirectResponse(\Drupal::url('action_error.content',[], ['query' => ['error' => '1'],'absolute' => TRUE,]));
$response->send();
return $response;

}

I want to display this error message at another method
function action_error(){
$messenger = \Drupal::Messenger();
$msg = $messenger->messagesByType($messenger::TYPE_ERROR);
print_r($msg); die();

}

As a result I got Blank array..
Method doSomeAction and action_error is in same class differentiated by routing.yml
I have checked error-log from back-end , displaying  some error i.e

RuntimeException: Failed to start the session because headers have
  already been sent by
  "\vendor\symfony\http-foundation\Response.php" at line 1286.

In D7

In drupal 7 drupal_set_message() & drupal_get_messages() available..We can easily handle message
Answer: It's not about how you set and get the message, although you normally don't get a message but display it in the system message block.
The issue is that you can't send a response from inside a Drupal 8 function. This sends the response headers too early, so that the session handling for the message doesn't work anymore. If doSomeAction() is a controller, then only return the redirect response, do not send it:
function doSomeAction(){
  $messenger = \Drupal::Messenger();
  $messenger->addMessage('error msg',$messenger::TYPE_ERROR,true);
  $response = new RedirectResponse(\Drupal::url('action_error.content',[], ['query' =>
    ['error' => '1'],'absolute' => TRUE,]));
  // $response->send();  ... don't send responses from inside a D8 function
  return $response;
}


Detect multicollinearity in maximum likelihood scenarios

Question: I'm estimating a binary logit discrete choice model with BIOGEME and want to check for multicollinearity of my predictors. BIOGEME uses maximum likelihood estimation (MLE) and not ordinary least square (OLS) method.
In OLS regression models, one can use $VIF = \frac{1}{1-R^2}$ to assess for multicollinearity.
My questions are:

Can I use VIF in the context of MLE as well?
In case, that yes: McFaddens $R^2$ is defined exactly the same as $\rho^2 = 1- \frac{L_1}{L_0}$, where $L_1$ is the estimated model and $L_0$ the nullmodel. Can I then derive: $VIF = \frac{1}{1-\rho^2}$ ?
If not: are there any other measures for multicollinearity in MLE models?

Obviously, I check for correlations in between the independent variables before the modelling. However, I'd like to have an indicator for my final model as well.
Answer: There needs to be a distinction made between predictor multicollinearity and VIF.
The variance-inflation factor (VIF) represents relationships among the coefficients of the independent variables, as captured in the coefficient variance-covariance matrix. The equation given above for unweighted ordinary least squares (OLS) takes advantage of the independence of the entries of that matrix from the dependent-variable values, outside of the estimate of overall variance. There is a direct relationship between the predictor multicollinearity calculated from that equation and the covariances among the estimated coefficients.
For models fit by maximum likelihood (ML), the relationships between the predictors and the dependent variable can influence the variance-covariance matrix, unlike with OLS. In an ML model the OLS formula for VIF will similarly show multicollinearity among predictors, but the relationship between the predictor multicollinearity and the coefficient covariances won't necessarily be so direct.
You might want to consider a different approach, rather than VIF, for evaluating predictor multicollinearity per se. The generalized VIF helps if your independent variables include categorical factors, and for ML models it will provide an estimate based directly on the variance-covariance matrix. See this page.
Comment: Thanks for your comment and the clarification. I indeed missed that $R^2$ is for the independent variables and has nothing to do with the dependent variable. Thanks also for the link, I'll have a look into CI, too!


Uma chave primária pode ser usada em uma chave estrangeira?

Question: O seguinte exemplo pode ocorrer?
| Id | nome | data | qnt |

PK -> Id
FK -> (Id, qnt)

Ou há algum tipo de restrição?
Comment: Pode ocorrer. Só não me parece muito correto uma FK com uma quantidade...
Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: 1) A única restrição para chaves estrangeiras é que elas devem apontar para uma chave única.
Note que toda PK, por definição, é uma chave única.
Pense o seguinte: a chave estrangeira indica quem é o registro pai, do qual o registro filho depende e sem ele ficaria órfão. Além disso o registro filho não pode ter dois pais (ponto!)
2) Uma chave é uma campo que identifica o registro, como um nome de uma pessoa. Uma chave única é um campo que identifica unicamente um registro, como um CPF.
3) Qualquer chave pode ser composta por mais de uma coluna.
Ai vai depender muito do schema mas em geral uma chave é algo que identifica o registro.
4) Um campo que será usado como chave nunca deveria ser mutável.
Isto é: nunca deveria ser um campo cujo valor possa ser alterado, por exemplo seu CPF, imagine que seu CPF pudesse mudar o tempo todo, como é que você poderia ser identificado por isso?
5) Um campo quantidade não é um bom candidato para ser usado como chave, ele é um campo (relativamente) mutável e não identifica o registro. Na verdade não passa de um atributo então não use-o como chave. Se você faz muitas pesquisas filtrando por este campo pode ser interessante indexá-lo para melhorar a performance mas não elevá-lo a uma chave.
Edit
@Maniero A implementação da constraint vai depender do SGBD, exemplos:
MSSQL e MySQL.
e a referência sobre o conceito de FK na Wikipédia
Porém mesmo que o SGBD permita isso é uma quebra da integridade relacional.
Por que? Bem se você muda o id do registro pai, sem alterar os registros filhos eles ficarão órfãos. Se um filho pode ter "n pais" então é melhor inverter a hierarquia e fazer o registro "ex-pai" referenciar o registro "ex-filho".
Se a relação for N para M então seria melhor criar uma tabela de relacionamento com FKs para "pais" e "filhos".
Pode até ser que exista alguma necessidade em algum lugar de criar uma FK para um chave not unique mas as poucas vezes em que vi tal coisa foram em erros graves de modelagem.
Comment: FK não precisam ser únicas nem ser imutáveis. É altamente desejável que seja assim, raramente existe um caso onde esta regra não é aplicável mas dizer que **deve** ser é, no mínimo, um exagero.
Comment: @bigwon Não acredito que seja um exagero. Essas são regras de integridade relacional e embora os SGBDs permitam que você não siga as regras eu prefiro usa-las. Isso ajuda a manter meus dados íntegros =)
Comment: Mas então você está afirmando na resposta algo que é apenas sua opinião. Para quem não sabe, a resposta pode induzir ao erro e a pessoa pode achar que é obrigatório.
Answer: O Id, que é chave primária, não só pode como frequentemente é usado em FKs.
Se quer saber se a chave pode ser composta, ou seja, usar mais de uma coluna como FK? Sim, pode e também é comum acontecer.
qnt além de ser um nome ruim para indicar alguma coisa (eu vou imaginar que seja quantidade) provavelmente não é uma boa escolha para fazer parte de uma FK. Mas sei lá, pode existir um motivo. Eu não sigo regras de ouro, eu vejo a necessidade. Normalmente colunas que possuem dados não muito estáveis não são recomendados para uso em FK. É preferível usar colunas que identifique alguma coisa. Uma quantidade não identifica nada.

Veja o artigo na Wikipedia (em inglês melhor).
Sobre chave composta.

Coloquei no GitHub para referência futura.
Comment: vlw! foi só um exemplo, eu sou bem específico na nomeação de campos, ou, variáveis... para não me perder rsrs
Comment: Uma palavrinha fora do assunto, mas talvez te ajude, comece a melhorar nos nomes das variáveis, você vai ver que no futuro, um nome conciso, mas completo, é o diferencial para não se perder. Só agora percebi o quão antigo é esse post. Jesus, me salva
Answer: Sim , um exemplo :
Nota_fiscal
Numero (pk)
Valor
Data
Nota_fiscal_item
Numero (pk) (fk nota_fiscal.numero)
Num_item (pk)
Desc_item
Valor
Entendendo claro que o modelo é uma grande simplificacão.
Comment: muito obrigado! ^^


How does one cause a Megaraid controller to "re-scan" the devices?

Question: We are using a Supermicro Megaraid card (2208) and we are trying to perform some SCSI operations directly on the drives using the passthrough ioctl. One issue that we have run into is that when we change something on the drive (say it's visible capacity), the megaraid controller does not "see" the change and tries to access the drive as if it still has the original capacity.
Physically pulling the drive out, waiting for a few seconds and returning it - solves the problem.
It seems that if we had a way to tell the Megaraid controller to "re-scan" the device we would be all set, the problem is that we don't know how to do it. Does anyone know how to do it?
Thanks in advance
Answer: Untested, because I only have production systems. My approach would be
storcli /cx/px reset

Answer: If pulling and re-inserting the drive helps, consider using the megarc utility to power off and re-power the drive:
megarc -physOff -a0 pd[x:y]
megarc -physOn -a0 pd[x:y]

Also take a look at MegaCLI - the CLI configuration utility for LSI MegaRAID controllers. It offers a whole variety of RAID- and PD-related commands and is more widely supported. If using it to offline and re-online the drive with the -PDOffline and -PDOnline commands would help as well, I would advise using this route instead.
Comment: The megacli options of pdoffline and pdonline don't seem to cause the controller to "re-scan" the drive, they seem more like virtual operations.


Exclude web part from flutter

Question: After a new update I noticed that when I use Flutter create myproject I includes web folder as well either I want it or not. So my question is that

Is there anyway to exclude web portion during FLutter create???
Answer: execute this command before creating the project:
$ flutter config --no-enable-web

Exclude web part from flutter


Error building release target with Growl framework included

Question: I just addred Growl integration to an Xcode application.  The source compiles and runs correctly under the Debug target while testing.
When I try to build the Release target however, I get the following error and I'm not sure why, or whoe to resolve it.
<code>Building target "EchowavesNotifier" of project "EchowavesNotifier" with configuration "Release" — (1 error)
    cd /src/echowaves-notifier-osx
    /Developer/Library/PrivateFrameworks/DevToolsCore.framework/Resources/pbxcp -exclude .DS_Store -exclude CVS -exclude .svn -strip-debug-symbols -resolve-src-symlinks /src/echowaves-notifier-osx/Growl.framework /src/echowaves-notifier-osx/build/Release/EchowavesNotifier.app/Contents/Frameworks
    strip: for architecture x86_64 object: /src/echowaves-notifier-osx/Growl.framework/Versions/A/Growl malformed object (unknown load command 5)
    pbxcp: warning: couldn't strip: /src/echowaves-notifier-osx/build/Release/EchowavesNotifier.app/Contents/Frameworks/Growl.framework/Versions/A/Growl: No such file or directory
    pbxcp: warning: couldn't strip: /src/echowaves-notifier-osx/build/Release/EchowavesNotifier.app/Contents/Frameworks/Growl.framework/Versions/A/Growl: No such file or directory
    pbxcp: warning: couldn't strip: /src/echowaves-notifier-osx/build/Release/EchowavesNotifier.app/Contents/Frameworks/Growl.framework/Versions/A/Growl: No such file or directory
    pbxcp: warning: couldn't strip: /src/echowaves-notifier-osx/build/Release/EchowavesNotifier.app/Contents/Frameworks/Growl.framework/Versions/A/Growl: No such file or directory
Build failed (1 error)
</code>
Is it some kind of 64-bit (x86_64) related issue?
Answer: I ran into this recently when upgrading Growl, and several other groups have noted it (I found some traffic on the Unison.app list). What seems to be happening is some kind of mismatch at the link step, though I haven't been able to isolate it.
The solution I've found so far is to delete the entire build/ directory and rebuild (which is much more than just doing a "clean" in xcode). So far I have not seen the problem recur for any developer after performing that. Please let me know if this does or doesn't fix your problem, since I want to know whether I need to continue hunting solutions for this problem should it come back.
Comment: compiling Growl.framekwork from the Growl source on 10.5 with Xcode 3.1.4 did indeed fix the problem for me
Comment: I did an `rm -rf build` from the command line, but still am getting the same error trying to build the Release target
Comment: Here's another work-around. http://forums.cocoaforge.com/viewtopic.php?f=6&t=21261 There is some belief that this is an xcode bug, and I recommend opening a radar to make sure Apple is tracking it.
Comment: interesting.  thanks for the link.

I'll try downloading the source and building it myself on Leopard.

I am indeed trying to build with Xcode 3.1.4 on Leopard.  I haven't tried building it on my 10.6 machine yet.


What is the conceptual meaning of a definite integral?

Question: I'm having trouble articulating my difficulty, but here's my best shot.  Thanks in advance for any light you can shed.
I understand that a definite integral is the limit of a Riemann sum, and can represent an area between a curve and the x-axis.
I have found a couple of problems in my first-year calculus textbook that have led me to believe that I do not have a full understanding of definite integrals.  These are applications problems, and although I have full solutions to them, I don't understand why the solutions produce answers that make sense, particular in regards to the units of the answers.
These are from the Larson Calculus text, eighth edition.
This first one, I understand, but I need to quote it for context to frame what it is I don't understand.  (I am not giving the actual functions because they aren't relevant to my misunderstanding.)

Water Supply:  A model for the flow rate of water at a pumping station
on a given day is:  R(t).  R is the flow rate in thousands of gallons
per hour, and t is the time in hours.  Approximate the total volume of
water pumped in 1 day.

This is my understanding:  R(t) is a rate in thousands of gallons per hour, and t is in hours.  If I integrate R(t) over the interval [0, 24], then the answer I get from the integral, in addition to being the area under R(t) from 0 to 24, will represent a volume of water.  This makes sense to me because if I were to graph R(t) and look at it as an area, the Riemann rectangles would have a width of hours and a height of thousands of gallons per hour and multiplying them together means the area will have units of gallons, because (gal/hr) times hours would leave gallons. So the integral will evaluate to a value representing gallons.
In general, integrating a rate of change should result in the net change over the interval, yes?  This makes sense to me.
Now, the second problem is this:

Temperature:  The temperature in degrees Fahrenheit in a house is T(t)
where t is the time in hours, with t=0 representing midnight.  The
hourly cost of cooling a house is $0.10 per degree.  Find the cost of
cooling the house if its thermostat is set at 72 F. by evaluating the
integral
$$C=0.1\displaystyle \int_{8}^{20}{T(t)-72} \ {\rm d}t$$

Now here, the function T is not a rate of change, it gives the actual temperature of the house at time t, and not the rate at which the temperature changes.
So I guess I have some conceptual misunderstanding of the definite integral because I can't reconcile the units or the meaning of what's going on here.
I can see that the 0.1 in front of the integral is there because in order to get the cost in $$ we need to multiply the $0.1 times the number of degrees, so it appears from the question that I am to interpret the integral itself as calculating a number of degrees.  But I don't understand how it could.
That is, if the units of T(t) are degrees, and the time is hours, then my area understanding of the integral should give the area calculated by this integral in units of degree times hours, or degree-hours?  Since the units of the 0.1 are dollars/degree, then multiplying dollars/degree by degree times hours results in dollars times hours, but it should come out in dollars alone, and I don't see how.
The integral would have to have units of degrees in order for the cost to come out in dollars.  How can it?  If the function T is not a rate, but an actual amount of something, like degrees, then what meaning do I give to integrating it over an interval?  I will get an area, yes, but would that mean anything necessarily?
If I integrate velocity, which is a rate of change of position, then I get the total change of position, or distance.  What if I have a position function, which is not a rate of change, and integrate that?  Does the result have any meaning?  That's what this temperature function seems to be doing. T(t) is not a rate of change function, it's like a position function.  If I integrate it, why do I end up with total degrees?
Comment: (.1 dollars per degree per hour) $\times (T - 72)$ degrees gives you dollars per hour.
Comment: "The **hourly** cost ... is $0.10 per degree"
Comment: Disregarding units for a moment, you should note that your cost is also dependent on how much time your thermostat is set at 72 F. For instance, if your temperature is 82F for an hour the cost will be equivalent to 77F for 2 hours. By the way, you may get a better physical understanding in http://physics.stackexchange.com/. For mathematicians the definite integral is simply the limit of the Riemann sum.
Comment: Overall, don't let one question phase you. An integral is an infinite summation of infinitesimal parts, like you said. There's nothing more to it than that.
Answer: As a(n aspiring) geometer, the conceptual meaning of the integral for me is that integration is the process of adding little flats volumes (or areas, or...) to get big generally curved volumes (...).

In $1$-d calculus the regions you integrate over may not be as interesting but the idea is the same.

That's really all there is to integration -- add up a lot of little things to get a (potentially) big thing.
The fact that integration over an interval of a single-variable rate of change function is equal to the total change of that interval is actually somewhat of a minor miracle.  That inverse relationship between the derivative and the integral doesn't work nearly as nicely in higher dimensions.  Even so, it really is useful ... in fact I'd say it's almost fundamental to calculus. :)

Mathematicians don't normally worry about units, but physicists do and they do tend to always work out.  So it is a good idea to use dimensional analysis to figure out if the quantities you're dealing with actually make sense.
Speaking of physics, here's one more image just for fun.

The thing you seem to have misunderstood in your problem is that the quantity \$0.10 actually has units of dollars per degree per hour (equivalently dollars per degree-hour).  You can see this from the beginning of that line which reads "The hourly cost ... is \$0.10 per degree".
The integral $\int_8^{20} (T(t) -72)dt$ itself doesn't give the total temperature change over the interval $8\le t\le 20$ -- it gives the value of the average temperature (measured from $72^\circ$) over that time interval times the length of the time interval.  For instance if the temperature were $85^\circ$ for the first 6 hours and then $83^\circ$ for the last 6 hours then the value of the integral would be $(84-72)\times 12 = 144$.  The units of this are then degree-hours.
The above comes essentially from the definition of an average.  To calculate the average value of a function $f$ over the interval $a\le t\le b$ we find that $f_{av} = \frac{1}{b-a}\int_a^b f(t)dt$.  Multiplying by $b-a$ on both sides we see that the integral $\int_a^b f(t)dt$ is equal to the average value of the function $f$ over the interval times the length of the interval.

Then we can see that dollars per degree-hour $\times$ degree-hour $=$ dollars, as expected.
Comment: This makes sense, thank you for pointing it out.  My continued difficulty, though, is I am hung up on why integrating T(t) should give degrees at all.  If I say d(t)=10t, where t = hours and d is the miles I drove, and integrate d(t) from 0 to 3, the answer is 45.  But that does not mean I have driven a total of 45 miles.  So why does integrating a function that gives the temperature of the house in degrees mean an answer of total degrees?  I can't wrap my head around that and I have got to be missing something very fundamental.
Comment: The integral $\int T(t)dt$ doesn't have units of degrees.  It has units of degree-hours.  Then because the constant out front has units of dollars per degree per hour (equivalently dollars per degree-hour) the quantity $C$ has units of dollars as expected.
Comment: The way to understand [blank]-hours (as opposed to [blank] per hour) is that 1 [blank]-hour corresponds to holding 1 [blank] over the course of 1 hour.  Whereas 1 [blank] per hour corresponds to 1 [blank] for every 1 hour.  IDK if that makes sense, but assuming you've taken classical mechanics try to think of something like impulse which has units of Newton-seconds.  So an impulse of 1 Newton-second is the amount of impulse you get when you apply a 1 Newton force for 1 second.
Comment: That is very helpful, thank you.  I have not had classical mechanics in many years, but I think it is clearer now.  1 Newton-second is a 1 Newton force applied for 1 second of time, and would that mean that 1 Newton per second would mean 1 Newton applied every second?  But possibly for less time?  No, I guess if a 1 Newton force applied for half a second, every one second, then you'd have 0.5 Newton-second per second.  So 1 Newton per second wouldn't really be meaningful without context?
Comment: Newtons per second would be the units of a **rate**.  This would tell you how fast the force on an object is changing.  In general divisions represent rates.  I don't know of a general term for the thing that multiplication represents.  But it's always something like this, Newton-seconds are the units you get when you want a quantity which is proportional not only to the amount of (average) force applied to an object, but also the amount of time that it was applied.  A rate of force change doesn't give you any indication of how long the force was applied, but impulse does.
Comment: Derivatives give you rates.  Integrals give you these unnamed multiplicative things.  The fundamental theorem of calculus says that when you integrate a derivative you get back the total change (as opposed to the rate of change).  But that doesn't help very much if the thing you're integrating can't be physically thought of as a rate (or mathematically thought of as a derivative).
Comment: Yes, that's it.  That's exactly what was hanging me up.  If I take a position function in feet and graph it against time, then integrating it  isn't going to give me anything meaningful except an answer with units of feet-hours, unless I do something else with it, like multiplying by the reciprocal of the interval of integration, which will return the units to feet and give the average function value.  Thank you so much for the gift of clarity, Bye_World.
Answer: At the very least the second question is poorly phrased. T(t) can't be the temperature in a house if the thermostat is set for 72 degrees. The question only makes sense if T(t) is the outside temperature.  Also, the integral should
have parentheses surrounding "T(t) - 72"
T(t) is temperature expressed as a function of time. T(t)-72 is the spending rate in dimes per hour at time t. Integrating the spending rate over the integration time gives the cost in dimes. Dividing dimes by 10 gives dollars.


zen of angular2 universal - when to app.browser.module.ts or app.node.module.ts

Question: In angular2 universal....the docs are 2 files
app.browser.module.ts
app.node.module.ts

https://github.com/angular/universal-starter
Both on a fresh repo look the same.  I assume one is for server side (node) and other is for client side (browser)?
So when I am adding routes, imports etc I am adding to both because I am unsure what do to.  If I have to add to both then why 2 files that look the same?
When would I add to one or the other where the diverge?  When do I add to both node and browser app?
Thanks
app.browser.module.ts
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal/browser'; // for AoT we need to manually split universal packages

import { App, Home } from './app/app';

@NgModule({
  bootstrap: [ App ],
  declarations: [ App, Home ],
  imports: [
    UniversalModule, // BrowserModule, HttpModule, and JsonpModule are included
    FormsModule,
    RouterModule.forRoot([
      { path: '', component: Home, pathMatch: 'full' }
    ])
  ]
})
export class MainModule {

}

app.node.module.ts
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal/node'; // for AoT we need to manually split universal packages

import { App, Home } from './app/app';

@NgModule({
  bootstrap: [ App ],
  declarations: [ App, Home ],
  imports: [
    UniversalModule, // NodeModule, NodeHttpModule, and NodeJsonpModule are included
    FormsModule,
    RouterModule.forRoot([
      { path: '', component: Home, pathMatch: 'full' }
    ])
  ]
})
export class MainModule {

}

Comment: rather stunned that the angular-universal team does not even  take a stab at answering the question.  Even there home home page is out of date and provides wrong setup info.
Comment: To answer your `"rather stunned that the angular-universal team does not even take a stab at answering the question. Even there home home page is out of date and provides wrong setup info."` I think the team is busy impleting Universal since it is very new. They need balance time creating new things and helping people. I would suggest if you want something be improved, create a PR [here](https://github.com/angular/universal/issues) instead complaining here
Answer: From the documentation:
https://github.com/angular/universal/blob/master/DOCUMENTATION.md
Note that in the starter repo app.node.module.ts and app.browser.module.ts are exactly the same, but in your app they will almost certainly be different as you specify node-only or browser-only providers in the imports section as appropriate for each specific platform.


Suppose $v\in [\pi/2, \pi]$ with $\tan v=-17$, find the exact expression. Find $\sin(v-3\pi)$

Question: I need help solving the problem thank you!
Answer: Use the formula $\sin(A-B) =\sin A \cos B - \sin B \cos A$ to simplify $\sin(v-3\pi)$ keeping in mind that $\sin(3\pi) = 0$ and $\cos(3\pi) = -1$.
$\tan v = -17$ implies that $\sin v = \cfrac {17}{\sqrt{290}}$ and $\cos v = \cfrac {-1}{\sqrt{290}}$.  Use thes values and you will get your answer. I hope you understand.
In the interval given $\forall \theta \in [\pi/2, \pi]$, $$\sin \theta \ge 0$$ $$\cos \theta \le 0$$ $$\tan\theta \le 0$$
Comment: no but $-\cfrac {17}{\sqrt{290}}$
Comment: i got it just got it thank you!!!
Comment: what formula would you use for cos v=


Mysql. Bind on unix socket: Permission denied

Question: Can't start mysql with:
130408 11:31:22 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
/usr/libexec/mysqld: Table 'plugin' is read only
130408 11:31:22 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
130408 11:31:22  InnoDB: Initializing buffer pool, size = 8.0M
130408 11:31:22  InnoDB: Completed initialization of buffer pool
130408 11:31:23  InnoDB: Started; log sequence number 0 19514977
130408 11:31:23 [ERROR] Can't start server : Bind on unix socket: Permission denied
130408 11:31:23 [ERROR] Do you already have another mysqld server running on socket: /var/lib/mysql/mysql.sock ?
130408 11:31:23 [ERROR] Aborting

130408 11:31:23  InnoDB: Starting shutdown...
130408 11:31:28  InnoDB: Shutdown completed; log sequence number 0 19514977
130408 11:31:28 [Note] /usr/libexec/mysqld: Shutdown complete
130408 11:31:28 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

Another mysql is not runnig:
[root@triton667 etc]# ps ax | grep mysql
 9195 pts/1    S+     0:00 grep mysql

my.cnf:
    [mysqld]
    datadir=/var/lib/mysql
    socket=/var/lib/mysql/mysql.sock
    user=mysql
    tmpdir=/tmp
    # Disabling symbolic-links is recommended to prevent assorted security risks
    symbolic-links=0
    max_allowed_packet=256M

    [mysqld_safe]

    log-error=/var/log/mysqld.log
    pid-file=/var/run/mysqld/mysqld.pid

Permissions on "/tmp" and "/var/lib/mysql" are 777/
Any suggestions?
UPD1:
[root@triton667 etc]# mysql_upgrade
Looking for 'mysql' as: mysql
Looking for 'mysqlcheck' as: mysqlcheck
Running 'mysqlcheck with default connection arguments
mysqlcheck: Got error: 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) trying to connect
FATAL ERROR: Upgrade failed

UPD2:
plugin.MYD, plugin.MYI and plugin.frm are exists in /var/lib/mysql/mysql/.
Nothing running on port 3306.
mysql.sock does not exist. I tried to create it myself, but after restart it was removed.
mount(all rw):
[root@triton667 mysql]# mount
/dev/md1 on / type ext4 (rw,noatime,usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0)
proc on /proc type proc (rw)
sysfs on /sys type sysfs (rw)
devpts on /dev/pts type devpts (rw,gid=5,mode=620)
tmpfs on /dev/shm type tmpfs (rw)
/dev/md0 on /boot type ext2 (rw)
none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)
sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)
nfsd on /proc/fs/nfsd type nfsd (rw)

This problem appeared today when I tried to clone my site on a subdomain.
Comment: run `mysql_upgrade` as suggested?
Comment: No.
touch /var/lib/mysql/mysql.sock - Also does not work
Comment: Is there a plugin.MYD, plugin.MYI and plugin.frm file under /var/lib/mysql/mysql ?
Comment: Also, does the mysql.sock file exist in the /var/lib/mysql directory?
Comment: Is something already running on 3306 port?
Comment: Is your filesystem mounted read-only?
Comment: @user168508 If you've resolved the issue, please post the solution as an answer and [mark it accepted](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work).
Answer: 1) First make sure you delete the existing socket file using the rm command.
rm /var/lib/mysql/mysql.sock

2) Kill all existing MySQL processes via the following command.
service mysql stop

3) Very important: Make sure the permission for the MySQL database directory under /var/lib/ folder should be mysql:root
chown -R mysql:root /var/lib/mysql

4) With the above information you should be able to start MySQL successfully and the socket file should be created successfully under the database directory.
service mysql start

Comment: I use a Ubuntu Server, and this didn't worked.
Answer: Thanks to @Abhishek's answer combined with mysqld output(Can't use /var/run/mysqld/mysqld.sock) I managed to solve this with one command:
chown -R mysql:root /var/run/mysqld

Then it starts properly:
root@***:~# service mysql start
df: Warning: cannot read table of mounted file systems: No such file or directory
[ ok ] Starting MySQL database server: mysqld ..
[info] Checking for tables which need an upgrade, are corrupt or were
not closed cleanly..

Comment: Your welcome from the future :)
Answer: Your problem can be caused by any condition that prevents the MySQL daemon from writing a socket file to the path /var/lib/mysql. The other answers, such as a read-only filesystem or incorrect directory ownership, address various reasons that MySQL may not be able to write to the socket.
Another possible reason is that /var/lib/mysql may have the incorrect SELinux context. You can diagnose this condition by checking for recent SELinux AVC denials after attempting to start the MySQL daemon:
ausearch -m avc --start recent
If SELinux is denying access to create the socket file, you will see an error message like this:
time->Thu Feb  2 03:46:27 2017
type=SYSCALL msg=audit(1566106187.784:152): arch=c000004e syscall=49 success=no exit=-13 a0=4f a1=7ff3fd652e80 a2=6e a3=7fcd2d6523d40 items=0 ppid=1 pid=1820 auid=4294967295 uid=996 gid=994 euid=996 suid=996 fsuid=996 egid=994 sgid=994 fsgid=994 tty=(none) ses=4294967295 comm="mysqld" exe="/usr/sbin/mysqld" subj=system_u:system_r:mysqld_t:s0 key=(null)
type=AVC msg=audit(1566106187.784:152): avc:  denied  { create } for  pid=1820 comm="mysqld" name="mysql.sock" scontext=system_u:system_r:mysqld_t:s0 tcontext=system_u:object_r:var_log_t:s0 tclass=sock_file

To resolve an SELinux denial, try to restore the default context of the directory (your distribution should set the correct context of mysqld_db_t when you installed MySQL or MariaDB):
restorecon -R -v -f /var/lib/mysql
If you have customized the contexts on your system, fixing the problem is beyond the scope of this post.
Comment: On CentOS 7 with SELinux this is what I was facing and restoring the context fixed it.
Answer: Based on what you write, I would suggest that you check if your filesystem is mounted read-only.

130408 11:31:22 mysqld_safe Starting mysqld daemon with databases from
  /var/lib/mysql /usr/libexec/mysqld: Table 'plugin' is read only
Answer: I tried all of the other answers to resolve the issue. It appears that when i set selinux to permissive: setenforce 0 I could start the server.
I then amended the sock directory /var/lib/mysql granting selinux permissions to the directory:
semanage fcontext -a -t mysqld_db_t "/var/lib/mysql(/.*)?"
restorecon -R -v -f /var/lib/mysql

Once done, i enable selinux using setenforce 1 started the mysql service and all was well.
Hope this helps others.
Answer: While the selected answer might do the trick, I had no luck with it. Only after following this suggestion to kill mysql processes I could then reboot and mysql was up.
Interestingly enough, in my case mysql was up after powering down and up again, but not after a reboot from the command line (and would not be started. except power off and on again)
Otherwise the symptoms were the same.
MulMic


How to insert cautionary key signature before repeat mark using Sibelius 7

Question: I'm arranging wind parts for the following song (excerpt below). This is the end of a repeated section that starts in D major and changes to F major halfway through. So, the repeat mark at the end of the section, (in the first and second time bars) sends the player back to D major. Therefore I need a cautionary D major key signature (as written in the music already).
So, how do I get these cautionary D major key signatures, using Sibelius 7, without changing the key of the following bars? Or would it just be easiest to do this with symbols in each of the parts? (Which isn't ideal…)
Comment: I don't know anything about Sibelius but have you tried this link? The answers appear to be good. http://www.sibelius.com/cgi-bin/helpcenter/chat/chat.pl?com=thread&start=624872&groupid=3&&guest=1
Comment: Looks good - I can't try it at the moment, as I'm doing something else. If it does work, you should put the link in an answer and I can let you have the bounty… I'll get back to you… You could put the link in an answer anyway...
Answer: This link might be useful:
Sib. 7.1.3: Cautionary key signature immediately before end repeat barline?
I'll paste an answer here anyway. It's also possible to ask your question on that forum I think, people over there might be more knowledgeable about this.
A sample answer:

Re: Sib. 7.1.3: Cautionary key signature immediately before end repeat barline?
Posted by Richard Hatton - 20 Feb 02:54PM
It can be done.

Have your repeat barline as usual and put in the key change (which will end up after the barline.
click on the key sigature on one of the staves and drag it back to before the barline.
Move the barline to the end of the system (either by dragging or by using the inspector. (if using the inspector I found an "X" value of -1.5 was about right)
Tidy up the key signature position relative to the barline by dragging.

Note you can move the key signatures using the inspector but you need to select all of them first, I found it easier to drag! Also do the final positioning in a Transposing score else you could have some key signatures runninginto the repeat barline.
--
Richard Hatton
Sibelius 7.1.3 ,Photoscore Ult. 7.0.2; Windows 7 64 bit; quad core i7, 16GB ram; core I5, 8 GB ram also with Sibelius 6.2 and Photoscore 6.1.
Comment: Yesterday I started writing an answer suggesting you drag the key signature left after you've inserted it. I didn't post the answer when I realised that although the score looks OK, it doesn't play back correctly. Sibelius places key changes at the beginning of a bar, rather than a cautionary at the end of a previous bar. So I think that the engraving construct that's been requested may not strictly be required. But I couldn't find any engraving articles that categorically state how this music example should look.
Comment: @BrianTHOMAS thanks for your advice. I kind of took your approach in the end anyway. When copying and arranging I'm not too fussed about playback.
Answer: The solution @Sazid_violin linked to 90% solves this problem, so I've awarded the bounty.
However, to get the cautionary natural on the D major key signature in the second time bar, I had to put an F major key signature in and hide it (shift-cmd-H). (BTW, I decided not to have a third time bar after all, so there is a double bar-line instead of a repeat mark, but I still needed to go into D major, so needed the same solution.) See below:

Just thought I'd post this here, in case anybody else has the same problem. I haven't "answered" the question...


Hypothesis testing: significance

Question: i conducted a survey that aims to find out if Australians prefer Australian phones over Chinese phones.
My hypothesis states: Australians prefer Australian phones over Chinese phones
This was measured by the following question: 'If you had to choose between two identical phones, would you purchase the Australian or the Chinese phone?'
There are four choices:

purchase Australian phone
purchase chinese phone
I'm indifferent
i don't know

I guess it is not enough to only state how many people chose which option right?
I am unsure which statistical test to use to accept or reject the null hypothesis. I was thinking about a multiple linear regression, but then i didn't know how to code my variables (dependent: choices 1-4; independent: amount of people who chose the option?)
Please help me in figuring out which test is appropriate and how to code the variables given. I appreciate your help a lot!!
Comment: Is this school work?
Comment: its for my research
Comment: Other things to consider in a study for publication: (a) Are phones available that were made in countries other than Australia and China? (b) Are Australian phones the same price as those made elsewhere?
Answer: Interviewing 200 randomly chosen Australians, suppose you got
87 favoring Australian phones, 77 favoring Chinese phones, and the
remaining 36 in one of the uninformative categories.
Then out of the $n = 164$ with relevant opinions you have $\hat p = 87/164 \approx 0.53 > 0.5$ in favor of Australian phones. Is that a large enough preference
for Australian phones to reject $H_0: p = .5$ against $H_a: p > .5,$
where $p$ is the population proportion of people with opinions who favor
Australian phones?
Under $H_0,$ the number $X$ in favor of A has $X \sim \mathsf{Binom}(n=164,\, p=.5).$ The P-value is $P(X \ge 87) = 1 - P(X \le 86) = 0.2412 > .05,$
so you cannot reject $H_0$ at the 5% level of significance. [Computation in R.]
1 - pbinom(86, 164, .5)
[1] 0.2411531

As another example, suppose you interviewed $2000$ Australian subjects,
with 869 preferring A, 771 preferring C, and the rest in uninformative
categories. Again here you have $\hat p = 869/1640 \approx 0.53.$ However, now under $H_0,$ you have $X \sim \mathsf{Binom}(n=1640,\, p=.5)$
and $P(X \ge 869) = 0.0083 < 0.05,$ so you could reject $H_0$ at the 5% level of significance (even at the 1% level).
1 - pbinom(868, 1640, .5)
[1] 0.008291582

Notes: (1) The people without relevant opinions are removed from the sample before analysis. (2) It is not only the proportion in favor of A
that matters; the effective sample size (of people with opinions) must also be taken into account in finding the P-value.
(3) Plots of the relevant binomial PDFs are shown below. P-values are probabilities to the right of the vertical red lines.

(4) You should report numbers or percentages of respondents in
uninformative categories so that readers can have some idea how
important 'country of manufacture' is to Australians.
(5) Some statistical software programs include a 'binomial test' or 'test of a single proportion' as standard procedures. Some do exact computations and some use normal approximations. Here is a printout from Minitab (slightly edited for relevance) for my first example above, using an exact
computation.
Test and CI for One Proportion

Test of p = 0.5 vs p > 0.5
                              Exact
Sample   X    N  Sample p   P-Value
1       87  164  0.530488     0.241

Hypothesis testing: significance


LDAP on Ubuntu 16 won't connect

Question: I've installed LDAP on an Ubuntu 16.04 machine, using this command:
sudo apt install slapd ldap-utils

This is my config file /etc/ldap/ldap.conf
#
# LDAP Defaults
#

# See ldap.conf(5) for details
# This file should be world readable but not world writable.

BASE    dc=domain,dc=local
URI     ldap://domain.local:389

#SIZELIMIT      12
#TIMELIMIT      15
#DEREF          never

# TLS certificates (needed for GnuTLS)
#TLS_CACERT     /etc/ssl/certs/ca-certificates.crt

I've checked status of LDAP, it's running, and I don't have any firewall running at all on the server in question:

However, when I run ldapsearch -x it tells me:

ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)

Here is the debug output:
ldap_create
ldap_sasl_bind
ldap_send_initial_request
ldap_new_connection 1 1 0
ldap_int_open_connection
ldap_connect_to_host: TCP domain.local:389
ldap_new_socket: 4
ldap_prepare_socket: 4
ldap_connect_to_host: Trying 192.168.9.74:389
ldap_pvt_connect: fd: 4 tm: -1 async: 0
attempting to connect:
connect errno: 111
ldap_close_socket: 4
ldap_err2string
ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)

Here is my hosts file, and if I ping that domain it returns the IP:
127.0.0.1       localhost
192.168.9.74    domain.local

Answer: ldapsearch simply cannot open a TCP connection to 192.168.9.74 port 389.
There could be many reasons for that (excluding the ones you already excluded in your question):

firewalls in between
slapd does not really listen on IP address 192.168.9.74 (check with netstat -tulpn)

LDAP on Ubuntu 16 won't connect