Need help using javascript with HTMLplayer

Question: I want to create an html5 player that will play multiple audio files sequentially. I found the code below which works perfectly in playing the files when the page opens, but I want to be able to control the audio with a player and controls. Can anyone help me with this?

var sounds = new Array(new Audio("https://www.w3schools.com/html/horse.mp3"), new Audio("https://www.w3schools.com/html/horse.mp3"), new Audio("https://www.w3schools.com/html/horse.mp3"));
var i = -1;
playSnd();

function playSnd() {
  i++;
  if (i == sounds.length) return;
  sounds[i].addEventListener('ended', playSnd);
  sounds[i].play();
}
<!DOCTYPE html>

Answer: You can do it by placing audio element with controls attribute inside the body element if I understood what you're trying to do.  Good luck!
Answer: Although it works, creating arrays with the new keyword is not recommended -- instead use the literal array:
let arr =new Array()
let arr = []
Using new Audio() creates an Object but not the HTMLMediaElement rendered in the DOM. In order to get the default controls we need to either write the markup in HTML or dynamically create an audio tag and append it to the DOM using JavaScript.
HTML
Note the controls attribute is needed to actually have the tag visible.
<audio src="http://example.com/path/to/file.mp3" controls></audio>

JavaScript
Here's the minimal script to dynamically add the same audio tag as above.
const audioTag = document.createElement('audio');
audioTag.controls = true;
audioTag.src = "http://example.com/path/to/file.mp3";
document.body.appendChild(audioTag);

The following demo has a playlist that can be controlled manually and loops automatically. Details commented in the demo.

// Reference <audio>
const player = document.querySelector('audio');
// Reference

const skip = document.querySelector('.skip');
/*
Object
- base property is a string of host
- path property is an array of strings of each path
*/
const list = {
  base: 'http://soundbible.com/mp3/',
  path: ['chinese-gong-daniel_simon.mp3', 'Dial%20Up%20Modem-SoundBible.com-909377495.mp3', 'Fake%20Applause-SoundBible.com-1541144825.mp3']
};
// Number of paths
const size = list.path.length;
// Reference <output>
const item = document.querySelector('.item');
// Declare counter
let counter = 0;
// Declare loop flag.
let loop = false;
/*
Function pass list object
Ternary that resets count when min and max are exceeded
Change the value of <output> to count+1
Change <audio> src to new url interpolated from list .base and .path properties
load() and play() audio
*/
const playlist = list => {
  let count = counter >= size ? size - 1 : counter < 0 ? 0 : counter;
  item.value = count + 1;
  player.src = `${list.base}${list.path[count]}`;
  player.load();
  if (count >= size || count < 0) {
    player.pause();
  } else {
    player.play();
  }
  return false;
}

// Reister the ended event on <audio
player.onended = function(e) {
  counter++;
  playlist(list);
  if (!loop) {
    if (counter >= size || counter < 0) {
      counter = size - 1;
      e.target.pause();
    }
  }
  return false;
}

/*
Register
 to click event
Delegate the click event to the e.target
e.target always points to the clicked element.
*/
skip.onclick = function(e) {
  const target = e.target;
  if (target.matches('.prev')) {
    counter--;
  } else if (target.matches('.next')) {
    counter++;
  } else {
    return false;
  }
  playlist(list);
}
button,
output {
  font: inherit;
  display: inline-block;
  font-size: 1.2rem;
  cursor: pointer;
}

.loop.cont::before {
  content: '\1f501'
}

.loop.once::before {
  content: '\1f502'
}
<!DOCTYPE html>

    <audio src='http://soundbible.com/mp3/chinese-gong-daniel_simon.mp3' controls></audio>

      <button class='prev'>⏪</button>
      <button class='next'>⏩</button>
      <output class='item'>1</output>

Comment: How do I stop it from looping? In other words,, how do I stop the playeronce the final file in the playlist has ended?
Comment: Thanks. This is working fine now. One final question - is there a way to have the audio files play consecutively in the player without the player reloading for each individual file? In other words, the multiple audio files would play like one longer file in the player
Comment: Only if you make one big file of all the mp3s  which is possible by using [Audacity freeware](https://www.audacityteam.org/) Don't forget to check the checkmark of this post to accept it.✅
Answer: try this code with jquery1.7 (suppose you have jq in js folder), here complete page code
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>AudioPlayer-playlist</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

song 01

song 02

song 03

song 04

song 05

song 06

song 07

song 08

song 09

song 10

<audio id="audio" controls type="audio/mpeg">
Sorry, your browser does not support HTML5 audio</audio>

Comment: Thanks for the response. I think you are misunderstanding my problem though. I would like the music files to play automatically and consecutively within the player, without requiring manual selection. For further clarification, when the page opens the visitor will click on the player and the playlist will then start. When item one ends item two in the playlist will commence automatically. If also do not need a visible playlist...
Comment: JBA You can put autoplay on your audio tag and display: none in your style. Autoplay it's not allowed by Chrome. I think You Can resolve with an iframe that loads your audio. Styling of course iframe display none . Believe me, autoplay it's not a good netiquette thing. The user must listen music when he wants and not when the webmaster wants
Answer: Solved! I used an iframe that load a page with the playlist in autoplay mode. Normally in Chrome this is not enough, autoplay
doesn'twork. I used embed tag (that allow autoplay) with an empty mp3 called sil.mp3, to trig the audio on the browser; in this
way the page loaded with iframe can autoplay. Here the code of the page with the iframe
<!DOCTYPE html>

<meta charset="UTF-8">
<title>The Invisible Playlist Example page</title>

<body

This page is playing a Playlist even if you can't see
      nothing:

      there is an iframe that loads audio

        <embed src="audio/sil.mp3" autoplay></embed>

Here the code of the page loaded with the iframe (mylist.html)
<!DOCTYPE html>

<meta charset="UTF-8">
<title>The Invisible Playlist Example</title>

This page is playing a Playlist even if you can't see
 nothing:

  audio = display:none; and has autoplay, not allowed in Chrome,
   Opera

     <audio controls autoplay></audio>

and at last the script (mylist.js) included in the page
(function () {

// Playlist array
var files = [
    "audio/song1.mp3",
    "audio/song2.mp3",
    "audio/song3.mp3"
];

// Current index of the files array
var current = 0;

// Get the audio element
var playlistPlayer = document.querySelector("#playlist audio");

// function that will be call at the end of the previous
function next() {
    // Check for last media in the playlist
    if (current === files.length - 1) {
        current = 0;
    } else {
        current++;
    }

    // Change the audio element source
    playlistPlayer.src = files[current];
}

// Check if the player is in the DOM
if (playlistPlayer === null) {
    throw "Playlist Player does not exists ...";
} else {
    // Start the player
    playlistPlayer.src = files[current];

    // Listen for the playback ended event, to play the next media
    playlistPlayer.addEventListener('ended', next, false)
}

})();

an example here http://giocaroli.xoom.it/pub/test/pag_loadin_playlist.html


centos , linux , apache permission issue

Question: I have a php file which executes a shell script

$ip_access = $_GET['ip_access'];
// run knock app
exec("/home/knock.sh ".$ip_access);

however when I access it I receive the following error in the logs "sh: /home/knock.sh: Permission denied"
 I created a new user and added it in the apache httpd.conf file but is still not working . Any advice how to set the permissions or how can I grant more access to the user to make it work would be highly appreciated .
Comment: Who does httpd run as (ps auxww|grep http) and what are the permissions on /home and /home/knock.sh (ls -lad /home ; ls -lad /home/knock.sh) ?
Answer: If you are running the script as the appropriate user, you may need to add the execute permission +x to the file. You can do it using:
chmod +x /home/knock.sh

As an alternative, you can use the following command (no need to add execute permission):
exec("bash /home/knock.sh ".$ip_access);

Answer: Check what mode you're running SELinux in.
getenforce

If you're running in Enforcing mode, you can troubleshoot SELinux problems by disabling SELinux temporarily:
setenforce 0

If the script runs, re-enable SELinux with setenforce 1 and start looking for where the problem is with your configuration versus the system's SELinux security policy.
If you're running in Enforcing mode, which is the default, you'll need to change the context of that file, because Apache can only execute files with the httpd_script_exec_t label by default. You'll want to run:
semanage fcontext -a -t httpd_script_exec_t /home/knock.sh
fixfiles restore /home/knock.sh

Afterwards, verify the script's SELinux context:
ls -lZ /home/knock.sh

If you're running in Enforcing mode and this still doesn't work, check your audit logs at /var/log/audit/audit.log.


Forced unwrap of a return type?

Question: I'm starting to get my head around optionals and forced unwrapping, except for in one particular context: when it is a return type to a function.
What is the difference between:
func myFunction() -> NSData { ... }

func myFunction() -> NSData! { ... }

func myFunction() -> NSData? { ... }

Furthermore, when I use a return value of NSData!, I am forced to use ? which seems odd.
func myFunction() -> NSData! { ... }
let data = myFunction()
data?.write()

Why do I need the ? if I force unwrapped the return?
Comment: In practice **never** use implicit unwrapped optional values as return types in functions / methods. Either the value can be `nil` then use `?` or the value will never be `nil` then use a `non-optional`.
Comment: For `NSData`, there is nothing different between those two lines of code. You can find a good explanation from Rob in the link sent by @rmaddy.
Comment: Possibly a duplicate of https://stackoverflow.com/questions/24061039/how-is-a-return-value-of-anyobject-different-from-anyobject
Comment: The answer linked by @rmaddy doesn't explain why Swift uses type `NSData?` for the `data` variable in the question.
Answer:
func myFunction() -> NSData { ... }

The above means that myFunction returns an instance of NSData.

func myFunction() -> NSData? { ... }

The above means that myFunction returns a value of type Optional<NSData> (also called NSData?). Optional is an enum with two cases: .some(value) and .none (also called nil). So the function returns either an NSData (wrapped in the .some case), or nil.

func myFunction() -> NSData! { ... }

The above means that myFunction returns a value of type Optional<NSData>, just like the NSData? return type in the previous example.
However, the use of ! means that, if you use the value of myFunction() in a way that doesn't type-check, the compiler will try unwrapping the returned value for you. So if you say this:
let maybeLength = myFunction()?.length

then the compiler will see that you are treating the return value of myFunction as an Optional<NSData>. But if you say this:
let dataLength = myFunction().length

then the compiler will see that Optional<NSData> doesn't have a length member, so it will pretend you wrote this:
let dataLength = myFunction()!.length

and if that compiles, it will carry on.
This behavior was defined in Swift Evolution proposal SE-0054, Abolish ImplicitlyUnwrappedOptional type.

Now let's finally consider this:

func myFunction() -> NSData! { ... }
let data = myFunction()
data?.write()

What is the type of data? The compiler has to infer the type of data based on the expression on the right side of the =. As I explained in the example above, the type of myFunction() is Optional<NSData>. So the type of data is Optional<NSData>, also called NSData?.
The compiler doesn't run into any trouble making data's type NSData?, so it has no reason to implicitly unwrap the return value of myFunction.
Comment: Awesome!  Thanks!
Comment: Could I conclude that a forced unwrapped return value is dangerous because it may cause an app crash when `nil` is returned?
Comment: It's dangerous to force-unwrap an Optional that might be nil. If you know the function won't return nil (based on what you're passing it), it's safe to force unwrap the value it returns.

Forced unwrap of a return type?


Given a bounded set $E$, there is a $G_\delta$ set such that the outer measures are equal

Question:
Question: Show that for any bounded set $E \in \mathbb{R}$, there is a $G_\delta$ set $G$ for which $E \subseteq G$ and $m^*(E)=m^*(G)$.

Let $\{I_n\}$ be a countable collection of open intervals such that $E \subset \bigcup\limits_{n=1}^{\infty} I_n$.  Observe the following: $$m^*(E) \leq m^*(\bigcup\limits_{n=1}^{\infty} I_n) \leq \sum\limits_{n=1}^\infty l(I_n) < m^*(E)+\frac{1}{2^n}.$$
Now let $G=\bigcap\bigcup I_n$.  $G$ is a $G_\delta$ set.  From this, we see that $E \subset G$.  Thus for each $n \in \mathbb{N}$: $$m^*(E) \leq m^*(G) \leq m^*(\bigcup\limits_{n=1}^{\infty} I_n) \leq \sum\limits_{n=1}^\infty l(I_n) < m^*(E)+\frac{1}{2^n}.$$
So we take $n \rightarrow \infty$.
Is my proof correct?
Comment: You should denote $I_{n,j}$ the collection of intervals which covers $E$ and approach up to $2^{-n}$ the outer measure of $E$ (which is finite). Here you take $n$ as an index, but we see $n$ outside the sum, and we don't know what it is. But you saw the idea and you just have to take now $G:=\bigcap_{j\geq 1}\bigcup_{n\geq 1}I_{n,j}$.
Answer: For each integer $n\geq 1$, let $\{I_{n,j}\}$ be a countable collection of open intervals which covers $E$ such that $$\sum_{j=1}^{+\infty}m^*(I_{n,j})\leqslant m^*(E)+n^{-1}.$$
Such a collection exists because the outer measure of $E$ is finite, as $E$ is a bounded subset of $\Bbb R$.
Let $G:=\bigcap_{n\geqslant 1}\bigcup_{j\geq 1}I_{n,j}$. As $\bigcup_{j\geqslant 1}I_{n,j}$ is open for each $n$, $G$ is a countable intersection of open sets, and it contains $E$. For $n\geqslant 1$, the following inequalities hold
$$m^*(G)\leqslant m^*\left(\bigcup_{j=1}^{+\infty}I_{n,j}\right) \leqslant\sum_{j=1}^{+\infty}m^*\left(I_{n,j}\right) \leqslant m^*(E)+n^{-1},$$
which concludes the proof.
Comment: Is the assumption that E is bounded necessary? Royden's definition of outer measure uses inf, so even if the set is not bounded, can't we still find "such a collection"?
Comment: @hl0202 I was thinking the same thing...
Comment: How do you approximate to an unbounded set from the outside?
Comment: Since this is outer measure and not Lebesgue measure, don't we have to assume countable subadditivity instead of additivity which means that $m^*(\cup_j I_{n,j}) \leq \sum_j m^*(I_{n,j}$?
Comment: @CarlGanz You are right. I have corrected.


Oscar Peterson I've got it bad and that ain't good bar 10: Dm7 flat 5 flat 11?

Question: This chord is played over a bass player on a d, it's coming right after a dm7.
From the bottom up
F# Ab C F Ab
Is that F# a flat 11? Is the Ab a flat 5 or a sharp 11?
Or is this a passing chord that is actually a d7 sharp 9 flat 5?
This is in Oscar Peterson's I've got it bad and that ain't good, last chord of bar 10. (The slower version..)
Comment: 1. What recording? 2. What is the question?
Comment: Hi Dan - welcome. Can you please read our [about] and [ask] page then edit your question to include things like a link to the recording, and to focus more on the way to describe or spell a chord than identifying a specific chord (as that would be off topic) thank you
Answer: First off, the chord is a D chord so the F# is the 3rd, not a b11. The term b11 is very rare, it's more theoretical than practical.
At face value the logical name for the chord you spelled out would be D7#9#11 (spelled with G#'s for the #11). It could also be called a D7b5#9 but b5 MIGHT imply playing the Ab lower in the voicing, closer to the root/bass note.
However I'm hearing just F#-C-E#, a regular D7#9. It's function is a dominant of the next chord. The chord is extremely brief, only a swing 8th note in duration but he does proceed to resolve the entire voicing down a semitone to a G13, F-B-E (the G played by the bass) and then go back and forth between the two voicings over the G in the bass.
This question might be closed but I hope it isn't because it is less about identifying and more about how to properly spell out a chord.
Comment: +1 for the answer, and if I could, another for your last para. (Although spelling out a specific chord would contravene the rules.) However, maybe there's an opportunity to ask without using a specific example, with a little editing.
Comment: There's the upside that a closed question with an upvoted answer will in fact hang around, if not specifically voted for deletion - https://meta.stackexchange.com/questions/10582/what-is-a-closed-or-duplicate-question It still might be better to try shape up the question to better conform, if anyone feels up to the task.


LEFT JOIN com mais de uma condição no ON - SQL Server

Question: Oi, Gente, tudo bem?
Estou montando uma query, e preciso fazer um join.
No caso, os registros da tabela AIV têm uma data de início e pode ou não ter uma data fim.
Eu quero que elas se cruzem da seguinte forma:
1 - Se a data fim da tabela AIV estiver nula, a data da tabela CPC deve ser maior que a data início da AIV;
2 - Se a data fim tabela AIV não estiver nula, a data da tabela CPC deve estar entre a data início e data fim da AIV;
Acontece que quando eu tento escrever dessa forma:
LEFT JOIN ApontamentoImpactoVigencia AIV ON
                                    AIV.AssuntoId = AA.AssuntoId
                                    AND
                                    IIF(AIV.Fim_Data IS NOT NULL, (CPC.Data between AIV.Inicio_Data and AIV.Fim_Data), CPC.Data >= AIV.Inicio_Data)

Ele apresenta erro, não aceitando o "between" e nem o sinal de >=
Se eu tento fazer destas maneiras:
LEFT JOIN ApontamentoImpactoVigencia AIV ON
                                AIV.AssuntoId = AA.AssuntoId
                                AND
                                CPC.Data >= AIV.Inicio_Data

E
LEFT JOIN ApontamentoImpactoVigencia AIV ON
                                AIV.AssuntoId = AA.AssuntoId
                                AND
                                CPC.Data between AIV.Inicio_Data and AIV.Fim_Data

O SQL Server aceita (mas daí não atende ao critério que preciso).
Portanto, o erro não está no "between" nem no sinal de ">=".....
Ou seja, tem algo a ver com o IIF.
(Com CASE WHEN acontece a mesma coisa)
Alguém tem alguma ideia de como resolver isso ???
Desde já agradeço!
Answer: Boa noite,
Acho que da forma como você colocou não vai funcionar pois o IIF espera um valor para quando a condição é verdadeira e outro para quando não é, e não uma outra condição. E o mesmo vale para o Case.
Segue uma sugestão para teste utilizando a função Coalesce para alterar o valor final do between se a data final for nula:
LEFT JOIN ApontamentoImpactoVigencia AIV ON
    AIV.AssuntoId = AA.AssuntoId
    AND
    CPC.Data between AIV.Inicio_Data and coalesce(AIV.Fim_Data, CPC.Data)

Edit: alternativa tradicional
LEFT JOIN ApontamentoImpactoVigencia AIV ON
    AIV.AssuntoId = AA.AssuntoId
    AND
    (
      CPC.Data >= AIV.Inicio_Data and
      (
         CPC.Data <= AIV.Fim_Data or
         AIV.Fim_Data is null
      )
    )

Espero que ajude
Comment: Vou tentar, obrigada
Comment: Vc conseguiu fazer o teste? Funcionou? Estou editando a resposta para acrescentar uma alternativa talvez mais tradicional
Comment: consegui sim, deu certo!


How to add x-max-length and x-overflow to MassTransit queue while configuring connection?

Question: I have a consumer, who needs to consume messages from an existing RabbitMQ queue. It works fine, when the queue is configured normally, without any settings.
services.AddMassTransit(config =>
{
    config.AddConsumer<OrderConsumer>();
    config.UsingRabbitMq((ctx, cfg) =>
    {
        cfg.Host("amqp://user:12345@localhost:54425");
        cfg.ReceiveEndpoint("transient-order-queue", c =>
        {
            c.ConfigureConsumer<OrderConsumer>(ctx);
        });
    });
});
services.AddMassTransitHostedService();

In order to get some work done, I need to configure the queue with a couple of features.
Features
x-max-length:   1000
x-overflow: reject-publish
arguments:
x-queue-type:   classic
durable:    true

How could I configure my consumer to connect to that queue? It gives me errors like that:

PRECONDITION_FAILED - inequivalent arg 'x-max-length' for queue 'transient-order-queue' in vhost '/': received none but current is the value '1000' of type 'long'

But I don't understand, how to add these args to the MassTransit configuration. Please, help me out!
Answer: Simply add them as queue attributes:
cfg.ReceiveEndpoint("transient-order-queue", c =>
        {
            c.QueueAttributes["x-max-length"] = 1000;
            c.QueueAttributes["x-overflow"] = "reject-publish";
            c.ConfigureConsumer<OrderConsumer>(ctx);
        });

Answer: Found the answer. You can add attributes to the queue with the following syntax:
cfg.ReceiveEndpoint("transient-order-queue", c =>
{
    c.ConfigureConsumer<OrderConsumer>(ctx);
    c.SetQueueArgument("x-overflow", "reject-publish");
    c.SetQueueArgument("x-max-length", 1000);
});

Answer: I'm use this solution
realize interface of IConfigureReceiveEndpoint
public class ConfigureReceiveEndpointQueueSize : IConfigureReceiveEndpoint
{
    public void Configure(string name, IReceiveEndpointConfigurator configurator)
    {
        if (configurator is IRabbitMqReceiveEndpointConfigurator rabbitMqConfigurator)
        {
            rabbitMqConfigurator.SetQueueArgument("x-max-length", 10000);
            rabbitMqConfigurator.SetQueueArgument("x-overflow", "drop-head");
        }
    }
}

and then add it to DI in STartup
services.AddTransient<IConfigureReceiveEndpoint, ConfigureReceiveEndpointQueueSize>();

this queue attributes would be add in every Consumer Message Queue


Can't cast Data from NSKeyedUnarchiver to Object

Question: I archive object to data and save it to disk success by NSKeyedArchiver, but when I get data from NSKeyedUnarchiver, I can't cast it to type Object. I try to do it in many ways, but none of them success. I hope you can help me to solve this problem.. here is my code:
class Person:
class Person: NSObject, NSCoding {
    func encode(with coder: NSCoder) {
        coder.encode(firstName, forKey: "fisrtName")
        coder.encode(lastName, forKey: "lastName")
        coder.encode(age, forKey: "age")
    }

    required convenience init?(coder: NSCoder) {
        guard let firstName = coder.decodeObject(forKey: "firstName") as? String,
            let lastName = coder.decodeObject(forKey: "lastName") as? String else {
                return nil
        }

        let age = coder.decodeInteger(forKey: "age")
        self.init(firstname: firstName, lastName: lastName, age: age)
    }

    let firstName: String
    let lastName: String
    let age: Int

    init(firstname: String, lastName: String, age: Int) {
        self.firstName = firstname
        self.lastName = lastName
        self.age = age
    }
}

Save data to disk:
let tuan = Person(firstname: "Tuan", lastName: "Hoang", age: 21)

            let directoryPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            let path = directoryPath.first!.appendingPathComponent("PersonData")
            let savePath = path.appendingPathComponent("data.plist")
            do {
                try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true, attributes: nil)

                let data = try! NSKeyedArchiver.archivedData(withRootObject: tuan, requiringSecureCoding: false)

                do {
                    try data.write(to: savePath)
                    print("Save data success")
                } catch {
                    print("Cant save data to path + \(error.localizedDescription)")
                }

            } catch {
                print("Cant not create directory + \(error.localizedDescription)")
            }

Load data:
    do {
                let savedData = try Data.init(contentsOf: savePath)
                print("Get data success")

                guard let data = try? NSKeyedUnarchiver.unarchivedObject(ofClass: Person.self, from: savedData) else {
                    print("Cant cast data")
                    return
                }
                print(data?.firstName)

            } catch {
                print("Cant get saved data ")
            }

Comment: Don't `try?`, catch the error.
Comment: you  need to catch the error and see where the problem is
Comment: @vadian it said that: The data couldn't be read because it isn't in the correct format when I try to unarchiverObject..
Comment: `requiringSecureCoding: false` This is not an answer to your question, but that's wrong. You should adopt NSSecureCoding.
Comment: thanks @matt. I realize that class Person must be extend to NSSecureCoding. And i have a typo..
Answer: your error is here:
    coder.encode(firstName, forKey: "fisrtName")

typo -> firstName
Comment: The *second* is not an error, it's [correct](https://developer.apple.com/documentation/foundation/nscoder/1409246-decodeinteger).
Comment: `decodeObject(forKey: "age") as! Int` crashes but not `decodeInteger(forKey: "age")`. I'm using it in several projects
Comment: try it yourself in code -> if you dont cast, it crashes
Comment: you are right, sorry, i had changed it in my code ...sorry.


Nagios not accepting regex in command

Question: I have this command defined:
define command{
command_name check_http_sane
command_line $USER1$/check_http -H $HOSTNAME$ -r "HTTP/1.1 (200|301|302|303|304|307|401|418|426)"
}

When I run it manually on command line, it works fine, but nagios (2.6) reports a "pattern not found" error. Do I need to escape something?

Edit: As stated below, I solved it by replacing check_http with my own script which works (good enough for our use case, anyway). Script: http://pastebin.com/hNmz6Wa1
Answer: The source code for check_http.c says the -r option checks the headers and the page contents. The problem you are seeing is probably the Nagios command macro interpreter trying to replace something in your regex string.
You should try escaping all of your (,| and ) characters. If that doesn't work, try just the parentheses and just the pipes. You might also try using single quotes instead of double quotes.
Answer: Since escaping didn't work either (and it does work without on command line, whyever) and I didn't want to spend more time debugging it, I wrote my own Nagios plugin to replace check_http, which works like a charm:
https://github.com/tao-software/nagios-plugin-http-tao
Comment: Publish and be damned !
Comment: Publish!
Comment: Moved the plugin to a git repo.
Answer: Your assertion that this "works fine" on the command line is questionable. When I run it manually, it does not "work fine":
./check_http -H localhost -r "HTTP/1.1 (200|301|302|303|304|307|401|418|426)"
HTTP CRITICAL: HTTP/1.1 302 Found - pattern not found - 650 bytes in 0.001 second response time |time=0.001410s;;;0.000000 size=650B;;;0
As Jeff Strunk suggests, you need to escape the parentheses (so the shell does not consume them), like this:
./check_http -H localhost -r "HTTP/1.1 \(200|301|302|303|304|307|401|418|426\)"
HTTP OK: HTTP/1.1 302 Found - 650 bytes in 0.001 second response time |time=0.001425s;;;0.000000 size=650B;;;0

Nagios not accepting regex in command


Operator norm of symmetric Matrix in Hilbert Space with Hermitian Inner Product

Question: Assume we have a positive definite real matrix $P$ and we define an inner product on a finite dimensional Hilbert space
$\langle x, y \rangle = x^\top P y\,$
and clearly the induced norm is $\| x\| = \sqrt{\langle x , x \rangle}$. Is there a way to compute the induced operator norm of a real linear symmetric operator represented by the matrix $A = A^\top$, i.e. $\| A\|$?
I know that for the special case when $P$ is the identity matrix we get that $\|A\|$ is the maximum singular value of $A$ but I couldn't figure out if there is something similar for general matrices $P \succ 0$.
Thanks very much for every hint.
Answer: In general, it will still be the maximum singular value of some matrix, although this matrix is a more complicated one: let $P=U_PSU_P^T, A=U_A\Sigma{U_A}^T$ be the SVD of $P$ and $A$ respectively. Then, substituting it into the scalar product, we can find the norm of A by definition:
$$
||A||=\sup_{||x||=1,||y||=1}(x, Ay)=\sup_{||x||=1,||y||=1} x^TPAy=\sup_{||x||=1,||y||=1}(U_Px)^TS\underbrace{U_PU_A^T}_R\Sigma(V_Ay)^T=\sup_{||x||=1,||y||=1}x^TSR\Sigma y=||SR\Sigma||_2,
$$
where $||.||_2$ is the usual maximum singular value operator norm.
However, is you are so lucky that the singular vectors of $P$ and $A$ coincide, then $R=U_AU_A^T=I$ and $||A||=||S\Sigma||_2 = \max_i\sigma_i(P)\sigma_i(A)$, i.e. the maximum product of corresponding singular values.
That being said, I suspect that it may be a bit late for the author by now...


How do I approximate instruments when arranging an orchestral piece for brass ensemble

Question: I am going to arrange Wagner's Prelude and Liebestod for British brass band. I am not sure if it will be a good fit, but it is worth a try.
The instrumentation that I am writing for is standard:
http://en.wikipedia.org/wiki/Brass_band#British-style

1 Soprano Cornet in E♭
8-10 Cornets in B♭ (in separate parts for 'Solo', 'Repiano', 2nd and 3rd cornets; there are 4/5 players on the 'Solo' part, one 'Repiano', two 2nd, and two 3rd)
1 Flugelhorn in B♭ (notated on the same part as the 'Repiano' in some older music)
3 Horns in E♭ (called Solo, 1st and 2nd)
2 Baritone Horns in B♭ (Each with separate parts)
2 Tenor Trombones (notated in B♭, playing separate parts)
1 Bass Trombone (the only brass instrument in the band notated in Concert Pitch (C) on Bass Clef)
2 Euphoniums in B♭ (Usually playing the same part with divisi sections)
4 Tubas (2 in E♭ and 2 in B♭, both notated in Treble Clef; often called Basses)
2 or 3 percussion players (with 2 or more timpani, glockenspiel, snare drum, triangle, cymbals, a drum kit and more)

I need to adapt parts from these orchestral instruments to fit the brass instrumentation.

Flute
Oboe
Clarinet
English Horn
Bassoon
Bass Clarinet
Harp? Probably not
Horn
Trumpet
Trombone
Tuba
Violin 1
Violin 2
Viola
Cello
Bass
Tympani
Isolde

Some parts are the same, and some correspond to obvious parts. Some are not obvious.
There might be some overlap between brass parts for strings. Cornets should represent most of the high passages, including flutes, violins, and Isolde.
What would be a reasonable way to represent Oboe, Clarinet, English Horn, Bassoon, Bass Clarinet, Viola, and Cello?
I thought of using flugelhorn, or mutes for cornets, but I don't know all of the options.
Comment: Is this your first arrangement for brass band? If it is, I'd suggest leaving it on your to-do list for the moment and do some smaller, less ambitious pieces first.
Comment: Interesting question! It would be helpful if you included a summary of the brass band instrumentation, as external links are not always reliable, long-term.
Comment: I would suggest to replace "Isolde" by "voice (soprano)". You need a distinguished tone color for that to stand out from the others, possibly the sopraon cornet warned against in other answers?
Answer: Great question! I just happen to have the Prelude on my desk at the moment - you've got a really interesting project on your hands there, but quite a lot of work - good luck!
Hopefully I can add to jjmusicnotes really useful advice with some ideas that will make this a far simpler project for you.
Firstly, from your question, it seems like you are "half-way" to understanding the basic approach your project will need. You acknowledge, for instance, that "Cornets should represent most of the high passages…"  Yes, this is likely to be the role taken by cornets in your arrangement and is a good approach. But, you also say, "Some parts are the same, and some correspond to obvious parts." This is not a useful approach; you would not simply copy trombone music from the Wagner into the trombone parts of your arrangement. Also, the question itself asks how to "approximate instruments" when arranging. This, again, is not always a useful approach; although a brass band is a beautiful ensemble, capable of a wide range of interesting timbres and techniques, it is never going to match the range of a full orchestra of winds, strings, brass and percussion. So, you should not simply be thinking about what will most sound like a cor anglais, for instance. Rather than trying to make your brass band version sound as similar as possible to the orchestral version (which will be very difficult), you should aim to use a range of contrasting instrumental colours available within the brass band instrumentation, just as Wagner uses a range of instrumental colours within the orchestra.
So what is the right approach?
Well, to understand how to go about your project, let me give you an example of a much simpler method of arranging; this will give you an insight into the different method your project requires.
If you wanted to arrange an SATB choral piece for string quartet, you have a very simple project. You could simply give the Soprano line to Violin I, Alto line to Violin II, Tenor line to the Viola and Bass line to the 'Cello. Okay, you have to remove the lyrics, check the ranges work okay and maybe change some phrasing, but essentially this is a one-to-one mapping of parts. It is like translating a single word from one language to another.
You cannot take this one-to-one mapping approach when arranging your brass band version of the Wagner. This is more like trying to translate a whole book; you need to understand the fundamental meaning of the text (or music in your case!) before creating the new version. Rather than simply giving music from one instrument of the orchestral music to one instrument of the brass band, you need to assess: what role this instrument plays in the original, what role groups of instruments play in the original and crucially what role different musical material has in the original (for instance, is it melodic, harmonic, part of the bass line, part of a countermelody etc.) You then assign this music from the original to instruments that are suitable for such a role in the brass band.
To complete this project successfully, you are not really arranging, you are re-orchestrating.
And yes, this is quite a lot of work. But there are two ways you can do this; one is a lot easier than the other.
Re-orchestrating the hard way.
Assess the role of all musical material in the original score. Assess which instruments (or groups of instruments) will effectively be able to perform each piece of musical material in your brass band version. This may change through your arrangement; musical material associated with particular instruments in the original may not always be associated with one instrument or group of instruments in your version. Instead, at any one time, you need to be thinking about which instrument or group of instruments are best able to play musical material within the overall musical texture.
A somewhat simpler approach.
Use a piano reduction of the original orchestral score (or four-hands piano, or piano and voice etc.) Well, this is essentially the same approach as above, but now the initial process of condensing the musical material of the orchestral score has already been done for you, meaning you can get on with the process of orchestrating straight away.
In reality, you will need to take an approach somewhere between the two. I would work from a piano reduction, but constantly refer to the orchestral score, to check that I am reflecting changes of timbre and techniques in the original orchestral version in the new version. But again, this needs to be approached with common sense; you are attempting to preserve interesting changes of timbre, texture, technique, tone and tessitura in the original when writing your brass band version. But you are not simply mimicking or copying the original. You can't give pizzicato instructions to your brass players, but how would you create a similar contrast of tone in your ensemble? No instrument in your ensemble may be able to easily play the flute part at the same pitch, it is more important that different pieces of musical material appear in the correct register relative to other music in your arrangement.
I could go on, but as jjmusicnotes pointed out, orchestration and arranging are an art; there are plenty of rules and useful approaches that can be learnt, but effective orchestration requires study, thought and practice.
Answer: Unfortunately, the answer to your question is one that you can only ultimately provide. Orchestration is an art form unto itself, and your choices are personal and unique to your sense of nuance and knowledge of the music.
For example, a particular melody or line given to a cornet will sound differently if given to the flugelhorn instead; though the same line works on both instruments.  It depends contextually in the music - what you feel is important to emphasize or leave out.
Orchestration is much more than attempting to mimic other instruments or effects.  Your overall goal is to preserve the integrity and character of the music, even though it is scored for a different ensemble.
There are dozens to ways to capture each of the instruments you listed, but not all of them are appropriate for the music.  Sometimes it is easier to find out what you don't want.
Answer: Even though almost every brass player living hates mutes (including me), use them extensively.  They are invaluable for managing timbre changes.  Just remember it takes a few beats to get the mute in and remove it.If you want an oboe-ish tone, a cornet in harmon (stem-in) or a metal straight gives a reasonable substitute.  (Holst used this trick with a straight in one of the Suites for Military Band.)  For bassoon, a tenor trombone in metal straight gets nasally.  For english horn, think cup mute.
For harp parts, consider mallet percussion (or piano, if available).
There will be a strong temptation to have the soprano playing much of the time. Resist temptation.  A brass band does not have the range of pitches available that a full orchestra does.  That's a limitation you accepted when you decided to transcribe for brass band.  Chord voicing can help, and if you can count on an ensemble with impeccable intonation, sum and difference tones at soft dynamics can create apparent pitches you can't reasonably ask for.
This sort of project can be done and turn out well -- Elsa's Procession to the Cathedral works as a brass band or brass choir piece.  But it requires careful consideration of the score and the available forces.
Consider providing alternate Baritone, Euphonium, Tenor Trombone and Tuba parts in concert-pitch bass clef.  North Americans will appreciate the consideration.
Good luck!
Answer: Nice to hear of someone arranging for Brass Band. As a young teenager (50 years ago), brass bands introduced me to classical music. These days I play recorder in an early music consort, but that's another story.
My thoughts are:

Violin 1, 2 and viola map roughly to solo, 2nd & 3rd cornet (and possibly tenor horn). This is necessary as they are the main body of treble sound in the brass band.
Soprano cornet and Flugel are excellent "color" instruments that should be used sparingly. Flugel will often pick up oboe solos, and soprano is good for the fiddly picollo, flute and clarinet parts.
Others have mentioned the use of mutes - there are straight mutes, bell mutes, top hats and others. Using these judiciously will provide a lot of the color otherwise missing in a brass ensemble.
Don't forget the Euphonium - it is a great instrument with a soaring sound that can well take on cello solo parts. In addition, it is incredibly agile - try googling Grandfathers Clock on YouTube, and listen to the last variation in particular.

I'd recommend listening to anything by Eric Ball to start to appreciate the truly magnificent sound that can be coaxed from a brass band. Journey into Freedom is arguably his best work.
Best of luck - this us a really worthwhile project.


Be sure C# code executes before shutdown

Question: I am developing an app that need to save the time when computer shutdown, I need to be sure that always computer shutdown/restart, this code executes.
I'm writing it at Form Closing event like this:
    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        if(e.CloseReason == CloseReason.WindowsShutDown)
        {
            Properties.Settings.Default.lastShutdown = DateTime.Now;
            Properties.Settings.Default.Save();
        }
    }

Usually the code is working and it's saving the DateTime in settings, but I think sometimes the app is closed before the saving is done and lost the data. I don´t know how much time has the app before closing when shutdown.
¿Is there any way I can be sure that code always finish before shutdown?
Thanks.
Comment: _"I think sometimes the app can be close before the saving is done and lost the data"_ -- that is always a possibility. The odds increase if your code is inefficient or otherwise slow, because Windows may terminate it. But the user can always kill your program outright, or the power could go out, or whatever. You need to be able to recover from those kinds of situations gracefully.
Comment: Also the provided code has lot's of cases were it never will be run. So if somebody just closes your form because he want's to you don't save a time. Why bother and wait for form_closing at all if you can just catch the windows message internally?
Comment: Aside from the already mentioned fact that nothing allows your code to know when a power failure is about to happen, the windows event system already *tries its best* to record shutdown and startup events. Why are you duplicating that functionality rather than just querying the event log?
Comment: I think it's duplicated
https://stackoverflow.com/questions/4617538/is-there-a-way-in-c-sharp-to-detect-a-windows-shutdown-logoff-and-cancel-that-ac
Comment: @Damien_The_Unbeliever That's a good idea, I'm going to try to query Windows event log instead of saving it. Do you know an example of how to read it? Thanks.
Comment: Possible duplicate of [Is there a way in c# to detect a Windows shutdown/logoff and cancel that action (after asking the user)](https://stackoverflow.com/questions/4617538/is-there-a-way-in-c-sharp-to-detect-a-windows-shutdown-logoff-and-cancel-that-ac)
Answer: You can attach a handler to the SystemEvents.SessionEnded event and run your code there. You can even cancel the shutdown / logoff event using the Cancel property.
The same code could be run on the FormClosing event but with CloseReason == CloseReason.UserClosing || CloseReason == CloseReason.ApplicationExitCall || CloseReason == CloseReason.TaskManagerClosing to cover all scenarios.
Answer: You could periodically save the last time you are alive for each session. e.g. Create a timer on the form. This way even if you lose power immediately you know the last time you were alive.
private void Form1_Load(object sender, EventArgs e)
{
    /* Set the last shutdown to the last time we were alive.. */
    Properties.Settings.Default.LastShutdown = Properties.Settings.Default.LastHeartbeat;

    this.timer1.Interval = 100;
    this.timer1.Tick += timer1_Tick;
    this.timer1.Start();

}

private void timer1_Tick(object sender, EventArgs e)
{
    Properties.Settings.Default.LastHeartbeat = DateTime.UtcNow;
    Properties.Settings.Default.Save();
}

Answer: I think it would be better if u save the variable periodically, instead of saving on 'shout down time'. This way if something goes wrong, u lose at most 1 interval.
Answer: Just save the whole time the time with a timer an when the computer is shutdown and starts again, u call the last entry in the config.
`Timer time = new Timer(1);
time.Elapsed += timer_elapsed();
private static void timer_elapsed(Object source, System.Timers.ElapsedEventArgs e) { YOUR CODE HERE}`


What is the probability that all three girls sit together at a circular table if seating is random?

Question: Mum, Dad and their six children (3 boys and 3 girls) are to be seated at a circle table at random.

What is the probability that all 3 girls sit together?
What is the probability that mum and dad sit opposite each other?

I did 3 girls=1
2 (adults) + 3 (boys) + 1 (the girls) $= 6! = 720$
The girls are arranged in $3! = 6$ ways
Right now I have a hard time continuing, since I'm not sure if I am going in the right direction.
Comment: For inspiration you could look at https://math.stackexchange.com/questions/1423575/permutation-around-round-table?rq=1
Comment: To compute the probability, you need to divide the number of favorable arrangements by the total number of arrangements.  What is the total number of arrangements?  What do you get for the number of favorable arrangements?
Comment: The total number of arrangement is 720 and the favourable is 5040. Would it be 720/5040?
Answer: Unless otherwise specified, in a circular arrangement, only the relative order matters.

Mum, Dad, and their six children ($3$ boys and $3$ girls) are to be seated at a circular table at random.  What is the probability that all $3$ girls sit together?

Seat the mother first.  Relative to her, the others can be seated in $7!$ ways as we proceed clockwise around the table.
For the favorable cases, we again seat the mother first.  If the three girls sit together, we have five objects to arrange as we proceed clockwise around the table relative to the mother: the father, the three boys, and the block of three girls.  The objects can be arranged in $5!$ ways.  The three girls can be arranged within the block in $3!$ ways.  Hence, the number of seating arrangements in which the three girls sit together is $5!3!$.
Thus, the probability that all three girls will sit together if the seats are randomly assigned is
$$\Pr(\text{all three girls sit together}) = \frac{5!3!}{7!}$$
Why was your solution incorrect?
As @gandalf61 pointed out in the comments, your answer
$$\frac{6!}{7!} = \frac{720}{5040} = \frac{5!3!}{7!}$$
is correct.  However, your reasoning was incorrect.
You made two errors:

You divided by $7! = 5040$ total arrangements, which suggests that you took relative order into account in the denominator.  However, you obtained $6!$ arrangements of six objects in your numerator, which suggests that you did not take relative order into account in the numerator.  If you take relative order into account in the denominator, you must take it into account in the numerator to be consistent.
You also did not take into account the $3!$ ways the three girls can be arranged within the block.

Mum, Dad, and their six children ($3$ boys and $3$ girls) are to be seated at a circular table at random.  What is the probability that Mum and Did sit opposite each other?

The denominator is the same as above.
For the favorable cases, seat the mother first.  There is only one way to seat the father opposite the mother.  Now seat the six children in the six remaining seats as you proceed clockwise around the table relative to the mother.

 $$\Pr(\text{Mum and Dad sit opposite each other}) = \frac{6!}{7!}$$
Comment: Since $5!3! = 6!$ the questioner's result for part (1) is numerically correct, even though their reasoning is wrong.


Order of elements and center of a subgroup of $GL_2(\mathbb{F}_7)$

Question: I'm stuck on the following question:
It is given that
        \begin{equation*}
   G = \left\{\begin{pmatrix}\bar{a}&\bar{b}\\ \bar{0}&\bar{c}\end{pmatrix}\text{ with $\bar{a}$ and $\bar{c}$ in $\mathbb{F}_7^*$ and $\bar{b}\in\mathbb{F}_7$}\right\}
  \end{equation*}
        is a subgroup of $GL_2(\mathbb{F}_7)$.

Determine which elements of $G$ have order 2.
Compute the center $Z(G)$ of $G$

For part one I found that $$\begin{pmatrix}\bar{a}&\bar{b}\\ \bar{0}&\bar{c}\end{pmatrix}^2 = \begin{pmatrix}\overline{a^2}&\overline{b(a+c)}\\ \bar{0}&\overline{c^2}\end{pmatrix}$$
so we must have $\bar{a}=\bar{c}=\bar{1}$ and $\bar{b}=\bar{0}$. But that's just the identity, so is there no element of order 2 or am I missing something?
For the second part I'm not really sure where to start.
Comment: What about $a=-1$ etc etc
Comment: Yes, of course. Then $a=\pm 1, c=\mp 1, b\in\mathbb{R}$  is a solution class and also $a=-1, c=-1, b-0$. Thank you! I can't believe I missed that
Answer: To calculate $Z(G)$, we can use
$$
Z(G)=\bigcap_{g\in G} C_G(g)
\leqslant \bigcap_{g\in G} C_{GL(2,7)}(g)
\leqslant C_{GL(2,7)}(g_1)\cap C_{GL(2,7)}(g_2)\cap C_{GL(2,7)}(g_3)
$$
where
$$
g_1=\pmatrix{1 & 0\\0 &-1},\
g_2=\pmatrix{-1 & 0\\0 &1},\
g_3=\pmatrix{1 & 1\\0 &1}.
$$
To simplify the calculation even further, note that any matrix commuting with these will commute with
$$
4(g_1 +I)=\pmatrix{1 & 0\\0 & 0}=e_{11},\
4(g_2 +I)=\pmatrix{0 & 0\\0 & 1}=e_{22},\
g_3 - I=\pmatrix{0 & 1\\0 & 0}=e_{12}.
$$
It's immediate to see that the matrices commuting with these three are just the scalars, so that
$$Z(G)\leqslant \{ cI\mid c\in\mathbb{F}_{7}^{*}\};$$
and of course the reverse implication is even more clear.


What is the correct test for differences of proportions with this design?

Question: I have a series of questions with binary choices, which are coded as 1 and 0. I created a percentage by adding up the "1" responses and dividing by the total number of questions. For example, for one respondent, if they gave a "1" response for 6 out of 10 questions, their rate would be 60%.
The design of the study is so that there are two different groups of respondents. One group got series A questions, and the other group got series B questions. Then, I calculated the mean percentage for each group. Series A is the control, while series B is the treatment. What is the correct statistical test to see whether there is a significant difference between these mean percentages?
Comment: You could make a contingency table of your data and then use a chisquare test.
Answer: I disagree with the suggestion on contingency tables and chi-square testing as it won't help you test the difference between means.  You've used your 10 questions to create a rating scale, and with that scale, means do apply.
People do differ as to how finely grained a variable must be before one can legitimately test means.  You'll see many disagreements over variables measured on a 1-5 scale.  But with a 0-10 scale, very few would object to the use of a means test.
You used the "proportions" tag.  It's true that proportions are involved to the extent that each person gives a "1" response to some proportion of the 10 questions. But once you go beyond the 0's and 1's and deal with the scale scores (what you call "ratings"), you are interested in the comparing the mean for the entire group, A vs. B.  You no longer need think about proportions at that point, just the mean of each set of scores. So a test of the difference between means (z-test or t-test for independent samples) is what you're after.
To illustrate why "proportion" no longer applies, suppose one group's scores are {.6, .3, .6, .6, .4}.  You could transform all such scores to {6, 3, 6, 6, 4} or even {60, 30, 60, 60, 40} without affecting a t-test's results.


Prove that, for vector fields, $[X,Y]=0$ implies $[X,[Y,Z]]=0$ for all $Z$

Question: I want to prove this claim : If $[X,Y]=0$, then for any tangent field $Z$, $[X,[Y,Z]]=0$
I try to do this by using local coordinate.
$$
X=\sum_{n=1}^{m}a_i\frac{\partial}{\partial x_i}\space\space\space,
Y=\sum_{n=1}^{m}b_i\frac{\partial}{\partial x_i}\space\space\space,
Z=\sum_{n=1}^{m}c_i\frac{\partial}{\partial x_i}\space\space\space$$
Then,
$$
[X,[Y,Z]]=\sum_{t=1}^{m}(\sum_{s,k=1}^{m}
a_s\frac{\partial b_k}{\partial x_s}\frac{\partial c_t}{\partial x_k}+
a_s b_k\frac{\partial^2 c_t}{\partial x_s\partial x_k}-
a_s\frac{\partial b_t}{\partial x_k}\frac{\partial c_k}{\partial x_s}-
a_s\frac{\partial^2 b_t}{\partial x_s\partial x_k}c_k-
\frac{\partial a_t}{\partial x_s}b_k\frac{\partial c_s}{\partial x_k}+
\frac{\partial a_t}{\partial x_s}\frac{\partial b_s}{\partial x_k}c_k)\frac{\partial}{\partial x_t}
$$
However, I couldn't make any progress.
Comment: Jacobi identity states that $[X,[Y,Z]] = [Y,[X,Z]]$ in case $[X,Y] = 0$. In your coordinates system, Swcharz lemma says $\partial_{s,k}=\partial_{k,s}$. That can be useful
Comment: Take $X=\partial/\partial x$ and $Y=\partial/\partial y$ on $\mathbb{R}^2$. If the claim is true then for any $Z=Z^1 \partial_x +Z^2 \partial_y$ we have $Z^1_{yx} = Z^2_{yx} = 0$, which is not true.
Answer: The result isn't true without additional conditions. For example in $\mathbb{R^3}$, take $X=\frac{\partial}{\partial x}, Y=\frac{\partial}{\partial y}, Z = xy\frac{\partial}{\partial z}$. Then $[X,Y] = 0$, but $[X,[Y,Z]] = [X,x\frac{\partial}{\partial z}] = \frac{\partial}{\partial z}\ne 0$.


Programmatically populate file field using Entity API

Question: I need to programmatically generate nodes using some data that I extract from different import files.
For the node creation I use Entity API.
I've written a simple function to which I pass the node data in a structured array and the function imports each field depending on how it's defined:
  function my_module_create_function($item, $node_type, $language) {
    $node = entity_create('node', array ('type' => $node_type));
    $entity = entity_metadata_wrapper('node',  $node);
    $entity->language = 'es';//LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
    //strings
    foreach ($item as $key=> $field) {
      switch ($field['field_type']) {
        case 'multiple-reference':
          if(is_array($field['value'])){
            $entity->$key = $field['value'];
          }else{
            //some alert log
          }
          break;
        case 'file':
          if (file_exists($field['value']) && isset($field['filename']))
          {
            $file = file_get_contents($field['value']);
            $filename = $field['filename'];
            if(isset($field['folder']) && file_exists($field['folder'])){
              $folder = $field['folder'];
            }else{
              $folder = "public://";
            }
            $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
            $entity->$key= (array)$file;
          }
          else
          {
            // some alert log
          }
          break;
        case 'long-text':
          $entity->$key->set(array(
            'value' =>  $field['value'],
            //'summary' => '',
            'format' => 'full_html',
          ));
          break;
        case 'geolocation':
          $entity->$key->set(array(
            'latitude' => $field['value']['latitude'],
            'longitude' => $field['value']['longitude'],
            //other elements added here (province, postal_code, country [es, en,...],additional, ...)
          ));
          break;
        default:
          $entity->$key= $field['value'];
        break;
      }
    }
    $entity->status = 1; //(1 or 0): published or not
    $entity->promote = 0; //(1 or 0): promoted to front page
    $entity->comment = 0; // 0 = comments disabled, 1 = read only, 2 = read/write
    // Save the entity
    return $entity->save();
  }

This function works great except for the file field type. When I try to import a node with a file it gives me this error:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048
  Column 'my_field_display' cannot be null

the thing is that I have used the same structure:
        $file = file_get_contents("file_path");
        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        $entity->$key= (array)$file;

for image fields (or multiple image fields using "[] =" instead of " = ") it works without any problem. Anyone knows if I'm doing anything wrong with this file field?
Any advice would be helpful
Answer: Ok, I found the answer to this question here.
Instead of:
        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        $entity->$key= (array)$file;

It should be:
        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        if($file !== false)
        {
          $entity->$key->file->set($file);
        }

This 'if($file !== false)' is optional just to be sure that we're passing a file object.

*Note that the difference is that we're not passing the file object as an array and also we're passing it to a 'file' atribute instead of
  passing it directly to the field.


É possível ter uma lista como atributo de uma tabela em um banco relacional?

Question: Estou fazendo um projeto em Java utilizando SQLite como Banco de Dados relacional. Basicamente o projeto é um banco de senhas, onde um Usuário pode ter várias plataformas cadastradas e cada plataforma tendo seu respectivo Login.
Segue abaixo como está implementada a classe User:
public class User {

    private Integer id;
    private String name;
    private String email;
    private Login login;
    private List<Platform> platforms;

    (...)
}

A questão é como posso armazenar no banco a lista de plataformas cujo o usuário possui uma conta. Se isso é possível, ou se terei que recorrer a um banco não relacional, por exemplo.
Comment: Já pensou em utilizar uma tabela a parte e definir uma `foreign key`?
Comment: Pelo que me lembro, o SQLite é compatível com MySQL, esse último possui o tipo JSON que pode ser usado para armazenar objetos e listas. Porém no SQL é mais comum (e na maioria das vezes melhor) usar chaves estrangeiras para conectar diferentes tabelas
Comment: Respondendo a primeira pergunta: Sim, eu defini três tabelas — User, Platform e Login, onde eu referencio as duas últimas como chave estrangeira na tabela User. Talvez meu problema seja minha ignorância quanto a aplicação do conceito de cardinalidade em banco de dados.
Comment: Respondendo a segunda: Interessante! Valeu pela dica. Vou dar uma pesquisada sobre o tipo JSON no MySQL, e pelo que me parece, pode até resolver meu problema. A forma ideal como imaginei seria justamente armazenar como JSON, e pensei que só teria em banco de dados não relacionais.
Answer: Não é possível fazer isso de forma natural. O mais comum é que uma lista seja outra tabela fazendo a correta normalização e relacionamento entre elas (veja mais).
Em alguns casos a normalização pode não ser necessária (tem que analisar o contexto, pensar em todos os detalhes e necessidades) e aí pode ser interessante gravar tudo na tabela mesmo simulando uma lista em uma coluna normal, provavelmente varchar, mas tem que lidar na mão como fazer isto.
Isto é uma forma de fazer no relacional algo não relacional, não precisa usar um banco de dados errado para quase tudo o que precisa por causa de um pequeno detalhe, que é o que muita gente faz hoje em dia.
O SQLite não tem nada próprio porque o objetivo dele é ser simples e flexível, então pode fazer tudo nele, mas nem sempre está pronto, você deve etratar, por exemplo fazer isso como um JSON (um formato que talvez seja complicado demais para algo tão simples). Outros bancos mais sofisticados podem lidar com isso de forma natural e própria sem precisar sair do modelo relacional.
Pode complicar um pouco o fato de ter que gravar um tipo complexo (Platform) já que precisa lidar com isso também, e vale para vários outros bancos de dados, poucos possuem recursos para lidar bem com isso e praticamente ninguém usa quando tem (não sei porque, se é desconhecimento, se é porque veem problema nisso). Mas nos comentários diz que tem uma tabela desse tipo então talvez só precise por na lista um ids participantes, o que talvez permita ficar tudo do mesmo tamanho e o formato do array simulado em um varchar seja muito simplificado.
Aproveito para dizer que provavelmente aprendeu o termo usado de forma equivocada (a não ser que esteja falando do banco de dados, que ele até cabe, ainda que é mais comum as pessoas usarem coluna para isto, o que parece mais correto).
Comment: Opa, obrigado pela resposta e pelos links de conteúdo. Provavelmente eu usei os termos de forma errônea, pois o que quis dizer com "atributo" seria justamente a coluna, como você mencionou. Agradeço pela correção.
Comment: É coluna no DB (mas há uso de atributo), o problema é o uso na classe, o correto é campo, porque atributo é outra coisa (não é culpa sua quase todo mundo ensina errado). Agora você pode votar em tudo no sute também.


Commutative diagram with exact sequences as columns and rows

Question: Suppose that we have the following commutative diagram of groups and homomorphisms $$\newcommand\twoheaduparrow{\mathrel{\rotatebox{90}{$\twoheadrightarrow$}}}
\begin{array}
A  & A_3 & {\hookrightarrow} & A_2 &{\twoheadrightarrow} & A_1 & \  \\
  & \downarrow{} & &\downarrow{}& &\downarrow{}\\
 & B_3 & \stackrel{}{\hookrightarrow} &B_2 & \stackrel{}{\twoheadrightarrow} & B_1  &   & \\
  & \downarrow{} & &\downarrow{}& &\downarrow{}\\
 &C_3 &  &C_2 & \stackrel{}{\twoheadrightarrow} & C_1  &  &
\end{array}$$
where all columns and rows are short exact sequences except the $3$rd row, where the map $C_2\to C_1$ is onto. (Sorry but not sure how to draw vertical arrows to denote $1$-$1$ maps and onto maps.)
Question

Is there a induced map $f:C_3\to C_2$ making the $3$rd row also a
  short exact sequence? Or at least can we prove that $f:C_3\to C_2$ is
  one-to-one?

I tried the five lemma but it does not seem to work here.
Comment: The snake lemma will help here.
Comment: Thanks @Hanno! So the answer to my question should be "yes"?
Answer: Yes, there is such a map. This can be shown by diagram chase:

For $c \in C_3$ choose $b \in b_3$ s.t. $b=(B_3\to C_3)(b)$. Then $f(c) := (B_2 \to C_2)\circ (B_3 \to B_2)(b)$ is well-defined.
$f(c) \in \ker (C_2 \to C_1)$ follows from $(C_2 \to C_1)\circ (B_2 \to C_2) \circ (B_3 \to B_2) = (B_1 \to C_1)\circ (B_2 \to B_1) \circ (B_3 \to B_2)$ since the last composition is zero.
To show $\operatorname{im}(f) = \ker(C_2 \to C_1)$, let $c_2 \in \ker(C_2 \to C_1)$ and choose $b_2\in B_2$ with $c_2=(B_2 \to C_2)(b_2)$. Hence $(B_2 \to B_1)(b_2) \in \ker (B_1 \to C_1) = \operatorname{im}(A_1 \to B_1)$. Hence we find $a_2 \in A_2$ s.t. $(B_2 \to B_1)(b_2)=(A_1 \to B_1) \circ (A_2 \to A_1)(a_2) = (B_2 \to B_1) \circ (A_2 \to B_2)(a_2)$. Hence $b_2 - (A_2 \to B_2)(a_2) \in \ker(B_2 \to B_1)=\operatorname{im}(B_3 \to B_2)$. Choose $b_3 \in B_3$ with $(B_3\to B_2)(b_3)=b_2 - (A_2 \to B_2)(a_2)$ and set $c_3 := (B_3 \to C_3)(b_3)$. Then $f(c_3)=(B_2 \to C_2)(b_2)=c_2$.
The injectivity of $f$ can be shown in the same pattern as in 3. Hint: You have to use the injectivity of $A_1 \to B_1$ and of $B_3 \to B_2$.

Note that $f$ also makes the diagram commutative.
Comment: Why was my answer downvoted ? Please give a reason. Thanks.
Comment: Not sure who did it; your answer seems perfect to me.


Python ansible json output

Question: I got the json output. How do I do I fetch key which can store as variable
sample:
"plays": [
{
    "tasks": [
        {
          "hosts": {
            "sw01": {
              "_ansible_no_log": false,
              "action": "set_fact",
              "ansible_facts": {
                "OS": "ios"
              },
              "changed": false
            }
          }
    ]
}]

Fetch variable:
    FACTS = output['plays'][0]['tasks'][0]['hosts']

like to fetch: sw01 and store as hostname. Then fetch OS value.
Thanks for the help
Comment: You just need to find value by key in nested json?
Comment: A JSON object translates to a dictionary in Python. You can enumerate the keys of a dictionary with .keys(). "sw01" is the only key in the hosts dictionary.
Answer: Here's the complete version
import json

data = """{
        "plays": [
            {
                "tasks": [
                    {
                    "hosts": {
                                "sw01": {
                                "_ansible_no_log": false,
                                "action": "set_fact",
                                "ansible_facts": {
                                    "OS": "ios"
                                },
                                "changed": false
                                }
                    }
                    }]
            }]
        }"""

output = json.loads(data)

hosts = output['plays'][0]['tasks'][0]['hosts']
for host in hosts.keys():
    print(host)

Python ansible json output


Can Perl handle this OOP concept - Explained in Animal Terms

Question: Sorry for being very vague but I do not know the name of the concept.  I will try to explain.  I'll try to put it in terms of animals to make it easy.
I have a generic superclass.  This superclass contains functions that all animals have to do.  For example I do not want to redefine "take_breath" sub in every animal subclass, so I define it once inside the Animals superclass and all of the animals (Animals::Cat, Animals::Dog, and Animals::Llama) can simply access $self->take_breath().  The animals also go through many of the same initialization routines so as opposed to redefining them every time I simply call $class->SUPER::new(@_) as well as do things specific to that animal.
With this being said every time an animal is initialized it goes through it's superclasses' initialization routines.  There are hundreds of animals and these are run hundreds of times.  It's not too big of a problem.
These animals are smart however and know how to use the LWP::UserAgent web browser.  In order to access the internet they must log into a web page and set their session cookies.  They all share the same login and would like to share the same browser.  In my current implementation the login routines are part of the superclass's new method.  This means when an animal is initialized this runs and the animal logs in.  As I said I have hundreds of animals and do not want to fire off hundreds of POST requests.  I would like to somehow fire off the login routine once and make it part of the super class.  Each animal can then access the "shared" web browser by doing $self->{'ua'}.
I hope this explains it, I am not sure what this OOP term is called.
TLDR for those who don't like Animals
I have a login routine in the superclass that creates an LWP::UserAgent, logs in, and sets session cookies.  The subclasses can all share one login.  I do not want to have to fire off hundreds of POST requests to log in for each subclass.  I would like to somehow log in once and share the prepared $ua object wil all subclasses.
Comment: Did not noticed the question sign in this text ;) But yes, you can easily implement this.
Answer: There are two ways to approach this:
1. Package variables
Not each animal instance has an UA, but the UA is part of being an Animal. You can initialize the UA on startup. The animals can access the UA via an accessor, or a variable:
package Animal;

my $ua = LWP::UserAgent->new();

sub ua { $ua }

and then
my $ua = $self->ua();

or
package Animal;

our $ua = LWP::UserAgent->new();

and then
my $ua = $Animal::ua;

Technical terms for this are class variable, or in languages like Java static method or static variable.
Java translations:
class Animal {
  private static LWP.UserAgent ua = new LWP.UserAgent();
  public static LWP.UserAgent getUa() { return ua }
  ...
}

and
class Animal {
  public static LWP.UserAgent ua = new LWP.UserAgent();
  ...
}

2. state variables
In newer Perls (>= v5.10?) you can declare variables with state. They declare lexical variables. The variable is initialized once during the lifetime of the program, not every time the statement is executed (as it would be with my).
use feature 'state';
package Animal;
sub new {
  my ($class, %args) = @_;
  state $ua = LWP::UserAgent->new;
  bless { ua => $ua, %args } => $class;
}

and then
my $ua = $self->{ua};

It may be useful to use a do block to perform wider intialization
state $ua = do {
  my $ua = LWP::UserAgent->new;
  ...;
  $ua;
};

or to offload initialization into a sub: state $ua = make_ua();
If you have to target earlier perls, you can enclose the new sub inside a seperate scope, and declare the variable there as a lexical for similar effect:
package Animal;

{
  my $ua = LWP::UserAgent->new;
  sub new {
    my ($class, %args) = @_;
    bless { ua => $ua, %args } => $class;
  }
}

The only difference here is when the UA is initialized. (And, of course, the number of irritating braces.) The intialization can be deffered, as Len Jaffe mentioned:
package Animal;

{
  my $ua; # just declare scope here
  sub new {
    my ($class, %args) = @_;
    $ua ||= LWP::UserAgent->new;  # $ua is false until initialized
    bless { ua => $ua, %args } => $class;
  }
}

Because objects are references, all animals will get the same UA.
Especially in C/C++, this is also called a static variable. The state modifier could be seen as a non-OO singleton constructor.
Comment: There's also the Singleton pattern implementation in which the constructor calls LWP::UA->new() but 'caches' the reference in class variable: $ua ||= LWP::UA->new()
Comment: @LenJaffe Yes, one could go full OO and implement the actual singleton pattern. But, using `state` is the *perlish* way to go (I'd say).
Comment: Why would the class variable be undef after having been instantiated by the first constructor?
Comment: I read the orig version of your comment, where the `my` was still present
Comment: force of habit. sorry. quickly noted and corrected :-) Your answer is good.
Comment: This is a great answer - especially the comparison with Java.  But I think it could be improved and made more complete by expanding the examples.  Using globals like ```our $ua = LWP::UserAgent->new();``` and then initializing parent objects in a subclass with ```my $ua = $Animal::ua;``` is fairly straightforward. However, the example code from the first part of the response ("Package variables") where you suggest ```sub ua { $ua }``` and ```my $ua = $self->ua();``` isn't complete enough for a new or intermediate user of perl to test your examples. If you did that I'd up vote this answer :)


If you reject the null hypothesis at 0.025 level of significance, is it true to say that you may or may not reject it at a significance of 0.01?

Question: If we just use the normal distribution, we can find that $ \alpha = 0.025 $ covers more area at the tails than $ \alpha = 0.01 $. So it's clear that you may or may not reject at $ \alpha = 0.01 $. But I'm looking for an intuitive explanation here. My reasoning is:
The level of significance, $ \alpha $, is the probability of making a Type - 1 error. At $ \alpha = 0.025 $, you're given more probability of making this error, and so you're given some "leeway" in rejecting it.
If $ \alpha = 0.01 $, you should be more careful than the previous case. So if you reject at $ \alpha = 0.025 $, you may or may not reject at $ \alpha = 0.01 $.
But if you reject at $ \alpha = 0.01 $, you'll always reject at $ \alpha = 0.025 $.
Am I correct in my reasoning?
Comment: Short answer: yes.
Comment: @jbowman Although many readers will understand what you mean, please be aware that the short answer to the question asked in the title is no!
Comment: @whuber - so it is! WorldGov - you should adjust the title to match the content of the question, or vice versa (in the latter case, as whuber points out, my comment is wrong.)
Comment: I've edited the question; and thank you for confirming my answer.
Answer: As answered by @jbowman in the comments, the stated explanation is correct.
I'm adding an answer to close this question.


How to prove that $7^{15} + 7^{16} + 7^{17} - 1$ is divisible by $10$?

Question: This was a question on my math exam. We weren't able to use calculators so proving by manually calculating the exact value would take too long.
In the end I ignored this question to save time but I'm still curious.
Comment: Do you have any thoughts at all on this question? Did you learn any techniques during your course?
Hint: $7^2 =49$ which equals $-1$ (mod 10)
Comment: Well, can you get the last digit of $7^{16}$ manually, to begin with?
Answer: Try modular arithmetic:
$$7^2=49\equiv-1\mod 10,$$
so $$7^{15}+7^{16}+7^{17}-1\equiv (-1)^{7}7+(-1)^{8}+(-1)^{8}7-1\equiv -7+1+7-1\equiv0\mod 10$$
and $7^{15}+7^{16}+7^{17}-1$ is divisible by $10$.
Answer: You can first make some observations:
$$ 7^1 \equiv 7 \mod 10$$
$$ 7^2 \equiv -1 \mod 10$$
$$ 7^3 \equiv 3 \mod 10$$
$$ 7^4 \equiv 1 \mod 10$$
$$ 7^5 \equiv 7 \mod 10$$
$$ 7^6 \equiv -1 \mod 10$$
$$ 7^7 \equiv 3 \mod 10$$
$$ 7^8 \equiv 1 \mod 10$$
You can conclude (or prove by induction) that
$$ 7^{4k+1} \equiv 7 \mod 10$$
$$ 7^{4k+2} \equiv -1 \mod 10$$
$$ 7^{4k+3} \equiv 3 \mod 10$$
$$ 7^{4k+4} \equiv 1 \mod 10$$
So
$$ 7^{15} + 7^{16}+ 7^{17} - 1\equiv 3 + 1 + 7 - 1 \equiv 0 \mod 10.$$
Comment: Ok, I see how could I have done that. I didn't think of this earlier for some reason. Silly me.
Answer: $$7^{15}+7^{16}+7^{17}=7^{15}(1+7+7^2)\equiv7^{15}\cdot7\pmod{50}$$
Now $7^2=49\equiv-1\pmod{50}$
$\implies7^{16}=(7^2)^8\equiv(-1)^8\pmod{50}$
Answer: $$7^{15}+7^{16}+7^{17}-1=57\times 7^{15}-1$$
$7^2\equiv -1\pmod {10}$ so we have $7^{14}\equiv (-1)^7\equiv -1\pmod {10}$ and therefore $7^{15}\equiv -7$ and
$$57\times 7^{15}\equiv (-3)\times (-7)\equiv 21\equiv 1\pmod {10}$$
Answer: 7^15(1+7+7^2)-1
=7^15(57)-1
(10-3)^15*(3(19))-1
(10*k - 3^15) *3 *19 -1
(10*K-3^16)*19-1
19*3^16-1 must be divisible by 10 if this is true
3^0=1
3^1=3
3^2=9
3^3=27
last digit of 3^4=1
               ^5=3
9
7...
repeats
-3^16 will have last digit of 1
19*-xxxxx1*-1
(10+9)*(-xxxxx1)-1
=-10*xxxx1 + 9*xxxxx1-1
=10*K  -xxxxxxx9 -1
=10*k-xxxxxxxx0
so 10 divides


Virtual Host Routing doesn't work in some conditions

Question: I have a apache2 conf file which should proxy to a internal host. For some reason it works in all situations exception for one. I have a default website setup which acts as a default site. This default site has a dedicated SSL certificate. When the routing goes wrong, I get a security error because the routing to the correct host is incorrect and it falls back to the default host.
This is the configuration I have setup for a virtual host.
<VirtualHost www.example.co.uk:80>
    ServerName www.example.co.uk
    Redirect permanent / https://example.co.uk/
</VirtualHost>

<VirtualHost example.co.uk:80>
    ServerName example.co.uk
    Redirect permanent / https://example.co.uk/
</VirtualHost>

<VirtualHost www.example.co.uk:443>
    ServerName www.example.co.uk
    Redirect permanent / https://example.co.uk/
</VirtualHost>

<VirtualHost example.co.uk:443>
    ServerName example.co.uk
    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateFile /etc/letsencrypt/live/example.co.uk/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.co.uk/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/example.co.uk/fullchain.pem
    SSLCACertificateFile /etc/letsencrypt/live/example.co.uk/cert.pem
    ProxyPreserveHost On
    ProxyPass / http://192.168.122.122:8080/
    ProxyPassReverse / http://192.168.122.122:8080/
</VirtualHost>

The routes that work:
http://example.co.uk
http://www.example.co.uk
https://example.co.uk
The route that doesn't work:
https://www.example.co.uk
As far as I can see all the routes are correct and should direct as they should. I have also tried the variation of the :443 virtual hosts to not include the "http". Any advice would be appreciated.
EDIT
As per advice, I have modified the www.example.co.uk:443 host to include the same as the SSL using:
<VirtualHost www.example.co.uk:443>
    ServerName www.example.co.uk
    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateFile /etc/letsencrypt/live/example.co.uk/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.co.uk/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/example.co.uk/fullchain.pem
    SSLCACertificateFile /etc/letsencrypt/live/example.co.uk/cert.pem
    ProxyPreserveHost On
    ProxyPass / http://192.168.122.122:8080/
    ProxyPassReverse / http://192.168.122.122:8080/
</VirtualHost>

Still no luck
Comment: (FTR) neardupe http://serverfault.com/questions/367818/redirecting-ssl-without-raising-an-alert and crosssite http://stackoverflow.com/questions/27673013/redirecting-https-www-to-https-non-www-without-seeing-certificate-error-
Comment: Thank you for those links they were very useful. Sadly I cannot upvote you but it explains why exactly I was experiencing this problem.
Answer: Looks like your www.example.co.uk:443 virtualhost doesn't enable SSL, nor load your certificate, key and chain of trust.
Comment: Ok, I thought the redirect would have sufficed as to enable the SSL, I'll give that a go thanks
Comment: I've tried as you have suggested but had no luck. I've amended my question with an edit
Comment: How are you testing/what is it your client shows?! Is there anything relevant in apache logs?
Comment: I've ended up finding the answer as a result of your answer. It seems the redirect does not work as expected. Enabling the SSL explicitly on the www.example.co.uk then led to a different type of SSL error which I didn't catch in my first response. The SSL error was that the certificate was not valid for the "www" version of the site only the "example.co.uk" version of the site.
Comment: Right! A classic .... You may be able to set a different certificate in there, although some clients (non-SNI capable) would always end up on the "first" certificate loaded (from your configuration point of view).
Comment: I've learned something today!  I'm not too worried about non SNI clients luckily but with the certificate being letsencrypt I was able to reissue the certificate quite easily with both domains on there without much hassle


MHD Energy Equation derivation

Question: I'm trying to go through a derivation for the energy equation in MHD in terms of partial derivatives, but I've hit a bit of a wall.
I start with the equation
$$\frac{d}{dt}\left(\frac{p}{\rho^{\gamma}}\right) = 0$$
and need to end up with it in the following format
$$\frac{\partial p}{\partial t}+\mathbf{v} \cdot \nabla p-c_{s}^{2}\left(\frac{\partial \rho}{\partial t}+\mathbf{v} \cdot \nabla \rho\right)=0$$
where,
$$c_{s}^{2}=\frac{\gamma p_{0}}{\rho_{0}}=\frac{\gamma k_{B} T_{0}}{m}$$
by using the material time derivative
$$\frac{d}{d t} \equiv \frac{\partial}{\partial t}+\mathbf{v} \cdot \nabla$$
I really am not too sure how to get from the first equation to the second. Would appreciate some help
Comment: If $p = p(x_{1},x_{2},\dots,t)$ then by the chain rule $$\frac{d}{dt} p = p_{t} + p_{x_{1}} (x_{1})_{t} + \dots$$ where subscripts in $t$ denote partial derivatives, then note that $(x_{i})_{t}$ represents the velocities. Now apply the product rule to the quotient $p/\rho^{\gamma}$.
Answer: Let's start with the adiabatic energy equation,
$$\frac{\text{D}}{\text{D}t}\left(\frac{p}{\rho^\gamma}\right) = 0,$$
where $\text{D}/\text{D}t$ is the material derivative. The eulerian form of the previous equation is
$$\frac{\partial}{\partial t}\left(\frac{p}{\rho^\gamma}\right) + \mathbf{v}\cdot\nabla\left(\frac{p}{\rho^\gamma}\right) = 0.$$
The change rule provides
$$\frac{1}{\rho^\gamma}\left(\frac{\partial p}{\partial t} + \mathbf{v}\cdot\nabla p\right) + p\left(\frac{\partial}{\partial t}\left(\frac{1}{\rho^\gamma}\right) + \mathbf{v}\cdot\nabla\left(\frac{1}{\rho^\gamma}\right)\right) = 0,$$
and multiplying by $\rho^\gamma$,
$$\frac{\partial p}{\partial t} + \mathbf{v}\cdot\nabla p + p\left(\rho^\gamma\frac{\partial}{\partial t}\left(\frac{1}{\rho^\gamma}\right) + \mathbf{v}\cdot\rho^\gamma\nabla\left(\frac{1}{\rho^\gamma}\right)\right) = 0.$$
Both time derivative and gradient can be written as
$$\rho^\gamma\frac{\partial}{\partial t}\left(\frac{1}{\rho^\gamma}\right) = -\frac{\gamma}{\rho}\frac{\partial\rho}{\partial t},$$
$$\rho^\gamma\nabla\left(\frac{1}{\rho^\gamma}\right) = -\frac{\gamma}{\rho}\nabla\rho.$$
Finally, plugging them into the last equation,
$$\frac{\partial p}{\partial t} + \mathbf{v}\cdot\nabla p - c_s^2\left(\frac{\partial\rho}{\partial t} + \mathbf{v}\cdot\nabla\rho\right) = 0.$$
where $c_s^2 = \gamma p/\rho$. In addition, taking the continuity equation, i.e.
$$\frac{\partial\rho}{\partial t} + \nabla\cdot\left(\rho\mathbf{v}\right) = 0,$$
or
$$\frac{\partial\rho}{\partial t} + \mathbf{v}\cdot\nabla\rho = - \rho\nabla\cdot\mathbf{v},$$
the MHD energy equation is given by
$$\frac{\partial p}{\partial t} + \mathbf{v}\cdot\nabla p + \rho c_s^2\nabla\cdot\mathbf{v} = 0,$$
or in conservative form,
$$\frac{\partial \rho  p}{\partial t} + \nabla\cdot (\rho\mathbf{v}p) = -(\rho c_s)^2\nabla\cdot\mathbf{v}.$$

MHD Energy Equation derivation


What's the best way to notate a timed arpeggio with specific cutoff

Question:
This is a short excerpt (the upper hand part) from a piano piece I'm working on. I'd like this arpeggiated chord to end exactly when the trill start and to be played with the same hand. What is the best way to mark this for the performer?
Comment: Related answer: [How to notate specific-note harp glissando?](https://music.stackexchange.com/a/116243/70803).
Answer: The second option is close, but the ties should not be open-ended, which means to let the notes continue to ring indefinitely. Instead:

A notation convention allows consecutive notes joined by a beam to be tied over to a chord, even though this does not show accurate durations for every note. (Elaine Gould, Behind Bars, p. 133)

Gould explicitly advises against the nineteenth-century practice of double-stemmed notes and also the use of multiple ties for each note.
Obsolete double-stemming

(Image Source: Gould p. 133)
Repeated tied notes
Answer: A phrase mark (a bow) over everything would make most players think to continue the arpeggio straight into the trill.
Comment: A keyboardist would assume it meant to play legato, not to retain each note. A pedal mark would also be incorrect, because of the change in timbre.
Comment: @Aaron - not if it's part of a chord. Guitar music is quite often written 'incorrectly', but we realise what's meant, and play it like it should have been written. Very often. And I'd probably pedal it anyway. Why wouldn't you if it all makes a chord?
Comment: On piano/keyboard, broken (arpeggiated) chords in which the notes are held versus not held are two completely different things and are notated to express that difference. I've never seen a (published) keyboard score in any genre that was notated in the way you describe.


Integral $\int\frac{\sin2x}{1+x^2}\,dx$

Question: $$\int\dfrac{\sin\;2x}{1+x^2}\;dx$$
My approach:
First of all I can try expanding $\sin \;2x$.
Which gives us,
$$\int\frac{2 \sin(x) \cos(x)}{1+x^2}\;dx$$
Then I can assume something like(probably flawed):
Let $\sin(x)=u$, thus, $\cos(x)dx=du$. Then, the integral would become,
$$\int\dfrac{u\;}{1+(\sin^{-1}\;u)^2}\;du$$.

I am not able to think the forward step from here. Or probably I must use other methods of integration(not sure)....Is there any mistakes in my above approach? If yes, where? And if not, what would be the forward step?
Comment: As Minus One-Twelfth points out, there is no simple approach here. It is not a matter of "no one has thought of it before", but rather "we can prove that there is no simple approach".
Comment: Do you expect there to be a nice answer? Remember, not all integrals have one! This is what WolframAlpha gives for your integral (it is not expressed in terms of elementary functions): https://www.wolframalpha.com/input/?i=Integral+of+sin%282x%29%2F%281+%2B+x%5E2%29.
Comment: So basically, you shouldn't expect there to exist a simple answer to your integral.
Comment: @MinusOne-Twelfth that's overly complicated....
Comment: @MinusOne-Twelfth I expect a simple approach, complex answer is fine.
Answer: let $I(t)=\int_0^x \frac{sin(tx)}{1+x^2},
     I'(t)=\int_0^x \frac{cos(tx)t}{1+x^2},
     I''(t)=\int_0^x \frac{-sin(tx)t^2}{1+x^2}$
which yields the equation if, we use integration by parts
$-I(t)t^2+\int_0^x 2tI(t)\frac{dt}{dx}dx = I''(t) -(1)$
further differentiating w.r.t t gives us $I'''(t)=-t^2I'(t)$
which means $I'(t)=A1cos(λt^2)+A2sin(λt^2)$
and I'(t) doesn't have an elementary antiderivative.
Answer: $$\int \frac{ \sin(2 x)}{(1 + x^2)} dx = \frac {((e^4 - 1) \,\mathrm Ci(2 i - 2 x) + (e^4 - 1) \,\mathrm (2 x + 2 i) + i (1 + e^4) (\mathrm Si(2 i - 2 x) + \mathrm Si(2 x + 2 i)))}{(4 e^2)} + C$$

Integral $\int\frac{\sin2x}{1+x^2}\,dx$


Are linear mixed models valid for time-varying IV with static DV?

Question: I have data from traumatic brain injury patients where EEG (IV) is collected for several days and used to predict a behavioral measure of outcome (DV) 6 months after patients are discharged. So, I have longitudinal data for my IV, but I have static data for my DV. Are mixed models appropriate here? Or does it not work because the DV is static? There are also a few covariates I want to account for, a few of which are static (sex, and age which doesn't really change either because the EEGs are only a few days apart), while other covariates are time-varying (e.g., medications). This would be a random intercept model, i.e., each patient has their own intercept, with fixed effects for EEG and covariates. So, the formula would be OUTCOME ~ 1 + EEG + AGE + SEX + MEDICATION + (1|PATIENT).
An alternative approach I thought of is to randomly sample one observation day per patient N times, enter the observations for each resample into a multiple linear regression, and then take the resample with the median test statistic across all N resamplings and report the results for that resampling (the test statistic in this case being the regression t-stat for EEG). Would this approach be preferable over using a linear mixed model?
Comment: If you only measured the DV one time for each patient, then the mixed model will not work, unfortunately. I'll let others weigh in on your proposed OLS approach. Do you have any reason to believe the EEG readings closer in time to the DV are more relevant for predicting the DV? If so, you may just want to use 2 or 3 of those as predictors rather than resampling. Or likewise if the first 2 or 3 are more important.
Answer: Answered in comments:
If you only measured the DV one time for each patient, then the mixed model will not work, unfortunately. I'll let others weigh in on your proposed OLS approach. Do you have any reason to believe the EEG readings closer in time to the DV are more relevant for predicting the DV? If so, you may just want to use 2 or 3 of those as predictors rather than resampling. Or likewise if the first 2 or 3 are more important.
– Erik Ruzek


What is the behavior of a WPF 4 ControlStoryboardAction trigger?

Question: I have a question that's been bugging me for a while:
I have a lengthy IO operation which I invoke asynchronously, and I want my UI to show a blinking text to tell the users that the data is loading.
I have an IsLoading boolean property in my ViewModel, and I used a ControlStoryboardAction to kickoff the blinking animation, which is set to repeat forever.  For my ControlStoryboardAction trigger, I configured a data trigger to see if IsLoading is true, and start my storyboard if true.
My problem is, when my IO operation returns, and I set IsLoading back to false, the animation continues to play.  I thought once the trigger condition evaluated to false, it would stop the animation?
I then added a second ControlStoryboardAction to stop the animation if IsLoading evaluted to false, but this didn't have any effect.  The animation continued to play after IsLoading was false.
Can anyone explain to me how trigger works in ControlStoryboardAction?  In normal data triggers in WPF, once the condition evaluated to false, the property would be set back to its original state.  It seems triggers in WPF actions don't work the same way?
Answer: Generally speaking, a DataTrigger will put properties back to their previous value when the specified condition is no longer true.
The same is not true of actions, though.  There's no way for the trigger to know what action would "undo" the effect of the triggered action, assuming that there is even such an action.
I think what you want to do is define another trigger on the opposite condition (e.g., using a boolean-not converter on IsLoading, adding an IsNotLoading property, etc.) that runs a "Stop" ControlStoryboardAction.


Spring Boot 2.x reports java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided

Question: I'm noticing a weird issue with multipart request here.
Below is the Jersey2 implementation used in Spring Boot 2.4.2:
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON})
public void upload(@FormDataParam("params") MyPojo req,
        @FormDataParam("file") FormDataBodyPart file, @Context HttpHeaders headers, @Suspended AsyncResponse ar)
{
    ...
}

and following the Spring Boot dependencies:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
</dependency>

I am able to successfully upload JSON and file (as multipart/form-data) using Postman but the same request from Java client throws below error:
Caused by: org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided

This article on SO says we need to add a CommonsMultipartResolver but why as it works all good from Postman client??
Appreciate any hints or suggestions, thanks.
Updating Java Apache client code:
        final Document document = getDocument(documentId);
        final String requestParams = getRequestParams(document);
        final String documentContentType = document.getContentType();
        final URL endpoint = getServiceEndpoint();

        final MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().addTextBody(REQUEST_PARAMS_PARAMETER_NAME, requestParams, ContentType.APPLICATION_JSON);
        if (isSendDocument() && documentFile != null) {
            entityBuilder.addBinaryBody(DOCUMENT_CONTENT_PARAMETER_NAME, documentFile, ContentType.parse(documentContentType), document.getContentType());
        }

        final HttpEntity reqestEntity = entityBuilder.build();
        connection = (HttpURLConnection)endpoint.openConnection();
        connection.setAllowUserInteraction(false);
        connection.setConnectTimeout(getConnectionTimeout());
        connection.setReadTimeout(getReadTimeout());
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.addRequestProperty(X_REQUESTED_WITH_HEADER_NAME, "XMLHttpRequest");
        connection.addRequestProperty(X_REQUESTED_BY_HEADER_NAME, "XMLHttpRequest");
        connection.addRequestProperty(ACCEPT_HEADER_NAME, ContentType.APPLICATION_JSON.getMimeType());
        connection.addRequestProperty(CONTENT_TYPE_HEADER_NAME, reqestEntity.getContentType().getValue());
        outStream = connection.getOutputStream();
        reqestEntity.writeTo(outStream);
        outStream.flush();

Comment: Can you try to disable the Spring multipart support with
`spring.servlet.multipart.enabled = true`
Comment: Sorry, my comment should have been to _disable_ it. I just copy and pasted it from a post on SO. I forgot to change it to false. Sorry about that.
Comment: check headers attentively, compare postman and the actual java-client call
Comment: Are the requests you're making with Postman and the Java client identical? `MultipartException` is a Spring Framework exception which would suggest that Jersey isn't handling the request made with the Java client.
Comment: @PaulSamsotha sorry I did not understand your suggestion. I'm using Jersey 2 implementation for exposing REST APIs (although it is running on Spring Boot application).
If it is an issue with Spring multipart support, how the request from Postman works? Also I've updated the question with Java client for reference. Thanks.
Comment: Look at the exception, you can see springframework. So it is the Spring framework multipart being used here in this request. That's why I suggested to try to disable it.
Comment: @PaulSamsotha But is this spring.servlet.multipart.enabled not set to true by default?

At least Spring Boot docs says so https://github.com/spring-projects/spring-boot/blob/v2.4.2/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/MultipartProperties.java#L46
Comment: I don't know, I don't use Spring, that's why I said to _try_. What other explanation would you have that the exception says anything about Spring? See above Andy's comment.
Comment: @PaulSamsotha Sorry for the late update. After setting spring.servlet.multipart.enabled=false in application.properties I started getting HTTP 400 for multipart POST request with above Apache http client code.

But Jersey client like in your post [link](https://stackoverflow.com/questions/27609569/file-upload-along-with-other-object-in-jersey-restful-web-service) works fine in sending a POST multipart request.

How this could be different?
Comment: A 400 says there is something wrong with the request. Are you sure the multipart request is in the correct format? Do you know what a raw multipart request supposed to look like? If so, you should check the entire request and make sure that it is correct. That includes the Content-Type header, making sure it has the boundary.
Answer: As we intend the multipart to be handled by the Jersey servlet, @PaulSamsotha suggestion to disable Spring Boot's multipart processing spring.servlet.multipart.enabled = false resolved the original issue posted in the question - "java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided".
Later, I was getting a Http 400 error only with Apache client and that was due to malformed JSON payload. Thanks for all the support.