d3.geoPath() vs d3.geo.path()

Question: I'm attempting to follow Mike Bostock's process to project to the bounding box of a feature in a topojson file.  My topojson file is already projected to Texas State Mapping System (EPSG 3081) from the command line using geoproject:
d3.geoConicConformal().parallels([34 + 55 / 60, 27 + 25 / 60]).rotate([100, -31 - 10 / 60])

However, copying his code exactly and modifying the relevant bits to match my data set results in the error "Uncaught TypeError: path.bounds is not a function" on this line:
var b = path.bounds(state),

Here is my complete code:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>JS Mapping Project</title>

A few things that I've discovered manipulating the code:
If I remove the projection by changing var path = d3.geo.path().projection(); to var path = d3.geo.path();, the error goes away (because the call to the broken code goes away) but the svg draw is broken:

If I change the path definition to var path = d3.geoPath();, suddenly the geometry draws correctly:

This won't work (and I don't know why geoPath() works in the first place) because then the rest of my calls to path fail.
As I was typing this, I realized that I forget the call to my projection variable. I changed .projection(); to .projection(projection);. Now my map looks really weird, but there aren't errors on the path.bounds line as before:

It would seem that my projection definition is wrong, despite using the formula from this StackExchange answer.
I changed the code from geoProjection() to geoIdentity() based on Mike Bostock's response to a comment on his Medium article. My map appeared to be projected, scaled, and centered correctly, but the all black and white color scheme didn't help. I added some quick coloring to the various layers and it now looks very broken:

I then thought maybe it was because I didn't add the ", function(a,b) { return a !== b; }" to the topojson.mesh function, but doing that made things more broken:

I double-checked my topojson file again at mapshaper.org, but my geometry is correct:

At this point I'm stumped. Something is wrong with the way I'm implementing topojson to render my data, but it matches the code I'm seeing in examples.
Answer: Had a breakthrough here. By changing the call to the feature from topojson.mesh to topojson.feature, the problem instantly resolved itself.  I don't know why .mesh works in this example, but it definitely didn't work for me.

EDIT:  I've identified why .mesh has been used in the example. It is to select only the internal boundaries so the coastline is not rendered, which is a great idea from a cartographic perspective. The thing I realized is to not apply a fill to those paths to prevent the drawing errors I had before.

d3.geoPath() vs d3.geo.path()


SQL Query not returning Null values

Question: I am using the query below to get the USD values, but when Unit_price is null then it has to return null values, and I am not getting null values. Please advise me where I am going wrong. Thanks!
DB: Oracle 11g
QUERY:
SELECT data_raw_id,
       f.ndc_cd,
       date_of_service,
       quantity_dispensed,
       p.unit_price,
       NVL((SELECT f.quantity_dispensed * pc.prc_amt
             FROM llpricing_lkup pc
            WHERE pc.ndc_cd = f.ndc_cd
              AND f.date_of_service BETWEEN pc.strt_dt AND pc.end_dt),
           f.quantity_dispensed * p.unit_price) usd
  FROM fact_data f
  JOIN product p
    ON f.ndc_Cd = p.ndc_Cd
 WHERE data_Raw_id in (44214229, 44214183, 41084896, 41244850, 41374409, 41501126, 41501107);

the output for the above query is below..

Please help me.
Answer: The simplest fix would be to enclose the usd expression in a case expression that specifies your business rule:
select data_raw_id
     , f.ndc_cd
     , date_of_service
     , quantity_dispensed
     , p.unit_price
     , case when p.unit_price is not null then
           nvl
           (
             ( select f.quantity_dispensed * pc.prc_amt
               from   llpricing_lkup pc
               where  pc.ndc_cd = f.ndc_cd
               and    f.date_of_service between pc.strt_dt and pc.end_dt
             )
           , f.quantity_dispensed * p.unit_price
           )
       end as usd
from   fact_data f
       join  product p
             on  p.ndc_cd = f.ndc_cd
where  data_raw_id in (44214229, 44214183, 41084896, 41244850, 41374409, 41501126, 41501107);

Looking at that, though, it seems you could simplify things by merging your scalar subquery into the main query as an outer join:
select data_raw_id
     , f.ndc_cd
     , date_of_service
     , quantity_dispensed
     , p.unit_price
     , case
           when p.unit_price is not null then
               f.quantity_dispensed * nvl(pc.prc_amt,p.unit_price)
       end as usd
from   fact_data f
       join  product p
             on  p.ndc_cd = f.ndc_cd
       left join llpricing_lkup pc
             on  pc.ndc_cd = f.ndc_cd
             and f.date_of_service between pc.strt_dt and pc.end_dt
where  data_raw_id in (44214229, 44214183, 41084896, 41244850, 41374409, 41501126, 41501107);

The 'return value y or z defending on whether x is null' logic can also be expressed using
nvl2(some_value, value_if_not_null, value_if_null)
so in your query I make that:
nvl2(p.unit_price, f.quantity_dispensed * nvl(pc.prc_amt,p.unit_price), null) as usd

but I always find nvl2 less readable than the equivalent case expression.
As for where you are going wrong, the llpricing_lkup scalar subquery fetches values regardless of product.unit_price, so as long as some quantity was dispensed and a pricing lookup row is defined covering the date of service then you will get a value.
Comment: Thank you very much William for detailed explanation.
Answer: NVL function in oracle returns the first not null value. Your NVL function -
NVL ((SELECT f.quantity_dispensed * pc.prc_amt
                        FROM llpricing_lkup pc
                       WHERE pc.ndc_cd = f.ndc_cd
                         AND f.date_of_service BETWEEN pc.strt_dt
                                                   AND pc.end_dt)
                   , f.quantity_dispensed * p.unit_price) usd

Is using some calculation from llpricing_lkup table and must be returning some values. Hence you are not getting any null value. You have to remove the sub-query if you want to get the null in usd column.
Comment: Thank you ankit for your help
Answer: The NVL() function accepts two arguments. If e1 evaluates to null, then NVL() function returns e2. If e1 evaluates to non-null, the NVL() function returns e1.
Syntax::
NVL(e1, e2)

So in your query Select statement inside the nvl function is not null that is why it returned USD column data . Please use below query at the place of NVL () function.
NVL (f.quantity_dispensed * p.unit_price,(SELECT f.quantity_dispensed * pc.prc_amt
                        FROM llpricing_lkup pc
                       WHERE pc.ndc_cd = f.ndc_cd
                         AND f.date_of_service BETWEEN pc.strt_dt
                                                   AND pc.end_dt)) usd

Comment: Thank you Ajeet for your help.

SQL Query not returning Null values


How can I effectively secure guitar strings to the tuning pegs?

Question: One of the bigger problems I face when restringing my guitars is properly securing the strings to the pegs.
How should I wind the strings around the pegs before tightening them to prevent the string slipping when the tension increases?
My electric guitar is an Aria MAC 57/7 (7 String). I use Ernie Ball Regular Slinky strings. The tuners are whatever is standard on this kind of guitar. I have never changed them.
Answer: Before putting a string trough a hole, bend it, so it would have an angle a bit more then 90 degrees. Then, when string is inside, start making circles around.
In this video Andrew shows how to do it and why you do it on an acoustic guitar:
Comment: I find it's best to tie a knot for nylon strings, as the bend is not enough to keep the string from slipping.
Comment: @Jasarien I use this technique for all of my stringed instruments (not just guitars) - acoustic and electric alike.  In my experience it works well.  Though none of my instruments use nylon strings, so I can't comment on those.
Comment: Does this technique differ for electric guitars and/or different types of strings?
Comment: @Jasarien Unfortunately, I do not own an electric guitar, so I cannot tell you this. But as far as I saw, pegs are not too different (if we are comparing with steel string acoustics)
Comment: I do this, but a little differently. I turn the hole parallel to the strings, and feed it backward, toward the bridge. Then pull taught. It creates the same bend. But I also maintain that same pull until it's roughly tuned-up and under tension.
Answer: What my father showed me how to do is a bit different, and I wish I could post a video or draw a picture. Maybe I will take one and post it. Let me try and explain the method though, take your string, unbent, and slide it through the tuning peg, then loop it around itself, so that when you tighten the tuning peg the string will be holding itself back. you usually need to make a small kink in it like above by pulling tight fir a quick second.
The nice thing about this method is you dont have to sit around and wind anything, the string does all the work.
Answer: Make sure you leave at least enough slack for the string to go around the post twice.
As you tighten, the protruding end of the string makes a circuit around the post. The first time it passes the business end of the string, guide it under the string. The second time it passes, guide it over the string.
Now the string wound around the post is pinching the protruding end, stopping it from slipping out. That, combined with the right-angle kink in the string on the opposite side of the post, will hold it tight.
Tune the instrument, and once you're happy, trim off all but 1cm or so of the protruding strings.
This works equally well for nylon and metal strings.
Answer: I always try to have about 4 inches worth of string wrapped around the peg. There are further things to do, such as locking tuners and tying the strings, but I find that having sufficient windings (but not too many) should be enough.
Answer: The way I have always done it, and works very well. Wrap the string three times around the tuning peg, then stick it through the hole, out the other side in between the wrapped part. Never goes outta tune


How to use normal chrome completely without chromedriver selenium python not duplicate

Question: How to use normal chrome completely without chromedriver selenium python not duplicate.
I am using python 3.8.8,os is windows 7 ultimate with pycharm as
IDE and chrome version is around 96. and my problem is that whenever I use my python script to scrape a website it uses chromedriver and when I specify what's given below:
<code>options = Options ()
options.add_argument(r"user-data-dir=my chrome path which is not Executable instead the user data")
#this works but when opening chrome it shows "browser is controlled by automated software" and changing it to normal chrome. Exe won't work
</code>
Sure it uses normal chrome with my credentials but it still needs chromedriver to work and when I delete the chromedriver it throw an error and when I go into selenium source code in a file called site.py(or sites.py) which I changed the variable self. executable to chrome.exe path and  it worked and it won't show the message browser is controlled by automated software but it won't do anything , it is just stuck there and what I want to do is use chrome as the browser to scrape without chromedriver in my pc is it possible? If yes please tell me how should I go on to do it and you can ask for further Clarification and details and Thanks in advance
Answer: By default, selenium is detected as an automated software and is flagged by most websites, and the flag is unable to be removed. There are, however, external libraries that can be installed that can remove the flag.
There are options here to try to get around the default flag and hide the fact the browser is automated.
Edit
I understand the question further, and see that you want a more portable chrome option. Chrome driver is a very specific program controlled by selenium and must be used. There is no substitute. You can use Firefox driver or internet explorer, but a webdriver must be used (hence the name driver for driving the main browser). When you specify the directory for the Chrome binary, you aren't removing the middleman of the chromedriver, only Specifying where chrome driver needs to look!
Comment: The response I gave was under the assumption of python.
Comment: Please note https://stackoverflow.com/users/17630235/keegan-m that i am using python and I don't know other languages and tell me how should I use normal chrome without chromedriver
Comment: Are you trying to use chrome without any special driver or code? I don't understand
Comment: Yes I want to use I don't know if it s possible I have chromedriver but if I want to make a pip module I prefer it dosen't rely on apps that most people won't download  chromdriver so that's why I want to use normal chrome instead of chrome driver and without relying on chrome driver
Comment: Also I didn't check deep into the link you gave sorry about that mate
Comment: Ohhhh I see. I will revise my answer.
Answer: Using Selenium you won't be able to initiate/spawn a new Browsing Context i.e. Chrome Browser session without the ChromeDriver.

The Parts and Pieces
As a minimum requirement, the WebDriver i.e the ChromeDriver talks to a browser through a driver and the communication is two way:

WebDriver passes commands to the browser through the driver
Receives information back via the same route.

Hence using ChromeDriver is a mandatory requirement.


How do I remove database from postgresql native app on mac?

Question: I am trying to remove a db in postgresql but its still viewable in the mac native app even after I have confirmed its been removed from the terminal. Should I be concerned?
Here is my terminal command and output
drop database if exists Javascript_Rails_Project_development;
NOTICE:  database "javascript_rails_project_development" does not exist, skipping
DROP DATABASE

Answer: You possibly created the database putting its name in double quotes as "Javascript_Rails_Project_development". Note the upper case letters.
Usually identifiers in SQL are case insensitive. If you quote them in such a way however, they become case sensitive. That is, there is no database named javascript_rails_project_development as the letters are all lower case.
Once created with the name double quotes and including upper case characters you need to address the object afterwards by a name in double quotes with the exact matching cases of the letters.
Try:
DROP DATABASE IF EXISTS "Javascript_Rails_Project_development" ;

And possibly avoid upper case and quoted names in the future all together. It's just making things more complicated in most of the cases.


Proof the iff statement of the lim sup

Question: I got a trouble in proving the iff statement of lim sup.
The following is what I got from my homework.
Let $X\subseteq \Bbb R^m$, $f:X\to\Bbb R$ be a function, and $y$ be a limit point of $X$. It is said that $L$ is the limit superior of $f$ at $y$, defined by  $\overline \lim_{x\to y}f(x)=\lim_{\delta \to 0^+} (\sup \{f(x):x\in E \cap B(y,\delta)-\{y\}\})$.
The problem I need to work is to verify the following assertions:
1) For all $L \in \Bbb R, \overline \lim_{x\to y}f(x)\le L \iff \forall \varepsilon\gt0\ \exists \delta \gt0\ \forall x\in X\cap B(y,\delta)-\{y\},\ f(x)\le L+\varepsilon$.2)For all $L \in \Bbb R, \overline \lim_{x\to y}f(x)\ge L \iff \forall \varepsilon\gt0\ \forall \delta \gt0\ \exists x\in X\cap B(y,\delta)-\{y\},\ f(x)\ge L-\varepsilon$.
The following was what I tried on the first assertion:
Suppose $\lim_{x \to y}f(x)=l\le L$. Then, by the definition of limit, I will have:  $\forall \varepsilon \gt0\ \exists \delta\gt0\ \forall x \in X\cap B(y,\delta)-\{a\}, \ |\sup f(x)-l|\lt \varepsilon$. That is, $\sup f(x) \lt l+\varepsilon$. Since $\forall x \in X\cap B(y,\delta)-\{y\}$, I will have $f(x)\le\sup f(x)$, then $f(x)\le\sup f(x)\lt l+\varepsilon \le L+\varepsilon$. I do not whether this attempt is on the right track since, strictly speaking, I can only get $f(x)\lt L+\varepsilon$.  And I have no idea about the second assertion.
Comment: Wait, have you stated the definition here? If that's the case, then there's nothing to prove.
Comment: @anonymous I'm pretty sure he means $\limsup\limits_{x\to y} f(x)$. But I agree that it is unclear what OP is asking.
Comment: @anonymous hope the new version can be better for you to help. Thx!
Comment: @nullUser hope the new version can be better for you to help. Thx!
Comment: @anonymous Sorry for my typos. It is $y$ but not $a$. Now I think everything is clear.
Comment: @anonymous Well, that is just what the problem states and what the problem asks for.
Answer: For convenience, let's call $X_\delta = E \cap B(y,\delta)\setminus \{y\}$.
1) Suppose $\overline\lim_{x\to y}f(x) = l \leq L$, and let $\varepsilon> 0$. Then there exists $h_\varepsilon > 0$ such that if $0 < \delta < h_\varepsilon$, then $\sup\{f(x): x\in X_\delta\}-l < \varepsilon$. We don't need absolute value here: as $\delta \to 0^+$ $\sup\{f(x):x\in X_\delta\}$ is decreasing, so $l \leq \sup\{f(x):x\in X_\delta\}$ and therefore $|\sup\{f(x):x\in X_\delta\}-l| = \sup\{f(x):x\in X_\delta\}-l$. Then for all $x \in X_\delta$, we have $f(x) \leq \sup \{f(x):x\in X_\delta\} < l+\varepsilon \leq L+\varepsilon$. So our desired "$\delta$" is $h_\varepsilon$. The fact that I got $<$ instead of $\leq$ is because I insisted on $\sup\{f(x): x\in X_\delta\}-l < \varepsilon$; of course it's completely equivalent to have $\sup\{f(x): x\in X_\delta\}-l \leq \varepsilon$.
For the reverse direction, suppose the RHS holds. We want to show that $\lim_{\delta\to 0^+}\sup\{f(x): x\in X_\delta\} = l \leq L$. Suppose not. Then $l > L$. Since $\sup\{f(x): x\in X_\delta\}$ decreases as $\delta \to 0^+$, we must have $\sup\{f(x): x\in X_\delta\}\geq l > L$ for all $\delta > 0$. Take $\varepsilon = l -L$. For all $\delta > 0$, we have $\sup\{f(x): x\in X_\delta\} - L \geq l - L > \varepsilon$, i.e. $\sup\{f(x): x\in X_\delta\} > L+\varepsilon$. Then there must exist $x \in X_\delta$ such that $f(x) > L+\varepsilon$. (If the supremum is larger than something, then there must be something in the set between that thing and the supremum.) In summary: $(\exists \varepsilon > 0)(\forall \delta > 0)(\exists x \in X_\delta) f(x)>L+\varepsilon$. This contradicts the RHS, and the proof is complete.
2) Suppose $\overline\lim_{x\to y}f(x) \geq L$. Since $\sup \{f(x):x\in X_\delta\}$ is decreasing as $\delta \to 0^+$, we must have $\sup\{f(x):x \in X_\delta\} \geq L$ for all $\delta > 0$. Let $\varepsilon > 0$ and $\delta > 0$. Then $\sup\{f(x):x \in X_\delta\} \geq L > L - \varepsilon$. Then there exists $x \in X_\delta$ such that $\sup\{f(x):x \in X_\delta\}  > f(x) \geq L-\varepsilon$, and we are done.
For the reverse direction, assume the RHS and suppose (aiming for contradiction) $\lim_{\delta\to 0^+}\sup\{f(x):x\in X_\delta\} < L$. Take $\varepsilon <  L-\lim_{\delta\to 0^+}\sup\{f(x):x\in X_\delta\}$. Then $\lim_{\delta\to 0^+}\sup\{f(x):x\in X_\delta\} < L-\varepsilon$. Then for some $\delta > 0$, we have $\sup\{f(x):x \in X_\delta\} < L-\varepsilon$. So for all $x \in X_\delta$, $f(x) < L-\varepsilon$. Thus $(\exists \varepsilon > 0)(\exists \delta > 0)(\forall x\in X_\delta) f(x)<L-\varepsilon$, contradicting the RHS.

Proof the iff statement of the lim sup


How can one justify if the graph is planar from adjacency matrix?

Question: Given an adjacency matrix of a graph $G$, I was asked to do the following without drawing the graph:
A) Find the vertex of largest degree.
B) Does the graph have an Euler Circuit?
C) Is the graph Planar?

I did A and B. How can one justify if the graph is planar from adjacency matrix?
Comment: You could try using a theorem that gives criteria for planarity. See https://en.wikipedia.org/wiki/Planar_graph
Comment: Which adjacency matrix are you given?
Comment: @Semiclassical I was asking for a general result. i.e. given any adjacency matrix can we comment on the planarity of the graph?
Answer: There are some simple conditions which, if transgressed, would mean that the graph is non-planar but in general there is nothing which could easily determine whether the graph is planar.
Since you said 'without drawing the graph' can we assume that the matrix is fairly small?
For a small number of vertices (e.g. $6$) it is easy to check whether or not the graph   contains $K_{3,3}$ or a subgraph homeomorphic to $K_5$.
The reference you have already been given
https://en.wikipedia.org/wiki/Planar_graph
should be useful for the simple conditions.
Answer: If you have adjancency matrix like this one $$A = \pmatrix{0&1&1&1&1&1 &1\\1&0&1&1&1&1&1\\1&1&0&1&1&1&1 \\1&1&1&0&1&1&1 \\1&1&1&1&0&1&1\\1&1&1&1&1&0&1\\1&1&1&1&1&1&0}$$
then this graph is clearly not planar since all degrees are $6$ and in planar graph must exists vertex of degree less than $6$.
Probably you have some matrix from which is easy to deduce some numercial estimation which says that it is not planar, like $e> 3n-6$ or something like this.


Search a 2D Array for a string of another 1D Array and then put them in a new 2D with the sorting of the 1D

Question: This title must be really confusing, so let me explain my problem.
I have a one-dimensional Array (let's call it "ids") which is sorted in the way I need it to be.
Then, I have another 2D Array which contains a name on position 0 and an id in position 1 (let's call  it "names").
So names[0][0] = name, names[0][1] = id.
Let me clarify that the 2 arrays are not of the same length!
What I want to do it so create a new 2D Array which has a name and an ID, but sorted like my one dimensional array (the ids are in the same order like they are there).
What I've tried so far is this (and all I am getting is a text file full of nulls):
for (int i = 0; i < ids.length; i++){
            String equal = ids[i];

            for (int j = 0; i < users.length; i++) {
                if(users[j][1].equals(equal)) {
                    sortedArray[i][0] = users[j][0];
                    sortedArray[i][1] = equal;
                }
            }

        }

        for (int i=0; i<sortedArray.length; i++){
            writer.println(sortedArray[i][0]+"\t"+sortedArray[i][1]);
        }

It might not be of any use, but since I am creating these by reading files, this is the rest of my code:
BufferedReader reader;
        BufferedReader reader2;
        PrintWriter writer;

        String[][] users = new String[39431][2];
        String[] ids = new String[22890];
        String[][] sortedArray = new String[22890][2];

        reader = new BufferedReader(new FileReader("allConnectedUsers.txt"));
        reader2 = new BufferedReader(new FileReader("ids.txt"));

        String sorted = "sortedNamesWithIDs.txt";
        writer = new PrintWriter(sorted, "UTF-8");

        String usersline = reader.readLine();
        String idsline = reader2.readLine();

        for (int i = 0; i < users.length; i++) {
            String splittedLine[] = usersline.split(" ");
            String name = splittedLine[0];
            String id = splittedLine[1];
            users[i][0] = name;
            users[i][1] = id;
            usersline = reader.readLine();
        }

        for (int i = 0; i < ids.length; i++) {
            String onlyIDs;
            onlyIDs = idsline;
            ids[i] = onlyIDs;
            idsline = reader2.readLine();
        }

Answer: I actually fixed it. It was a pretty dumb mistake.
In the nested loop, I wasn't checking for "j" or increasing it, but i.
Sorry for this dumb mistake, thanks if you even read it.


Evaluating the Impact of National Policies Using Panel Data

Question: I have a panel data set covering various countries over various years. I have information about the years in which these countries published an entrepreneurship policy - some countries only published one in the past 20 years, while others published a new one every five or ten years. I also have an annual estimate of the level of entrepreneurial activity for each country.
I'd like to evaluate whether the launch of these policy documents resulted in an increase of entrepreneurial activity in these countries. However, I am not sure how to approach this question methodologically, since the policies were introduced in different years and sometimes countries introduced various policies over the time that my data set covers.
I don't think I can use the typical methods for evaluating the impact of treatment (such as difference-in-difference and instrumental variables regression), since the introduction of a treatment, which in my case is the introduction of policies take place across different years and sometimes there are several "treatments" for individual countries.
I would greatly appreciate your help with this question, as I am stuck not having found guidance searching through my books and the existing questions on Cross Validated.
Answer: Just a partial answer, but maybe it'll help.
You talk about several "treatments" for a single country. One approach to deal with this phenomenon is a
Difference-in-difference-in-differences estimator. There is also a good description of this estimator in  Woolridge's Econometric Analysis of Cross Section and Pannel Data .
Regarding the different points of time of the changes it might be helpful to standardise the data giving t=x for the year of the impact in the measure in a specific country.
Comment: Dear @Ferdi - thanks a lot for your quick answer. I am sorry for formulating the question in a way that led you to misinterpret it (just fixed the description). I don't have only one country that introduced various policies over this time period, but several of them. Eg. South Korea introduced one in 2004 and then another in 2010, and Belgium in 2002, 2009, and 2015 for instance. Some of the countries only ever introduced one policy.
Comment: Also @Ferdi - by giving t=x, what exactly do you mean?
Comment: You do not necessarily have to look at the difference between 2004 and 2005, but you could look at the difference between the period of introducing a policy and the period before(e.g. 2003 and 2004) for South Korea or 2001 and 2002 for Belgium)
Comment: Thanks for the clarification @Ferdi. How would I analyze the difference between before a policy was implemented and after its implementation, given that the implementation varies between countries in my data set. Or do you mean that I would analyze each country separately from the others?
Comment: It does not make sense to analyze each country separately from each other. You will not have a control group. If you analyze all countries together you have got a treatment and a sufficiently large control group.


Why do harmonics sound good?

Question: Harmonics, as in multiple of a fundamental frequency, sound good to our ears. A few examples:

Octaves, i.e. doubling the frequency. We assimilates pitches separated by octaves to a same pitch class. The octave of a B♭ still is a B♭ ; the octave of a G still is a G.
Choosing the right temperament to preserve as many perfect fifths (multiplying the frequency by 3) without throwing the third away (multiplying the frequency by 5) as possible is an endless debate.
We try to avoid inharmonicity in most instruments, i.e., we want partials to be as close to harmonics as possible.

This is probably the most basic fact I acknowledge when I'm thinking about music. But it also is a fact I've always taken for granted. If I ever were asked to justify that fact, I couldn't really.
What is the underlying reason why harmonics sound good?
My best guess would be "there probably is a physiological reason". After all, simple oscillating systems often are quite harmonics, and our auditory sensors could very well be. Or maybe it is cultural: most simple, readily available oscillating systems are quite harmonics, thus even the first instruments must have been. The voice, I think, is too.
Does anyone have any insight on the question?
Comment: Not always -- go high up enough to get the equivalent of a semitone harmonic and you may not like the result.
Comment: @CarlWitthoft If you keep the harmonics in between, I have no issue with at least the 15th harmonic. Well, it sounds very metallic, but not false by any mean. Just playing a low note and it's 15th harmonic is weird, likely because, well, the 15th harmonics of any instrument is quite low and there is nearly four octaves between the fundamental and it's 15th harmonic, so our ears naturally distinguish them.
Comment: I was being humorous, but typically us musicians would allow the 4th octave to be played against the 15th harmonic (rather than the base note) .
Answer: Music: a Mathematical Offering by Dave Benson has a lot to say about this. The gist of it is, it's not precisely harmonics (in the sense of integer multiples of the fundamental frequency) that sound good; more important are matching partials (and the avoidance of nearly-matching partials). A relevant excerpt:

For pure sine waves, the ear detects nothing special about a pair of signals exactly an octave apart, and a mistuned octave does not sound unpleasant. Interval recognition among trained musicians is a factor being deliberately ignored here. On the other hand, a pair of pure sine waves whose frequencies only differ slightly give rise to an unpleasant sound. Moreover, it is possible to synthesize musical sounding tones for which the exact octave sounds unpleasant, while an interval of slightly more than an octave sounds pleasant. This is done by stretching the spectrum from what would be produced by a natural instrument. ...
The origin of the consonance of the octave turns out to be the instruments we play. Stringed and wind instruments naturally produce a sound that consists of exact integer multiples of a fundamental frequency. If our instruments were different, our musical scale would no longer be appropriate. For example, in the Indonesian gamelan, the instruments ... do not produce exact integer multiples of a fundamental.... So the western scale is inappropriate, and indeed not used, for gamelan music.

Even in Western music, this often becomes relevant. For example, pianos (especially smaller pianos) are slightly inharmonic, because of the stiffness of their strings. As a result, piano octaves are tuned to be slightly wide, so that the fundamental of one note will match the slightly-off "second harmonic" of the note an octave below.
Comment: What's exactly do you mean when you say, *"partial" ?*
Answer: Harmonics are very common in nature and musical instruments. If you plug the low A string on a a guitar, it will products 110Hz, 220Hz, 330 Hz, 440 Hz. That's simply physics and reflects the way the string moves. See for example http://hyperphysics.phy-astr.gsu.edu/hbase/waves/string.html, third picture down.
This true for all musical instruments. Basic physics results in all fundamental notes always coming together with their harmonics (unless you play sonata for sine wave generators).
Now if you play two notes at the same time. Say an A and E, you get the fundamentals and the harmonics of both notes. That's a lot of frequencies and can get messy real quick. Now if the two notes are harmonically related, there harmonics are often the same. The third harmonic of the A is the same frequency as the second harmonic of the E etc.
As a result if the fundamentals are harmonically related, you have a lot less frequencies in the overall combination than if they are different. Hence the spectrum is "cleaner" and "less cluttered".
It also minimizes "beating". Beating occurs when two frequencies are close together: you will get a modulation that occurs with the difference of the two frequencies which sounds "harsh" and "unmelodic".
Comment: We *craft the guitars* so that the partials are (close to) harmonics. By choosing souple strings, e.g. — stiff strings can be inharmonic, as it's the case for the piano high register. Now for guitar, it's not obvious (an everyday string already is quite harmonic) ; but the reason the bars of a vibraphone are thinner in the centre is to have harmonic partials.
Answer: When you add harmonics to a fundamental sine wave, the periodicity of the result remains the same: whenever the waveform of the fundamental repeats, that of the harmonics repeat as well.
There are no beatings or artifacts with a frequency lower than that of the fundamental.  That means that you get a tone quality that is as constant as that of the fundamental.
Answer: It has primarily biological basis. Simply speaking - sounds transformed to the neuron impulses and when it goes simultaneously it feels good (for brain and the rest of body) otherwise it is a signal/chemical mess, stubby flow and we feel a bit of pain. So to go simultaneously we just need to solve some harmonic equations (where the math physics helps us) to find proper frequencies which will produce oscillations in whole numbers - to coincide and resonate instead of trying damp each other. Such air flow will be perceived as considerable. So not so magic.. about tone (but not timbre).
Comment: I don't think this is true: Neurons are excited by a bending wave of the basilar membrane in the cochlea. Different frequencies are simply exciting different areas on the membrane and there is nothing inherently different about harmonic or in-harmonic excitation. Neither one results in equal spacing of the excitation points.
Comment: Yes, different areas on the membrane and different sensosry neurons, but then signals are aggregated by intermediate neurons (excitment propagates further in the brain and we can already "feel" something about it) where signal clash occurs to make us feel pain. It is simplification, e.g. to be more detailed: incoming audio information in the "head" is splited in two ways and goes to _amygdala_ to "feel & react" (ASAP) and to _neocortex_ areas for more precise and highlevel analysis. Sound perception is very interweaved with consciousness (as well as other perceptions and their interpretations)
Answer: This may be an oversimplification, but there are plenty of accurate technical responses to this question already in this post so I'll take a more abstract approach:
To my ears, more harmonics means more sonic information. In other words, additional timbre and 'dirt' gives a sound additional characteristics.
Further, most sounds (excluding perfect waveform emulation like a sine wave) tend to have higher sounds as part of their base sound (aka - harmonics). These higher sounds are based on the fundamental, and are naturally linked according to the law of sound (see 'harmonic series'), and further the experience and behavior of the fundamental. This is similar to 'bootstrapping' in computer programming.
Comment: [This](http://arxiv.org/pdf/physics/0412118v2.pdf) law of sound? In which case, I would be interested in justification as to why "Notice that all natural sound can be treated as composed by a linear combination of harmonic waves with frequencies related to the fundamental one, f_0, as f_n = n*f_0 for integer n (= 1, 2, 3, ...). All these harmonic components are considered as consonant with the fundamental and the relative weight of these harmonics is a characteristic of the sound source, which frequencies spectrum defines one of the most important sound quality, the timbre." is true.
Comment: I'm not sure this is an answer to the question. If it is, I certainly don't get it: I read it as "Sounds with more partial sound richer", am I wrong?
Comment: Essentially, yes. It's a difficult question to answer because, in my opinion, the question is subjective and I'm trying to elaborate it's definition in an effort to answer it. A richer cake might taste better because it has deeper flavors. Why does it taste good? Because it does, potentially. There's no right answer here, in this sense.
Comment: I really believe you did not understand the question, then. I am wondering why (my possibly restraint view of) music tend to favor integer ratios between frequencies. I'm also wondering if you don't mix up partials and harmonics (I know I used to). I don't have a good equivalent for your cake analogy, but let's say I'm wondering why berries go well with chocolate and not with buckling. Is it cultural? Are there physical or physiological reasons behind it?
Comment: It's possible I don't understand your question, though I am a pro. Your question felt more theory-based in nature and given the other technical responses I wanted to balance it out with a more 'natural' response, however this doesn't seem to be what you wanted. Perhaps you'd be interested if I expanded my thoughts on the Law of Sound / Harmonic Series? I'd be happy to but don't want to commit the time if that's not what you're interested in.
Comment: Not exactly that article, no, but it succeeds at a mathematical theory from what I can tell. The section you referenced is in line with the point I was making about the the harmonic series and the physics of sound - which was my initial effort but more from an audible-based understanding (it's sound after all). Unfortunately, in context of your question, I'm not as trained in the math of this reasoning, so I'm not sure what else I can offer your question. For me, there is level at which it loses effectiveness, in application and discussion. It sounds like we have different thresholds for that.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/40417/discussion-between-edouard-and-hailthemelody).
Comment: @hailthemelody Speaking of "dirt," I remember many years ago hearing for the first time a perfectly tuned (mathematically) Kurzweil synthesizer, the equivalent of a supercomputer in the music world, that replicated the sounds of an orchestra. The intonation was so perfect, that it sounded boring. Then, the teacher played a recording of the same work played by a human orchestra. The difference was night and day, and the reason was that what we react to is the reaching for, and struggle against, absolute perfection, but not perfection itself. We can't relate to perfection. Sorry, off topic.
Comment: I resonate with your response fully @maxfinis. I think that might be the difference in this question though - Édouard might be looking for a more purely mathematical exploration of the physics of sound as the launching point for how different cultures have developed a taste for what sounds 'good' to them. Though as is demonstrated in this chain of messages, he and I are still trying to figure out each other on this one, so take my interpretation of his position with a grain of salt.

Why do harmonics sound good?


Given $Z_n\rightarrow 0$ in probability and $W$ a random variable, proving $WZ_n\rightarrow 0$

Question: Given $Z_n\rightarrow 0$ in probability and $W$ a random variable, I need to prove $WZ_n\rightarrow 0$.
I was given a hint: show that for every $\delta,\epsilon<0$ we have
$$\{|WZ_n|\geq\epsilon\}\subset\{|Z_n|\geq\delta\}\cup\{|W|\geq\frac\epsilon\delta\}$$
I'm not sure how to get to this conclusion, and I'm not even sure how it will help-
If we prove the hint, we get $$\lim_{n\rightarrow\infty} P(|WZ_n|\geq\epsilon)\leq\lim_{n\rightarrow\infty} P(|Z_n|\geq\delta)+ P(|W|\geq\frac\epsilon\delta)$$
I understand that $\lim\limits_{n\to\infty} P(|Z_n|\geq\delta)=0$, but why does $P(|W|\geq\frac\epsilon\delta)=0$?
I do know $ P(|W|\geq\frac\epsilon\delta)\leq\frac{E|W|\delta}\epsilon$, from Markov's inequality.
Comment: Just to clarify, is $Z_n\rightarrow 0$ in probability?
Comment: Yes, I'm sorry I forgot to mention that. I will edit
Answer: First off, the equality should be an inequality:
$$\lim_{n\rightarrow\infty} P(|WZ_n|\geq\epsilon)\leq \lim_{n\rightarrow\infty} P(|Z_n|\geq\delta)+ P(|W|\geq\frac\epsilon\delta)=0+P(|W|\geq\frac\epsilon\delta).$$
Notice that $\delta>0$ is arbitrary and the left hand side is independent of $\delta$. Thus, take a second limit of $\delta\rightarrow 0$.
To prove the hint, it's easier to prove the complement:
$$\{|W|\geq \epsilon/\delta\}^c\cap \{|Z_n|\geq \delta\}^c\subseteq \{|WZ_n|\geq \epsilon|\}^c,$$
which when simplified should be apparent.
Comment: Oops, of course it's an inequality. Will edit. Thanks! But why does the hint hold in the first place?
Comment: And, what promises $EW$ is finite?
Comment: @Whyka: Why do you need $EW$ to be finite? There's no need for Markov's inequality, just the definition of convergence in probability. See edit for the proof of the hint.
Comment: Oh, I see. You mean $P(|W|\geq\frac\epsilon\delta)\rightarrow 0$ when $\delta\rightarrow 0$.
Thanks a lot!
Answer: I believe is easier to use the subsequence definition of convergence in probability.
$\{Z_n W\}$ is clearly a sequence of random variables (since it is product of r.v's). To show that $\{Z_n W\} \xrightarrow{ P} 0$, we will show that for any subsequence $\{Z_{n_k} W\}$ there is a further subsequence $\{n_\ell\}$ of $\{n_k\}$ such that $\{Z_{n_\ell}W\}\xrightarrow{a.e.} 0$.
Let $\{Z_{n(k)} W\}$ a subsequence. Since $Z_n \xrightarrow{P}0$, for $Z_{n(k)}$ there is a subsequence such that $Z_{n (k (\ell))}\xrightarrow{a.e.} 0$ and since $W$ is real-valued then $Z_{n(k (\ell))} W\xrightarrow{a.e.} 0$ and hence $\{Z_n W\} \xrightarrow {P} 0$.


What are the technical terms of these fiddle sounds?

Question: I am curious to know what these 3 sounds, produced by a fiddle, are called:
Sound 1
Sound 2
Sound 3
Comment: In non-technical terms, how is sound 2 being produced?
Comment: I can't play them :(
Comment: When you click on a link, in upper right corner there is an arrow pointing down, when you click on that it gets downloaded, its just a wav file.
Answer:
Ricochet or Flying Spiccato bowing with a harmonic note at the end.
Tapping / Knocking on the wood of the violin, probably with a knuckle from the bow hand.
Heavy Staccato or Marcato, stopping the bow on the string.
Comment: Some of these, and other non-classical effects are demonstrated here: https://www.youtube.com/watch?v=NprC8ZorM0A


Como calcular diferença entre datas utilizando a biblioteca time.h

Question: Vi que tem uma função na time.h que calcula diferença entre data fui no site Link da documentação time.h, não entendi muito bem como realizar o esse calculo, por exemplo queria calcular a diferença entre a data 12/09/2018 e 12/09/1997
Código que a pagina forneceu
<code>#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, struct tm, difftime, time, mktime */

int main ()
{
  time_t now;
  struct tm newyear;
  double seconds;

  time(&now);  /* get current time; same as: now = time(NULL)  */

  newyear = *localtime(&now);

  newyear.tm_hour = 0;
  newyear.tm_min = 0;
  newyear.tm_sec = 0;
  newyear.tm_mon = 0;
  newyear.tm_mday = 1;

   seconds = difftime(now, mktime(&newyear));
   printf ("%.f seconds since new year in the current timezone.\n", seconds);
   return 0;
 }
</code>
Comment: E está tendo algum problema?
Comment: Maneiro na verdade eu não entendi como se calcula a diferença das datas eu introduzindo as datas via teclado
Answer: Faltou muito código aí para o seu progama se comportar da maneira que você descreveu!
Segue um código testado e comentado capaz de resolver o seu problema:
<code>#include <stdio.h>
#include <time.h>
#include <string.h>

#define BUF_TAM_MAX (32)

int main( void )
{
    int ret = 0;
    char buf[BUF_TAM_MAX];
    struct tm tma, tmb;
    time_t diff;

    /* Inicializa struct tm */
    memset( &tma, 0, sizeof(tma) );
    memset( &tmb, 0, sizeof(tmb) );

    /* Le data inicial */
    printf("Entre com a data inicial (DD/MM/AAAA): ");
    fgets( buf, sizeof(buf), stdin );

    /* Desmonta data inicial */
    ret = sscanf( buf, "%02d/%02d/%04d", &tma.tm_mday, &tma.tm_mon, &tma.tm_year );

    if(ret != 3 )
    {
        printf("Data Inicial Invalida!\n");
        return 1;
    }

    /* Ajusta struct tm inicial */
    tma.tm_mon -= 1;
    tma.tm_year -= 1900;

    /* Le data final */
    printf("Entre com a data final (DD/MM/AAAA): ");
    fgets( buf, sizeof(buf), stdin );

    /* Desmonta data final */
    ret = sscanf( buf, "%02d/%02d/%04d", &tmb.tm_mday, &tmb.tm_mon, &tmb.tm_year );

    if(ret != 3 )
    {
        printf("Data Final Invalida!\n");
        return 1;
    }

    /* Ajusta struct tm final */
    tmb.tm_mon -= 1;
    tmb.tm_year -= 1900;

    /* Calcula diferenca em segundos */
    diff = difftime( mktime(&tmb), mktime(&tma) );

    /* Exibe resultados */
    printf( "Diferenca em segundos: %ld\n", diff );
    printf( "Diferenca em minutos: %ld\n", diff / 60 );
    printf( "Diferenca em horas: %ld\n", diff / (60 * 60) );
    printf( "Diferenca em dias: %ld\n", diff / (60 * 60 * 24) );

    return 0;
}
</code>
Testando:
<code>Entre com a data inicial (DD/MM/AAAA): 12/09/1997
Entre com a data final (DD/MM/AAAA): 12/09/2018
Diferenca em segundos: 662688000
Diferenca em minutos: 11044800
Diferenca em horas: 184080
Diferenca em dias: 7670
</code>


MoneyMask não Funciona no Device

Question: O Plugin Jquery não funciona no device, alguém saberia como resolver isso?
A questão é o seguinte, pesquisei sobre o  porque de o plugin MoneyMask não funcionar dentro do device e descobri que os plugins de mascara utilizam o evento Keydown que retorna um objeto que contem o seguinte elemento:
event.Keycode

Retorna sempre 0 no Android 4.0+ o plugin não funciona.
 Alguém saberia como resolver?
Comment: Amigo eu pesquisei e fiz testes e descobri o seguinte...
O moneyMask e outras maskaras utilizam o metodo Keydown do javascript, sendo necessário identificar qual tecla esta sendo utilizada a reconhecendo com o event.keycode mas no android 4.0+ ele não fornece esse parâmetro pra você assim fazendo com que o plugin não funcione.
Comment: Amigo na verdade não existe código a mostrar pois o plugin funciona normalmente no navegador.
Comment: Bom, eu pesquisei por dúvidas e problemas, não encontrei nada relacionado a não funcionar fora de navegadores. [Edite](http://pt.stackoverflow.com/posts/49048/edit) a sua pergunta e inclua mais detalhes (se possível, o código), tente torná-la mais especifica e relevante para outros usuários que (talvez) tenham o mesmo problema futuramente. - [Como perguntar](http://pt.stackoverflow.com/help/how-to-ask).
Comment: Editei a pergunta ficou melhor?
Comment: Eu já tive esse problema antes, troca KeyCode por KeyPress e vê se funciona, creio que é um problema com o Navegador.
Answer: Não sei se você pode editar o código do plugin em questão, mas se puder, atualize para keyup ou outro tipo de evento não relacionado ao teclado como "change".

MoneyMask não Funciona no Device


What does ENXIO mean for an i2c ioctl?

Question: I have an i2c adapter exposed to userspace as /dev/i2c-0. When I use i2cdetect from the i2c-tools package on that adapter, I see my device listed on this adapter and I am able to perform get, set, and dump operations on it from the command line.
I have some C code that tries to perform a write on it using the ioctl I2C_RDWR operation.
Here's the stripped-down code that I am working with (provided only for context, and running it isn't important to answering the questions).
fd = open ("/dev/i2c-0", O_RDWR | O_NONBLOCK);

/* other stuff happens here */

if (ioctl (fd, I2C_FUNCS, &funcs) != 0)
    return -1;
if (!(funcs & I2C_FUNC_I2C))
    return -1;

/* i added this bit of debug just to be sure fd didn't
 * get inadvertently closed along the way.
 */
if (fcntl (fd, F_GETFD) != 0) {
    return -1;
}

/* build the ioctl message payload */

ret = ioctl (fd, I2C_RDWR, &payload)
if (ret) {
    fprintf (stderr, "ioctl returned %d. Reason: %s (errno=%d).",
             ret, strerror(errno), errno);
    return -1;
}

return 0;

I've also tried using the smbus ioctl functions, which looked like this.
fd = open ("/dev/i2c-0", O_RDWR | O_NONBLOCK);

/* other stuff happens here */

if (ioctl (fd, I2C_FUNCS, &funcs) != 0)
    return -1;
if (!(funcs & I2C_FUNC_SMBUS_WORD_DATA))
    return -1;

/* i added this bit of debug just to be sure fd didn't
 * get inadvertently closed along the way.
 */
if (fcntl (fd, F_GETFD) != 0) {
    return -1;
}

/* build the ioctl smbus message payload */

if (ioctl (fd, I2C_SLAVE_FORCE, dev) != 0)
    return -1;

ret = ioctl (fd, I2C_SMBUS, &payload);
if (ret) {
    fprintf (stderr, "ioctl returned %d. Reason: %s (errno=%d).",
             ret, strerror(errno), errno);
    return -1;
}

return 0;

In all cases, the program always hits the fprintf and this is the output:

ioctl returned -1. Reason: No such device or address (errno=6).

According to man 3 ioctl, the "generic" reason for an ENXIO error is:

ENXIO The request and arg arguments are valid for this device driver, but the service requested cannot be performed on this particular sub-device.

As Ian pointed out in the comments, however, the information regarding STREAMS in the above man page isn't relevant on Linux and I should be using man 2 ioctl -- which, unfortunately, mostly just says that ioctls don't really conform to any standard, and anything goes.
This raises three questions.

What does this imply for an i2c adapter? Does the driver for this device not support reading and writing using this method?
The man page contains specific descriptions of return codes for the I_ prefixed operations, but not for other operations. Is there somewhere else I can look for information specific to I2C ioctl operations?
Where can I find the source for the i2c ioctl functions?
Comment: For i2c, I think ENXIO means it got an unexpected NAK.
Comment: Have you read the kernel documentation about this Dev Interface? https://www.kernel.org/doc/Documentation/i2c/dev-interface imho, the I2C_RDRW ioctl interface is quite complex, would be interesting how your payload is built. Maybe there's the error. The doc also says that I2C_SMBUS ioctls are "Not meant to be called  directly; instead, use the access functions
  below." So I'd try using them. This Interface looks much easier anyways.
Comment: The reference to STREAMS devices is a bit of an irrelevance for Linux as it does not support [STREAMS](https://en.wikipedia.org/wiki/STREAMS). You should really be looking at [`man 2 ioctl`](http://linux.die.net/man/2/ioctl).
Comment: @IanAbbott hmmm, that one doesn't even mention ENXIO. :(
Comment: See the "CONFORMING TO" section. :)
Comment: @IanAbbott you were right about the unexpected NAK. i found the solution and developed it into a full answer below.
Comment: @WoodrowBarlow Your answer does not mention that a hardware NACK was the reason for the ENXIO.—It reads like you are blaming the existence of a software emulation...
Answer: Usually, it means the device did not respond. The specifics depend on your hardware.
The common I2C ioctl code is part of the i2c-dev package, which is part of the lm-sensors project. These ioctls do not have their own man page, but do have documentation in the kernel source tree.
In the kernel, the implementation is all kept in drivers/i2c/i2c-dev.c and drivers/i2c/i2c-core.c. The entry point is i2cdev_ioctl(). None of this common code returns ENXIO.
Eventually, this common code needs to call down to hardware-level driver functions on the i2c bus. The hardware drivers for i2c busses are stored in drivers/i2c/busses/. Each of these drivers can implement one or both of the master_xfer (used for I2C_RDWR ioctls) or smbus_xfer (used for I2C_SMBUS) functions.
In my case, the device actually didn't have dedicated i2c hardware and was using what appears to be a bit-banging software emulation implemented in function bit_xfer of drivers/i2c/algos/i2c-algo-bit.c. The ENXIO came from function bit_doAddress.
Comment: Tip: Use `dmesg` to read the kernel logs. Usually it will have a reason why something failed (ex. an I2C timeout error if the device did not respond).

What does ENXIO mean for an i2c ioctl?


How to show filesize when content type contains more than one file?

Question: I'm using Drupal 7 and having File 7.14 field installed.I have a content type (named file) containing more than 1 file. I have a view that shows the filesize of all the files of the content of that content type named file.
For doing that I have added  a relationship in Views to "select File Usage: File"
The filesize is nicely shown for content that contains only one 1 file.
However for content containing more than 1 file the filesize is only shown for the first file but not for the 2nd 3th etc.
Here is how my query currently looks like:
SELECT node.title AS node_title, node.nid AS nid, node.language AS node_language,   file_managed_file_usage.filesize AS file_managed_file_usage_filesize, 'node' AS  field_data_field_file_node_entity_type
FROM
{node} node
LEFT JOIN {file_usage} file_usage ON node.nid = file_usage.id AND file_usage.type = 'node'
LEFT JOIN {file_managed} file_managed_file_usage ON file_usage.fid = file_managed_file_usage.fid
WHERE (((node.status = '1') AND (node.type IN  ('file'))))
ORDER BY node_title ASC
LIMIT 50 OFFSET 0

Can anybody explain me how to change the View settings so that the filesizes of the other files are also be visible?
Answer: Actually it works fine for me without additional settings
My configuration :

I used content-type : Article and create some fields file
Your first step is good, you need to add a relationship select File Usage: File
Then in your fields section you can add : Content: Title , File: Size, File: Name

I have a listing of all the name of the file with their size.
If you want you can group by Articles.


Does this "reverse distributivity" ever occur: $a \circ (b\times c) = (a \times b) \circ (a \times c)$?

Question: I was reading a book containing a typo to the effect that they defined the distributive property as:
$$
a \circ (b\times c) = (a \times b) \circ (a \times c) \tag{*}\label{*}
$$
which is wrong of course. I will call the property (*) "reverse distributivity" for now. It got me wondering:

Are there any examples of structures with this "reverse distributivity"? What can we say about such a structure? And are there names for these things?

Some findings so far:
If we assume the existence of neutral elements, then things quickly degenerate. Assume that $(M, \circ, 1_\circ, \times, 1_\times)$ is an algebraic structure with two binary operators satisfying (*), and where $1_\circ$ and $1_\times$ are neutral elements. Then we have:
$$
1_\circ  = (1_\circ \times 1_\times) \circ (1_\circ \times 1_\times)
\stackrel{\eqref{*}} = 1_\circ \circ (1_\times \times 1_\times)
= 1_\times
$$
so the identity elements are in fact equal. Let $1 := 1_\times = 1_\circ$. Then, for any $a,b\in M$:
$$
a \times b = 1 \circ (a \times b) \stackrel{\eqref{*}} =
(1 \times a ) \circ (1 \times b) = a \circ b
$$
so in fact the two compositions are the same. In this case (*) becomes
$$
a \circ (b\circ c) = (a \circ b) \circ (a \circ c)
$$
which seems to be known as self-distributivity and shows up in a number of places (e.g. group conjugation and logical implication).
But if we want two (different) compositions that satisfy (*), then this shows that they at least cannot both have neutral elements. (If we only assume the existence of $1_\times$, then we can show that $a \circ a = a \circ 1_\times$ for all $a$). I haven't gone much further than this.
Comment: You can always take $\times = $ anything and $x\circ y = C$ (any constant.)  Both sides of the identity are just $C$.
Answer: I will treat the case where $\times$ forms a monoid with unit element $1$. From monoids, one can go in two directions: towards group-like structures or towards lattice-like structures. The group-like cases are all trivial, but we can find many non-degenerate lattice-like examples.
So consider a monoid $(M,\times,1)$ and assume that we have an operation $\circ$ that satisfies the reverse distributivity law $a\circ(b \times c) = (a \times b)\circ(a \times c)$ for any $a,b,c \in M$. It follows then that have $b\circ c = (1 \times b)\circ(1\times c)=1\circ(b\times c)$ for all $b,c \in M$.
Define the function $f: M \rightarrow M$ as $f(x) = 1\circ x$. Then reverse distributivity becomes $f(a \times b \times c) = a\circ (b \times c) = (a \times b) \circ (a \times c) = f(a \times b \times a \times c)$. Vice versa, any function $f: M \rightarrow M$ satisfying $f(a \times b \times c) = f(a\times b \times a \times c)$ for all $a,b,c \in M$ gives rise to a reverse distributive operation via $a\circ b = f(a \times b)$. Therefore:

Any potential $f$ must satisfy $f(a) = f(a \times a)$ for all $a \in M$. This follows by setting $b,c = 1$ in the equation above.
If $M$ is a group, then all such functions $f$ are in fact constant. To see this, notice that $f(a\times b \times c) = f(a \times b \times a \times c)$, then set $c=1$ and $b=a^{-1}$ to conclude $f(1) = f(a \times a^{-1}) = f(a \times a^{-1} \times a) = f(a)$ for all $a \in M$.
If $M$ is an idempotent commutative monoid (semilattice), then the equality $f(a \times b \times c) = f(a \times a \times b \times c) = f(a \times b \times a \times c)$ holds for any function $f: M \rightarrow M$. This observation yields plenty of non-degenerate examples. For example, consider the Boolean algebra $\{\text{true},\text{false}\}$ of truth values, and set $\times$ to be disjunction $\vee$. Define $a \not\vee b = \neg(a \vee b)$. The pair $(\vee,\not\vee)$ satisfies reverse distributivity, i.e. $a \not\vee (b \vee c) = (a \vee b) \not\vee (a \vee c)$. Similarly for $\wedge$.

If the structure $(M,\times)$ is a general semigroup, then these observations fail. Interestingly, by analyzing all 14 non-constant binary operations, we can show that all suitable pairs of operations $(\times, \circ)$ over truth values have $a \circ b = f(a \times b)$ for some $f$. However, there is a three-element structure $(S,\times,\circ)$ with $(\times,\circ)$ satisfying reverse distributivity that does not have $a \circ b = f(a \times b)$ for any function $f$ and with $a\times b$ non-constant. E.g. Consider the two operations below.
<code>x|012    o|012
-----    -----
0|121    0|011
1|211    1|011
2|111    2|011
</code>
Since $b \times c \neq 0$, we have $a \circ (b \times c) = 1 = 1 \circ 1 = (a \times b) \circ (a \times c)$, but not $a \circ b = f(a \times b)$, since that would give $0 = 0 \circ 0 = f(0 \times 0) = f(1) = f(1 \times 1) = 1 \circ 1 = 1$.
edit: While I'm sure that someone, somewhere has already named these structures, I doubt that there's a widely-agreed-upon name for them, even among people who actively study these structures (especially given that we don't have such a name even for the self-distributive case, and even when equipped with additional axioms. Viz. racks, crystals, automorphic sets, etc.).
Comment: This is nice. Let me just suggest some corrections (of some typos, certainly). In the end of the third paragraph, you mean $a\circ b = f(a\times b)$. And in the end of the BA example, you mean reverse distributivity (not commutativity); in the same example, I think the symbol $\not\vee$ doesn't read very well, since the slash is mostly concealed with the $\vee$ symbol.
Comment: One question: Can't we just shrink the Cayley tables in your examples to 2x2, i.e. $a\times b=1$, $a\circ b = b$ for $a,b\in\{0,1\}$. Then we still don't have $a\circ b=f(a\times b)$ for any $f$ by your own argument, right? So what you said about "all suitable pairs of operations $(\times,\circ)$ over truth values" doesn't seem to hold...
Comment: @Milten: Quite right! I got my notes mixed up. The intended statement was that " all suitable pairs of operations (×,∘) over truth values have a∘b=f(a×b) for some f or a×b constant", and I had a different (non-constant) intended example for the 3-value case.
I'll edit the answer with the correct example, and fix the typos pointed out by amrsa.
Comment: This is certainly the sort of answer I was hoping for. It shows that we get only more or less trivial situations if $(M,\times)$ has almost any sort of interesting structure. The semilattice case is of course less trivial, but $\circ$ still doesn't bring anything new to the table. This explains why we don't come across (or talk about) the property, which is actually what I was hoping to learn and should probably have written in the question. I think I will still study for completion the symmetric case of $(M,\times)$ just a monoid and $(M,\circ)$ having more structure, like in a ring.
Answer: For a yet trivial example in which $\circ$ and $\times$ denote different operations (and $\circ$ has a neutral element, and additionally, they're both associative and commutative), consider $M = \{0,1\}$, with $\circ$ being the usual product, and $\times$ a null product (that is, $x \times y = 0$, for all $x$ and $y$).
Then the equation
$$x \circ (y \times x) = (x \times y) \circ (x \times z)$$
reduces to
$$x \circ 0 = 0 \circ 0,$$
which is true.
It is not a very interesting example, but the answer to your question is yes, there exist such structures.
The example you deduced from the existence of identities for both operations (both operations being equal and self-distributive) is also perfectly legitimate.
There are many more others (some without any of the trivial aspects the above examples show), but concerning names, usually these structures are only named if they are found to be interesting in some context.
As a rule, the answer to the question "Are there such algebras satisfying these axioms" is yes, at least if the axioms are equalities. In these cases, there's always at least the trivial example, that is, the one-element algebra with whatever are the operations.
Comment: One might note that your example generalises to any case where $\circ$ has a right annihilating element $0$, i.e. $x\circ 0 = 0$, and then let $x\times y = 0$. This is a nice parallel to the other trivial solution $x\circ y =$ (a constant).
Comment: @Milten Yes, you have the example you yourself came up with, my example, the example given in a comment by Jair Taylor, the family of examples given in Z.A.K.'s answer, and if you want to, you can come up with a whole lot of other examples. For example, if $(A_i)$ is a family of examples, then so is $\prod_i A_i$, and also any subalgebra of that one and any homomorphic image. This enable us to construct infinitely many examples which are not trivial at all, but that doesn't mean they are interesting.


Convergence of standardized means of a Bernoulli variable / CLT

Question: The Question
Consider a binary random variable X that satisfies:
$Pr(X = 0) = \theta \ \ \ $ and
$Pr(X = 1) = 1−\theta $
for $\theta \in (0, 1)$ an unknown parameter.
Suppose an i.i.d. sample of size $n$ drawn from the distribution of X, $\{x_{i}, i = 1, \cdot \cdot \cdot , n\}$, is available, and $\hat{\theta}_{n} = \frac{1}{n}\sum^{n}_{i=1}x_{i}$ is considered as an estimator of θ.
Show that $\sqrt{n}(\hat{\theta}_{n} - \theta) \overset{d}{\rightarrow} N(0,\theta(1-\theta))\ as\ n \to \infty$
So this question is frustrating me, as it's a fundamental question, and I've really missed the big picture on it. I'll list two of the failed directions I look off in, but I'm just looking for some redirection here onto the right path.

Attempt #1
So for this approach, I just thought I'd brute force it. But I feel like this question is alluding to the CLT, so I was ready to abandon if it didn't feel like it was going to pay off....effectively my algebraic manipulation was:
$$
\begin{align*}
E[\sqrt{n}(\hat{\theta}_{n} - \theta)] &= \sqrt{n}E[(\frac{1}{n}  \sum^{n}_{i=1} x_{i}) - \theta] \\
&= \frac{1}{\sqrt{n}}E[ \sum^{n}_{i=1} x_{i}] - \sqrt{n}E[\theta] \\
&=  \frac{1}{\sqrt{n}} \cdot np - \sqrt{n}E[1-p]\\
&=  \sqrt{n} p - \sqrt{n}(1-p)\\
&= \sqrt{n}(2p-1)
\end{align*}
$$
Which is not great, as this will explode as $\lim_{n\to\infty}$

Attempt #2
I was very much following the proof of the CLT that uses characteristic functions. i.e. starting with:
$$
\begin{align*}
Z_{n} &= \frac{n(1/n)\sum x_{i} - n\theta}{n(\sigma / \sqrt{n})} \\
...\\
&= \sum \left( \frac{Y_{i}}{\sqrt{N}} \right), \ \ Y_{i}=\frac{x_{i}-\theta}{\sigma}
\end{align*}
$$
But inevitably, this leads me to expanding out $\varphi_{Z_{n}}(t) =  \prod_{i=1}^{N}\varphi_{Y}\left(\frac{t}{\sqrt{n}}\right)$ and showing that my standardized variable is $\sim N(0,1)$, which is a nice regurgitation of the proof, but a failure on my part to adapt it.

I'm keen to know, were any of my approaches getting close, and what fundamental have I failed to realize?
Comment: In attempt #1 what do you think $E(X_i)$ is?

Showing what the expectation is won't tell you the distribution, of course; you'd have to establish that.
Comment: Are you supposed to prove it without using the CLT? I.e. without taking the CLT as a known result.
Answer: There's a bug in your question definition:
If $\theta = \Pr\{X=0\}$, then the estimator for $\theta$ should be $\hat\theta = 1-\frac{1}{n}\sum x_i$ and not what you wrote.
Here's why: suppose that $\theta = \Pr\{X=0\}$ is large (=close to 1). Then, $X$ will be mostly zero, so $\frac{1}{n}\sum x_i$ will be close to zero!
It is more common to define $\theta = \Pr\{X_i = 1\}$, and with this notation, $\hat\theta$ will be indeed $\hat\theta = \frac{1}{n}\sum x_i$.
This will fix the problem with Attempt #1 (you will get zero at the end). Also, try not to use both $p$ and $\theta$ do describe the same thing...


Why is git is failing to push to origin

Question: I have a process whereby local changes made in a live environment can be committed and merged to a develop branch (so they are available to developers.)
The process goes something like this - within the live directory (which is a checkout of master)
git fetch
git add -A
git checkout -b hotfix
git commit -m"Hotfix of live changes"
git fetch . hotfix:develop
git push origin develop

But the push yields:
$ git push origin develop
To git@gitlab.[...]:group/repo.git
 ! [rejected]        develop -> develop (non-fast-forward)
error: failed to push some refs to 'git@gitlab.[...]:group/repo.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

I do not understand why my local develop is behind the origin develop.
The use of git fetch . hotfix:develop is based on what I understand from this article.  (It's important to me that I don't check out develop here.)
Merge, update, and pull Git branches without using checkouts
Always more to learn with git... :-)
Comment: You say "goes *something like* this", but the next steps are quite critical: we will need to know *exactly*, not approximately. In particular your `git checkout -b hotfix` creates a new branch at the current commit, which is not updated by the first `git fetch` and therefore is the same as it was before the `git fetch`, so we need to know what commit and/or branch you were on at the time. So, is it definitely `master`? And if so, when was `master` last updated, and how, with respect to `develop`?
Comment: Apologies, just an imprecise turn of phrase. But those are the exact steps. And I am on the head of master before running these commands. But develop could have had lots of updates since master was last committed to.
Answer: OK, per comment, the actual sequence is:
1   $ git checkout master
2   <some number of edits to various files>
3   $ git fetch
    [fetch messages occur here]
4   $ git add -A
5   $ git checkout -b hotfix
    [checkout message occurs here]
6   $ git commit -m"Hotfix of live changes"
    [commit output occurs here]
7   $ git fetch . hotfix:develop
    [more git fetch messages here]
8   $ git push origin develop
    [this step fails]

I added the $ command prompt, and some numbers at the left to identify the various steps.  I will also assume that all steps succeed except for step 8.

In step 1, you have your index and work-tree in sync with the tip-most commit of branch master in your repository.  But the tip commit of master need not have any relationship to the tip commit of branch develop, and this is going to matter when we get to steps 7 and 8.  (When we do get to step 7 I'll add some detail about what we can deduce from its success.)
Moreover, we know nothing of what is in the other Git repository, over on origin.  Presumably your master is related, in some way, to their master, perhaps even in sync.

Now, in step 2, multiple different developers muddy-up the work-tree.  The index still matches the tip of master but the work-tree differs.  As an aside, this step is not good practice, since we have no idea, after the fact, who did what: "multiple developers did things."  We will (through Git's mechanism) be able to figure out the grand total "things", but not the who did what part—nor the most important part of all, why they did those things.

In step 3, you have your Git contact the Git that handles the other repository, via the URL stored under the remote name origin.  This obtains any new commits and tags they have, and any other data needed to make those commits and tags complete and usable.  It updates your Git's origin/* remote-tracking branches, so now your origin/master, origin/hotfix (if they have a hotfix), and origin/develop match their master, hotfix (if they have one), and develop.
Again, the "they" step 3 is the other repository, being handled by the other Git, on the system at the URL stored under the name origin.  They are also the one rejecting your git push in step 8, so "what they have" is pretty crucial.  You'd think this step 3 is important, and it might be, except, we never refer to these origin/* remote-tracking branches ever again!

Now we go on to step 4, git add -A.  This copies all files from the work tree into the index.  (We're working in our repository; the "they" in steps 3 and 8 fade back into the background and the only "they" left are the various developers.)  We don't know who modified files in step 2, or what their intents were, but we can use Git to compare the updated index against the HEAD commit.
It would make more sense, logically speaking, to swap this step with step 5, although the effect will be exactly the same.

Now in step 5 we create a new branch named hotfix.  This new branch points to the same commit that we are already on, i.e., to the tip of branch master, which we have not changed in any way since step 1.  This particular form of git checkout does not touch anything in the index or work-tree.  It only creates a new branch and puts us on that branch.  The new branch points to the same commit hash that master points to, so that if, right now, we run:
$ git rev-parse master; git rev-parse hotfix

we will see the same hash ID twice.1  Or, if we were to draw the commits as a graph, we might see something like this:
...--o--o--*   <-- master, HEAD->hotfix

where * is the current commit, and the series of os are previous commits on branch master, which are also now on branch hotfix.
We still, as yet, have no idea where our own develop points, much less origin/develop, as that's not in any of our steps.

1git rev-parse means "parse a revision", i.e., turn it into a commit ID.  Every branch or tag name simply identifies one specific commit.  Branch names simply have the special property of moving to accommodate new commits, as you add them to the branch.  Note that they normally move forward, which is where this idea of "fast forward" comes from.

We now move on to step 6, which makes a new commit.  The new commit is, as usual, made from the contents of the index, which we set in step 4 to match the contents of our work-tree.  (It would make more sense to swap steps 4 and 5: create the new branch first, then update the index.  But as long as both steps succeed it doesn't really matter which order we use.)  Since our current branch is now hotfix, we end up with this graph drawing:
...--o--o--o   <-- master
            \
             *   <-- HEAD->hotfix

The current commit is now the new one we just made, which is exclusively on hotfix.  The previous commits on master are still on master, and are also on hotfix (commits are on all the branches that point to them, even if indirectly).
Note that the new commit's message is "Hotfix of live changes", which is not terribly useful.  We can git show the commit to compare it to the previous (tip-of-master) commit, but that won't tell us anything about who made these changes, much less why.  Compare to, e.g., a log message reading:
fix special case hit-counter problem

When viewing a page that fribbles a kravitz, if the weebly
area of the jitterbox has glubiframes, the page hit-counter
increments by 3 instead of 1.  We now account for the kravitz
fribbling so that the second adjustment is -1, so that the
total hit counter adjustment is 1 instead of 3.

Not only does this tell us why git show is showing us a -1 instead of a +1 in something related to kravitzes, it tells us what the problem being fixed was.  Should this fix introduce a new problem, we know where to start looking.

We now move to step 7.  This runs git fetch again, but instead of connecting to another Git, our own Git now plays both sides of the "internet-phone" connection, copying commits from our own repository to our own repository.  No actual copying is needed, so the only thing this does is update references—branch names, in our case—as directed by the refspec argument, which in this case is hotfix:develop.
If step 7 succeeds, that tells us a lot about where our develop was before.  This particular git fetch command will only move a branch name in a "fast forward" fashion.  This means we can redraw our "before" graph a bit.  It must have looked something like this:
...--o--o--o   <-- develop, master
            \
             *   <-- HEAD->hotfix

or:
...--o--o   <-- develop
         \
          o   <-- master
           \
            *   <-- HEAD->hotfix

so that the label develop can simply "slide forward" (and maybe down if necessary) so that after the git fetch step, it points to the same commit as hotfix:
...--o--o--o   <-- master
            \
             *   <-- develop, HEAD->hotfix

If the "before" picture had develop pointing to some commit that was not already on hotfix, we would get the same kind of "rejected - non fast forward" error we are getting in step 8.
It doesn't matter how far back our develop was, just that it was somewhere "behind" hotfix.  It was able to move in a purely forward direction (rightwards, in these graph drawings), perhaps very fast so as to skip over many commits, to point to the same commit as hotfix.
Importantly, however, we still don't know about origin/develop.

Now we move on to step 8, which actually fails.  Here our Git calls up that same other Git as in step 3.  This time, though, our Git sends our commits to them, instead of getting their commits over to us.  (Hence push instead of fetch.)  The one new commit we have that they don't is the one we added in step 6, so that's the one commit we send them.
Having sent them that commit, we then ask them to set their develop to point to this new commit * that we just sent them.
They say no.
The reason they say no is that for them, this operation is not a fast-forward.  Let's go take a guessing look at what they have in their graph, now that we have sent them our commit *.  It must look something like this—we can't be sure, without going over to their system and running git log --graph commands on their repo, but we can make a pretty good guess:
             o   <-- develop
            /
...--o--o--o   <-- master
            \
             *   <-- [proposed develop]

If they were to move their develop to point to the new commit * that we sent them, they would lose the commit at the tip of their develop.  There might be more than one such commit, but there is definitely at least one.  They will have to move their develop backward over these commits, to get to the one I'm assuming here is their master, and then forward to *.  If there weren't at least one such commit, they would accept our proposal and make their develop point to our new commit * that we just sent them.

Now, the remaining question is: how do we fix this?  There are a lot of options, but the most important one is probably to stop using step 2 entirely :-) because step 6 is really poor practice.  But if you can't do that yet, then you will need to do a real merge or rebase, to combine the new commit (the one still marked *) with the one at the tip of their own develop.
To do that, you will need a new repository, or at the very least, a new work-tree (see the git worktree documentation).  Let's say here that you choose to use a new repository.  You can either git clone the existing repository, or git push the existing commit to a new branch in some existing repository.  For instance, to push the local develop commit to a new branch on origin, replace step 8 with:
git push origin develop:newbranch

(where newbranch is a name not yet in use as a branch or tag name).  Assuming my graph drawing of what's in their repository is accurate, this will produce:
             o   <-- develop
            /
...--o--o--o   <-- master
            \
             *   <-- newbranch

and now, over on that other system, you can git checkout the various branches and merge them or rebase some commit(s) or whatever.
We might also note that step 3, in the eight steps above, is not very useful as it is right now.  It updates origin/master and origin/develop in the repository on the live server, but then we never do anything with these updates.  We might as well just skip it.  If we don't develop directly on the live server in the first place—as we shouldn't—we'll just git fetch and git checkout and git merge or git rebase whatever we need on our development machines, build and test it, and then send the result somewhere (probably a test system for testing, before we send it to the final server for real deployment).
Comment: Wow. Thanks for the incredible detail. I understand the flaws in the situation (live editing? gasp!) but without going into detail, this process is actually quite safe and as trade-off against a more conventional setup which would involve greater overheads, it's something we're happy with. Your answer has provided me with some good insight to fill gaps in my git knowledge - but I'm primarily marking this answer as accepted because you introduce me to git worktree which appears to be a light-weight alternative to my original goal of merging without having to create another repository.  Thanks!
Comment: It's worth noting that `git worktree` is new as of Git version 2.5 (and has at least one big bug fix in 2.6) and is still marked "experimental" as of 2.10.x (not sure about 2.11). It has at least one rough edge I've run into, but it works pretty well.
Answer: That is because your HEAD does no merge cleanly with origin. In other words someone pushed changes that are not part of your local history so you need to integrate those changes before you can push again. git pull and resolving the conflicts should do it.
See git's hint:
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.

Comment: Thanks. But as I say, I'm wanting to do this without a checkout. There will never be conflicts (different files are edited by developers and in this live environment).
Comment: You must allow git to merge locally in order to convince it that there is no conflicts.
Comment: What do you mean by you never want conflicts?  This is a shared code base so of course it will have conflicts. Do you possibly mean you never want a merge commit?  If so look into git pull with rebase option
Comment: Ad "There will never be conflicts", there is no way for git to know so it rejects the changes as the merge is not just adding commits at the top (fast forward). In distributed development it is up to the contributor to ensure things are mergable without conflicts and the result of the merge, even when it is without conflicts, still does what you want.
Comment: Thanks for your comments - yes, I can now see that there's no way to reassure git that there won't be conflicts (and that would of course be a dangerous feature!). @torek's suggestion at the end of his post of using git worktree to provide a light-weight environment for doing the merge should do what I need.

Why is git is failing to push to origin


How to change the Look and Feel of a JDesktopPane?

Question: I set the LAF of my project to the System default look and feel. Now I'm trying to put a JDesktopPane inside one of my panels but I want all my internal frames to use the java default LAF. Is there a way to change it without changing the LAF of the whole project?
Comment: possibly a dupplicate of: http://stackoverflow.com/questions/2713067/is-it-possible-to-set-different-look-and-feel-for-different-panels-within-a-same
Comment: can someone please give me an answer for this. how do I use the .setUI() method?
Comment: It is mentioned at the top of the [`UIManager`](http://docs.oracle.com/javase/7/docs/api/javax/swing/UIManager.html) documentation 'update component tree'.  There are a number of quirks (bugs) with mixing PLAFs.
Answer: import java.awt.BorderLayout;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.plaf.DesktopPaneUI;

public class AddingInternalFramestoaJDesktopPane {
  public static void main(final String[] args) throws Exception {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JDesktopPane desktop = new JDesktopPane();
    desktop.setUI(new DesktopPaneUI() {
    @Override
        public void installUI(JComponent c) {
            // TODO Auto-generated method stub
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
            } catch (Exception e) {
                e.printStackTrace();
            }
            super.installUI(c);
        }
    });
    JInternalFrame internalFrame = new JInternalFrame("Can Do All", true, true, true, true);
    desktop.add(internalFrame);
    internalFrame.setBounds(25, 25, 200, 100);
    JLabel label = new JLabel(internalFrame.getTitle(), JLabel.CENTER);
    internalFrame.add(label, BorderLayout.CENTER);
    internalFrame.setVisible(true);
    frame.add(desktop, BorderLayout.CENTER);
    frame.setSize(500, 300);
    frame.setVisible(true);
  }
}

Answer: enter image description here
deks.setUI(new DesktopPaneUI() {
    @Override
        public void installUI(JComponent c ) {
            // TODO Auto-generated method stub
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
            } catch (Exception e) {
                e.printStackTrace();
            }
            super.installUI(c);
        }
    });

and with this some file needs to include

import javax.swing.JDesktopPane;
import javax.swing.UIManager;
import javax.swing.plaf.DesktopPaneUI;

its important

JDesktopPane deks=new JDesktopPane();
Comment: Welcome to SO. Please read this [how-to-answer](http://stackoverflow.com/help/how-to-answer) for providing a quality answer.


Single CMS site on dedicated server

Question:
Possible Duplicate:
Can you help me with my capacity planning?

We're about to launch a huge website, expecting a HUGE traffic especially in the first few weeks. It will be a Joomla CMS based community website. We expect 20k-50k unique visits each day. Usually pages make 25-35 mysql queries, but there are some with even 140 where Max memory usage is about 20-25MB.
Please can you look at this config and make some comments and suggestions. This I've tested using ab -n 500 -c 10 but my concern is that it's not a real benchmarking.

2 x Intel X5650 Processor (total 24 cores)
12 x 2.66 GHz HyperThreaded Cores
32 GB
CentOS 6.2 on Virtuosso layer, cPanel
PHP 5.3.10 with mod_suhoshin, mod_fcgid, APC

<code><IfModule prefork.c>
    StartServers     5
    MinSpareServers   5
    MaxSpareServers   10
    ServerLimit      48
    MaxClients       44
    MaxRequestsPerChild  10000
</IfModule>
Timeout 300
KeepAlive Off

<IfModule mod_fcgid.c>
    FcgidMaxRequestLen 1073741824
    FcgidMaxRequestsPerProcess 1000
    FcgidMaxProcesses 1000
</IfModule>
</code>
Comment: Yes, it's off-topic for stack overflow, but that doesn't make it a good question for server fault.
Comment: There's no possible way we can help you with this question.  It's far too site-specific.
Comment: I was going to ask on stackoverflow, but found a similar question which was closed as they said it was rather related to server config.
Answer: I think what counts in here is the MySQL-config as well as how well you've worked on sending the right caching-headers for static content.
In fact your benchmark is telling you not what you were asking for, since it is only focused on the PHP-scripts + MySQL-queries. However a site-request is more.
Your benchmark does not include requests for

images
JavaScript-files
CSS-files
AJAX-calls (if relevant)

I recommend you to look for slow and inefficient queries as well.
You could start here:
MySQL's slow query log.
You should also keep in mind that "ab" takes only one specifig page-request into account. So if your server is well configured, you are hitting caches from the 2nd request on...
Comment: Thanks Ems. For all static contents we're using CDN network. I haven't noticed any slow queries yet, but I suppose there'll be some on very heavy load? We're also testing GreenSQL database proxy, for query cache and SQL injection protection.
Comment: You can configure the slow query log - "slow" depends on your scenario and is subjective. Try to set your server under load and tweak that config to show you queries which might not use indices they way they should.

Single CMS site on dedicated server


Inverter uma frase (PYTHON)

Question: Queria saber como eu inverto e também remover pontuaçao em uma frase do tipo:
Entrada
inverte('Anda apanhar um capotinho, Capitu, dizia-lhe ele.')

Retorno esperado
'ele lhe dizia capitu capotinho um apanhar anda'

Coloquei desta forma, mas ainda nao entendo muito bem essa parte, entao sei que esta bem errado...
def inverte(frase):

    if '-' or ',' or '.' in frase:
        virgula = frase.replace(',', ' ')
    ponto_final = virgula.replace('.', ' ')
    return str.reverse(ponto_final)

    if '?' in frase:
            virgula = frase.replace(',', ' ')
    ponto_final = virgula.replace('.', ' ')
    ponto_interrogacao = ponto_final.replace('?', ' ')
    return str.reverse(ponto_interrogacao)

    if '!' in frase:
            virgula = frase.replace(',', ' ')
    ponto_final = virgula.replace('.', ' ')
    ponto_interrogacao = ponto_final.replace('?', ' ')
    ponto_exclamacao = ponto_interrogacao.replace('!', ' ')
    return str.reverse(ponto_exclamacao)

Comment: Você não precisa fazer um `if` pra verficar se a pontuação está na string, é só fazer o [`replace`](https://docs.python.org/3/library/stdtypes.html#str.replace). Pra reverter pode utilizar 3 funções: [`list`](https://docs.python.org/3/library/functions.html#func-list), [`reversed`](https://docs.python.org/3/library/functions.html#reversed) e [`join`](https://docs.python.org/3/library/stdtypes.html#str.join) para, respectivamente, converter a string em uma lista, reverter os itens da lista e unir os textos na lista em uma string, por exemplo, `''.join(reversed(list(text)))`
Comment: esta com replace direto, mas estava dando erro já que algumas frases nao tinham algumas pontuaçoes, e tentei ajeitar assim. quanto seu return, eu havia tentado e me mostra um erro: ExternalError: TypeError: Cannot read properties of undefined (reading 'sk$type') on line 12

e o codifo ficou:
Comment: def inverte(frase):
    '''

    '''
    travessao = frase.replace('-', ' ')
    virgula = travessao.replace(',', ' ')
    dois_pontos = virgula.replace(':', ' ')
    ponto_virgula = dois_pontos.replace(';', ' ')
    ponto_final = ponto_virgula.replace('.', ' ')
    ponto_interrogacao = ponto_final.replace('?', ' ')
    ponto_exclamacao = ponto_interrogacao.replace('!', ' ')
    return str.join(reversed(list(ponto_exclamacao)))
Comment: Seu código está com problema de identação, pesquise como funciona os blocos/escopos no Python
Answer: Se quer saber como inverter uma frase e remover sua pontuação, uma solução nos parâmetros informados na pergunta pode ser obtida com o módulo de Operações com Expressões Regulares utilizando a função findall() para obter uma lista de palavras de uma frase a partir dum padrão de correspondência e então inverter essa lista.
import re

m = re.findall(r"[^\-,.?!\s]+", "Anda apanhar um capotinho, Capitu, dizia-lhe ele.")[::-1]

print(*m)
#ele lhe dizia Capitu capotinho um apanhar Anda

findall() retorna uma lista contendo todas as correspondências não sobrepostas de um padrão de correspondências dentro de uma string.
O padrão de correspondência [^\-,.?!\s]+ pode ser interpretado como:
Apanhe um ou mais caracteres que não sejam ou - ou , ou . ou ? ou ! ou um caractere de espaço.
A subscrição [::-1] pega a lista obtida com findall() e a retorna invertida.
O código acima trabalhado na forma de uma função:
import re

def inverter(frase, regex=re.compile(r"[^\-,.?!\s]+")):
  return " ".join(re.findall(regex, frase)[::-1])

print(inverter("Anda apanhar um capotinho, Capitu, dizia-lhe ele."))
#ele lhe dizia Capitu capotinho um apanhar Anda

Quanto código apresentado na pergunta não faz o que deseja e me abstenho de tecer comentários sobre pois a tentativa de seu reparo só traria confusão.
Comment: Pra complementar, dependendo da definição de "palavra", a regex pode ser ajustada - e ficar cada vez mais complicada - (ex: beija-flor é uma única palavra, deveria ser invertida para "flor beija"?) - Enfim, segue alguns posts relacionados: [aqui](https://pt.stackoverflow.com/a/450163/112052), [aqui](https://pt.stackoverflow.com/a/348269/112052) e [aqui](https://pt.stackoverflow.com/a/401529/112052).
Answer: Minha solução pra isso seria usar split na frase, transformando cada palavra da frase em um item de uma lista e em seguida inverteria a lista, logo depois o percorreria reformando a nova frase e para remover a pontuação usaria RegEx siga o exemplo:
import re

def inverterFrase(frase):
    novaFrase  = ''
    for palavra in frase.split()[::-1]: novaFrase += f' {palavra.lower()}'
    novaFrase = re.sub('[^\w\s]',' ',novaFrase)

    return novaFrase

resultado = inverterFrase('Anda apanhar um capotinho, Capitu, dizia-lhe ele.')
print(resultado)

Comment: oi, entao, ainda nao me ensinaram importar o re e nao fazia ideia, por isso acabei nao especificando. Saberia alguma outra forma sem ser importanto o re?
Comment: @MayaraFigueiredo neste caso pode continuar utilizando `replace`
Answer: Seguindo mais ou menos o que vc propôs na sua solução e o que vc comentou nas soluções acima (que queria uma solução sem o uso de import), a solução abaixo pode te ajudar:
def inverte(frase):
    frase = frase.lower()

    pontuacoes = ['.', ',', '!', '?', '-']

    for p in pontuacoes:
        frase = frase.replace(p, ' ')

    frase_lista = frase.split()
    frase_lista_invertida = frase_lista[::-1]
    frase_invertida = ' '.join(frase_lista_invertida)

    return frase_invertida

Alguns detalhes:

Reparei que na sua saída esperada, a frase toda está minúscula. Por isso, na primeira linha da função uso o método lower() para deixar a frase recebida toda em letras minúsculas.
Na lista pontuacoes vc pode colocar todas as pontuações adicionais que deseja ignorar. O loop for logo abaixo irá substituir todos esses caracteres por espaço.
Deixei todos os passos para inverter o texto em variáveis separadas, para que vc consiga identificar todo o processo quando reproduzir o código.

frase_lista divide a frase em lista de palavras
frase_lista_invertida inverte a lista de palavras
frase_invertida pega a lista de palavras invertidas e insere um espaço entre as palavras. Além disso, retorna a lista para uma string.

Qualquer dúvida é só falar que tento lhe ajudar.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Answer: fiz dessa forma e deu certo:
def inverte(frase):

    travessao = frase.replace('-', ' ')
    virgula = travessao.replace(',', ' ')
    dois_pontos = virgula.replace(':', ' ')
    ponto_virgula = dois_pontos.replace(';', ' ')
    ponto_final = ponto_virgula.replace('.', ' ')
    ponto_interrogacao = ponto_final.replace('?', ' ')
    ponto_exclamacao = ponto_interrogacao.replace('!', ' ')
    frase_minuscula = str.lower(ponto_exclamacao)
    frase_separada = frase_minuscula.split()
    frase_invertida = frase_separada.reverse()
    return str.join(' ',frase_separada)

Answer: conheço uma forma de inverter a frase e eu faria dessa forma:
palavra = 'Anda apanhar um capotinho, Capitu, dizia-lhe ele.'

print(palavra[::-1])

resultado seria esse: .ele ehl-aizid ,utipaC ,ohnitopac mu rahnapa adnA
espero ter ajudado com isso, ainda não conheço uma forma de retirar a pontuação... vou acompanhar também caso eu encontre uma resposta
Comment: Ele quer que inverta as palavras, não as letras.
Comment: para retirar a pontuaçao eu usei:

def inverte(frase):
    '''

    '''
    travessao = frase.replace('-', ' ')
    virgula = travessao.replace(',', ' ')
    dois_pontos = virgula.replace(':', ' ')
    ponto_virgula = dois_pontos.replace(';', ' ')
    ponto_final = ponto_virgula.replace('.', ' ')
    ponto_interrogacao = ponto_final.replace('?', ' ')
    ponto_exclamacao = ponto_interrogacao.replace('!', ' ')
    return ponto_exclamacao

Inverter uma frase (PYTHON)


Something In My Code Is Ignoring Everything After The Ampersand

Question: I can't for the life of me figure out what in this code is getting rid of the &. If someone enters a URL like http://example.com/?ref=me&id=1 I need the whole URL to show up in the echo. But it's cutting off everything after the &.
Here is the code that's being used.
HTML:

Enter the site URL that people will go to when they click your banner and click update to store it:

<input id="ban<?php echo $key;?>" type="text" value="" size="100">  <input type="button" class="buttonHAdd" value="Update" onclick="updateBannerURL('<?php echo $directoryfile ;?>', 'ban<?php echo $key;?>')">

Use the following HTML to display the banner on your site:
<span id="htmlban<?php echo $key;?>" style="background-color: #ffffff">

Script:
function updateBannerURL(bannerFile, id) {

if($("#"+id).val() == "") {
  alert("You have not entered a site url");
  return;
 }
$.ajax({
    type: "POST",
    url: "update.banner.php",
    data:'m='+$('#memberId').val()+'&b='+bannerFile+'&u='+$("#"+id).val(),
    dataType: 'json',
    success: function(data, textStatus) {
        $('#html'+id).text(data.bannerHtml);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
       $('.workareaTip').html('Hmm... Looks like an error occurred.');
   }
   });
}

PHP File update.banner.php
<?php
$domain = 'https://example.com/banner';
$u = $_POST['u'];
$b = $_POST['b'];
$m = $_POST['m'];
$array = array('bannerHtml'=>
    ''
    );
echo json_encode($array);
?>

With that code, I can enter in: http://example.com/?ref=me&id=1 and here is what it echos back: http://example.com/?ref=me totally ignoring everything after the ampersand.
Comment: I suggest to you use `data: { m: $('#memberId').val(), b: bannerFile, u: $("#"+id).val() }` on post request.
Answer: You either need to encode the data you are sending using encodeURI() on each variable, or just pass the data properly:
data: {
    m: $('#memberId').val(),
    b: bannerFile,
    u: $("#"+id).val()
},

Comment: It works because the way you were manually doing it before, neither javascript or PHP could tell whether the `&` was a new variable or part of the string, by doing it the way I have, Javascript encodes the ampersand so it parsed as part of the string.

Also, if my answer is correct, select the green tick under the voting arrows to mark it as such.
Comment: Awesome. I did check the green tick. I would have before you wrote this but it made me wait 6 minutes lol. Anyway, thank you so much!
Comment: I don't know why that works but it does lol. Thank you so much @Enstage