Why did Shostakovich use such long note values for such fast notes?

Question: I've loved Shostakovich's 8th quartet for ages but only just now looked at the score. I imagined the second movement would be a sea of black notes given its breakneck pace and was shocked to see that it's mostly whole, half, and quarter notes.  The indicated tempo is whole note = 120 (quarter note would then blaze by at 480 b.p.m.).  Second movement is about 5 minutes in.

Why didn't he use 16th notes and a more standard tempo?
Comment: Good question. Maybe he was commissioned as a copyist for his own piece and was paid by the measure… :)
Comment: My guess: 1) Visual consistency with the notation from the 1st movement, 2) Easier to read without lots of beams cluttering up the page.
Comment: P.S. You might consider making this a more general question, using the Shostakovich as an example of the larger idea: why use long notes instead of short. (But be careful to make clear the question is not about the time signature itself but rather the choice of notational values.)
Comment: @nuggethead Understandable. I've seen enough scores with long notes played fast and short notes played slowly, that perhaps I've just stopped noticing. (With regard to the latter, see the second movement of [Beethoven's Piano Sonata Op. 2, No. 3](https://www.youtube.com/watch?v=3asWeutbY0c&t=566s))
Comment: @phoog Oh, good point! Writing all those beams by hand .... Yikes!
Comment: @It'sHEDLEY but to me it's way HARDER to read.  I can't fathom half notes at that tempo.
Comment: @It'sHEDLEY easier to read and also, perhaps more significantly, to write.
Answer: First of all you should note that this is notated alla breve, so comparing the time to quarters per minutes serves little purpose. Could this have been notated in 2/4? Yes, absolutely! Writing it like this though makes writing and engraving a lot easier, because it avoids beams.
Furthermore it is not an uncommon practice in orchestral music to resort to bigger note values with faster tempi. Just consider the famous Scherzo from Beethoven's 9th:

This is notated in 3/4 with a MM of whole bar = 116, which would account to whopping 348 quarters per minute, with the later Presto section in 2/2 accounting to (disputed) 464 quarters per minute.
The final Presto of Beethoven 5 is notated alla breve with whole measure = 112, accounting to 448 quarters per minute.
And yes, these are quite extreme cases, but it shows that orchestral musicians are not entirely unused to such notation, as all of this cases could be notated in half the tempo with halved note values. And yes, Shostakovitch's tempo is even a bit more extreme than that, but not by far, and considering the nature of the piece it is not unreasonable for it to be extreme.
Of course there are many reasons for why one does this: It could even simply be tradition to notate certain types of pieces in certain time signatures, and then the tempo gradually increased. But you need to keep in mind that with increasing number of staves notation quickly becomes increasingly complex, and having beams everywhere does not really help there.
So arguable Shostakovitch could have notated this differently, but it is not like this notation here is particularly weird or uncommon. In fact this is not the only time Shostakovitch resorts to big note values for fast pieces. Take his Db fugue: It is indicated at 138 dotted half notes per minute, or 414 quarters. And if you look at the score I think it is quite clear that notating this with half note values in half the tempo would absolutely make this much less transparent to read.
In this particular case the benefit is a bit less. Compare for yourself:

The second one is just a bit more cluttered, but not to the extent that it would be really hard to read.


Tomcat virtual host configuration

Question: Background:
I have a host configured in my Tomcat's server.xml as:
<Host name="mydomain.com"
    appBase="webapps/myapp"
    unpackWARs="true"
    autoDeploy="true"
    xmlValidation="false"
    xmlNamespaceAware="false">
        <Context path="" docBase="."/>
    </Host>

Problem:
When I type http://mydomain.com into my browser, it works well. But when I type http://www.mydomain.com it shows a blank page.
Workaround I tried:
I tried to create another host as:
<Host name="www.mydomain.com"
        appBase="webapps/myapp"
        unpackWARs="true"
        autoDeploy="true"
        xmlValidation="false"
        xmlNamespaceAware="false">
            <Context path="" docBase="."/>
        </Host>

Result:
It seemed to work okay ( when I typed http://www.mydomain.com, it would show me regular site ). But later I discovered this way Tomcat creates two instances of the same application; that invalidates this approach.
Please let me know if in your opinion there is a better workaround.
Many Thanks!
P.S.
This is my first question at serverfault.com, I am not sure if this question has been asked before ( at least I couldn't find any ). Link to any such related question would also be appreciated.
Answer: You need a virtual host name alias.
<Host name="www.mydomain.com" ...>
  ...
  <Alias>mydomain.com</Alias>
  ...
</Host>

Comment: Thanks a lot XCondE, had no idea that it would be so simple :)

Tomcat virtual host configuration


Geo Push Notifications with Parse.com

Question: I'm trying to implement geo push notifications using the Parse.com JavaScript API.
I need to send a a push notification in a near sphere of 1 km of a certain GeoPoint. My code is below:
Parse.initialize("<MyApplicationId>", "<MyParseRestAPIKey>");

            var ponto = new Parse.GeoPoint(latitude, longitude);

            // Find users near a given location
            var userQuery = new Parse.Query(Parse.User);
            userQuery.withinMiles("location", ponto, 1.0);

            // Find devices associated with these users
            var pushQuery = new Parse.Query(Parse.Installation);
            pushQuery.matchesQuery('owner', userQuery);

            Parse.Push.send({
              where: pushQuery,
              data: {
                title: "Geolocalização Urba me",
                alert: "A partir de agora você vai receber muitas promoções"
              }
            }, {
              success: function() {
                alert("Notificação enviada com sucesso!");
              },
              error: function(error) {
                alert("Notificação não enviada!");
              }
            });

I always get the success message, but it doesn't work. In the Parse dashboard the campaing was created, but no push was sent.
What I'm doing wrong?
Best regards,
Answer: I dont know the javascript, but for the start i'll check what the first query fill fetch. Maybe the first returns no users. So after this line:
userQuery.withinMiles("location", ponto, 1.0);

insert this:
query.find({
  success: function(results) {
    alert("Successfully retrieved " + results.length + " users.");
  },
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
});

This one should return at least 1 user, for the push notifications to work. Again, I dont know the javascript language well, I just want to help you.

Geo Push Notifications with Parse.com


php sql delete button

Question: I'm trying to make a delete button from sql. I started a function called $del but I don't know how to complete it, in the form of a delete button echoe'd out beside the current echo statements.
$con = mysql_connect("localhost", "user", "pass");
if (!$con) {
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("database", $con);
$sql = "INSERT INTO camps (city, map, park, day, details)
    VALUES ('$_POST[city]','$_POST[map]','$_POST[park]','$_POST[day]','$_POST[details]')";

if (!mysql_query($sql, $con)) {
    die('Error: ' . mysql_error());
}

$number = 0;
$del = mysql_query("DELETE FROM camps WHERE user_id= '$number'");

$result = mysql_query("SELECT * FROM camps");

while ($row = mysql_fetch_array($result)) {
    echo "" . $row['city'] . "";
    echo "
";
}

Answer: You will need to make your links pass a param to a script that will delete that record.
Your links would looks something like this
 echo "" . $row['city'] . "";

Then your delete can just grab the params from the $_GET gloabal, and pass them into your sql like so
  $del = mysql_query("DELETE FROM camps WHERE user_id=" . $_GET['user_id']);

This current query will delete all camps for that user (adjust params / sql as needbe).
However, you should NEVER pass user vars into your sql strings. You leave yourself open for sql injection attacks. I would recommend using PDO to escape your sql. I would also recommend using the post method for any destructive db operation so that you don't accidentally alter something.

php sql delete button


Do ensemble techniques increase VC-dimension?

Question: Techniques like Adaboost use a ensemble of weak classifiers to obtain a "better" classifier.
Does(Can) the final classifier have a greater VC-dimension than the weak classifier?
An intuitive explanation  would suffice.
Comment: Well, just thinking about the definition of VC-dimension, do you think (say) boosted decision stumps can shatter a larger number of points than a single decision stump?
Answer: It depends on the ensemble method you use. Usually the VC-dimension increases. But in the case of AdaBoost, you can find the answer here:
http://www.cs.princeton.edu/courses/archive/spr08/cos511/scribe_notes/0305.pdf
http://cseweb.ucsd.edu/~yfreund/papers/IntroToBoosting.pdf


What things we have to take care of while finding the degree of field extension, splitting fields for some polynomial?

Question: I've just started field theory from Gallian. It may happen that the reasoning I'm providing for this problem seems weird. But this is all by what I tried to learn from some problems on maths stack exchange.

Suppose $\mathbb F \subset \mathbb C$ is the splitting field of
  $x^7-2$ over $\mathbb Q$ and $z=e^{\frac {2\pi}{7}}$ a primitive
  seventh root of unity. Let [$\mathbb F: \mathbb Q(z)]=a$ and $[\mathbb
 F: \mathbb Q(2^{(1/7)})]=b$. Then
(A) $a=b=7$
(B) $a=b=6$
(C) $a>b$
(D) $a<b$

Since degree of field  extension  is the degree of irreducible polynomial  whose root is $e^{\frac {2\pi}{7}}$ and the coefficient is in $\mathbb Q(2\pi/7)$. Here the polynomial is $p(z)=z^7-1$. So $a=7$,similarly $b=7$ but this wrong. I don't know the correct answer.
If possible please explain me in detail how to find the degree of field extension, splitting fields for some polynomial. What things we have to take care of while finding the degree of field extension, splitting fields for some polynomial?
Comment: Note that $x^7-1$ is not irreducible: $x^7-1 = (x-1)(x^6+\ldots+x+1)$, and $1 \in \mathbb Q$.
Comment: ... but $x^7 - 2$ is irreducible over $\mathbb{Q}$, e.g. by Eisenstein's Criterion.
Answer: First, you have a typo, $\large z = e^{\frac{2\pi}{7}i}$. Anyway, note that $\mathbb{F} = \mathbb{Q}(z)(2^{\frac{1}{7}}).$ So $[\mathbb{F} : \mathbb{Q}(z)]$ is the degree of the minimal polynomial of $2^{\frac{1}{7}}$ over the field $\mathbb{Q}(z)$. The minimal polynomial is still $x^7-2$, so $[\mathbb{F} : \mathbb{Q}(z)] = 7.$
Now, alternatively $\mathbb{F} = \mathbb{Q}(2^{\frac{1}{7}})(z)$. So $[\mathbb{F} : \mathbb{Q}(2^{\frac{1}{7}})]$ is the degree of the minimal polynomial of $z$ over $\mathbb{Q}(2^{\frac{1}{7}})$. The minimal polynomial of $z$ is $\textbf{not}$ $x^7-1$, this is not irreducible. The minimal polynomial of $z$ is $1 + x + x^2 + x^3 + x^4 + x^5 + x^6$ (for a discusion of minimal polynomials of primitive roots of unity, check out the Wikipedia page on Cyclotomic Polynomials.) Anyway, we see that $[\mathbb{F} : \mathbb{Q}(2^{\frac{1}{7}})] = 6$.
Side note: Though this is not asked in the question, we can see that $$[\mathbb{F} : \mathbb{Q}] = [\mathbb{F}: \mathbb{Q(z)}][\mathbb{Q}(z):\mathbb{Q}]= 7*6 = 42.$$


Find all abelian groups of order 60

Question: Find all abelian groups of order 60
$\mathbb{Z}_{60} \cong \mathbb{Z}_{2^2} \times \mathbb{Z}_3\times \mathbb{Z}_5$
$\mathbb{Z}_{30}\times \mathbb{Z}_2 \cong  (\mathbb{Z}_2\times \mathbb{Z}_3\times \mathbb{Z}_5)\times \mathbb{Z}_2$
$\mathbb{Z}_{15}\times \mathbb{Z}_4 \cong  (\mathbb{Z}_3\times \mathbb{Z}_5)\times  \mathbb{Z}_{2^2}$
Is it right?
Comment: Aren't the right hand sides of the first and last ones the same?
Comment: Why is this tagged with "real analysis"? This is abstract algebra, not analysis.
Answer: Hint: The Fundamental Theorem of finitely generated abelian groups can be used here. See, for example, Joseph Gallian's textbook Contemporary Abstract Algebra or another undergraduate abstract algebra text.
Answer: The fundamental theorem of finite abelian groups says that Every finite abelian group is the direct sum of cyclic groups, each of prime power order.
The prime factors of 60 are $60 = 2^2 \cdot 3 \cdot 5$ and we can write 60 as the product of primes in the following ways:
$2^2 \cdot 3 \cdot 5$
$2 \cdot 2 \cdot 3 \cdot 5$
Therefore every abelian group of order 60 must be isomorphic to one of the groups
$\mathbb{Z}_4 \times \mathbb{Z}_3 \times \mathbb{Z}_5$
$\mathbb{Z}_2 \times \mathbb{Z}_2 \times \mathbb{Z}_3 \times \mathbb{Z}_5$
Comment: There is another canonical way to write the groups. They are all possible direct products of cyclic groups of increasing orders $m_1, m_2, ...$ such that $m_1|m_2|m_3...$. In this case the two results would be $C_{60}$ and $C_2 \times C_{30}$ respectively.
Comment: See: https://math.stackexchange.com/a/2541773/465208

Find all abelian groups of order 60


event.preventDefault() not working with AJAX

Question: I've been having some trouble with an AJAX form today. I've tried lots of things, yet can't get it to work.
My jQuery should prevent the form to submit. It has to go through AJAX. Yet, it seems to ignore event.preventDefault(); and just submits the form.
The form is part of 'single-page'. Single-page is a page which is loaded via AJAX. The form is a standard form with POST method.
Question:
Why does event.preventDefault() not work and how do I fix this issue?
Form:
<form id="comment-form" action="commentsystem.php" method="post">
<input type="text" placeholder="Write a comment..." name="commentTxt" />
<input type="hidden" value="'.$row['id'].'" name="postID" />

    <input type="submit" value="" />

Jquery:
$('#comment-form').on('submit', function (event) {
    // Stop the browser from submitting the form.
    event.preventDefault();

    // Serialize the form data.
    var formData = $('#comment-form').serialize();

    $.ajax({
        type: 'post',
        url: $(form).attr('action'),
        data: formData,
        success: function (response) {
            $('.comment-container').append(response);
        }
    });
});

Commentsystem.php:
$sql = "INSERT INTO comments (postID, userID, comment) VALUES ('$_POST[postID]', '$_SESSION[id]', '$_POST[commentTxt]')";

if ($conn->query($sql)===TRUE){
    echo '
'.$_SESSION[id].''.$_POST[commentTxt].'
';
} else{
    echo 'Something went wrong while sending your comment.';
}

Comment: return `false` from the function
Comment: @DanielKrom - that's should not be necessary / useful, if `event.preventDefault` is being used: [.submit() docs](https://api.jquery.com/submit/)
Comment: Change - `$(form).attr('action')`- to `$('form').attr('action')`
Comment: Or to - `$(this).attr('action')`
Comment: Btw, you can check for javascript errors using firefox web developer feature so you know which exactly to fix.
Answer: Late to the party! I recently had this issue, hoping this will help someone else. I'm not sure why this happened, but on my localhost the following worked fine but on production preventDefault wasn't working.
$(document).ready(function() {
    $(document).on('submit', ".edit-form", function(event) {
        event.preventDefault(); // Stop form from submitting normally
        var url = $(this).attr("action"); // where to post to
        // more code
        return false; // added for good measure(might not need)
    });
});

Apparently the .on() doesn't like being in $(document).ready(), and from some reading it doesn't need to be. Which is great if you are using it like I was, because I was replacing forms that also needed it.
So all you need to do is remove the $(document).ready(){}; and see if it works just like this.
$(document).on('submit', ".edit-form", function(event) {
    event.preventDefault(); // Stop form from submitting normally
    var url = $(this).attr("action"); // where to post to
    // more code
    return false; // added for good measure(might not need)
});

As I said I'm not sure why this works, I haven't messed with jQuery in a long time, all I know is that it on my localhost preventDefault worked as expected and on production it ignored it. If anyone could point me in the the right direction of why it would work on local and not production? It would be appreciated. Maybe the hosting companies PHP settings? (haven't a clue, grasping at straws at this point)
Answer: I've figured it out myself. Am posting my own answer because it might help out someone else.
I changed:
$('#comment-form').on('submit', function (event) {

to:
$(document).on("click",".comment-submit", function(event) {

Note that I added a class to my submit button in the form.
I have no idea why this is working, but it does. If anyone could explain, that'd be appreciated.
Comment: be careful, now, your users might be able to submit not with a click but with moving focus on submit button (with tab) then press enter
Comment: Thanks for pointing that out. I'll see what I can do to prevent that.
Comment: Can't you do `$(document).on("submit","#comment-form", function(event) {` to still handle "submit" and not "click"? The reason might is because your form HTML is itself created dynamically (by an earlier ajax call...you mentioned it in the question). Probably the form didn't exist at the point that your code ran to try and bind an event to it, and consequently the event did not get bound to anything because the jquery selector didn't match any elements. See http://api.jquery.com/on/ under the section "Direct and delegated events" for an explanation of the use case for this syntax.


Find the order of the function(recurrence)

Question: I am trying to find the order of the following recurrence:
$Q\left(1\right)\:=\:1\:$; $Q\left(n\right)\:=\:Q\left(\lfloor\frac{n}{2}\rfloor\right), n > 1$.
From what I can tell the value of this function is always $Q\left(1\right)\:=\:1$, because we will always have the following:
$Q\left(n\right)\:=\:Q\left(\lfloor\frac{n}{2}\rfloor\right) = Q\left(\lfloor\frac{n}{2^2}\rfloor\right) = Q\left(\lfloor\frac{n}{2^3}\rfloor\right) = ... =Q\left(1\right)\:=\:1$. So the order is $\Theta(1)$
Am I correct or maybe I am missing something ?
Answer: From what you wrote, you aren't missing anything. The function is actually equal to $Q(x)=1$.
However, if I were you, I'd double check if you didn't miss something from the definition of $Q$.
Comment: @Student Maybe the question was supposed to be "solve $x^2-3=0$", and then, the answer would be still more different. Such speculation is futile.
Comment: Maybe the recurrence was intended to be be Q(n) = Q(floor of n/2) + O(1). In this case it looks like the order would be Theta(lgn) right ?


Found ddl change for a table in CDC management console

Question: our target db is DB2 and source is ORACLE, we found ddl changes in CDC management console and i need to fix the instance in to proper running condition.
Answer: Paul Vernon answer assumes that what you are looking for is how to replicate DDL changes.  I will assume that you don't want to replicate DDL changes, but just restart the subscription after minor layout changes (for example, after a column size has been increased or a column you are not going to replicate, changes).
If that is the case, right-click the specific table map on your subscription, and update table definition. I am not sure but I think after that, you have to refresh the entire subscription.  If the table is very large, you will want to avoid refreshing them all, but that's another question.
Off course, if in the table change, a column has been added and you want to deal with it, you can edit column map and make the specific assignment you want to that column.
I hope this helps.


How to add an additional class to each element in the menu-local-task.html.twig template?

Question: I need to change the admin tab template by adding my wrapper and class to it.
This is the default code:

{{ link }}

My code:

{{ link }}

Currently, the "DefTabs__tabItem--active" class is added to the active link, but I need to add an additional CSS class "DefTabs__tabItem" to each DIV element. How can I do this?
Answer: Create an array, ex:
{%
    set classes = [
      is_active ? 'is-active',
      'my-second-class-name',
    ]
%}

{{ link }}

Currently, the "DefTabs__tabItem--active" class is added to the active
link, but I need to add an additional CSS class "DefTabs__tabItem" to
each DIV element.

By the way, no need to repeat yourself with the naming, do this:
{%
    set classes = [
      'DefTabs__tabItem',
      is_active ? 'active',
    ]
%}

{{ link }}

Then in CSS you can target the active with .DefTabs__tabItem.active { ... }
Comment: @ВладимирПомелов sorry was guessing, its `{{ link['#title'] }}` and `{{ link['#url'] }}` an upvote to the questions answer would be appriciated
Comment: Your method works. Could you also suggest how to use the {{ link}} element and display the title and URL separately in the right places?
Comment: I tried this option, it doesn't output anything


Gradle build multi modules project with transitive dependencies

Question: I have problem with building my simple app. It contains 3 modules, ejb, rest and ear in which rest should be included. To achieve it I wrote build.gradle as one below. But I still have problems. Built ear looks like:
ear-1.0.ear
|--ejbs-1.0.jar
|--rest-1.0.jar
|--lib
   |--ejbs-1.0.jar
   |--other libs..

As you can see, I have here duplicated ejbs-1.0.jar. It's no something I want so I have tried to work this around. I have tried 2 approaches I found on web but neither of them worked. First one (comments with label 1) excluded all rest dependencies from going into lib dir. Second (label 2) did the same but also included rest-1.0.jar into lib, making it even worse.
Now I have no idea how to write my build.gradle so it puts jars made from subprojects in root dir, and their dependencies in lib dir. I have also tried to write something like comments with label 3, but this makes script fail.  Is there easy way to excluded it like that with similar syntax?
project(":ejbs") {
    apply plugin: "java"

    dependencies {
        compile group: 'javax.ejb', name: 'javax.ejb-api', version: '3.2'
        compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.2'
        compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.2'
    }
}

project(":rest") {
    apply plugin: "java"

    dependencies {

        compile project(':ejbs')
        compile group: 'javax.ejb', name: 'javax.ejb-api', version: '3.2'
        compile group: 'javax.ws.rs', name: 'jsr311-api', version: '0.11'
        compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.2'
        compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.2'
    }
}

project(":ear") {
    apply plugin: "java"
    apply plugin: "ear"

    dependencies {
        //1: def nonTransitive = {transitive = false}
        deploy project(":ejbs")
        deploy project(":rest")
        earlib project(path:":ejbs", configuration:"compile")
        earlib project(path:":rest", configuration:"compile")//1: , nonTransitive
        //2: add('earlib', project(':rest')) {
        //    transitive = false
        //}
        //3: earlib project(path:":rest", configuration:"compile") {
        //    exlude project(':ejbs')
        //}
    }
}

Comment: Have you tried `exclude module: 'ejbs'` instead of `exclude project ':ejbs'`?
Comment: No matter if I use exclude project or module. I still gets following exception. `Could not find method exlude() for arguments [org.gradle.api.internal.artifacts.ProjectBackedModule@4006c95c] on DefaultProjectDependency{dependencyProject='project ':rest'', configuration='default'}.`
Answer: I finally found a solution. I made it this way:
project(":ear") {
    apply plugin: "java"
    apply plugin: "ear"

    dependencies {
        deploy project(":ejbs")
        deploy project(":rest")
        earlib project(path:":ejbs", configuration:"compile")
        earlib(project(path:":rest", configuration:"compile")) {
            exclude module: 'ejbs'
        }
    }
}


printing error for an empty input

Question: I am trying to do a calculator app for android where i take two inputs for 2 numbers and output the result along with the function it does(i.e. addition or subtraction...).
public void Add(View view)
{
    float a=0,b=0,res=0;
    EditText num1 = (EditText) findViewById(R.id.editText1);
    EditText num2 = (EditText) findViewById(R.id.editText2);
    TextView function = (TextView) findViewById(R.id.textView4);
    TextView ans = (TextView) findViewById(R.id.textView5);
    a=Float.parseFloat(num1.getText().toString());
    b=Float.parseFloat(num2.getText().toString());
    String str1 = Float.toString(a);
    String str2 = Float.toString(b);
    if(str1=="")
    {
        function.setText("Enter both Numbers");
        ans.setText("");
        return;
    }
    if(str2=="")
    {
        function.setText("Enter both Numbers");
        ans.setText("");
        return;
    }
    res=a+b;
    String str = Float.toString(res);
    function.setText("addition");
    ans.setText(str);
}

so this is what i am doing. i take 2 inputs. convert them to float variables a and b. now my issue is if the user did not input an input and try for the solution, then i must produce some error saying 'enter both the numbers'. on doing it as above it's not working.
nor does it works in this manner
if(str1=='\0')
{
    function.setText("Enter both Numbers");
    ans.setText("");
    return;
}

this produces error when the input is zero.
So please help how to identify if there is no input given and to produce the error at that time.
Comment: Each time you use `==` instead of `equals`, god kills a dinosaur.
Comment: please give stack trace
that helps to suggest solution
i this Float.parseFloat(num1.getText().toString()) gives NumberFormatException
Answer: Put the test before converting to Float.
Your test need to be some thing like this:
 if (num1.getText().toString().trim().isEmpty()){
    // show error
 }

Comment: it gives that 'the method trim() is undefined for the type Editable'
Comment: @vinayawsm how about now?
Comment: its working fine. but what could be the problem in using try catch methods(throwing exceptions)?
Comment: @Babibu this also gives when num1 is null or contains character
Comment: @DarshanPatel If num1 is null we want an exception to be thrawn and the application to crush, this way we know we have a bug.
Answer: Use:
if(str1==null || str1.trim().equals(""))

printing error for an empty input


Should functional testing simulate UI events or check for preconditions?

Question: I am struggling with this question since I noticed that many functional testing frameworks (like Selenium for the web or UISpec for iOS) actually simulate UI events while testing. I am asking: couldn't it be sufficient just to check for preconditions such as that, e.g., the target and selector for a button are set correctly and then fire the selector manually? Why do I need to simulate touches? This has the con that you have to know more about the UI elements you're testing (you have to know what makes them to behave correctly), but since I am the one writing the tests, maybe this doesn't matter?
Could anyone shed some light on this?
Answer: Simulating touches can be useful for determining crashes caused by obscure or unplanned user behaviour - a particularly common one is having two items pressed simultaneously. It also allows you to create potentially quite esoteric tests: for example, random user input for a sustained period of time to attempt to crash or break your application in ways you wouldn't expect. The level to which you'd do this would depend on your app, and how important it was to you.
Your alternative approach also has some disadvantages when it comes to multi-touch. Whilst it would be fairly straightforward to fire a button selector through some sort of automatic test rather than simulating user input, what happens if you have an app that deals with swiping, pinching, or other multiple input gestures? In those cases the desired result may not be as black and white as the on/off of the button: you may have many shades of grey and differing output that required validation.
Simulated UI testing actually has quite a long history - there's an interesting story (well, interesting to me) about the original MacPaint and how a random UI input test was able to assist in reproducing obscure or difficult crashes here: http://www.folklore.org/StoryView.py?story=Monkey_Lives.txt


Laravel Eloquent hasMany and BelongsToMany not returning using with

Question: I am trying to do a single query to get back an order and the card to charge, but getting an error.
Card model:
class Card extends Eloquent {
    protected $guarded = array();

    public static $rules = array();

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function orders()
    {
        return $this->hasMany('Order');
    }
}

Order model:
class Order extends Eloquent {
    protected $guarded = array();

    public static $rules = array();

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function card()
    {
        return $this->hasOne('Card');
    }

    public function address()
    {
        return $this->belongsTo('Address');
    }

    public function orderItems()
    {
        return $this->hasMany('OrderItem');
    }
}

What I am trying to get back:
$order = Order::with('card')->find($id);

This obviously doesn't work and I have tried several combos. I think the issue is with my models/relationships.
Any idea how I can get back the order with the card/token details?
DB info: Each order can have only one card_id and each card can be in many orders. There is no order_id in the card.
Orders table basically:
id | card_id

Cards table:
id | token

Trying to get the token col to return with the Order.
Comment: Can you provide a description of the database schema.
Comment: @LoganBailey  Added. Very basic.
Answer: In your Order model, you need to change this:
public function card()
{
    return $this->hasOne('Card');
}

to this:
public function card()
{
    return $this->belongsTo('Card');
}

The reason is that you are defining the inverse of the hasMany relationship. With the belongsTo relationship, Eloquent will look for a card_id column on the orders table.
Comment: Good grief. That was it. Thanks!


Guitar's individual bridge saddle intonation cannot be adjusted further

Question: I picked up a cheap (used) guitar on which the intonation was all out of wack.  I've followed the instructions in this answer about fixing the intonation using the adjuster screws on the bridge.  My guitar sounds much better now, but several of the strings still need to be tightened further.  However, I have already tightened them to the point where the springs balancing the screws are basically being crushed, and I can't physically tighten them any more.
Here is a picture of the bridge:

As you can see, the adjusters for the A, G, and B strings are extremely tight already.  (Also, I am missing the high-E string at the moment since it broke and I haven't replaced it yet.)
How can I adjust things to allow further tightening?  Or does this suggest something else is wrong with the setup of the guitar?  (I did note that the neck appears to be poorly aligned - the strings are much higher near the pickups than they are near the nut.)
Comment: you probably should have all the strings on and tuned up while doing intonation. The answers mention the tremolo but are not explicit: if your tremolo is a little slack and leans towards the nut, this will affect the range of adjustment.
Comment: I'll just add that depending on the quality of the guitar you may need to set the floating bridge to be flush with the body to get the extra range for your intonation adjustments.  Doing that will change your action and everything though, so keep that in mind.
Answer: How's action? And how far are the strings from "correct" intonation?
For example lowering the saddle has the same effect of tightening the saddle screw (which stretches the string).
Slightly thighten the truss rod (straightening the neck) can help too, if the neck relief permits it (i.e. if is not already too straight).
Usually the bigger the string gauge the less adjustments are necessary, so you can try a bigger gauge set.
That said, intonation is the last thing to do while setting up a guitar.
Make sure you have the correct action and neck relief before doing intonation.
Also check if the neck is correctly seated in the body pocket. Guitar looks like a strato clone so it should have a bolt-on neck, try removing it, cleaning the neck pocket and reseat it correctly. A trick is also tune to pitch and slightly (1/4 of a turn) unscrew the neck bolts, so the tension of the strings pulls the neck firmly in the pocket, the screw them back.
Check the tremolo system, too, here's a good tutorial on youtube.
After you're sure the neck is seated, action is comfortable and neck relief is good (you don't want a too straight or too concave neck) proceed with intonation. Remember to check not only at 12th fret, but also at 15th and 17th fret, possibly with a tuner and not by ear only.
If you still find you need to tighten some saddle more than allowed, then you can remove the spring from the intonation screw to gain some turns.
And keep in mind, you can "never" get perfect intonation, expecially with a tremolo and a "cheap" guitar. Often 2-5 cents off is good enough.
Comment: Thanks, most of the problem was the action, I think; it was quite high. I lowered it and re-set the intonation, and now all my strings are in the right place except the A-string; it's still about 9-10 cents sharp at the 12th fret (after tightening the saddle all the way), but I can live with that.  That video series was very informative although most of the modifications he talks about are beyond what I can do at the moment.
Comment: Not sure about 15th and 17th frets, but 19th is good as there is a matching harmonic there.Also if the action is high, the strings will stretch as they are fretted, giving a false pitch.
Answer: Fender has pages about how to properly set up their guitars, and I would say this is close enough that you can use their Stratocaster directions.
First, you want a reasonably flat neck. Use the truss rod. Go slowly, turn a quarter turn at a time, and some bowing is okay. When done, if you fret at the highest and lowest fret, you should only have a gap at the 11th fret big enough to slide a playing card between the fret and the string.
The neck pocket on my Telecaster is such that I needed to put a shim in to allow me to get the action low enough. I cut a small piece off a business card and placed it in the pocket near the body. You might not need this.
The next step is the bridge. You set the action with Allen wrenched, and your bridge height should follow the curve of the neck. Lead players generally like a low action so their fingers don't have to work so hard. Rhythm players generally like a higher action so they can strum hard if they want without buzz or rattle. Slide players often like their action a little higher so that slide won't accidentally hit the frets. All of these actions are likely lower than what you likely have right now.
The last step is setting intonation, and that will have to change when you change string gauges. Most of what you have set before this point should stay stable between string changes, but intonation changes. There are two groups of strings: the unwound and the wound. Numbering starts at the smallest string and moves up. The unwound strings are, in standard tuning, the E and B strings ; the wound strings are G, D, A and E strings. (You sometimes see an unwound G.) The thicker the string, the further back the saddle. When done, your saddles should look like two stacked backslashes.
I've included the link to Fender's Setup Guide, which rightfully goes into further detail than I have. I haven't gotten to the can-of-worms that setting up your tremolo bridge can be.
Comment: Good tip on the action; it was indeed too high.  Fortunately I did not need to adjust the truss rod; the neck is already perfectly straight as far as I can tell.


Analytical Expression for Moment of Generalized chi-squared distribution

Question: Consider $Z\sim N(0,1)$ and the moments:
$$
E\left[ \left(C_1(Z+\sqrt{\lambda})^2 - C_2\right)^t\right].
$$
Here, $C_1$, $\lambda$ and $C_2$ are arbitrary constants which are all positive. $t$ is a nonnegative integer. Is there an analytical form for these moments in terms of $t$, $\lambda$, $C_1$ and $C_2$?
So far, I have identified that $C_1(A+\sqrt{\lambda})^2 + C_2$ follows a generalized chi-squared distribution. Where, following the notation on the wiki, $k=1$, $\lambda = \lambda$, $w = C_1$, $m=C_2$, $s=0$. However, I do not see any analytical expression for the moments on the wiki.
I see there are analytical moments for the noncentral chi-squared distribution. I also know how the moment generating function of the noncentral chi-squared distribution can be used to obtain moments for the generalized chi-squared distribution. However, I am able to obtain an analytical expressions using that approach.
Comment: Assuming $t$ is a *non-negative* integer, expand the argument as a polynomial in $Z$ and apply linearity of expectation.
Comment: I imagine lambda is positive, is t as well, or either C for that matter?
Comment: For what it's worth, Mathematica could not solve this integral, even with the assumptions that t and lambda > 0. (Edit: Integral t doesn't help either, unfortunately).
Comment: Thank you for that last comment. I will post an answer below. I feel that this is the correct method.
Answer: Following the suggestion provided by @whuber:
$$
\left(C_1(A + \sqrt{\lambda})^2-C_2\right)^t = \sum_{k=0}^t\text{nCr}(t, k)\left(C_1(A + \sqrt{\lambda})^2\right)^k\left(-C_2\right)^{t-k}
$$
Then apply the expectation operator:
$$
\text{E}\left[\left(C_1(A + \sqrt{\lambda})^2+C_2\right)^t\right] = \sum_{k=0}^t\text{nCr}(t, k)C_1^k\text{E}\left[\left((A + \sqrt{\lambda})^2\right)^k\right]\left(-C_2\right)^{t-k}
$$
Note that $\text{E}\left[\left((A + \sqrt{\lambda})^2\right)^k\right]$ is the $k$-th moment of a noncentral chi-squared distribution with analytical form reported here.


Agendar serviço no Azure

Question: Ola, alguém sabe como faço para agendar a execução diária de um .exe no Azure? Tenho um notificador de email que precisa rodar todos os dias, é um projeto em C# que gera um executável e gostaria de colocar ele no Azure e deixar executando toda manhã.
Não tenho um VPS nem como deixar na minha máquina local pois não tenho como deixa-la ligada 24/7. Seria algo semelhante ao agendamento do windows.
Comment: Encontrei um post sobre serviços em background no Azure, vou testar e se funcionar coloco aqui: https://azure.microsoft.com/en-us/documentation/articles/web-sites-create-web-jobs/
Answer: Consegui configurar seguindo o tutorial aqui.  Dentro dos Serviços de Aplicativos no Azure é só clicar em "Trabalhos Web" e preencher o seguinte formulário:

Ele permite enviar o zip com o .exe e escolher a forma de disparo, no meu caso foi Agendado e a periodicidade é especificada com base em uma expressão CRON, para executar todo dia as 6:30 da manhã:
<code>0 30 6 * * *
</code>
Fiz dessa forma mas pode ser feito usando a interface do agendador do Azure:

O bacana é pode visualizar os logs também. Vi que ele permite também chamar outros tipos de arquivos: bat, js, py, cmd.

Agendar serviço no Azure


Uncaught TypeError: undefined is not a function :/

Question: Hi I am stuck on this error for a while and can't seem to find where the problem comes from...
I am basically dynamically making multiple list items with buttons in them for each row in my database with php:

                <?php
                for($i=0;$i<count($_SESSION['upgrades']);$i++)
                {
                    $class = '';
                    if($_SESSION['upgrades'][$i]['gekocht'] == TRUE)
                    {
                        $class = 'gekocht';
                    }
                    echo '

                    <button class="upgradebutton'.$class.'" data-id="'.$_SESSION['upgrades'][$i]['update_id'].'">'.$_SESSION['upgrades'][$i]['naam'].'</button>

';
                }
                ?>

And then check if it has that class I append to it when the upgrade is already bought on each button click with javascript:
$(document).ready(function(){
$('.upgradebutton').click(function(){
    if(!$(this).hassClass('upgradebuttongekocht'))
    {
        var upgrade_id = $(this).attr("data-id");
        alert(upgrade_id);
        $(this).addClass('gekocht');
        window.upgrades[upgrade_id][gekocht] = 1;
    }else{
        alert("already Bought");
    }
});
});

Comment: hassClass? I beleive it should be hasClass
Comment: Wauw thans man I feel stupig right now...
It was just a spell fault...
Answer: Just use hasClass instead of hassClass
http://api.jquery.com/hasclass/
:)


Best practice for transfering MSSQL Databases and all accounts to new server?

Question: One of our customers has installed a new SQL server and needs to take down the old SQL box. Both servers are running Microsoft SQL Server 2008. The applications all access the current SQL server via hostname so the plan is to transfer everything then cut over the connections by updating DNS.
My question is: "What is the best way to actually move the databases and all associated accounts to the new server?"
Nothing about the current set up is documented. I need to figure out how to move over all the databases, stored procedures, SQL agent jobs, and SQL authentication accounts to the new server (note: the only account password I have is the sa password).
I am not a MSSQL guru so any help would be appreciated. Let me know if I need to clarify anything.
Answer: I guess a Backup/Restore would be appropriate here.
Update:

If you additionally need logins to be transferred, use:
http://support.microsoft.com/kb/918992/en-us
If you need all database objects to be transferred, use the Copy Database Wizard instead of Backup/Restore
Comment: You can transfer logins by using:
http://support.microsoft.com/kb/918992/en-us
Not sure about the security settings/agent jobs
Comment: The Database copy wizard seems to be able to copy all associated objects: http://sql-articles.com/articles/dba/how-to-use-copy-database-wizard/
Comment: The backup/restore feature would handle the databases themselves but not the security settings, accounts, agent jobs, etc...
Comment: +1 +1. Thanks guys. Don't know how I missed that KB article and the blog post is a nice find too.
Comment: I've added those the answer. Glad I could help out.


Trouble designing grunt workflow, with rev and usemin, for webdev

Question: I'm going to start using grunt-rev & grunt-usemin with grunt-watch for my web development needs (a RESTful Web App specifically).
I have a local development machine which will run grunt-watch to attach revision identifiers on my JS files. I git commit and git push my tree to a git repo, and then ask the production server to git pull the changes from the git repo to show them to the web visitors.
The problem is that I don't want my git repo to store different filenames (due to grunt-rev) on each commit. That would be bad, because then I wouldn't be able to do git diff between commits without having my screen get flooded with the contents of files that appear and disappear, and also it could (sometimes) take up a lot more storage than if it only stored the small diffs of the files.
The only solution I see is to add the build directory containing the versioned filenames in my .gitignore, so as to not store those files (with the constantly changing filenames) in git. But wouldn't that mean that I would have to run grunt-watch on my production server as well, in order to produce the build directory with the versioned filenames there as well? But that gets complicated: a new process has to run on the remote server, maybe with its small chances of error in processing the files. Not the solution I was hoping for.
Do you people have another solution? What would you suggest I did?
Answer: What I do to solve this, is to remove previous "build" files before committing and deploying a new file. There is no need to keep older files that have been generated, because you can always rebuild them with the source files (which are in git).
Comment: If you remove `/build` before committing, then the git repository does not contain `/build`, so where does the production server download `/build` from?
Comment: I keep /build in my git repo and use something like this to clean it of old versions before commit: https://github.com/gruntjs/grunt-contrib-clean
Comment: You mean the git repo has an empty `/build` directory? Or does it have a `/build` that contains only new and relevant files, as opposed to containing old garbage that hasn't been cleaned?
Comment: Yes it only contains the last build, so you can use that on your production server as well.
Comment: So you get different filenames (containing revision ids) in every commit, in your git repo?
Comment: For external CSS/JS files yes, also prevents caching


How do I correctly add images to a facet-wrapped ggplot? My current output returns images as monochromatic silhouettes

Question: I am attempting to create a facet-wrapped scatterplot that displays pitch movement data for three major league pitchers. The only thing I can't figure out is how to add headshot images of these three players to each pitcher's data. My current code 1) takes several minutes grabbing/placing the player headshots, despite there only being three images, and 2) outputs the headshots as red silhouettes. Why are the images appearing this way and how can I fix? Code and visual of output below.
library(baseballr)
library(dplyr)
library(tidyverse)
library(grid)
library(mlbplotR)
library(ggplot2)

# pull data for three different pitchers
senga <- baseballr::statcast_search_pitchers(start_date = "2023-03-30",
                                             end_date = "2023-04-03",
                                             pitcherid = 673540)
strider <- baseballr::statcast_search_pitchers(start_date = "2023-03-30",
                                               end_date = "2023-04-03",
                                               pitcherid = 675911)
kirby <- baseballr::statcast_search_pitchers(start_date = "2023-03-30",
                                             end_date = "2023-04-03",
                                             pitcherid = 669923)
# bind to one df
df <- rbind(senga,strider,kirby) %>%
  filter(pitch_type != 'PO')

player_cleaned_data <- all_data %>%
  # Only keep rows with pitch movement readings and during the regular season
  filter(!is.na(pfx_x), !is.na(pfx_z),
                game_type == "R") %>%
  mutate(pfx_x_in_pv = -12*pfx_x,
                pfx_z_in = 12*pfx_z)

# Make a named vector to scale pitch colors with
pitch_colors <- c("4-Seam Fastball" = "red",
                  "2-Seam Fastball" = "orange",
                  "Sinker" = "cyan",
                  "Cutter" = "firebrick",
                  "Fastball" = "gray",
                  "Curveball" = "blue",
                  "Knuckle Curve" = "pink",
                  "Slider" = "orange",
                  "Changeup" = "#4cbb17",
                  "Forkball" = "hotpink",
                  "Split-Finger" = "#FC6C85",
                  "Sweeper" = "coral",
                  "Knuckleball" = "black")

# Find unique pitch types to not have unnecessary pitches in legend
pitch_types <- unique(player_cleaned_data$pitch_name)

player_cleaned_data %>%
  ggplot(aes(x = pfx_x_in_pv, y = pfx_z_in, color = pitch_name)) +
  geom_vline(xintercept = 0) +
  geom_hline(yintercept = 0) +
  geom_point(size = 2, alpha = 0.45) +
  # Scale the pitch colors to match what we defined above
  scale_color_manual(values = pitch_colors,
                     limits = pitch_types) +
  # Scale axes and add " to end of labels to denote inches
  scale_x_continuous(limits = c(-25,25),
                     breaks = seq(-20,20, 5),
                     labels = scales::number_format(suffix = "\"")) +
  scale_y_continuous(limits = c(-25,25),
                     breaks = seq(-20,20, 5),
                     labels = scales::number_format(suffix = "\"")) +
  theme(text = element_text(family = "Trebuchet MS"),
        plot.title = element_text(size = 20, face = 'bold'),
        axis.title = element_text(size = 12),
        legend.title = element_blank(),
        legend.text = element_text(size = 11),
        plot.caption = element_text(size = 10),
        legend.key = element_rect(fill = NA)) +
  coord_equal() +
  labs(title = "Pitch Movement Profiles",
       subtitle = "2023 MLB Season | Pitcher's POV",
       caption = "Data: Baseball Savant via baseballr",
       x = "Horizontal Break",
       y = "Induced Vertical Break", color = "Pitch Name") +
  facet_wrap(~full_name) +
  mlbplotR::geom_mlb_headshots(aes(player_id = pitcher), x = 17, y = 17, width = .2)

Answer: The first issue is that you specified the color aes as a global aesthetic. As mlbplotR::geom_mlb_headshots inherits the global aes your headshots get colored according to pitch_name. To fix that I added color=NULL but you could also use inherit.aes=FALSE. Second, the issue with the long rendering time is that you add a picture for each row of your data, i.e. you add the images multiple times. Instead, you only need a reduced dataset which could be achieved using data = ~distinct(.x, pitcher, player_name) in mlbplotR::geom_mlb_headshots:
library(baseballr)
library(tidyverse)
library(grid)
library(mlbplotR)
library(ggplot2)

player_cleaned_data %>%
  ggplot(aes(x = pfx_x_in_pv, y = pfx_z_in, color = pitch_name)) +
  geom_vline(xintercept = 0) +
  geom_hline(yintercept = 0) +
  geom_point(size = 2, alpha = 0.45) +
  # Scale the pitch colors to match what we defined above
  scale_color_manual(
    values = pitch_colors,
    limits = pitch_types
  ) +
  # Scale axes and add " to end of labels to denote inches
  scale_x_continuous(
    limits = c(-25, 25),
    breaks = seq(-20, 20, 5),
    labels = scales::number_format(suffix = "\"")
  ) +
  scale_y_continuous(
    limits = c(-25, 25),
    breaks = seq(-20, 20, 5),
    labels = scales::number_format(suffix = "\"")
  ) +
  theme(
    text = element_text(family = "Trebuchet MS"),
    plot.title = element_text(size = 20, face = "bold"),
    axis.title = element_text(size = 12),
    legend.title = element_blank(),
    legend.text = element_text(size = 11),
    plot.caption = element_text(size = 10),
    legend.key = element_rect(fill = NA)
  ) +
  coord_equal() +
  labs(
    title = "Pitch Movement Profiles",
    subtitle = "2023 MLB Season | Pitcher's POV",
    caption = "Data: Baseball Savant via baseballr",
    x = "Horizontal Break",
    y = "Induced Vertical Break", color = "Pitch Name"
  ) +
  facet_wrap(~player_name) +
  mlbplotR::geom_mlb_headshots(
    data = ~distinct(.x, pitcher, player_name),
    aes(player_id = pitcher, color = NULL),
    x = 17, y = 17, width = .2
  )

Comment: Works great!  Explanation was extremely helpful. Much appreciated.


Stress (Linux) Settings, Expectations, and Questions

Question: Just got some new Cores and RAM in last week, wamnted to stress test them and see if they were any good.  Unfortunately I couldn't find any real resources on how to do this without an OD so I fired up StressLinux.
Dual QC Xeon 2.66's with HT, 16GB of RAM, fired up Stress with:
stress --cpu 10240 --io 256 --vm 16 --vm-bytes 1G --vm-keep --timeout 2000

Fires Back (amongst other things):
<-- worker 8129 got Signal 9
now reaping child worker process
failed run completed in 2009s

What does this mean?  Where do I go from here?
[[ EDIT ]]
In addition, what are good and testing settings for such a machine?  As of this edit I am using:
stress --cpu 30000 --io 2000 --vm 30 --vm-bytes 1G --vm-keep

And I still can't seem to get the CPU temps above <60C...  Then again, it is a Dell PowerEdge 1900, and the airflow is insane...  But shouldn't I be able to raise the temps a little more?
[[ EDIT AGAIN ]]
Maybe I should rephrase the question towards what I thought the obvious direction would be: How do I tax the processors to the extreme (what settings) to ensure I have rock solid chips (ie, before the second-hand warranty runs up).
I am using "heat" as a measure of taxation because it's the only way I know of.  Low heat (only 20C above idle) would indicate to me that I am not pushing them as hard as I could.
A natural extension of that question may be: "Is there a way to tell just how much stress I am actually putting on the cores? Or how much more headroom I have?
Where's my oven?
Comment: `But shouldn't I be able to raise the temps a little more?`  You're clearly just not trying hard enough.  To raise the temperature of the processors, remove the heatsinks and use the fans to suck air from your oven over the processors...  all of which begs the question of why you're intentionally trying to cook your processors.
Comment: Touche.  I have rephrased the question.
Comment: Buy spare parts. They're probably cheaper than spending your day on trying to heat up your server room via software.
Comment: Not spending a day, just a side thing.  We're waiting on drives for an Array anyway, just figured I would see if I could max it out.  Spares are fairly cheap.  Like I said, just poking it.
Answer: You're doing it WRONGEST.
Seriously - this is NOT how you "stress test" a system.
How hot the CPU gets is a poor measure of CPU workload -- I could have an lightly CPU easily exceed its designed operating temperature parameters (and probably trip its thermal protection circuit and shut off). I could have a CPU going full-bore at zero degrees if I were willing to cool it with liquid helium.
You are testing the efficiency of your cooling system, nothing else.

If you want to determine if a system is stable and functional simply put any general processor and memory intensive workload on it (try re-compiling an operating system: make world is still the standard stress test in the BSD community).

If the system crashes it's not stable, and you can start looking at components (RAM, CPU, Motherboard) to determine why.
If it survives you have one datapoint indicating possible stability, but remember:
You can never tell how strong something IS, only how strong it WAS right before failure.

If you induce a failure in testing you know the component is now no longer serviceable. Whether it was bad when you got it or not you can't say - your stress test may have caused the failure (particularly if you're using "heat" as your arbiter of stress: Running a CPU above its maximum rated temperature is a great way to destroy it).

Modern computers sold by reputable vendors use high quality parts which are extensively tested by the manufacturer prior to sale.  Companies like Intel rely on their good name to keep their business.
Accordingly, the chances of you having a bad CPU are relatively low. The chances of bad RAM, or a bad hard drive are significantly higher, but this is why we have ECC RAM and RAID arrays.
Comment: My question was evidently not constructive, which I fail to understand how a question can be such, but your question was very constructive.  Thank you.

I obviously did not understand the 'idea' of 'stress testing,' that fact, coupled with this answer (or any such answer, really) makes the combined whole patently 'constructive' for other users in the same situation, but I digress.

Again, thank you.


iPhone: How to get size of an item in a xib?

Question: I made a custom class from UITableViewCell as MealItemDetailCell.
In its xib, I dragged a UITableViewCell and then added items to the cell. When populating the Table that displays the MealItemDetailCells, the cells' bottoms are all cut off since they're larger than the table's default height.
I see where I can use heightForRowAtIndexPath and set it to something large enough, but I might want to edit the items in the custom cell, and then this height might not be appropriate. Is there any way to programmatically retrieve the height of the TableViewCell from the xib file?
In the controller, when I provide a cell for populating the table, I tried cell.frame.size.height, but that seemed to return the default cell height of 45. cell.window.size.height gave me the whole iPhone window.
My current xib cell is 110 high, seen from the Size Inspector when clicking on the TableViewCell when looking at the MealItemDetailCell.xib.
I would expect some attribute to be readable so that I can get this.
I searched for a while, but I couldn't find anything close. Any thoughts or guidance? Thanks.
Update (response to Henry Hong below): I see differing values in the Size Inspector. There's the "row height" value under the "Table View Cell" (top) section. Then there's a value in "Height" under the "View" section (under Show "Frame Rectangle"). The "row height" doesn't change when dragging the xib's table cell boundary until I uncheck and recheck the "custom" checkbox. Although, just trying this again, I see both follow the actual cell size when finishing dragging! And now, but not before, using the value incremented up/down arrows, I see the cell outline move as expected. But the "row height" still stays the same. I'm sure this is documented somewhere, but I guess I just have to get the "row height" number matching the actual/final edited xib cell height.
Answer: In interface builder click on the tableview and then in the ruler section set the height for the cell to 110 otherwise you get the standard height which is 44.
Hope it helps!
Cheers
Comment: Well, I don't have a .xib for the tableview. I just instantiate a tableviewcontroller programmatically. So, I'm not sure that this would apply.
Answer: cell.frame.size.height should be able to retrieve the height of the view from nib file.
Just make sure u have already assigned a value to the "row height" with size inspector in interface builder.
or it will return the default height.
Comment: Responded above (ran out of room here).
Answer: I guess you can fix your problem implementing the UITableViewDelegate method tableview:HeightForRowAtIndexPath:  and return the height for the cell that in your case is 110.
Cheers,
Alessandro
Comment: But that assumes I know the height of the cell. I'd like to be able to graphically edit the cell in its xib and be done with it. I don't want to have to visually get the size from a Size Inspector box, and then type it into the return value for HeightForRowAtIndexPath. That's why I detailed my experience with the boxes and values above.
Answer: Most of the provided answers cover your question. As far as I can see, the 'Row Height' in interface builder is just a convenience value, since editing the height directly via number is not allowed – only by dragging.
Interface builder writes this value into the xib data structure as 'rowHeight':
<tableViewCell contentMode="scaleToFill" selectionStyle="blue" indentationWidth="10" shouldIndentWhileEditing="NO" rowHeight="65" id="3" customClass="PaperInfoCell">

However, despite parsing the nib yourself, it doesn't seem to be written in any property of the instance – hence your only solution that removes double bookkeeping is to instantiate the nib and get the row height from the cell's frame.
As a side note, all of that is less of a burden when using iOS8, auto layout, and UITableViewAutomaticDimension.


Finding angles between a linear function and the y-;x-axis and their respective consines

Question: I've run into a problem while finding a directional derivative of a function.
The function is as follows:
\begin{align}
      z &= \frac{x}{y} \\\\   \end{align}
The task is to find its directional derivative at a point M whose coordinates are x=1, y=1 in the direction of a vector defined by f(x) that is perpendicular to the graph of f(x)=2x-1 at the point M.
I found that the perpendicular in question is as follows:  \begin{align}
      f(x) &= \frac{-x+3}{2} \\\\   \end{align}
Next, my job is to find cos(x) and cos(y) to plug into the formula:
\begin{align}
z'_{l}=f'_{x}cos(x)+f'_{y}cos(y)
     \end{align}
The problem here is that my teacher and I have considered two different angles and, despite getting the same end results, do not agree about the intermediate steps.
My cosines are the following:
\begin{align}
    cos(x) &= -\frac{2}{\sqrt5} \\\\
cos(y) &= \frac{1}{\sqrt5}   \end{align}
I got cos(y) by considering that a vector defined by \begin{align}
      f(x) &= \frac{-x+3}{2} \\\\   \end{align}
points from origin to the second quadrant, where angle x, the angle with the x-axis, is one that is greater than 90°, and angle y, the angle with the y-axis, is one that is less than 90°, it is adjacent to the y-axis as seen from the second quadrant.
My teacher has instead considered both angles to belong to the first quadrant (they haven't considered the vector coming from the origin in the same way I have), which means both angles amount to over 90°. Their angle y is one that is adjacent to the y-axis as seen from the first quadrant.
I was pretty sure my logic was very flawed while performing the computation, but I'd like to know what the truth here is for certain. The question is, which is the angle with the y-axis that is given by the function described above?
Thank you.
Answer: I would most often think of a 2D direction vector as $\mathbf{v}=\left\langle \cos\theta,\sin\theta\right\rangle$  for an appropriate angle $\theta\in[0,360^{\circ})$ measured counterclockwise from the positive $x$-axis. However, we can also write $\mathbf{v}=\left\langle \cos\theta_{x},\cos\theta_{y}\right\rangle$  for an appropriate pair of angles $\theta_{x}$ and $\theta_{y}$ (I would not recommend using $x$ and $y$ for angles as one could get confused).
No matter which quadrant $\mathbf{v}$ lies in, we can take $\theta_{x}=\theta$ (measured counterclockwise from the positive $x$-axis), and $\theta_{y}$ to be either the clockwise angle from the positive $y$-axis: $90^{\circ}-\theta_{x}$ or the counterclockwise angle from the positive $y$-axis $\theta_{x}-90^{\circ}$, since $\cos\left(\theta_{x}-90^{\circ}\right)=\cos\left(90^{\circ}-\theta_{x}\right)=\sin\theta_{x}=\sin\theta$.
In your specific example, there are two directions perpendicular to the graph of $f(x)=2x-1$: an approximately "east southeast" direction $\left\langle \dfrac{2}{\sqrt{5}},-\dfrac{1}{\sqrt{5}}\right\rangle$  and an approximately "west northwest" direction $\left\langle -\dfrac{2}{\sqrt{5}},\dfrac{1}{\sqrt{5}}\right\rangle$ . Suppose $\theta\approx153^{\circ}$ so that $\left\langle -\dfrac{2}{\sqrt{5}},\dfrac{1}{\sqrt{5}}\right\rangle =\left\langle \cos\theta,\sin\theta\right\rangle$ . Then if we define $\theta_{x}=\theta$ and $\theta_{y}=\theta-90^{\circ}\approx63^{\circ}$ (the counterclockwise angle from the positive $y$-axis to the vector), we indeed have $\left\langle -\dfrac{2}{\sqrt{5}},\dfrac{1}{\sqrt{5}}\right\rangle =\left\langle \cos\theta_{x},\cos\theta_{y}\right\rangle$ , so that your calculation works fine.
I don't quite understand from your description which $y$-angle your teacher has calculated, but values of $\theta_{y}$ approximately equal to $-63^{\circ}$ or $297^{\circ}$ would also work for the $y$-coordinate if they were using the $\left\langle \cos\theta_{x},\cos\theta_{y}\right\rangle$  setup you were. And values approximately equal to $153^{\circ}$ or $27^{\circ}$ or $-207^{\circ}$ would work if they were using a $\left\langle \cos\theta_{x},\sin\theta_{y}\right\rangle$  setup like I am more used to. Note that the angles which work would also all change if your teacher were using $\left\langle \dfrac{2}{\sqrt{5}},-\dfrac{1}{\sqrt{5}}\right\rangle$  instead of $\left\langle -\dfrac{2}{\sqrt{5}},\dfrac{1}{\sqrt{5}}\right\rangle$ .


NGINX + OpenSSL + Docker. Cannot load certificate key Permission denied. SSL:error:0200100D:system

Question: I want to deploy a SSL certified angular app using nginx reverse proxy on docker (using docker compose). I've generated self-signed certification with openssl and made the configurations to the nginx config file. But I get error message in docker container:
[emerg] 1#1: cannot load certificate key "/etc/ssl/private/aims.key": BIO_new_file() failed (SSL: error:0200100D:system library:fopen:Permission denied:fopen('/etc/ssl/private/aims.key','r') error:2006D002:BIO routines:BIO_new_file:system lib)
nginx: [emerg] cannot load certificate key "/etc/ssl/private/aims.key": BIO_new_file() failed (SSL: error:0200100D:system library:fopen:Permission denied:fopen('/etc/ssl/private/aims.key','r') error:2006D002:BIO routines:BIO_new_file:system lib)

I've generated the key with this command from this gist:
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout aims.key -out aims.crt -config aims.conf -passin pass:[...]

This is the docker compose:
version: "3.8"
name: aims

services:
  ...

  web-app-proxy:
    image: nginx:alpine
    container_name: web_app_proxy
    ports:
      - 443:443
      - 80:80
    volumes:
      - ./web_app_proxy.nginx:/etc/nginx/nginx.conf:ro
      - ./aims.crt:/etc/ssl/certs/aims.crt
      - ./aims.key:/etc/ssl/private/aims.key

This is the nginx config file (web-app service comes from another docker compose):
worker_processes 1;

events { worker_connections 1024; }
http {
    sendfile on;
    large_client_header_buffers 4 32k;

    upstream web-app {
        server web-app:4200;
    }

    server {
        listen 80;
        server_name web-app;

        location / {
            return 301 https://$host$request_uri;
        }
    }

    server {
        listen 443 ssl;
        server_name web-app;

        ssl_certificate /etc/ssl/certs/aims.crt;
        ssl_certificate_key /etc/ssl/private/aims.key;

        location / {
            proxy_pass         http://web-app;
            proxy_redirect     off;
            proxy_http_version 1.1;
            proxy_cache_bypass $http_upgrade;
            proxy_set_header   Upgrade $http_upgrade;
            proxy_set_header   Connection keep-alive;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Proto $scheme;
            proxy_set_header   X-Forwarded-Host $server_name;
            proxy_buffer_size           128k;
            proxy_buffers               4 256k;
            proxy_busy_buffers_size     256k;
        }
    }
}

I've seen the problem relates with running the docker container as root, but I don't know how to do it. (Using only docker compose or compose + dockerfile, not docker run / docker exec).
If I create a dockerfile and separate from compose, when I deploy I get:
PEM_read_bio_PrivateKey() failed (SSL: error:0909006C:PEM routines:get_name:no start line:Expecting: ANY PRIVATE KEY)

When I see aims.key encoding is ASCII, and I couldn't make a conversion as suggested in this post (even using sudo).
Answer: Regardless of your docker configuration, an nginx process will be launched as the user specified in the nginx configuration file. I believe you are getting a 'permission denied' error because you generated your certificates with sudo.

Check what user nginx is running as. In shell, type sudo ps aux | grep nginx
You should see something like this: My user is nginx, yours might be www, www-data or something else.

root      776967  0.0  0.0  22332  7884 ?        Ss   Oct23   0:00 nginx: master process /usr/sbin/nginx
nginx    1262783  0.5  1.8 447744 427960 ?       S    16:18   0:00 nginx: worker process
nginx    1262784  0.5  1.8 447744 427960 ?       S    16:18   0:00 nginx: worker process
nginx    1262785  0.5  1.8 447744 427960 ?       S    16:18   0:00 nginx: worker process
nginx    1262786  0.5  1.8 447744 427960 ?       S    16:18   0:00 nginx: worker process
nginx    1262787  0.0  0.0  25864  6392 ?        S    16:18   0:00 nginx: cache manager process

Now you need to give access to cert files to your user.
sudo chown nginx:nginx /etc/ssl/certs/aims.crt
sudo chown nginx:nginx /etc/ssl/private/aims.key

Replace 'nginx' with the user from the above output

While this is not recommended you can tell nginx to run as root. Add user root; to the top of your nginx configuration.
Comment: If this isn't enough, you might need to run `sudo chmod +r /etc/ssl/certs/aim.crt` and the same for the private key


Snakemake - Jupyter lab notebook does not find kernel

Question: When writing a program in a jupyter lab notebook using R or python I install specific conda environments as kernels to access that environment-specific packages from a single jupyter lab installation in the base conda environment
After finishing developing the notebook I want to plug it into my snakemake file to ensure later reproducibility and of course, I do that with the respective conda environment .yaml file so that all the needed packages/libraries are provided.
Now comes the problem: the rule which references the notebook, is not reproducible on another machine/environment, as it tries to access/run a kernel which is specific to my development environment
Does anyone have a workaround or solution to this particular problem?
EDIT:
More detailed steps leading to my problem

Setup a conda environment (matplotlib_env) for a specific tool or task (here: matplotlib)

conda create -n matplotlib_env python=3.8 ipykernel matplotlib nbconvert

I created a ipython kernel so my jupyter-lab instance from the base environment can access the conda environment and the respective packages (matplotlib)

python -m ipykernel install --user --name matplotlib_env --display-name "Python_maplotlib"

I created a short notebook (1) that uses the kernel configured in step 2 (Pyhton_matplotlib 2)

import matplotlib.pyplot as plt
plt.plot([1,2,3],[1,4,9])
plt.savefig('exp.png')

Having finished the task I want to plug it into my snakemake workflow for management and reproducibility reasons. For that, I define a rule, with the respective notebook and conda environment .yaml file (automatically generated via: conda env export > matplotlib_env.yaml).

rule make_plot:
    output:
        "exp.png"
    conda:
        "matplotlib_env.yaml"
    notebook:
        "make_plot.ipynb"

Executing the rule works fine as long as the original conda environment (with the configured kernel) still exists. As soon as I remove the original conda environment (optionally also the kernel from the kernelspec list) I get an error message, as the kernel can not be found anymore and the snakemake generated conda environment does not possess the kernel, the notebook is looking for.

snakemake -p --cores 1 --use-conda make_plot

ERROR message after removing the original environment
[NbConvertApp] ERROR | Failed to run command:
...
FileNotFoundError: [Errno 2] No such file or directory: '/home/miniconda3/envs/matplotlib_env/bin/python'

ERROR message after removing kernel from kernel list
...
raise NoSuchKernel(kernel_name)
jupyter_client.kernelspec.NoSuchKernel: No such kernel named matplotlib_env

Comment: Are you running with `--use-conda`?  Can you post the notebook rule and conda yaml?  I've not used a specific conda environment for notebook rules, but it should work.
Comment: Hi, thanks for the response and interest!
Yes, I am using --use-conda.
I have edited the original post and added a minimal example of the problem I am facing.
Comment: Hi , did you ever find a solution to this? Running into this now.
Comment: Hi, nothing better than my workaround below. Personally, I recommend using notebooks either for interactive development and then generate a script for your workflow or when the processed notebook has a purpose (e.g., communication or tutorial).
Answer: I found a workaround:
Before saving your notebook the last time switch kernel to the default python or R kernel from your base environment. These always have the same default name post-installation (eg "Python 3"). Thereby, when executed via snakemake the notebook looks for the default Python/R kernel and finds the new installation provided via the snakemake --use-conda option.
This is not the most elegant version, but if you need/want to plug notebooks into your workflow, it is good enough.
The most rigorous would be to turn the notebook, once done, into a script with clearly defined input and outputs. This script is then plugged into the snakefile, via a corresponding rule, instead of the notebook.


postfix logs showing ??? as command from client

Question: I am running an Ubuntu 18.04.6 LTS server with the postfix 3.1.0-3ubuntu0.4 package.
Both the Apple Mail client and the Postbox client experience a weird delay when first sending an email to the smtp service. Eventually Apple Mail retries and works but Postbox gives up.
In the initial exchange, the email client appears to send a '???' as a command after the server greeting, or at least it is logged that way by postfix. The line in the log looks like (actual ip address redacted):
Nov 23 17:11:09 mail postfix/smtpd[3367]: < ipxx-xxx-xxx-xxx.ph.ph.cox.net[xx.xxx.xxx.xxx]: ???
To which the server responds:
502 5.5.2 Error: command not recognized
What is going on here? I cannot find anywhere that the string '???' is considered a valid SMTP command. Is this some sort of hack for older systems?
While both of the above clients seem to send this, the iOS email client does not.
I have not found any documentation of this or tolerating this as a postfix setting.
Answer: Postfix replaces non-printable() characters with ? in its logs.
One way this could happen is a client instructed to establish a TLS connection yet using a port number where postfix is talking plaintext. The binary TLS1.3 ClientHello not being a valid SMTP command would show as ? in logs. The servers offer to upgrade an already existing unencrypted SMTP connection to a secure channel via the STARTTLS compatibility hack would usually go unnoticed. A clever MUA might recognize this mistake - and retry with settings deviating from configuration - where clever could easily venture in dangerous territory.
Assuming your postfix is setup to allow that; Configure your clients to use port 465/tcp ("Message Submission over TLS protocol") together with the instruction to use TLS right away. That is the recommended secure option for submitting mail. A few keywords that will help you identify the options that go together:

port
reserved for message submission via
what it is labelled in software settings

465
SMTP over TLS (recommended)
implicit TLS, TLS, SMTPS, clean TLS, wrappermode

587
SMTP plaintext with optional TLS
explicit TLS, STARTTLS, optional TLS, RFC 3207


Invalid resource in copy source ARN - while copying between the same accesspoints

Question: I am trying to copy a file from a source access point to a destination access point with the same url except a different file names:
e.g.
aws s3 cp s3://arn:aws:s3:eu-west-2:1234567890:accesspoint:my-access-point-name/path/to/local-1234567890.inprogress s3://arn:aws:s3:eu-west-2:1234567890:accesspoint:my-access-point-name/path/to/local-1234567890

Giving:
copy failed: s3://arn:aws:s3:eu-west-2:1234567890:accesspoint:my-access-point-name/path/to/local-1234567890.inprogress to s3://arn:aws:s3:eu-west-2:1234567890:accesspoint:my-access-point-name/path/to/local-1234567890
An error occurred (InvalidArgument) when calling the CopyObject operation: Invalid resource in copy source ARN

Answer: Replacing : with / just before the access point name worked!
aws s3 cp s3://arn:aws:s3:eu-west-2:1234567890:accesspoint/my-access-point-name/path/to/local-1234567890.inprogress s3://arn:aws:s3:eu-west-2:1234567890:accesspoint/my-access-point-name/path/to/local-1234567890

Strange : is fine if one of the source or destination is access point ARN but not both.


Why Does $a^0 = 1$ and $a^{-p} = {\frac{1}{a^p}}$ if $(a \not = 0) , p \not= 0$?

Question: Why does $a^0 = 1$ and $a^{-p} = {\frac{1}{a^p}}$ if $(a \not = 0)$ and $p \not= 0$?
How can we prove these formulas?
Comment: Are you looking for formal proofs or intuitions about why these statements are true?
Comment: Based on your [previous question](https://math.stackexchange.com/questions/3279408/how-to-prove-a-cdot-bn-an-cdot-bn), is $p$ supposed to be in $\Bbb{R} \setminus \{ 0\}$? Also, $a^{-p} = \frac{1}{a^p}$, not $a^{\frac{1}{p}}$.
Comment: I think of $a^0$ like an empty product, which is $1$
Answer: This is just an intuition test of why the properties should be defined like this:
The fundamental property of the exponential functions is the following:
$b^x\cdot b^y=b^{x+y}$.
The other properties are derived in such a way that the mentioned property is satisfied.
For example: since we want the equation to be fulfilled
$$b^0\cdot b^x=b^{0+x}=b^x$$
we must define $b^0:=1$.
Since we want the following equation to be fulfilled
$$b^{-x}\cdot b^x=b^{-x+x}=b^0=1$$
we must define $b^{-x}:=1/b^x$. Since we want the following equation to be fulfilled
$$\underbrace{b^{1/n}\cdot b^{1/n}\cdots b^{1/n}}_{n\, \textrm{factors}}=b^1=b$$
we must define $b^{1/n}:=\sqrt[n]{b}$. Similarly, we must to define $b^{m/n}:=(\sqrt[n]{b})^m.$
Answer: $$a^{0} = a^{n-n} = \frac{a^{n}}{a^{n}} = 1$$
Also,
Do you mean
$$ a^{-n} = \frac{1}{a^{n}}? $$


Fast Secure way to upload data into Amazon S3

Question: We want to upload data in a secure way from our datacentre, which is a bank to Amazon s3.
Fast way - Tsunami UDP (It seems that UDP protocols are much faster compared to tcp protocals like scp,ftp etc).
However, Tsunami UDP cant directly stream into s3, but I can across this post with
https://blogs.aws.amazon.com/bigdata/post/Tx20YXSQ49507II/Moving-Big-Data-Into-The-Cloud-with-ExpeDat-S3-Gateway.
This plugin seems to be able to do so.
Any other recommendations here
Secure  -
Amazon Direct Connect might have added costs so not considering for the initial phase.
Amazon Import/Export - This might only be feasible for the first time upload.
Any recommendations here to create a secure channel between aws and the datacentre
Comment: There are a lot of possible answers, which is not the kind of question Stack Overflow is intended to address.  You seem to be solving a non-problem, given that S3 natively supports HTTPS *and* parallel multipart uploads, which remove any real or imaginary advantage UDP transfers might provide over TCP.
Comment: @BMW Instead of encryption, i was looking for a secure network kinda answer. Not very good at networking, but is it possible to use https kinda of tunnel for udp transfers, so we were absolutely sure no one is able to tap into the channel in the middle.
Comment: HTTPS uses encryption. How about ExpeDat mentioned in the link? `[Tsunami UDP] doesn't support native encryption` however later it says `ExpeDat, by Data Expedition Inc., addresses these shortfalls.`.
Comment: @prog_guy, think about Openvpn + GPG, it is cheap (open source) with no cost and fast. https://en.wikipedia.org/wiki/OpenVPN, support udp
Comment: @Michael-sqlbot : It was stated that "upload/download your data to Amazon S3 via SSL-encrypted endpoints. " So does this mean, if I use the aws cli or multipart-upload, the data is encrypted before going into the internel channel (tcp) and unencrypted before it is stored into S3.
Answer: If you are looking to upload files directly to S3 from data source location you can go for EvaporateJS. It also provide good security.


Como montar mosaico de 3 'colunas' CSS?

Question: Estou tendo dificuldades para montar o mosaico do exemplo abaixo para a versão mobile do meu site
A versão em orientation:portrait deve ser algo similar a essa:
..........................
.          |             .
.  Img 1   |             .
.          |             .
...........|  Img 3      .
.          |             .
.          |             .
.  Img 2   |             .
..........................

E quando o site for colocado em landscape
Quero que as mesmas fiquem em 3 colunas assim:
  ...........................
  .      |        |         .
  .      |        |         .
  . Img1 | Img 2  | Img 3   .
  .      |        |         .
  ...........................

Sobre as imagens qual o tamanho as mesmas devem ser?
Comment: Tem que ser CSS puro?
Comment: Aberto a todas as soluções, preferência css puro, mas se tiver outra solução boa eu aceito também.
Comment: Eu recomendo muito utilizar o Bootstrap, ele vai manter um responsivo limpo e as dimensões das imagens "não irão perder" seus pixels.
Answer: Fiz inline para facilitar.
Portrait:

Landscape:

Media Querie você resolve
Answer: Pode separar "estas diferenças" em arquivos .CSS diferentes:
<link rel="stylesheet" media="(orientation: portrait)" href="portrait.css">
<link rel="stylesheet" media="(orientation: landscape)" href="landscape.css">

Ou ter um arquivo padrão que se aplica a tudo no seu site, e ter uma condição específica como p pseudo-código demonstra abaixo:

Veja aqui mais exemplos de media-queries
Mais exemplos de uso
Answer: Uma forma é usar o flex, junto às media-queries:

.container{
  display: flex;
  max-width: 300px; /* Você pode trocar a largura aqui livremente */
}

.container .all, .container .last{
  display: flex;
  flex-flow: column;
}

.all, .last{ width: 100%; }

.all .image, .last .image{
  width: 100%;
}

.last .image{
  width: 200%;
}

@media(orientation: landscape){
  .container{
    display: block;
    max-width: initial;
  }

  .container .all, .container .last{
    display: inline-block;
    width: initial;
  }

  .image{
    display: inline-block;
    width: auto !important;
    height: 300px;
  }

}

Answer: Tente usar este CSS, uso em vários projetos e funciona perfeitamente pra mim.
Dá para personalizar com o número de colunas desejado.
#photos {
    line-height: 0;
   -webkit-column-count: 3;
   -webkit-column-gap:   0px;
   -moz-column-count:    3;
   -moz-column-gap:      0px;
   column-count:         3;
   column-gap:           0px;
}

#photos img {
   width: 100% !important;
   height: auto !important;
}

Como montar mosaico de 3 'colunas' CSS?


two hands playing different things - how do you feel or hear or pronounce it?

Question: I'm playing djembe for 4 years, and now trying to play dun-duns. Basically, it's two sticks and two drums or a bell+drum for now.
I'm trying to learn some rhythm in which the bell on the left hand and the stick/drum on the right don't match in some parts. I wonder how you feel it inside? Is it two different rhythms just sounding at the same time? Or is it one single mixed rhythm?
For the previous rhythm I was only able to play it when I "merged" two hands into one pattern in my head, but it feels a bit wrong, especially that the left hand basically was just doing the "metronome" hits.
For example,
1   2   3   4
. .. .. . . . .   [bell hits, left hand]
S     S S D D S   [sangban / dundun hits, right hand]

If you imagine yourself playing this, what would be the "feeling" of this rhythm?
Or this
(like son-clave with metronome on the left hand)
1   2   3   4
.   .   .   .   [bell hits, left hand]
S  S  S   D D   [sangban / dundun hits, right hand]

Comment: Are you learning from anyone? I feel like my advice isn't the most important here; I'm trained in Western classical contexts, and you're asking about the polyrhythms common to many West African contexts. These skills have been transmitted millions of times before now, and I'm sure they have their own methods and mnemonics. I can't say for sure whether the approach is to "merge" two rhythms into one, or to simply "rub your stomach and pat your head" by holding both in your mind simultaneously.
Answer: Actually when you play dundun, you play 2 (or more) instruments.
The drum and the bell. Each instrument have their own rhythm, but in the end, when they reach your ear, they are already mixed into one polyrhythm.
So the short answer is: both approaches are correct if you can only deliver the final effect. If you think you cannot then you need more practice to grow the muscle memory. It will help your hands keep playing what they know well while you focus/do/think of something else - be it drums or not.
Polyrhythms and polymeters
West African music is full of polyrhythms and polymeters.
In the traditional dundun style, the combined melody of dundunba, sangban and kenkeni (and bells) is usually a polyrhythm - notes (or whole phrases) are more likely to alternate than overlap. You won't hear any polymeters, triplets or even notes shorter than 8ths in the dundun part. These techniques are very popular with djembe or other solo drums though. Some dundunfolas use them when playing a dundun set.
Dundun practice
Let me share a few techniques I use to improve my feeling, memorize patterns and fight the constant feeling of being lost in this crazy music that I can't stop falling in love with.
Feel the beat
Memorize melodies in reference to the beat. Always. This means pretty much what you described as playing the metronome hits with one hand and the actual melody with the other. Or you can just sign your melody, vocalize it, and clap the beat with your hands. Dancing to it can help too. Once you can sing it, it means your brain has learned and now it can teach your hands. Otherwise you can end up learning the wrong melody without even realizing (until you come to play with other people).
Learn the bell
Many rhythms share the same bell pattern. Others can sound quite similar, but it's important to know the difference so you won't get lost in time. When you learn a few key patterns then you can... that will be said later.
The pattern you've mentioned x-xx-xx-x-x-x-x- is one of those popular and good to know. It hides a little challenge in hearing the second beat in the pause between the double stokes. Others worth mentioning are:

x-x-xx-x-x-x you can learn in both 6/8 and 4/4 feelings
-xx-xx-xx-xx worth spending a lifetime, dunumba style (6/8)
xx-xx-xx-xx- e.g. soko sangban (6/8)
x-xx-xx-xx-x e.g. soko dundunba, soli (6/8)

Bell rules

drum stroke is always supported with the bell stroke
all pauses are single 8th notes
avoid triple strokes

So you play only 8ths: either a single note stroke, a double stroke and there is an 8th note pause between each stroke.
F...orget the rules
And learn the triple stroke x-xxx-xxx-xxx-xx pattern too. It may be quite challenging at higher tempos.
Forget the bell
You can also take a more relaxed approach and let the bell follow your melody naturally, filling in the gaps to match your drum strokes. This is much more effective when you already know some patterns, otherwise you may end up playing metronome (there's nothing wrong with that, but you may find it hard to come up with another pattern quickly unless you've memorized some).
Independent hands
As you have already realised, playing just one mixed melody is much more viable, but it comes at a cost. When you make a mistake it will probably knock out your both hands. Also it feels somewhat harder to improvise/variate when you operate on the combined melody.
Finally I don't think it is possible to develop fully independent hands (excluding those playing 40h/day), but I can assure you constant practice (and only this) is the key to improvement. At some point your muscles will learn how to play patterns without the constant supervisory of your conscious mind. You will be able to remind yourself (the more you practice the more quickly) and then play a sequence of bell-drum patterns just by thinking about the first few notes. Think of typing on your phone with text suggestions on. This is your language. Patterns are the vocabulary.
Answer: Generally,
When the 2 rhythms are too complex for you to be heard independently while playing, mentally merging the two is a good tool to learn a polyrhythm. It would be a very different feeling for you to play it and to listen to it from another player.
Once you manage to play it (by merging the 2), you can practice to gently focus your attention on one of your hand while keeping playing both hands, and then doing so with the focus on your other hand. After some practice (it can takes time), you will be able to hear the two parts independently, and you will feel more freedom in your listening and playing.
Your first example,
In your first example, all the sangban/dundun hits (right hand) are also played by the bell (left hand), so it is not necessary to mentally think the two independently. You can just consider the sangban/dundun hits as stress on some of the bell line., and the bell as a clave.
Answer: I think the term you're looking for is composite rhythm.
It is the single rhythm that results when you combine, or overlap, two separate rhythm which are performed at the same time.
In this example...

...there are two rhythms, one in the treble clef and the second in the bass clef. The third clef, the bottom one, shows the composite rhythm.
Note that while the treble and bass clefs are actually performed the bottom composite clef is not actually played. The composite clef only shows that when the two rhythms are combined it is almost entirely stead eighth notes except for the two sixteenth notes at the end of the passage.


How to find weight by maximizing the rank ordering performance

Question: How to find the weight such that the final value (weighted sum) n range 0-1 represented as probability, as weight1 * var1 + $weight2 * var 2.... that would maximize the rank ordering performance? (AUC or any other performance measure, a new reference).
The logistic regression does not provide the desired solution.
The data I'm dealing with look like this: (with var1...varX is a variable converted to probability measure) so I would like to aggregate the individual measurement of risk across different tools to single risk measure including some confidence interval. The exit variable is target binary response variable that indicate the risk materializing.

How to approach it or which tool to use to achieve this? I'm using r statistical software so suggesting a r package would be also helpful.
Comment: I'm unclear what you are looking for. What does "rank ordering performance" mean? If you had three weights in your example, how would you calculate the "rank ordering performance"?
Comment: I have added reference regarding the "rank order performance" which is a measure I know of, if there is other measure its fine as long as I have the "best aggregated probability" that explains the 0/1 response variable in max optimal way.
Comment: Hm. You added a link to a Google search (in itself not a good idea, since (a) everybody gets different search results, and (b) search results change over time) for "Accuracy and ROC curve", which is something different from "rank ordering performance". I don't think people will dig through their personal search results to try to figure out what you mean. Please make it easy for us to help you, by providing full details and using references only as backup.
Comment: @Stephan: reference updated.  Question also remains what would be the best method to evaluated the performance. One can look into the calibration like here: https://stats.stackexchange.com/questions/493023/brier-score-of-calibrated-probs-is-worse-than-non-calibrated-probs
Comment: Also this method by @whuber would be adequate to me: https://stats.stackexchange.com/questions/25482/visualizing-the-calibration-of-predicted-probability-of-a-model/25489#25489
Comment: Ah. We started out with "rank ordering performance", you added a search for AUC and accuracy, and now we are at "AUC or any other performance measure", with a link to the Brier score. All these are quite different, some more closely related than others. Can you decide which performance measure you want?
Comment: It does not matter which of these is used, I have tried to communicate an example on which to benchmark the performance.  But if this is the only outstanding question then AUC would be the preferred statistic.
Comment: Very good, thank you, we are getting somewhere. Next question: I assume you want your weights to sum to 1?
Comment: @Stephan. Thank you for holding up with me on this. Yes, I would expect the weights to sum to 1 (but I'm not sure if I claim this with absolute certainty, but I would say so).
Answer: You have a straightforward optimization problem. The Optimization CRAN Task View is a very helpful resource.
First off, your objective function takes (in your example) three weight parameters. These are matrix-vector multiplied with your variables. The result is a vector of class membership probabilities. We compare these to the actuals (exit) and calculate the AUC. This can be done using auc() in the pROC package. This entire function needs to be fed into the optimization algorithm.
Next, your optimization is nonlinear (since the AUC does not depend linearly on the weights). You also have constraints: your weights must be nonnegative and less than one. These are box or bound constraints in the Task View. However, we also have the constraint that they must sum to one. This is not a box/bound constraint any more, but a linear constraint, so any tool on the Task View that only discusses box/bound constraints is not helpful.
I settled on the Rsolnp package, not because I have any experience with it, but because it was the first one to look helpful. It looks like it performs minimization (though it apparently nowhere says so explicitly).
Read your dataset (next time, best to provide the data as an MWE, ideally as the output of dput()):
dataset <- data.frame(
    var_prob1 = c(.95,.12,.34,.61,.17,.26,.78),
    var_prob2 = c(.28,.18,.33,.77,.70,.48,.05),
    var_prob3 = c(.77,.74,.47,.67,.14,.38,.43),
    exit = c(0,0,1,0,1,0,0))

Define the objective function - since we want to maximize the AUC and Rsolnp minimizes, we minimize negative AUC:
library(pROC)
objective <- function(parameters) {
    -as.numeric(auc(response=dataset$exit,
        predictor=(as.matrix(dataset)[,1:3]%*%parameters)[,1]))
}

Finally, call the solver:
library(Rsolnp)
n_parameters <- ncol(dataset)-1
result <- gosolnp(
    fun=objective,
    eqfun=function(parameters)sum(parameters),
    eqB=1,
    LB=rep(0,n_parameters),
    UB=rep(1,n_parameters))

Comment: OK, I'm sorry I couldn't be more helpful. You could take a look at the optimization task view and see whether something else addresses your problem. Unfortunately, R is not really strong at optimization.
Comment: many thanks for this. For the with the example above, its not converging, there is endless iteration which I have to force to stop. I'm just running the code you have provided.
Comment: Strange. How long did you let it run? It does take a little while, but it terminates correctly for me. (It takes a while because it tries the underlying solver with multiple random starting values, a good practice). Which R and package versions are you running (`sessionInfo()`)? I have R 4.2.1, `Rsolnp` 1.16 and `pROC` 1.18.0.
Comment: compiler_4.1.3 tools_4.1.3, with packageVersion("Rsolnp")
[1] '1.16'
Comment: packageVersion("pROC")
[1] '1.18.0'
Comment: The main difference seems to be that I have R 4.2.1, you have R 4.1.3. I don't know whether this is important, but you could try upgrading.
Comment: (+1) thanks, I see, unfortunately I have to stick with the current R version because of other dependencies etc. I have to find another way to solve this. many thanks for your proposed solution. I hope perhaps someone else will be able to contribute with some "simpler - less depended" solution.


Remove several specific characters in a for loop for dataframe

Question: I need to remove several specific characters in a column of dataframe, and I have tried code as this, but it does not remove any value, please help to check for the code.
for(i in Merged$root_name){
  i= gsub("[[:punct:]]$","",i)
  i= gsub(" ASA$","",i,ignore.case = T)
  i= gsub(" AS$","",i,ignore.case = T)
  i= gsub(" AB$","",i,ignore.case = T)
  i= gsub(" plc$","",i,ignore.case = T)
  i= gsub(" ltd$","", i,ignore.case = T)
  i= gsub(" corp$","",i,ignore.case = T)
  i= gsub(" limited$","",i,ignore.case = T)
}

Comment: Can we see a reproducible sample of your df `Merged`?
Comment: Do you mean `Merged$root_name <- gsub("(?:[[:space:]]*(?:\\b(?:A(?:SA?|B)|plc|ltd|corp|limited)\\b|[[:punct:]]))+$" , "", Merged$root_name, ignore.case = TRUE)`, see [the regex demo](https://regex101.com/r/B4rH1D/2).
Comment: Probably, the regex above is better used with `perl=TRUE` in `gsub`.
Comment: Sample for the root_name column as below:`Asia Offshore Drilling Limited|
Transeuro Energy Corp.|
Awilco LNG ASA|
London Mining Plc|
Nordic Financials|
Hofseth BioCare|
Petromena ASA|
Seajacks International Ltd|
North Energy|
IDEX ASA`
Comment: So, you just want `Merged$root_name <- gsub("(?:[[:space:]]+(?:A(?:SA?|B)|plc|ltd|corp|limited)|[[:punct:]]+)$", "", Merged$root_name, ignore.case = TRUE)`? Check [**this regex demo**](https://regex101.com/r/B4rH1D/3)
Comment: Does `i` exist outside the loop?
Answer: You can combine all the patterns together
Merged$changed_root_name <- gsub("[[:punct:]]$|ASA$|AS$|AB$|plc$","",Merged$root_name, ignore.case = TRUE)

Comment: That is not the same what OP has, what if those values come in immediate succession at the end of the string?
Comment: @WiktorStribiżew Do you mean string like `"ASASA"` would leave empty string as per OP's attempt and would leave `"AS"` in my code?
Comment: No, `ASASA` must be kept as is, I think.
Comment: I guess the pattern should be `"[[:punct:]]$|\\sASA$|\\sAS$|\\sAB$|\\splc$"`, i.e., including a space