Mixing/Mastering headroom

Question: I understand that headroom is needed between the mixing and mastering processes.  For example, after a mix is done it may sit at -6dB so the person mastering the song has headroom to play with.
I have heard that if you send a slightly-below 0dB track to a masterer they will tell you to fix it and send it back to them with more headroom. That makes sense as they need headroom to play with.
I am trying to figure out if there's any difference between mixing something to -6dB and sending it to a masterer or mixing something to slightly-below 0dB and having the masterer pull the volume fader on the track down by -6dB to compensate.
I'd think that there'd be no difference, but I feel like I'm missing something fundamental about that. So, is there a difference and if so, what is the difference?
Comment: I understand where you're coming from but I don't want to hunt down links. So your answer is that it is a false premise and there's no difference.
Comment: Well, imo the main question is based on a false premise - so having some background as to where the information came from might give us a hint as to how you arrived at the false premise.
Comment: I agree with Tetsujin, it would help to see an example of what you're reading that talks about a mix "sitting at -6 dB so the mastering engineer has 'headroom'", because that could mean several different things and it's not clear what you're asking about. Normally, **no** mix would "sit at -6 dB". If "sit at" means peak levels, then -6 dB is unnecessarily low - might as well make then between -1 and -3 dB. If "sit at" means average levels, then -6 dB is **way** too high. If the crest factor is more than 12 dB, then it doesn't matter where the peaks are (within reason).
Comment: "I have heard that" where? Please provide citations.
Comment: numerous videos and online tutorials. Sorry but I prefer not to detract from the main question with tons of links.
Comment: Don't worry about the difference between 0 dBFS and the peak level of your mix, worry about the difference between the peak level of your mix and the *averaage* level of your mix. That's the *crest factor*. Don't compress away your crest factor, and find or get a metering plugin or meters in your DAW that will show you both the average and peak levels of your mix, so you know what your crest factors are when you are mixing. Crest factors around 15 - 21 dB are good.
Comment: One other thing about my comment, if the mastering engineer either raises or lowers the total gain on your mix, then that doesn't change the crest factor of your mix, so again, you want to worry about your crest factor, not your peak level. Note that the first sentence of your question doesn't really make sense. I think you've got a problem where you haven't learned enough about audio engineering to be able to even ask about what you're trying to understand.
Answer: There appears to be a slew of miscomprehension as to why mixing to -6dB is a good or bad idea. Let me throw in some quick persuasion as to why this is 'a false premise'.

If you mix to -6dB you immediately add 6dB of random noise to your noise floor. You've just thrown those extra bits away, wasted them for no reason.

The amount of compression does not change your resulting headroom.
Over-compressing the mix is going to annoy the mastering engineer no matter how many dBFS you leave him at the top.
You've already crushed the life out of it & he has nothing to work with. This is the same whether you hit -0.01dB or -18dB.

The Mastering engineer wants clean. He wants breathing room.
He wants headroom in the actual audio, not in the final level.
'Clean' is achieved by not doing 1, or 2. above.

If you were to save your mix at 32-bit float then minor considerations aside [rounding, floating point error I'm going to ignore just for this one purpose] then you could send your mix at +18dB & it wouldn't make the slightest difference.

We no longer in this digital era have a compulsory 'absolute' 0dB before the track is mastered for the consumer. We have floating point internally, we only go to fixed point at output. At that point what we do have these days, to combat the Loudness War, is we have LUFS. [I'm not going to explain LUFS, Google it :P]
LUFS, however, is held as 'the ultimate weapon' by Apple Music, Spotify, YouTube etc.
This is [as we're down to fixed decimal point sound at consumer level] bounded by our 0dBFS, but weighted to an average 'loudness', which these broadcasters will not let us exceed… if you do, they'll just turn your whole track down.
This bit is the mastering engineer's concern.

So, in conclusion…
Mix to -0.01 dBFS if you want, or leave a comfortable 0.3dB if it makes you happier. Your DAW metering will be able to spot any real overs.
Don't comp the sh*t out of it. This will irritate the mastering engineer & he will either do a bad job or send it back to be fixed.
Comment: Now you're getting the idea ;) You need to leave the mastering engineer **breathing room**. This not the same as wasting 6dB at the top.
Comment: We're now getting into the realms of gain-staging & going far beyond the remit of the original question. Just bear in mind that any mix operation needs a calculation. Every calculation makes the sound 'dirtier' by some infinitesimal degree. Your job is to reduce these as much as you can, whilst mainly just ignoring what goes on inside the DAW, which probably works at 64-bit floating point to reduce this calculation error so far as to make it negligible… you only need to worry at output.
Comment: I'm assuming the asker is a bit confused about these things, so I suggest making it clear what you mean by "mixing to -6 dB". I would normally guess that means mixing so that the average level of the mix is -6 dB, but that would be a very hot, compressed mix, so I wouldn't expect there to be much discussion about "mixing to -6 dB" other than "don't do that, target your average levels somewhere between -21 and -12 dB". So maybe you're talking about mixing so that the peaks are around -6 dB? Nothing wrong with that, but maintaining a crest factor is what you want in any case.
Comment: Thanks for the explanation you provided. I guess I should be more clear. Instead of mixing I should say leveling as I was not intending to say I'd compress anything (as I'd leave that to mastering)
Comment: What is mixing if it doesn't involve 'levelling'? You **do** need to comp unless you're doing classical or jazz. **How** you comp is all a part of the mix engineer's job. The mastering engineer is the guy with the golden ears who turns your mix into something fit to be released. He is not going to do the mix for you. That's your job.
Comment: I guess I'm used to seeing compression plugins on the masterers side (as well as the mixers). I guess it needs to be done in both places, with the mindset to not squash it completely in the mix before giving it to the masterer
Comment: There is a thing called inter-sample overs, but since AFAIK they only occur in actual playback/listening, you don't need to avoid them in the mixdown if you're not doing the final master. Right?
Comment: So to further clarify, each individual track should have headroom in mixing b/c something like eq/compression/effects/plugins can spike it up too high and/or squash it. The master fader should be set as close to 0dB as possible to reduce unwanted noise before rendering to a stereo file for the masterer. Sound about right?
Comment: @piiperiReinstateMonica - tbh, I've personally always used -0.3dB & a brick-wall limiter right at the final output to avoid these, in both mix & mastering stages & have never had anyone mention I got stray overs. I haven't studied that part to the *n*th degree, so really can't say for sure.
Comment: This is all pretty much 'artistic expression' but you can comp any & all parts of a track or a mix to achieve your 'glue', but if you aim for 'what you hear on the radio with a pop song' you've probably already over-cooked it. this is something you just have to try out. The first time you ever hear your mix on the radio will be the first time you ever get to know if you really got it right. [Modern plugins have 'radio' emulators to help you with this.]
Comment: And just so I understand, there IS a difference between rendering a stereo file at -6dB and having the masterer up the fader by 6dB to compensate and just rendering a stereo file to just before 0dB and having the masterer do nothing to compensate. And that difference is unwanted noise? If that's true then isn't there noise between whatever the mix is and upping the level on the master fader before rendering to a stereo file?  I think that's where I'm confused
Comment: In other words (extreme example) , let's say the cumulative output of all tracks combined is -12dB. Would I up the master fader by about that much, or would I up each individual track until the cumulative is closer to 0dB? And if I did tha, wouldn't I squash the headroom from the individual tracks?
Comment: So without gain staging, are the 2 scenarios equivalent in terms of noise? Masterer uses fader post-render vs mixer uses fader pre-render?
Comment: Too many questions. Sorry, but we're way past answering your question now & into the entire theory of 'how to record & mix'. Far too broad for anyone to deal with, & especially not in comments. Subscribe to a magazine like Sound On Sound, do some real long-term research. This is a topic that takes **years** to get to grips with.
Comment: Thanks for the explanations! I think I got a starting point going forward here: https://www.izotope.com/en/learn/gain-staging-what-it-is-and-how-to-do-it.html
Comment: Yeah, unfortunately the videos/threads etc don't specify those things and I am new at this so I'm sure I was off in the understanding and translations somewhere along the line
Answer: Suppose that some of the tracks on an album spend most of their time at an amplitude which is 1dB below the peak amplitude, and others spend most of their time 5dB below the peak amplitude.  If one were to start by mixing the first group of tracks with a peak amplitude of 0dB, there would be no way to avoid having the tracks in that group sound louder than tracks in the second group except by cutting the volume on them.  If one were to instead start by mixing the first group of tracks with a main amplitude of -6dB, peaking at -5dB, then one could mix the second group with the same main amplitude, letting it peak at -1dB.
I don't think there's anything particularly special about -6dB as a value except that it's large enough to accommodate many scenarios but small enough not to cause too much needless loss of signal quality.  Different genres of music benefit from different amounts of headroom, and how the dynamic range of the piece being mixed is expected to compare with that of other pieces that will be mixed.

Mixing/Mastering headroom


Vertx js and Redis Sentinel Connectivity

Question: Am Working on the versions of Vertx 3.5.0 Version and Redis with master and Slave Architecture .In their Official Site they have didn't mention of their redis sentinel Support.
So can i create a jar file which gets the Master Details of Redis and use that jar file in Vertx-js Program to get the Master Details and make the Connectivity.
Answer: 3.5.0 does contain basic support for Redis Sentinel but was not properly documented. It is now updated to be polyglot and there is a small reference to it on the new docs:
https://github.com/vert-x3/vertx-redis-client/blob/master/src/main/asciidoc/java/index.adoc#redis-sentinel
This should be available on 3.5.1 but you can already use it on 3.5.0 as the only missing parts were polyglot generation and the docs themselves.


Maximum likelihood estimate for a parameter $a$

Question: How to find maximum likelihood estimate for a parameter $a$ in distribution:
$$f(x)=\begin{cases}  \frac{\left| x\right| }{a ^{2} }  &\text{for } x \in\left[ -a;a\right] \\0 &\text{for } x \not\in\left[ -a;a\right] \end{cases}$$
I did the following steps:
$$L\left( a;x_{1},...,x_{n}\right) = \prod_{i=1}^{n} \frac{\left| x_{i}\right| }{a^{2}} = \frac{ \prod_{i=1}^{n}\left| x_{i}\right|  }{a^{2n}}$$
$$\ln L = -2n \ln a + \sum_{i=1}^{n} \ln  \left| x_{i}\right|$$
$$\frac{\partial \ln L}{\partial a} =  \frac{-2n}{a}=0$$
What to do next?
Normally (in other examples) i got something like this: $c*=\frac{1}{\overline{X}}$ where $c*$ is some estimated parameter, but here I will get $a*=\infty$, which is wrong IMO.
Comment: Is this for some subject, or for similar self-study from a text or similar? If so, could you please add the `self-study` tag?
Answer: Your mistake is simply in taking the derivative and setting it equal to zero without thinking about what you're actually doing (not all maxima are turning points, he said, meaningfully). What you're actually identifying there would be a minimum.
Let
$$\sum_{i=1}^{n} \ln  \left| x_{i}\right|=K\,,$$
say, and draw the log-likelihood function.
... but take care about what the smallest possible value for $a$ is.


Finding the inverse Laplace transform of $Y(s)=\frac{1-e^{-{\pi}s}}{(s^2+1)(s^2+4)}+\frac{s+1}{s^2+4}$

Question: I've encountered an IVP, and I need to solve it by applying the Laplace transform. The problem is:
$$y^{''}+4y=g(t), y(0)=y^{'}(0)=1$$
where $g(t)=\sin(t)$ for $0\leq{t}\leq\pi$ and $g(t)=0$ for $\pi\leq{t}$
Now, the Laplace transform is:
LHS: $L\{y^{''}\}+L\{4y\}=s^2Y(s)-sy(0)-y^{'}(0)+4Y(s)=(s^2+4)Y(s)-s-1$
RHS: $L\{g(t)\}=L\{\sin(t)-\sin(t)u(t-\pi)\}=\frac{1-e^{-{\pi}s}}{s^2+1}$
Then I get:
$$Y(s)=\frac{1-e^{-{\pi}s}}{(s^2+1)(s^2+4)}+\frac{s+1}{s^2+4}$$
Now I'm struggling with finding the inverse transform of $Y(s)$. Can anyone help me with this probelm. Thank you in advance!
Answer: Rewrite $Y$ into
$$Y(s)=\frac{1-e^{-{\pi}s}+(s+1)(s^2+1)}{(s^2+4)(s^2+1)}$$
We can expand the contour of the inverse laplace transform with a semicircle. Note that the poles of $Y$ are all of order $1$. By the residue theorem it follows that
$$\mathcal L^{-1}\{Y(s)\}(t)=\sum_{j\in\{i,-i,2i,-2i\}}\operatorname{Res}(Y(s)e^{st};j).$$
Comment: I just realized I made a mistake in my calculation and I've edited it. But this does not influence the essence of your answer. I'll look into it. Thank you very much!
Answer: This is mechanized in CASes. E.g. the command of Mathematica does the job:
<code>InverseLaplaceTransform[(1 - Exp[-Pi*s])/(s^2 + 1)/(s^2 + 4) + (s +
 1)/(s^2 + 4), s, t]
</code>
$ -\frac{1}{3} \theta (t-\pi ) (\sin (t) (-\cos (t))-\sin (t))+\cos(2 t)+\frac{1}{2} \sin (2 t)+\frac{1}{3} (\sin (t)-\sin (t) \cos (t))$
Comment: What is the $\text{os}$ function? I used to think that it is misspelled $\cos$ but since you write is as \text{os}, it shall not be the case.
Comment: @KirylPesotski: Thank you. Fixed.


next line thingy doesn't work when used proper syntax

Question: f.write(str(Path))
f.write("\n")
f.write(str(Monthly))

path is a string but Monthly is date. I can Insert all in a text file but I am not getting the desired output:
The output that I wish should be
D:\python
2021-04-08

But the output that I get is
D:\python
               <---causing error is this gap
2021-04-08

The extra line after the path is causing problems.
Answer: You literally used two newlines that caused the blank space. You may remove any of them to fix the issue for getting the desired output.
f.write(str(Path))
f.write("\n")
f.write(str(Monthly))

Comment: That was typo
Write function will give error as they are two args


Internet Explorer to Firefox javascript migration library - does one exist?

Question: I am working on a legacy ASP.NET web site that is highly dependent on Internet Explorer.  I would like to migrate it to non-IE browsers.  I know there are a large amount of differences (as detailed at quirksmode.org, etc.), so I'm searching for a javascript library that can help minimize the amount of source I'd have to change.
I'm hoping that my lack of success in finding such a beast so far means that I'm just a bad google-er, and not that I'm just going to have to slog through coming up with replacements/workarounds for all of IE's proprietary functionality that this site currently uses (it uses quite a bit).
Any help you can provide will be greatly appreciated.  Thanks!
Answer: Frankly you should probably convert the site to a well known multi-platform javascript library such as ExtJs or jQuery.
This'll let you standardize your javascript to work on all browsers (including ie)
Answer: I suspect that you're going to have to slug through a little.  I don't know much about IE, but I'm really happy when I use jQuery.  There are many functions and modules that expand the functionality available.  And there is lots of help here on Stack Overflow and at api.jquery.com.
Good luck!


Disk latency within a virtual machine

Question: I've been looking at some performance issues on a clustered virtual machine in our organisation. Actually this problem seems to affect most of the virtual machines I have looked at. Both host and VM are 2008R2 with SP1.
I believe - from what I have read in various articles and advice I have been given - that I/O latency is the most important metric to be looking at. I've looked at this metric in three different places:

LUN latency on the storage appliance
Logical disk average sec/write and average sec/read on the Hyper-v host
The same as above, but on the virtual machines themselves

This is in an effort to narrow down the source of any latency that might be happening. Sure enough, this is what I found....
What I'm seeing is what I would consider to be acceptable latency (3-15ms) on the LUNs, up to 20ms (still acceptable) on the Hyper-V host. When I look at the same metrics on a VM I'm seeing regular spikes of up to 300ms for up to 10 seconds at a time and an average of about 20-30ms.
This particular VM is a SQL server, but the same applies to non-SQL servers too. The relevant exceptions are added to our AV solution to avoid on-access scanning of DB files. Also, our VHDs are of a fixed size as opposed to dynamically expanding.
So for my question:
What are the likely causes of this latency, and/or what other metrics could I be using within the VM (or even on the Host) to narrow this down?
Answer: Measuring time within a VM can be problematic, as the virtual processors don't execute continuously.  If you want to get a clear view of what's actually happening, use Performance Monitor in the management OS.  Look for Hyper-V Virtual Storage Device.  You can correlate that with data from Resource Monitor, too, to see what's contending for access to the disks.
In general, the response time of a particular VHD will have everything to do with what else is happening on the volume hosting that VHD.
Comment: When you say 'volume', I guess you would be referring to the CSV as opposed to any volume the LUNs might sit in?
Comment: I'm not sure what your terminology is getting at.  Yes, CSV is the file system that is typically used for VHDs, and that sits on a volume, which is shared across the host cluster.  That volume sits on top of a LUN, which is part of a disk pool, usually (with Server 2008 R2) in a SAN.  What, specifically, are you asking?
Comment: Sorry, we have volumes on our storage appliances too. Are you suggesting that the logical disk metrics on the VM are useless?
Comment: Additionally, Microsoft assert that the same metrics *can* be used: http://technet.microsoft.com/en-us/library/cc768535%28BTS.10%29.aspx
Comment: No, I'm not suggesting they're useless.  I'm merely pointing out that time within a VM is virtualized, and thus measurements of anything that tries to look at small time quanta will result in messy data.  Data you collect over long periods of time will be generally right.  Looking at any small-span time period may not be accurate.
Comment: Ok, that's a very useful clarification. Do you think you could add that to your answer please? Unfortunately, set you alluded to doesn't contain a metric for latency.
Comment: There's a similar opinion in the [comments here](https://support.microsoft.com/en-us/kb/943556?wa=wsignin1.0).
Answer: Your 'disk latency' on the VM could be CPU latency on the host since the host has to use CPU cycles for IO requests.
Is the host heavily loaded overall? Or is it just running a lot of VMs? Not sure what the hyper-v equivalent, but the VMWare metric is CPU ready time - basically how often is the VM waiting on the host to run.
Comment: The idle time overall is about 80-90% on the host, so not the host is not overloaded.

Disk latency within a virtual machine


Interesting combinatorics question

Question: As a child I had a deck of cards which consisted of maybe 50 cards. On each card there were 6 objects. Players had to pick 2 cards from the deck, and the player who first spotted the difference between the 2 cards won.  The interesting thing was, that for evry 2 cards it was true that they only differed in 1 object.
Can someone explain how to construct such cards?
Comment: As ${9 \choose 6} =84$, you could have a deck of $84$ cards, each with six symbols out of nine.   Any pair would share at least three, but could share up to five.  It would be neat to see if you could throw away some $30$ of them and have each pair differ in two or three, making an error correcting code.
Answer: One trivial way to construct such cards is to use a total of $55$ objects.  Let's label the objects $A,B,C,D,E,1,2,\ldots,50$.  Each card shows a set $\{A,B,C,D,E,k\}$ with $1\le k\le 50$.  But this is almost certainly not what the OP wants!
Comment: Yes, I thought of this solution too, but as far as I remeber in my deck there weren't 55 objects.
Comment: @user137425 There is no other way to create a deck where each card differs only in one object. A deleted answer showed a way to create a deck where no more than 2 objects were different.
Comment: @JohnHabert, it's not obvious to me that there is no other way to create a deck where each card differs only in one object.  Could you post a proof?
Comment: Simple to prove. Without loss of generality, start with two cards ${A,B,C,D,E,1}$ and ${A,B,C,D,E,2}$. Now say you want to add a third card. It necessarily has to be of the form ${A,B,C,D,E,k}$ where $k\ne 1, 2$, otherwise it would differ from either the first or the second card in two or more places. Same argument for the remaining $47$ cards.
Comment: @user75267, the third card could be $A,B,C,D,1,2$.
Comment: @BarryCipra Posted a proof as an answer. A few small details left out that I can add if needed.
Comment: @BarryCipra, I interpreted the question incorrectly, and thought that the order of the objects mattered as well.
Answer: In response to my comments that Barry Cipra's solution is the only way to construct the deck with only one object different, I'm posting a short proof of that fact.
Consider a deck of $50$ cards that has the property that every card differs in only one object from any other card and is not built where every card has $5$ objects the same and differs in only one spot (so not Barry's deck). Pick two cards at random and call the objects on them $A,B,C,D,E,F$ and $A,B,C,D,E,G$. Using only the so far named objects ($A,B,C,D,E,F,G$), it can be shown that there are only $7$ cards possible using these objects. Because the deck contains more than $7$ cards, there is a card that uses a new object, call it $H$. Pick any $5$ of the already used symbols and add $H$ to the card. This new card (say it is $A,B,C,D,E,H$ for easy reference) must differ in $2$ spots from $5$ of the $7$ already constructed cards. This is a contradiction to the assumptions. So either the deck is really built like Barry has suggested or the deck can not force every pair of cards to be different in only one symbol.
Comment: You are taking 6-subsets out of a total of 7 objects, i.e., $\binom{7}{6} = \binom{7}{1} = 7$ for the 7 possible cards.
Comment: Your contradiction assumes that the deck includes more than just the first two cards formed using objects $(A,B,C,D,E,F,G)$.  What if it doesn't?
Comment: A 2 card deck doesn't fit the OP description. So technically, I'm contradicting either (1) it keeps one symbol different on every pair, (2) it is constructed different from your suggestion, or (3) the deck has more than 7 cards.
Comment: @JohnHabert, you misunderstood my comment, which is admittedly a picky one.  What I meant is, having labeled the first two cards with the $7$ letters $(A,B,C,D,E,F,G)$, your proof assumes there is at least one more card using $6$ of those $7$ letters.
Comment: @BarryCipra I understand now. Since every card can differ in only one spot, every card has to use $5$ of those symbols. From there, you can still arrive at a contradiction since any card using $5$ of those symbols plus a new one and doesn't include $A$ will differ in two places from one of the first two cards. More cases than I originally thought but still breaks.

Interesting combinatorics question


Why audio events are not firing with BackboneJS but others are?

Question: I don't understand why the click events are firing ok but not the timeupdate one.
No event is firing from <audio>, I tried with canplay, play, pause, timeupdate, ...
If I display the controls in the template a click .audio event will fire if I click on the player though.
var PlayerView = Backbone.View.extend({
    tagName : 'div',

    template: _.template($('#player-template').html()),

    initialize: function() {
        this.$el.html(this.template(this.model.toJSON()));
    }

    events: {
        'timeupdate .audio': 'onTimeUpdate',
        'click .btn_play': 'onClickPlay',
        'click .btn_pause': 'onClickPause'
    },

    onTimeUpdate: function () {
        console.log('player ' + this.model.get('id') + ' : event = onTimeUpdate');
    },

    onClickPlay: function () {
        console.log('player ' + this.model.get('id') + ' : event = onClickPlay');
    },

    onClickPause: function () {
        console.log('player ' + this.model.get('id') + ' : event = onClickPause');
    },

});

$(function(){
    var model = new PlayerModel({'id' : 1});
    var view = new PlayerView({'model' : model});
    $("#players").append(view.el);
})

The template :

Answer: Backbone internally converts the events object and binds the events by delegation. This means that
events: {
        'timeupdate .audio': 'onTimeUpdate',
        'click .btn_play': 'onClickPlay'
}

ends as
this.$el.delegate('.audio','timeupdate', this.onTimeUpdate);
this.$el.delegate('.btn_play','click', this.onClickPlay);

But there's a catch:

Uses event delegation for efficiency. [...] This only works for
  delegate-able events: not focus, blur, and not change, submit, and
  reset in Internet Explorer.

And it would appear that audio events are not delegate-able.
However, setting directly the callbacks does work, for example you could replace your initialize function by
initialize: function() {
    this.$el.html(this.template(this.model.toJSON()));
    _.bindAll(this,'onTimeUpdate');
    this.$('.audio').on('timeupdate', this.onTimeUpdate);
}

Comment: Indeed, thanks @nikoshr for the clarification. I was also having problems when binding keypress events to an input box that was outside of my `el` div (and it worked if I put it inside).

Most examples just suggested using `$('#your-div').keypress(this.your_event)`, but I wanted to know *why* the `events: { }` approach wasn't working. Now I know.


PHP mysqli statement execute() not working

Question: I havn't found something equally on stackoverflow.com, so i post my question in the hope someone have an idea what's wrong with my code or something i'm using.
Before i begin: On my productive webspace the same code works, the problem is located at the xampp-installation for my local development-server... sigh
I have a little webapplication for my family and me to document the work at home (e.g. to empty the bin), so we can distribute money to our kids, depending on how much they done by themself (a little bonus to the pocket money they get without homework)
The code to insert a line into my db-table is:
function AddGarbEntry($DBConnection, $DBPrefix, $UserID, $GarbID)
{
    $stmt = $DBConnection->prepare("INSERT INTO t_".$DBPrefix."_entries (idUsers,idGarbType) VALUES (?,?)");
    $stmt->bind_param("ii", $UserID, $GarbID);
    $stmt->execute();
    $stmt->close();
}

The part of the script, where i call this function is:
$con = new mysqli($_SESSION["DBHost"], $_SESSION["DBUsername"], $_SESSION["DBPassword"], $_SESSION["Database"]);
AddGarbEntry($con, $DBPrefix, $_POST["user"], $_POST["garbagetype"]);
$con->close();

I've already checked the Session-Variables (They are all filled with the correct values), and the POST-Values (They are filled correct either).
In my MySQL-Log a can find the following lines:
170423 11:54:38    66 Connect   rldmla_1@localhost as anonymous on rldmla_db1
           66 Prepare   INSERT INTO t_garb_entries (idUsers,idGarbType) VALUES (? , ?)
           66 Close stmt
           66 Quit

So, i can see, that the prepare is working, but there is no sign, that my testserver runs the execute()-Command. The error-logs of php, apache and mysql have no entry about that.
Curiously, if i'm using a specific function of my website to update already existing lines (also prepared-statement, but an update-statement), my insert code works properly for about two times, after that it stop working until i update my table again.
I've tried the actual version of xampp (7.1.x) and the older version (7.0.15), but the problem is the same. Xampp is running as x86-version on a x64-running Windows Server 2012-Machine. I've only installed the modules Apache, PHP and MySQL.
I don't have any clue, what i'm doing wrong. Any help is appreciated.
Greetings, Ronny
Comment: Does `$stmt->error;` return anything? And you probably shouldn't store the DB info in the session, particularly passwords shouldn't be there. Use a file with definitions or a config which you parse from instead.
Comment: You can check if an error has occurred in the last statement. With this `printf (" Error:% s. \ N ", $ stmt-> error);` immediately after the `execute`.
Comment: I tried that, but stmt->error is empty :(
Answer: Urks.... Now I've got the clue:
I changed my Xampp-Installation to a linux based virtual machine, where i've installed Apache, PHP, MySQL and phpMyAdmin. After that the missing execute-line was in the MySql-Logfile.
So, nothing to do here anymore.
Thx @all for supporting me :)
Greetings, Ronny


Como selecionar valor Option com retorno de dados Ajax?

Question: Tenho o seguinte código HTML:
<select id="priorities-info" class="form-control selectpicker" data-live-search="true" disabled="" tabindex="-98">
    <option value="1" data-tokens="Alta">Alta</option>
    <option value="2" data-tokens="Média">Média</option>
    <option value="3" data-tokens="Baixa">Baixa</option>
</select>

Estou tentando comparar o data-tokens desta forma:
$('#priorities-info').each(function() {
    $(this).attr('selected', this.dataset.tokens == responseData.Type);
});

Mas não estou conseguindo, alguém tem alguma ideia?
Comment: Qual o valor de `responseData.Type`?
Comment: @Marconi `Type: Média`
Answer: No seletor acredito que você deva incluir os options e verificar se o valor do atributo data-tokens é igual ao retornado pelo ajax:

$('#priorities-info option').each(function() {
  if ( $(this).attr('data-tokens') == 'Média')
    $(this).prop('selected', true);
});

<select id="priorities-info" class="form-control selectpicker" data-live-search="true" tabindex="-98">
    <option value="1" data-tokens="Alta">Alta</option>
    <option value="2" data-tokens="Média">Média</option>
    <option value="3" data-tokens="Baixa">Baixa</option>
</select>
Comment: Obrigado Lucas, só uma observação se alguém estiver utilizando o **Bootstrap Select**
igual a mim, aconselho a colocar `$('#priorities-info').selectpicker('refresh');` após o `if`
Comment: Maravilha @WagnerViana!


feature hashing as a form of encryption

Question: Is feature hashing a really bad way to do encryption?
I want to encrypt my documents but in a format that some ML algorithms can be trained on them one day.
Answer: Let me start with a disclaimer: https://security.stackexchange.com/questions/18197/why-shouldnt-we-roll-our-own.
Is the idea to be able to do machine learning on hashes of your document features, so that you can keep the plain-features encrypted?
Lets say you want to do some sort of unsupervised clustering on your documents. You might be able to do so in your scheme, if each feature is hashed in the same way. On the other hand, you can't use salting anymore, so your documents are much more vulnerable to dictionary attacks.
There are other issues as well. As an example, you can think about "encrypting" a plain-text file in the following way: assign each word in the dictionary a random ID and replace the words in the file with these IDs.
While it's a little bit more difficult for a human to read this text file, this is the sort of puzzle that usually goes on the back of a cereal box (minus the decoder ring). You can get a pretty good guess of the contents just by examining co-occurrences.
In general, I think that what you're trying to do is an open problem, and your success would vary based on how much information you preserve in these features. I'm not familiar with it, but you can try searching for "Privacy Preserving ML" to get some pointers.
Comment: Are you referring to homo-morphic encryptions by privacy preserving ml? Isn't that stilll at a proof of concept stage since it is expensive to train the classifiers on encrypted data?
Comment: I'm honestly not familiar with this area at all. Sorry :-).

feature hashing as a form of encryption


Cauchy problem for $u_t + uu_x =0$

Question: Discuss the solution of $u_t+ uu_x= 0$ with the following Cauchy data:
a) $u(x,0)= x ; 0\leq x\leq 1$
b)$u(x,0)=1/2; 0\leq x\leq 1$
Sketch the domains in the $x-t $ plane where the solutions are determined. Does the solution develop a singularity at any time? If yes, discuss the reasons for the break down of the solution.
My trials:
For a) by the methos of characteristic I got the solution u(x,t)=x/(1+t). So it has singularity at t=-1, is it possible? And then for b) methos of characteristics is not giving a solution. So if someone explain the solution of this kind problems it will be of great help. Thanks in advance.
Comment: What is the initial condition outside the interval $[0, 1]$ in each case?
Comment: there is no other condition..I have written the complete as it has been asked
Comment: I see. Your answer for a) seems correct. For b), I believe the solution is $u(x, t) = 1/2$ for $0 \le x - \frac 12 t \le 1$.
Comment: can you just write your solution, or take a photo of your solution and upload it here for part b), I can then accept that as an answer.
Answer: Suppose the parameters for characteristics are $\eta$ and $\xi$.
The characteristics are defined by
$$
\frac{\partial t}{\partial \eta} = 1, \frac{\partial x}{\partial \eta} = u, \frac{\partial u}{\partial \eta} = 0.
$$
Solving gives $t(\eta, \xi) = \eta + c_1(\xi)$, $u(\eta, \xi) = c_3(\xi)$, $x(\eta, \xi) = c_3(\xi)\eta + c_2(\xi)$.
Pick the parametrization of the initial solution curve: $t(0, \xi) = 0$ and $x(0, \xi) = \xi$. It follows that $c_1 = 0$, $c_2(\xi) = \xi$ and $t = \eta$. The initial condition determines $c_3$:
a) $u(0, \xi) = \xi$, so $c_3(\xi) = \xi$. It follows that $x = \xi(\eta + 1)$. Since the initial condition is only given for $\xi \in [0, 1]$, the domain in which the solution may exist is $(x, t) \in \{(\xi(\eta + 1), \eta) \mid \xi \in [0, 1], \eta \in \mathbb R\}$. Inverting the transformation $(\xi, \eta) \mapsto (x, t)$, we get $\xi = \frac{x}{t+ 1}$, so the singularity exists at $t = -1$. The solution is $u = \xi = \frac{x}{t+1}$.
b) $u(0, \xi) = \frac 12$, so $c_3(\xi) = \frac 12$. It follows that $x = \frac 12\eta + \xi$. The domain in which the solution may exist is $(x, t) \in \{(\frac 12\eta + \xi, \eta) \mid \xi \in [0, 1], \eta \in \mathbb R\}$. Inverting the transformation, we get $\xi = x - \frac 12 t$. The solution is $u = \frac 12$. There is no singularity. The solution is valid throughout the domain $\{ (x, t) \mid \frac t2 \le x \le \frac t2 + 1, t \in \mathbb R \}$.

Cauchy problem for $u_t + uu_x =0$


Why doesn't Eclipse recognize import java.JOptionPane?

Question: I'm on the Eclipse program for Java developers, and for some reason, Eclipse doesn't recognize import javax.swing.JOptionPane when creating a new class.
If you attempt to make a new class and have the code imported automatically, nothing pops up

In fact, nothing remotely related to javax.swing pops up. Any ideas on what's going on? I removed the JRE system library and re-added it again. But that didn't work.
Comment: @howlger I fixed it, I just uninstalled jdk and eclipse, and reinstalled it.
Comment: A quick [google](https://www.google.com.au/search?client=safari&rls=en&dcr=0&q=eclipse+javax.swing&oq=eclipse+javax.swing&gs_l=psy-ab.3...0.0.0.120188.8.131.52.0.0.0.0.0..0.0....0...1..64.psy-ab..0.0.0....0.X2AlhOCgVQ4) brings up a few possible remedies - Have you tried any? If so, which ones didn't work for you?  In what ways is your problem "seemingly" different from the others who had similar problems?
Comment: Based on your error message, [this previous answer look promising](https://stackoverflow.com/questions/860187/access-restriction-on-class-due-to-restriction-on-required-library-rt-jar)
Comment: You type JOptionPane in Choose a Type Textbox and then related package will show below. After that choose the below package.
Comment: @MadProgrammer That's what I meant when I said "remove JRE library and re-add it."
Comment: @Myo Typing javax.swing.JOptionPane should produce the same thing as typing JOptionPane. Also, simply typing JOptionPane doesn't work either.
Comment: @MadProgrammer Replying to your first comment, I saw the question about https://stackoverflow.com/questions/14181142/eclipse-doesnt-find-javax-swing. I followed every step and it matches up. But JOptionPane still isn't showing.
Comment: Have you tried to create a new fresh workspace and project to see if it occurs there? It shouldn't, of course, but I recall having instances where the metadata of a workspace or project seemed to be messed up.
Comment: @M.leRutte Yup, I just tried creating a new workspace. The same error occurs.
Comment: @Crescendo Could you add the details of 1. the jre/jdk that you're configuring. 2. `java -version` on your machine 3. eclipse version that you're using.
Comment: Also, could you state, how is this is not a duplicate of https://stackoverflow.com/questions/14181142/eclipse-doesnt-find-javax-swing already?
Comment: @nullpointer I fixed the problem. Kind of a dumb mistake too
Comment: @Crescendo shall this be marked as Off-Topic in that case?
Comment: Are type filters (_Window > Preferences: Java > Appearance > Type Filters_) set? If no, does rebuild the Java index (in _Window > Preferences: Java_ click the _Rebuild Index_ button) fix the problem?
Answer: Here are some things that could be causing a problem:

Make sure you have a JDK installed and selected in eclipse
Window > Preferences > Java > Installed JREs

Make sure it's in your build path
Project > Properties > Java Build Path > Libraries

One of the Libraries should be something along the lines of "JRE System Library [JDK9]". If there isn't one, add it with:
Add Library > JRE System Library

Your project should be a Java project
Project > Properties > Builders

Should have a "Java Builder" entry.
After doing all that, rebuild your project with Project > Clean then select your project. If none of that works, completely uninstall Java, reinstall the JDK and JRE then repeat steps 1-3. Source.
Comment: I deleted Eclipse, and redownloaded it last night. It turns out that if you manually type in `import javax.swing.JOptionPane`, a red box on the right appears. But the program still runs. Is there a way to fix that part?
Comment: Hmm. Seems like an eclipse glitch. What JDK version are you using, and what eclipse version?
Comment: Nevermind, I found out what was wrong with eclipse. Not sure what, but I just uninstalled everything, reinstalled everything, and installed Eclipse into the C: folder.
Comment: Does this mean I get the bounty?


How do I call a textfield from within an UIAlertController?

Question: So, I am making an app where when the "Start" button is pressed, an Alert via UIAlertController pops up and there are two textfields asking for the players' names, where I will move the player names to the game's screen (it's a Tic-Tac-Toe app) via
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
So my question at the moment is how to get the values that the user inputs into the TextFieldWithConfigurationHandler to my GameScreen. My code for the UIAlertController is as follows:
@IBAction func startButton(sender: AnyObject)
    {
        var playerNameEntry = UIAlertController(title: "Player names", message: nil, preferredStyle: .Alert)

        playerNameEntry.addTextFieldWithConfigurationHandler({textfield in textfield.placeholder = "Player 1"})

        playerNameEntry.addTextFieldWithConfigurationHandler({textfield in textfield.placeholder = "Player 2"})

        var continueButton = UIAlertAction(title: "Continue", style: .Default, { action in

            self.performSegueWithIdentifier("gameSegue", sender: nil)

        })

        playerNameEntry.addAction(continueButton)

        var cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)

        playerNameEntry.addAction(cancelButton)

        self.presentViewController(playerNameEntry, animated: true, completion: nil)

    }

thanks for taking to time to read this and if you answer, thanks tenfold
Answer: In your continueButton handler, you have access to the alert controller as playerNameEntry. Therefore you can access its textFields array:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertController_class/#//apple_ref/occ/instp/UIAlertController/textFields
Therefore you can access the text of each of those text fields.
    var continueButton = UIAlertAction(title: "Continue", style: .Default, { action in
        // code goes here
        let tfs = playerNameEntry.textFields as [UITextField]
        // ...do stuff with the `text` of each text field...
        self.performSegueWithIdentifier("gameSegue", sender: nil)
    })


Completion of a ring

Question: Consider the ring $$R= \mathbb{Z}_p[x,y]/((x^2-2+y^2)(x^2-y^2)+p^ry),$$ where $p$ is an odd prime and $r$ is an integer greater than $1$. I want to show that the completion of $R$ at $(p,x,y)$ is isomorphic to the completion of a ring of the form $$\mathbb{Z}_p[x,y]/(xy-v)$$ at the origin, where $v \in (p) \cap \mathbb{Z}_p$. I don't seem to be able to work this out.
Answer: The completion is equal to $\mathbb Z_p[[x,y]]/((2-x^2 -y^2)(x^2 - y^2)-p^ry)$. Now the element $2 -x^2 -y^2$ is invertible in $\mathbb Z_p[[x,y]]$, since it has an invertible constant terms, and so we can rewrite this as $$\mathbb Z_p[[x,y]]/(x^2 - y^2 - u),$$ where $u = (2 - x^2 - y^2)^{-1}p^r y.$
Now if we write $s = x-y, t = x+y,$ then $\mathbb Z_p[[x,y]] = \mathbb Z_p[[s,t]]$ (again using that $p$ is odd to inert the relationship between $(s,t)$ and $(x,y)$), and hence we may rewrite the completion as
$$\mathbb Z_p[[s,t]](st - v),$$ which is the required form.
Added: As YACP alludes to in a comment, the element $v$ is a multiple of $p$, but does not lie in $\mathbb Z_p$.  However, I don't think it's possible to achieve this last condition (although I don't have time now to check it carefully).
Comment: Is $v \in (p) \cap \mathbb{Z}_p$? (Btw, what means $\mathbb Z_p$ here?)
Comment: @YACP: Dear YACP, $v$ is a multiple of $p$, but you're right that it's not in $\mathbb Z_p$; I didn't pay attention to that requirement.  And I took $\mathbb Z_p$ to mean the $p$-adic integers; what else might it mean?  Regards,

Completion of a ring


Can I reassign eth1 and eth2 without rebooting the server

Question: Say I have eth0 - my management interface,
then eth1 with mac1 and eth2 with mac 2- additional nics running.
How can I reassign eth1 with mac2 and eth2 with mac1 and bring them up without the reboot?
Comment: Why do you need to swap the mac adddress?
Comment: Put'em down, change addresses, then put'em up again.
Comment: What Linux distribution?
Comment: I tried to put them down, change the HWADDR entries in /etc/sysconfig/network-scripts/ifcfg-eth1 and ifcfg-eth2, change the entries in /etc/iftab, then do ifrename and service network restart or ifdown/ifup eth1 and eth2 - doesn't work without reboot. Any ideas?
Comment: put them down, change eth2 mac address first to other address, e.g: ifconfig eth2 hw ether 00:11:22:33:44, then ifconfig eth2 w.x.y.z netmask ww.xx.yy.zz up. do it for eth1 (using eth2 mac addr), and then change eth2 mac addr using old eth1 mac addr.
Comment: ifdown doesn't really makes the interface down. It looks and says but it doesn't totally. You will have to change a logic in those scripts(ifdown). Actually ifdown should restart the system, you will have to change that logic, so that system does not restart it.
Comment: sorry not in ifdown, in /etc/init.d/network script.
Answer: Edit file /etc/init.d/network
You can comment/remove line ./ifdown $i boot from below
action $"Shutting down interface $i: " ./ifdown $i boot

like this :
action $"Shutting down interface $i: "

       # ./ifdown $i boot

to stop system from reboot on /etc/init.d/network restart.
You will have to check whether mac addresses gets changed by doing this. Or you will have to reboot the system.
Answer: You can use the ip command to change the name of an interface.

assign eth0 the new name swapit
assign eth1 the new name eth0
assign swapit the new name eth1


Gutenberg render locate_template

Question: I wanna render a simple template with gutenberg serverside with create-guten-block.
init.php:
function melaniemueller_templateparts_block_cgb_block_assets() {

register_block_type(
        'cgb/block-melaniemueller-templateparts-block', array(

            'render_callback' => 'mmu_block_render',
        )
    );
    }
}

// Hook: Block assets.
add_action( 'init', 'melaniemueller_templateparts_block_cgb_block_assets' );

function mmu_block_render($attr, $content) {
       locate_template( 'custom\php\templates\header\header_main_1.php', true );
    }

block.js:
registerBlockType( 'cgb/block-melaniemueller-templateparts-block', {
    // Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
    title: __( 'melaniemueller-templateparts-block - CGB Block' ), // Block title.
    icon: 'shield', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
    category: 'common', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
    keywords: [
        __( 'melaniemueller-templateparts-block — CGB Block' ),
        __( 'CGB Example' ),
        __( 'create-guten-block' ),
    ],

    edit: function( { attributes } ) {
        return (
            <ServerSideRender
                block="cgb/block-melaniemueller-templateparts-block"
                attributes={ attributes }
            />
        );
    },

    save: function( { } ) {
        return null;
    },
} );

But if I wanna render this part I get a bug in the edit-function in Quirks-Mode in Chrome.
Error loading block: The response is not a valid JSON response.

Has anyone an idea what I did wrong?
Comment: @Melanie I think you forgot to return something in your render callback (`mmu_block_render`).
Comment: It is already returned in the  `locate_template` [source](https://developer.wordpress.org/reference/functions/locate_template/)
Answer: The setup of your block registration is fine. The issue is your function mmu_block_render() not returning a valid value for the <ServerSideRender> to render.
The <ServerSideRender> is used to render a preview of dynamic content in the Block Editor. It is not intended to load complete template files as your function is attempting to do. As such locate_template will not return a valid value.
Below are two examples, the first reproduces the error seen and the second shows the same function corrected to render a valid result. I chose the function the_title() as it is most commonly in header template files:
Invalid
<?php
function mmu_block_render($attr, $content){
    // the_title echo is set to "true", printing the value
    return "". the_title('
', '
', true)."";
}
?>

Valid
The value of the_title is returned and the callback function renders as expected eg:
<?php
function mmu_block_render($attr, $content){
    // // the_title echo is set to "false", returning the value
    return "". the_title('
', '
', false)."";
}
?>

If you replace your function and run the two examples above, you will be able to  then work on taking the key part/s of your template file and ensuring that they return a value value and render correctly.

Gutenberg render locate_template


Questions about a function with $f(0)=0$ and a bounded derivative

Question: Let $f:\mathbb{R}\longrightarrow \mathbb{R}$ be differentiable with $f(0)=0$. If $1<f'(x)<2$  for $x \in \mathbb{R}$ .
Then which of the following statements is true on $(0,\infty)$:
A) $f$ is unbounded
B) $f$ is increasing and bounded
C) $f$ has at least one zero
D) $f$ is periodic.
Comment: Eariler comment was incorrect. Now, the function is unbounded, as $f(x) \geq x$ for all $x$.
Comment: Can u justify It more
Comment: Justification is in the answer below.
Comment: If you don't show us what you have attempted, your question will be closed, sooner or later. Besides, in not-SMS English "u" is "you". Please be correct with us.
Answer: Clearly, $f$ is unbounded. Assume $M>0$ is a bound for $f$, Then the MVT tells us that  for some $\xi$ with $0<\xi<M+1$, we have $f(M+1)=(M+1)f'(\xi)>M+1$, contradiction. So A is correct
As the example $f(x)=\frac32x$ shows, B, C, D are incorrect.
Comment: Isn't C correct since f has a zero at zero?
Comment: The interval considered is $(0,\infty)$ which excludes $0$.
Comment: Thanks, I missed that part of the question.


How to correct url path

Question: I am using a key to connect with it's node nid but when I click on Next it gives path /node/node/256 instead of node/256. Here is my code:
$key = array_search($nid , $nids);
print $key;
$next = ($key + '1');
$previous = ($key - 1);
$total=count($nids);
$next_link =    "Next";
$previous_link = "Previous";

$nids is an array. How to handle this situation?
Answer: Use l() to construct URLs in Drupal.
$next_link = l('Next', 'node/' . $nids[$next]);
$previous_link = l('Previous', 'node/' . $nids[$previous]);

Comment: @Adi If a path has an alias, `l()` will use the alias automatically
Comment: thanx anil they show in url their nid if we want to show its alias then what i do?
Answer: Alternatively if you wanted just the alias, but not the whole link then you could use drupal_get_path_alias:
$alias = drupal_get_path_alias('node/'.$nid);

Answer: Correct next and prev node url by content type
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load($nid);
  $type = $node->type;

  $prev = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('n.status', 1, '=')
    ->condition('n.type', $type, '=')
    ->condition('n.created', $node->created, '<')
    ->orderBy('n.created', 'DESC')
    ->range(0, 1)
    ->execute()
    ->fetchField();

  $next = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('n.status', 1, '=')
    ->condition('n.type', $type, '=')
    ->condition('n.created', $node->created, '>')
    ->orderBy('n.created', 'ASC')
    ->range(0, 1)
    ->execute()
    ->fetchField();

  if ($prev) {
    $prev_link = l('Previous', 'node/' . $prev);

  }
  if ($next) {
    $next_link = l('Next', 'node/' . $next);
  }

}

How to correct url path


Detect Duplicate Items in DataFlow

Question: I've been building out a service that processes files using a Queue<string> object to manage the items.
public partial class BasicQueueService : ServiceBase
{
    private readonly EventWaitHandle completeHandle =
      new EventWaitHandle(false, EventResetMode.ManualReset, "ThreadCompleters");

    public BasicQueueService()
    {
        QueueManager = new Queue<string>();
    }

    public bool Stopping { get; set; }

    private Queue<string> QueueManager { get; }

    protected override void OnStart(string[] args)
    {
        Stopping = false;

        ProcessFiles();
    }

    protected override void OnStop()
    {
        Stopping = true;
    }

    private void ProcessFiles()
    {
        while (!Stopping)
        {
            var count = QueueManager.Count;
            for (var i = 0; i < count; i++)
            {
                //Check the Stopping Variable again.
                if (Stopping) break;

                var fileName = QueueManager.Dequeue();
                if (string.IsNullOrWhiteSpace(fileName) || !File.Exists(fileName))
                       continue;

                Console.WriteLine($"Processing {fileName}");

                Task.Run(() =>
                    {
                        DoWork(fileName);
                    })
                    .ContinueWith(ThreadComplete);
            }
            if (Stopping) continue;

            Console.WriteLine("Waiting for thread to finish, or 1 minute.");
            completeHandle.WaitOne(new TimeSpan(0, 0, 15));
            completeHandle.Reset();
        }
    }

    partial void DoWork(string fileName);

    private void ThreadComplete(Task task)
    {
        completeHandle.Set();
    }

    public void AddToQueue(string file)
    {
        //Called by FileWatcher/Manual classes, not included for brevity.
        lock (QueueManager)
        {
            if (QueueManager.Contains(file)) return;

            QueueManager.Enqueue(file);
        }
    }
}

Whilst researching how to limit the number of threads on this (I've tried a manual class with an incrementing int, but there's an issue where it doesn't decrement properly in my code), I came across TPL DataFlow, which seems like its a better fit for what I'm trying to achieve - specifically, it allows me to let the framework handle threading/queueing, etc.
This is now my service:
public partial class BasicDataFlowService : ServiceBase
{
    private readonly ActionBlock<string> workerBlock;

    public BasicDataFlowService()
    {
        workerBlock = new ActionBlock<string>(file => DoWork(file), new ExecutionDataflowBlockOptions()
        {
            MaxDegreeOfParallelism = 32
        });
    }

    public bool Stopping { get; set; }

    protected override void OnStart(string[] args)
    {
        Stopping = false;
    }

    protected override void OnStop()
    {
        Stopping = true;
    }

    partial void DoWork(string fileName);

    private void AddToDataFlow(string file)
    {
        workerBlock.Post(file);
    }
}

This works well. However, I want to ensure that a file is only ever added to the TPL DataFlow once. With the Queue, I can check that using .Contains(). Is there a mechanism that I can use for TPL DataFlow?
Comment: Whatever is consuming and submitting the files has the responsibility of not posting them twice. If your reading  files from directory you could tag them, or cache the path as @VMAtm suggested. But if users or otherwise clients are submitting them you'll need to treat the processes as a job. Where each file represents a single job with a single result.
Answer: Your solution with Queue works only if file goes into your service twice in a small period of time. If it came again in, say, few hours, queue will not contain it, as you Dequeue it from there.
If this solution is expected, then you may use a MemoryCache to store file paths being already handled, like this:
using System.Runtime.Caching;

private static object _lock = new object();

private void AddToDataFlow(string file)
{
    lock (_lock)
    {
        if (MemoryCache.Default.Contains(file))
        {
            return;
        }

        // no matter what to put into the cache
        MemoryCache.Default[file] = true;
    // we can now exit the lock
    }

    workerBlock.Post(file);
}

However, if your application must run for a long time (which service is intended to do), you'll eventually run out of memory. In that case you probably need to store your file paths in database or something, so even after restarting the service your code will restore the state.
Answer: You can check it inside of DoWork.
You have to save in Hash already works items and check current filename doesn't exist in hash.

Detect Duplicate Items in DataFlow


Julia - Developing package and updating changes without restarting Jupyter Notebook kernel

Question: I'm developing a package in Julia, and I'm using Jupyter Notebook to do some testing. The problem is, every time I make a change to my package, I need to restart the kernel.
I heard that the package Revise.jl is supposed to solve this type of problem, but even after sniffing through the documentation, I didn't quite understand how to properly use it with Jupyter Notebook.
How does one properly avoid restarting the kernel for Jupyter every time one makes a change to the package?
Just to give some more context. I have a folder with the following structure:
<code>Manifest.toml
Project.toml
Readme.md
./examples/Notebook.ipynb
./src/function.jl
./src/MyPackage.jl
</code>
Comment: Doesn't it just work if you run `using Revise` in the first cell of your notebook, before `using MyPackage`? When you modify some source file and re-run a cell in your notebook, doesn't it automatically pick the change? (I just checked it works for `includet`, but was too lazy to check for full-fledged packages)
Answer: I figured out what was going on.
So indeed, one just need to use the Revise.jl package.
The reason it wasn't working for me is that I was importing MyPackage before Revise, and you need to import Revise first. Hence, once I restarted the Kernel and used Revise before MyPackage, things worked flawlessly.
Comment: To avoid needing to remember, you can load Revise automatically whenever you start Julia: https://timholy.github.io/Revise.jl/stable/config/#Using-Revise-by-default-1


Website doesn't load properly from htdocs/web

Question: Built a website on localhost, moved it to shared-hosting where webroot is htdocs but when visiting the website through the hosting's given IP address it obviously doesn't load the website, because the index.php is inside htdocs/web/?
This is very limited shared-hosting, no control panel and no way to edit apache's configs, only .htacess files accessible in htdocs.
Current attempts:
a. Homepage loads fine, but /web/ is added in the URL in the address bar for every sub-page.
RewriteEngine On
RewriteRule ^(.*)$ /web/$1 [L]

b. Homepage loads and no /web/ is added for any links in e.g. main menu navigation while from homepage and clicking them even loads the page without /web/ added to the URL, but the /web/ is added back to the menu once you're within any subpage.
 RewriteRule ^(.*)$ web/$1 [L,NC]

Menu links from homepage

Same menu links from within subpages

Interesting find, while you can visit content pages from menu links, you cannot access e.g. /user when trying to login, you get WSOD Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it. You have to enter web/user in order to login.
update: Similar issue described here https://www.drupal.org/forum/support/installing-drupal/2022-02-21/redirects-to-external-urls-are-not-allowed-by-default-use-drupalcoreroutingtrustedredirectresponse#comment-14996104 but no actual solution, only the mention of the redirection to /web/? How to redirect properly without /web/ showing in URL adress bar?
Answer:
This is very limited shared-hosting, no control panel and no way to
edit apache's configs, only .htacess files accessible in htdocs

Look for a new hosting company, until then you can use the legacy composer project:
composer create-project drupal/legacy-project my_site_name_dir

and then require all the components you had before.
Instead of install.php for a new database, you can put a copy of the existing database and sites/default/files directory in the fresh composer project and clear the cache. If this produces errors, check that you have exactly the same versions of all modules.
Comment: Any links with more in-depth steps for migrating from recommended to legacy? Especially for last paragraph?
Comment: You'll see in the new composer project what is missing from the existing site. Just try it. Always copy the database and the files so that if it doesn't work you can delete the new project directory and start over.
Comment: This is the right answer and solved the problem. Also do not forget to copy themes and libraries directories. You do not need to run install.php, only copy the database and copy/paste required modules in the composer.json
Comment: For themes and libraries not managed by Composer. Compare both site directories in Midnight Commander and copy missing files or folders from left to right. And yes, that's important to mention not to run install.php, I add this to the answer.


PHP site runs on linux but not on windows

Question: I developed a website that runs perfectly on Linux, but when I try to run it on the Windows production server, the php script doesn't work. Everything that's in the code after this line doesn't do anything:
require_once __DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'returner.php';

I thought that the proble could be related to the paths of the files, so I modified the code to use DIR and DIRECTORY_SEPARATOR to avoid any kind of problems with the paths. I tested if the path was working using file_exists and the file was located, but my code still does nothing when I try to run it on the Windows server.
/index.php includes /lib/returner.php
/lib/returner.php includes /lib/login.php
Code:
index.php:
...
div class="container" role="main">
    <?php
        require_once __DIR__ . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'returner.php';
        echo '
';
        echo '
' . returnSede() . '
';
        ...

returner.php:
...
<?php
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'login.php';
    $sede = $_POST['selectSede'];
...

Comment: Turn on error reporting and read your logs.
Comment: @Eugen php will translate them if needed. I typically just use `/` and it works fine.. Also, OP is using the pre-defined constant DIRECTORY_SEPARATOR which should account for that.
Comment: windows have dir separator '\' and linux '/'
Answer: It seems like your code should work.
Just in case, this answer on Stack Overflow might shed some light. I'll kind of summarize:
If you're only worried about Unix-based or Windows, hard coding the path with forward slashes ("C:/test.txt") will work.
There can be discrepancies due to what type of quote you use:

for instance, "\123" translates to "Q"
Windows requires "C:\\test.txt" or 'C:\test.txt' or "C:/test.txt"

Another answer on the same question suggests doing something like this:
define('DS','/');
define('BASE_ROOT',str_replace('\\',DS,dirname(__FILE__)));
require_once BASE_ROOT . DS . 'includes' . DS . 'init.php';

Comment: using \__DIR__ has the same result than using dirname(\_\_FILE__) and my code isn't using any normal or backslashes, I'm using DIRECTORY_SEPARATOR to avoid having a mess with / and \ depending on the platform.
Comment: From the documentation linked in those other answers, it seems that using DIRECTORY_SEPARATOR can have problems. The only counter-example I've read, however, was when using double quotes and DIRECTORY_SEPARATOR which can result in an unescaped backslash in double quotes which can give unexpected results. I'm curious to see what the actually fix for your situation is.


Covariance with conditional expectation

Question:
Suppose $X$ and $Y$ are random variables, $E(Y^2) < \infty$ and
$\varepsilon = Y - E(Y|X)$ so that $Y = E(Y|X) + \varepsilon$.
Given that $E(\varepsilon | X) = E(\varepsilon) = 0$, show that
$Cov(\varepsilon , E(Y|X)) = 0$.

This question has multiple parts so $E(Y^2) < \infty$ may or may not be applicable in this case.
Here's what I tried so far. I used the fact that $Cov(X,Y) = E(XY) - E(X)E(Y)$ and $Cov(X,Y) = E[(X - E(X))(Y-E(Y))]$ and concluded that $Cov(\varepsilon , E(Y|X)) = E(\varepsilon E(Y|X))$ or in other words, $E(\varepsilon E(Y)) = 0$.
From there, I guess the only thing I have to show is that: $E(\varepsilon E(Y|X)) = 0$, but I'm having trouble doing this.
Am I going in the right track or is this completely the wrong approach to tackling this problem?
Comment: Substitute for $\varepsilon$ in $E(\varepsilon E(Y|X))$, and use the law of total expectation by conditioning on $X$
Comment: Substituting, I get $E((Y-E(Y|X))E(Y|X)) = E(YE(Y|X) - E(Y|X)^2)$. I don't see how I can use the law of total expectation to get anywhere useful.
Answer: $$E\Big((Y-E(Y\mid X))E(Y\mid X)\Big) = E\Big(YE(Y\mid X) - [E(Y\mid X)]^2\Big) $$
$$E\Big(YE(Y\mid X)\Big) - E\Big([E(Y\mid X)]^2\Big) $$
Now by the law of total (or is it iterated - I always forget) expectation, we have for the first term
$$E\Big(YE(Y\mid X)\Big) = E\Big[E\Big(YE(Y\mid X)\mid X \Big)\Big] = E\Big[E(Y\mid X)E(Y\mid X ) \Big] = E\Big([E(Y\mid X)]^2\Big)$$
so the whole expression equals zero.
Comment: How can you take the expected value of a product of random variables to be the product of expected values? What I'm trying to say is how do we know that $Y$ and $E(Y∣X)$ are independent of each other?
Comment: $Y$ and $E(Y\mid X)$ are not _unconditionally_ independent -but it doesn't matter. $E(Y\mid X)$ is a function of $X$. When we take its expectation _conditioning again_ on $X$, it goes out of the expectations operator, as a matter of basic properties of expected values, irrespective of what other variables may be present. In general, $E(Yh(Z)\mid Z) = h(Z)E(Y|Z)$, irrespective of the _unconditional_ relation between $Y$ and $Z$.
Comment: Using that property, it makes solving this question a lot more easier. Thanks! However, why did you tell me to substitute for $\varepsilon$? Wouldn't it be equally correct to do $E(\varepsilon E(Y|X)) = E(E(\varepsilon E(Y|X) | X)) = E(E(\varepsilon | X)E(Y|X))$?
Comment: I took the twisted route, you found the simpler. Bravo!

Covariance with conditional expectation


Method of Gradient Descent in Python

Question: So I'm running a simple algorithm for gradient descent in python, trying to find the minimums of functions.
My code is reasonably straightforward, I feel it is intuitive. I've tried with the simple example of a second order polynomial.
def s(x):
    return x**2

def t(x):
    return 2*x

def steepd(a, alpha, epsilon):
    b = a - alpha*t(a)
    while abs(t(a)) > epsilon:
        if t(b) ==0:
            return b
        else:
            a = b
            b = a - alpha*t(a)

         return b

   print(steepd(2,0.1,0.001))

x = np.arange(-10,10,0.01)
plt.plot(x,s(x))
plt.show()

I'm not getting anywhere near close to the minimum however, even by varying both alpha and epsilon significantly.
Can someone point out what the issue is?
Cheers.
Answer: Your code terminates only if t(a) is within epsilon of zero, so there's no way it would produce a value that violates this constraint unless your indentation is broken (as it is in your question body) and your code really looks like this:
def steepd(a, alpha, epsilon):
    b = a - alpha*t(a)
    while abs(t(a)) > epsilon:
        if t(b) ==0:
            return b
        else:
            a = b
            b = a - alpha*t(a)

        return b

Indentation in Python is important. Here, your while loop never runs more than once because of that return statement at the end and steepd is more or less just a - alpha*t(a). You'll need to properly indent the return statement for your code to function the way you want.

Method of Gradient Descent in Python


Show that $C_4$ is not an interval graph and every $C_n$ for $n$ $\ge 4$ is not an interval graph

Question: Show that $C_4$ is not an interval graph. Can you use the same argument to show every $C_n$ for $n$ $\ge 4$ is not an interval graph ?
This is my opinion :Label the vertices in $C_4$ as in figure

Assume that $C_4$ has an interval representation, because $a$ is not conneted to $c$, their interval must be disjoint, say the interval of $a$ is to the left of the one of $c$.
Since $b$ is adjacent to both both $a$ and $c$, it therefore must overlap the whole region between $a$ and $c$.
But the same also holds for $d$, so the intervals of $b$ and $d$ intersection (a contradiction).
Any graph that contains $C_n$, $n$ $\ge 4$
For notice that interval graphs are closed under taking induced subgraph : if we have an interval graph $G$, we can get an interval representation for any induced subgraph $G'$ of $G$ by taking one of $G$ and deleting all intervals of vertices in $G$ that are not in $G'$.
Is the opinion true ? High appriciated if someone can help me to prove this problem "that $C_4$ is not an interval graph. Can we use the same argument to show every $C_n$ for $n$ $\ge 4$ is not an interval graph ?"
Comment: Your general idea is right, but try to write it in terms of intervals. Note that if $A$ is an interval containing $b, c \in \mathbb{R}$ and $b < c$, then $A$ contains $[b,c]$.
Answer: Let $G$ be a general graph with vertices $q_i$ and interval representation with corresponding intervals $J_i$. Note the union of two intervals with a common point is an interval. Suppose $a_1 \in J_1$ and $a_k \in J_k $. Then if there is a path $q_1q_2\dots q_k$, then $[a_1,a_k] \subseteq\bigcup_{i=1}^k J_i$ and this is shown by induction.
Let $p_1,p_2,\dots,p_n \in C_n$ for $n \geq 4$. Assume $C_n$ has an interval representation with corresponding intervals $I_1, I_2, \dots, I_n$. We have two paths from $p_2$ to $p_n$ and they are $p_2p_3\dots p_n$ and $p_2p_1p_n$. Let $I_2 = [a_2,b_2]$ and $I_n = [a_n,b_n]$ and WLOG assume $b_2 < a_n$. Then pick $c$ with $b_2 < c < a_n$. As $\bigcup_{i=2}^{n} I_i$ amd $I_2 \cup I_1 \cup I_n$ are intervals containing $b_2$ and $a_n$, it must also contain $c$. By construction $c \in I_1$ and $c \in I_k $ for some $k = 3,4,\dots ,n-1$. But this is a contradiction as $p_1$ is not adjacent to any such $p_i$ for $i =3,4,\dots ,n-1$.


What is a Neapolitan 6th?

Question: In studying music theory I have heard the term Neapolitan 6th quite a few times, but I'm not quite sure what it is. What is a Neapolitan 6th and how is it used in a composition?
Answer: It is a Major triad built on the lowered 2nd scale degree. It's usually in first inversion, hence the "6th" part of the name. So if I'm in C-minor, the Neapolitan 6th (sometimes analyzed as N6 or bII6) would be a Db-major triad, probably with the F in the bass. They are chromatic harmonies, and their primary function is to go to V.
EDITED TO ADD: There is a very particular voice-leading involved also, usually the voice that has the b2 note moves directly to the leading tone in the upcoming dominant harmony. This is a rare example of a diminished melodic third being standard practice.
A good example is in beats 3 and 4 of the 3rd measure of the first movement of Beethoven's "Moonlight" Sonata. The piece is in c#-minor, and the 3rd measure starts on A (VI) and moves to a D Major chord in first inversion (the Neapolitan). The D-natural root  of that chord is chromatic to the key, and is what causes the harmony's somewhat exotic quality. It's an alteration of the diatonic d#-dim (iio) chord that could just have easily have been used here, but would have been far less dramatic. Either way, the next harmony is V (with some cadential 6/4 action thrown in for seasoning).
Comment: That's an interesting question. Technically, I suppose the lowered-2nd scale degree that primarily gives the chord it's unique quality is just natural to Phrygian and Locrian, and the weird thing would be to build a chord on the *raised* second scale degree. But a lot of music in Phrygian and Locrian (I'm thinking primarily of metal and industrial music) uses bII as a *dominant* function--a chord leading straight to i. Ultimately, once you're talking about modal stuff like that, the general functionality of common-practice chords is at best shifted substantially.
Comment: Mini extra question: Can a Neapolitan chord be applied to mode that has a minor second i.e. Phrygian and Locrian?
Comment: @EJP That isn't true. It is usually in first inversion, and the earlier in Common-Practice music we're talking about, the more necessary the inversion was, but by the 19-century root-position examples become more and more common.
Comment: Yeah, could be interesting. Perhaps clarify exactly what you mean by "applied"? Obviously a major chord built on a minor second scale degree makes sense in Phrygian and Locrian, it's precisely what you would expect. But the point of a Neapolitan chord in common-practice tonal music is that it's *unexpected*, so, in that sense, the feel of a Neapolitan can't be captured in modes in which it isn't chromatic. So what exactly are you looking for?
Comment: Great answer! Concerning this: "There is a very particular voice-leading involved also, usually the voice that has the b2 note moves directly to the leading tone in the upcoming dominant harmony. " I think it's weird in the sense that you (almost?) never see a diminished third. But it's not weird when you consider the general tendency to lead the voices to the nearest available tone (while avoiding forbidden parallels of course).
Comment: Another way of explaining the diminished third in the resolution: the root of the Napeolitan is a descending leading tone to the tonic, which has a tendency to descend into the tonic. But the Napeolitan (esp. Napealitan 6th) is also a subdominant, and thus has a tendency to progress to a dominant. This has an ascending leading tone at the raised 7th degree. Connecting the dimished 2nd to the raised 7th satisfies the need to descend the descending leading tone, and still resolve to the tonic by way of a "detour" via the ascending leading tone.
Comment: Yes, I think that's precisely the reason. It's a compromise between a very common melodic move in Phrygian, and standard raised leading tone of common practice music.
Comment: It is *always* in first inversion, hence the '6th' part of the name. If it isn't inverted, or in another inversion, it isn't a Neapolitan 6th. Bach is full of them. Mozart uses one very cleverly in *Cosi fan Tutte* which is of course set in Naples.
Answer: A Neapolitan sixth chord is a "chromatic" triad in first inversion that is built a half step above the tonic.  In C-major, the Neapolitan sixth chord is a D♭/F chord.  In a-minor, it is a B♭/D chord.  The chord is indicated as N6.
In harmony, the function of the Neapolitan sixth is to prepare the dominant, just like the subdominant or the supertonic chord.  We must remember that the term "half step" indicates a minor second in this case.  We must NOT write the chord as a C♯/E♯, A♯/Cx, etc.
The Neapolitan sixth can also occur after a German sixth chord.  A German sixth chord is one of the augmented sixth chords.  In C-major, the chord is known as A♭add+6 chord, with the notes A♭, C, E♭, and F♯.  If a German sixth chord resolves to the neapolitan, it can serve as a pivot chord to tonicize the Neapolitan as a tonic.  The A♭add+6 chord is enharmonically equivalent to A♭7.  In this case, the German sixth chord could lead as a secondary dominant to the Neapolitan, so the progression is: Ger. 6 - N6.
Comment: If Ab7 resolves to Db, it's not a true German 6th chord, just a dominant of the Neapolitan. But the Neapolitan can proceed to the German 6th exploiting the enharmonic ambiguity between these two chords, as in one of Schubert's favorite progressions: V7/N - N6/4 - Ger6 - V(6/4 - 5/3)

What is a Neapolitan 6th?


Finding recurrence relation given the generating function

Question: So I'm given the generating function $F(x)={1+2x\over1-3x^2}$
I'm supposed to find the recurrence relation satisfied by fn.
I managed to get it into 2 separate geometric series and derive $f_n = {5(3^n)-(-3^n)\over6}$
but can't derive it in terms of past values of $f_n$.
Help please, I have exam tomorrow!!!
EDIT: I just realised the $f_n$ I derived is wrong, ignore that.
Answer: $F(x)=\sum_{i\ge 0}a_ix^i$, where $a_0=1,a_1=2$ and $a_i=3a_{i-2}$ for $i\ge 2$.
Comment: Do you mind elaborating how you arrived at the answer? I have trouble expanding the function.
Comment: @huhehu: I multiplied the left hand of $(1-3x^2)\sum_{i\ge 0}a_ix^i=i+2x$ and equated coefficients.
Comment: Ah yes, I found it! Cheers!
Comment: @huhehu: It's really just the reverse of the process that you use to derive a generating function from a recurrence.


Is there a non-WYSIWYG-module that lets me use Media ver. 2 images with multiple image styles?

Question: I have a library of images that I access for reuse via the Media (ver. 2.0) Browser and attach to nodes using the file field. When I use an image inside a node, I want to indicate a specific Image Style (e.g. "Thumbnail", "Medium", etc.).  The out of the box setup of D7 let me specify one (1) image style to be used for a field in each display mode (i.e.  "Default" and "Teaser"). I want to be able to choose between image styles.
I may want to use the "Medium" style for the first image field in one node, and "Large" in for the first field in another.
After some googling, I've found some suggestions for doing this, but they're all based upon using WYSIWYG for image insertion, and I don't want WYSIWYG.
Looking at the answer to Multiple image styles, I see that I can do get access to different image cache versions of an image through either template file or hook_preprocess_node() - so I should probably be able to do this with a custom module that manipulates the image field render object during preprocessing.
However, before I embark upon writing such a custom module, I want to ask if this module (or something similar to it) already exists?  I have searched for it, but so far found nothing that does not use WYSIWYG.
Answer: As I can see Entity Image Style can be used with the Field collection module to achieve this task. However the Entity Image Style module is not yet a stable module. As per the logic this should achieve your goal.
Other resources:
Formatter Field module


How to return different types based on std::is_same check

Question: Consider the following code:
template<typename T>
T foo() {
    if (std::is_same<T, int>::value)
        return 5;

    if (std::is_same<T, std::string>::value)
        return std::string("bar");

    throw std::exception();
}

When called with foo<int>(), it throws an error cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'int' in return.
I know the solution is to use template specialization, but I'm asking whether it is somehow possible to keep the current mechanism with checking the type via std::is_same?
Answer: Both branches of an if must be valid at compile-time, even if one of them is never executed.
If you have access to C++17, change the ifs to if constexpr:
template<typename T>
T foo() {
    if constexpr (std::is_same<T, int>::value)
        return 5;

    if constexpr (std::is_same<T, std::string>::value)
        return std::string("bar");

    throw std::exception();
}

Before C++17, you will have to emulate this by using template specialisation:
template<typename T>
T foo()
{
    throw std::exception();
}

template <>
int foo<int>() {
    return 5;
}

template <>
std::string foo<std::string>() {
    return "bar";
}

If your real foo does more work than this example and specialising it would lead to code duplication, you can introduce a helper function which will encapsulate only the return/throw statements, and specialise that.
Answer: In pre-C++17 compiler, you can use tag dispatching to get what you need.
template <typename T> tag_t {};

int foo(tag_t<int> t) { return 5; }

std::string foo(tag_t<std::string> t) { return "bar"; }

template<typename T>
T foo() {
    return foo(tag_t<T>());
}


Time Signature Calculation

Question: How to determine the time signature?

I already got this question wrong from my quiz, and I'm studying for the final for this music theory class.
I understand there are
5 quarters notes
1 half note
10 eight notes
I was deciding between 12/8 and 6/8 due to the eight notes and eventually went for 12/8. Could someone help me with how to count this time signature?
Comment: It sounds like 3/4. All of the given options are wrong. ;) And so is the notation. Add two barlines.
Comment: @piiperiReinstateMonica  The question clearly states that this is a single measure.  Thus, 12/4
Comment: @piiperiReinstateMonica I suppose you mean "add three barlines."
Comment: @phoog Exactly! I was just checking that you're awake.
Comment: Presumably this is the bit of the test where you have to work out what the time signature is, whether it really makes sense to write it that way or not. It's an exercise in deduction. Next will come, 'How could this be better written?', in part b of the test. It's a computer multiple choice, there's no space to put "I wouldn't have done it that way".
Comment: I'd note further that breaking this into four sections does appear to be rhythmically pleasing, further supporting a 12/4 claim
Answer: One way to work it out - count the 8ths (quavers).
You get 24 of them, so that's not going to be right for 12/8, nor for 6/8.
So try again, count the quarters - now you get 12 of them.
That means it's certainly not going to be 4/4.
Even by process of elimination, therefore, it must be 12/4
… but you already just confirmed this for yourself - there are twelve crotchets (quarter notes), 12/4.
'scuse the hand-drawn…
Comment: This makes so much sense and thank you for the hand-drawn
Answer: Like in maths fractions, number wise, the top number tells 'how many', the bottom number tells 'of what'.
So, counting the whole bar, there are 12 crotchets.That gives you an answer.
And, since 12 should be divisible by 3, and written thus, as in 'lots of 3', that will work.
An explanation rather than a direct answer!
Comment: I kept going with the eighth notes and could not think about counting by quarter notes. This makes so much sense. Thank you very much
Answer: One good strategy for multiple-choice questions is process of elimination.  To apply that strategy here, look at the beaming of the eighth notes.
12/8 and 6/8 imply groups of three.  That is, they are "compound" meters.  The beaming does not reflect groups of three.  Similarly, the longer note values are not dotted, and there are no instances where a quarter note is grouped with an eighth note.  This is clearly not a compound meter, so we can eliminate those choices.
This leaves us with a choice between 4/4 and 12/4.  In 4/4, no more than four eighth notes should be beamed together, but here we have a group of six.  Without further analysis, we can eliminate 4/4, leaving 12/4 as the only possible answer.
At this point, we might notice that one of the facts given in the question is that the notation is described as one measure.  It looks like you're supposed to consider whether bar line have been omitted, but that's not actually what they're asking.  They present you with "a given measure," and all you have to do is add up the durations of the notes it contains.  This is the equivalent of three whole notes, six half notes, twelve quarter notes, or 24 eighth notes.
Thus, by two independent lines of reasoning, we arrive at the same answer: 12/4.
Comment: I do like a process of illumination - throwing light on the problem...
Answer: It's not 12/8 or 6/8 because the bar doesn't add up to either 12 or 6 eighth notes. It's not 4/4 because it doesn't add up to 4 quarter notes.   So it must be 12/4.
An unusual question.  Partly because it's so simple to answer by simple arithmetic.  (@Michael Lee, I'm afraid you badly need to revise your knowledge of basic notation!)
This sort of question is more typically about ADDING barlines, in which case the best answer, based on the note groupings (though the first 4 beamed 8ths are a bit suspect) would have been to make it 4 bars of 3/4.
Answer: You don't have to consider only the rhythm! The melody is also important to define the content and the sense of the phrase.
If we  look at the group of the 6 beamed eighth notes you can hear unambiguous a motif of 3/4 which is confirmed by the succeeding half  and fourth note.
The beginning of the phrase fits well in a 3/4 time with the underlying harmony, however it  isn't absolutely clear: This could be as well a 6/4 time.
Another appropriate and also possible solution would be to interpret the first half of the phrase  by a change of the time signature into 3 bars of 2/4 ... but this would result in a completely different texture.
Edit:
If this is a multiple choice, you have to choose 12/4 and surely not 12/8.
12/8 would be 4 x 3/8. There would be only 3 eight notes tied together (like 6/8 and 3/8 rhythms 12/8 is build by dotted quarter and dotted half notes, also a quarter and an eighth note, with other words the subdivision of 3/8 will always be visible!)
Comment: 3/4 is not one of the choices available for the answer.
Comment: I didn't understand the question as a multiple choice. In this case theres only 12/4 as possible solution.

Time Signature Calculation


Python boto - How can I get allocation id of elastic ip

Question: When I use boto(python sdk for aws) to assign elastic ip to my instance in vpc, it reported the following error:
    <Response>
      <Errors>
         <Error>
           InvalidParameterCombination
           <Message>You must specify an allocation id when mapping an address to a network interface</Message>
    </Error>
    </Errors>
    <RequestID>d0f95756-c36f-417a-9fa9-1158c4aa19e9</RequestID>
</Response>

But I found nothing about allocation id in ec2-medata.
Anybody know how can I get allocation id from API?
I already seen it in console:
try:
        conn = boto.ec2.connect_to_region(zone, aws_access_key_id='a-id', aws_secret_access_key='s-id',debug=2)
        conn.associate_address(allow_reassociation=True, public_ip=kw['ip'], network_interface_id=nid, dry_run=True)

Comment: try:
        conn = boto.ec2.connect_to_region(zone, aws_access_key_id='aid', aws_secret_access_key='sid',debug=2)
        if kw.has_key('type') and kw['type'] == 'elastic':
            conn.associate_address(allow_reassociation=True, public_ip=kw['ip'], network_interface_id=nid, dry_run=True)
        else:
            conn.assign_private_ip_addresses(allow_reassignment=True, network_interface_id=nid, private_ip_addresses=kw['ip'])
Comment: That's not readable - please add it to your question, formatted etc.
Comment: See code example here: http://engineerwithoutacause.com/amazon-ec2-deployment-with-boto.html
Answer: If you use get_all_addresses it should return a list of Address objects which have an allocation_id attribute associated with them.  The allocation_id will be non-None for any addresses that are associated with a VPC.
import boto.ec2
c = boto.ec2.connect_to_region('us-east-1')
addresses = c.get_all_addresses()
for addr in addresses:
    print('%s - %s' % (addr.public_ip, addr.allocation_id)

Does that help?


independent events (probability)

Question: Two people $A$ and $B$, one by one draw one ball each from a purse containing $5$ white and one red ball and then keep it aside, the person who gets the red ball wins the game, find the probability if $A$ wins?
Comment: Pls refer to https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: Please use Mathjax to render the math thank you.
Comment: Alright guys, will do , thank you XD
Comment: I am new here XD, I don't know what u mean by Mathjax and also I dont know how to post a question using that? :/
Comment: Wait, do they continue drawing balls until someone wins?
Comment: they continue untill a person gets a red ball
Answer: It may seem counter intuitive, but the answer is $\frac{1}{2}$. It's not hard to see with a little case work
$$P(A)=\frac{1}{6}+\frac{5}{6}·\frac{4}{5}·\frac{1}{4}+\frac{5}{6}·\frac{4}{5}·\frac{3}{4}·\frac{2}{3}·\frac{1}{2}=\frac{1}{2}$$
But I want you to think of this: let's say $A$ and $B$ play a different game, one in which they split the six balls three each. In this new game, obviously, the chance of $A$ winning is $\frac{1}{2}$, again. This is not a coincidence, these two games are pretty much the same.
In the original game, let's say the players continued to draw balls even after one of them got the red ball. Then at the end they are each left with 3 balls, and it basically becomes equivalent to the two players playing the second game.

independent events (probability)


I am getting a promise object in the output of a flask app I am working on. How can I get the value from the promise object?

Question: So basically, I am using fetch to get the data from my database. I wrote a few JS functions that will take effect once the user clicks on the like button. One of those functions will post the new data to the server (that is what it is intended to do later on but for now, I am just printing the output). The output from that function is a promise object that is being returned to the server in the form of a json object. How can I get my desired output which is the VALUE of that promise?
The JavaScript code:

The python/flask code:
@app.route('/postlikes/<string:post_name>', methods=["GET","POST"])
def postlikes(post_name):
    if request.method == "GET":
        post = Image.query.filter_by(post_name=post_name).first()
        # return "{'post likes':" + "'" + str(post.likes) + "'}"
        return {"post_likes":post.likes}
    else:
        print(request.json)

My desired output:
{'post_likes':1}

or
{'post_likes':'1'}

the output I am getting:
{'post_likes': '[object Promise]1'}

P.S the initial value of the likes on the post_likes is 0.
Comment: These calls here `let currentLikeNum = getLikeNumber()` are asynchronous (they are marked with the `async` keyword), and since you don't await them, you see the promise. Either wrap all of it in an async method, and await it, or use the `then` method to complete the promise chain
Comment: You really should have a `/postlikes//increment` endpoint that you call once, instead of doing 3 server requests when the button is clicked!
Answer: getLikeNumber() returns a promise because an async function always returns a promise.
The keyword async just makes your whole function one big promise that await other promises inside its body, crudely abstracted.
So when you write :
    let currentLikeNum = getLikeNumber() // currentLikeNum is a promise return
    fetch('/postlikes/'+postName, {
      method:"POST",
      body: JSON.stringify({
      post_likes:currentLikeNum+1  // currentLikeNum is a promise return converted to a string + "1"

So what you want is to either keep your function myFunction async and await your promise to keeps only the returns, like you already did with getLikeNumber()
Or with the old way :
getLikeNumber().then( res => {
    //do your post here with the res variable
})

But that would not be consistent with your previous function.
In any case I would suggest to read one tutorial on async/await VS .then/.catch to continue your project comfortably.
Have a nice day !


When to take left and right limit of equation?

Question: I have problems understanding when to take the left and right limit of an equation. For example,
according to my teacher, you have to take the left and right limit of this equation:
$$ \lim _ {x \to-2} = \ \frac{x}{x^2 + 8 \cdot x + 12}$$
but not this equation:
$$ \lim_{x\to 1} = \ \frac{x^2 - 1}{x^2 - 2 \cdot x + 1}$$
Can anyone explain to my why?
Comment: AFAIK there is no such thing like 'a limit of equation'. Additionaly I can't see an equation in your question. Could you, please, clarify?
Answer: Hint: $$x^2+8x+12=(x+6)(x+2)$$ and $$x^2-2x+1=(x-1)^2$$
and use that $$\frac{(x-1)(x+1)}{(x-1)^2}$$
and $$\frac{x}{(x+6)(x+2)}$$ and you have to compute the limit in both directions.
Comment: What I understand of this, is that you ALWAYS have to take the left and right limit?
Comment: Yes, this is right.
Answer: Both limits that you have there do not exit. The reason they do not exist is because their one-sided limits are not equal (that's how you prove whether a limit exists or does not exist). In fact, they're so-called infinite limits (they do not exist even as infinite limits):
$$
\lim _ {x \to-2} \frac{x}{x^2 + 8 x + 12}=
\lim _ {x \to-2}\frac{x}{(x+2)(x+6)}\implies\\
\lim _ {x \to-2^-} \frac{x}{(x+2)(x+6)}=+\infty,\ \lim _ {x \to-2^+} \frac{x}{(x+2)(x+6)}=-\infty\implies\\
\lim _ {x \to-2^-}\frac{x}{(x+2)(x+6)}\ne\lim _ {x \to-2^+}  \frac{x}{(x+2)(x+6)}\implies\\
\lim _ {x \to-2}\frac{x}{x^2 + 8 x + 12}=DNE.
$$
You do exactly the same procedure for the second limit:
$$
\lim_{x\to 1}\frac{x^2 - 1}{x^2 - 2x + 1}
\lim_{x\to 1}=\frac{(x - 1)(x+1)}{(x-1)^2}=
\lim_{x\to 1}\frac{x+1}{x-1}\implies\\
\lim_{x\to 1^-}\frac{x+1}{x-1}=-\infty,\ \lim_{x\to 1^+}\frac{x+1}{x-1}=+\infty\implies\\
\lim_{x\to 1^-}\frac{x+1}{x-1}\ne\lim_{x\to 1^+}\frac{x+1}{x-1}\implies\\
\lim_{x\to 1}\frac{x^2 - 1}{x^2 - 2x + 1}=DNE.
$$
So, you do have to consider the two one-sided limits of the second limit in its analysis because that's the way to answer the question about its existence. It does not exist as an infinite limit because the two one-sided limits do not equal the same type of infinity.


Manipulating React Slick classes with Tailwind CSS

Question: Is there any way to make this possible?
I have a project in Next 13 which is styled with Tailwind CSS.
The homepage has several React Slick sliders which I need to manipulate (margins, overflow...), and which look like this:

      <Slider {...settings}>
        {subcategoryItems.map((item) => (

           {CONTENT}

        ))}
      </Slider>

So I can't see HTML elements and classes (slick-slider, slick-list, slick-slide, slick-active...) of React Slick to change them directly by entering Tailwind CSS classes.
In the same folder of every component, I have {ComponentName}.module.css file.
And this is two ways that I have tried to access those React Slick classes via .module.css file:
1st attempt
*Component.jsx
import styles from "./{Componentname}.module.css";

<ul className={`${styles.sliderWrap} md:min-w-[500px] w-full`}>
   {Slider}

-First variant of targeting CSS classes:
*Component.module.css
.sliderWrapper .slick-slider .slick-list .slick-track{
    @apply my-[0] mx-[20];
}

-Second variant of targeting CSS classes:
*Component.module.css
.sliderWrapper .slick slider{
    @apply my-[0] mx-[20];
}

But it was not working, even after adding "!important":
@apply my-[0] mx-[20] !important;

Chrome dev tools were not showing these properties at all!
2nd attempt
*Component.jsx
import styles from "./{ComponetName}.module.css";

<ul id={`${styles.sliderWrap}`} className={`md:min-w-[500px] w-full`}>
    {Slider}

-First variant of targeting CSS classes:
*Component.module.css
#sliderWrapper .slick-slider .slick-list .slick-track{
    @apply my-[0] mx-[20];
}

-Second variant of targeting CSS classes:
#sliderWrapper .slick slider{
    @apply my-[0] mx-[20];
}

Also, both variants were not working, even after adding "!important":
@apply my-[0] mx-[20] !important;

And Chrome dev tools were not showing these properties at all.
3rd attempt
Added class to react-slick settings then tried to style via that class.
*Component.jsx
const settings = {
    className: "sliderWrapper"
}

*Component.module.css
.sliderWrapper .slick-list .slick-track{
    @apply my-[0] mx-[20];
}

4th attempt
Added class to a Component element via ClassName, and then tried to access slider classes via it like in previous examples, but it was not working.
*Component.jsx

    {Slider}

To be clear, I managed to manipulate these React Slick classes via "Styled Component", but my manager told me that I have to be consistent with technologies, and solve this with Tailwind CSS because it is possible.
I'm unsure if there is any way to solve this with a tailwind.config.s file. Any help is welcome Im stuck on this for the third day...
Answer: Let me answer to my own question because I have found solution.
At parent component build some class with which you can access to react-slick classes. For example:
<ul className={`${styles.sliderWrapper} md:min-w-[500px] w-full`}>
  <Slider {...settings}>
    {subcategoryItems.map((item) => (

       {CONTENT}

    ))}
  </Slider>

Then in .module.css file use that class and global selector :global to overwrite slick slider classes.
.sliderWrapper :global .slick-list .slick-track{
   @apply my-[0] mx-[20];
}


Calc 2: Integration by Parts w/ trig identities

Question: $$\int e^{3\theta}\sec^4(e^{3\theta})\tan^{11}(e^{3\theta})d\theta$$
I just want to make sure that I'm doing this correctly so that I can understand the material. I would also appreciate any tips or shortcuts for this type of problem!
So I started off with substitution:
$$x=e^{3\theta},\;dx=3e^{3\theta}d\theta,\;d\theta=\frac13\frac1xdx$$
To get:
$$\frac13\int\frac xx \sec^4x\tan^{11}xdx \Rightarrow
\frac13\int\sec^4x\tan^{11}xdx$$
Since $\tan^{odd}$:
$$u=\sec x,\;du=\sec x\tan x\;dx$$
$$\frac13\int\sec^3x\tan^{10}x(\sec x\tan x)dx$$
$$\frac13\int u^3(u^2-1)^5du$$
$$\frac13\int\sec^3x\tan^{10}x(\sec x\tan x)dx$$
$$\frac13\bigg(\frac{1}{14}u^{14}-\frac{5}{12}u^{12}+u^{10}-\frac54 u^8+\frac56 u^{6}-\frac14 u^{4}\bigg)+C$$
$$\frac{1}{42}\sec(e^{3\theta})^{14}-\frac{5}{36}\sec(e^{3\theta})^{12}+\frac13\sec(e^{3\theta})^{10}-\frac{5}{12} \sec(e^{3\theta})^8+\frac{5}{18} \sec(e^{3\theta})^{6}-\frac{1}{12} \sec(e^{3\theta})^{4}+C$$
Is this correct?
Answer: Your working is correct.  However you would get an easier integral by substituting $u=\tan x$, giving
$$\int\sec^4x\tan^{11}x\,dx=\int(1+\tan^2x)\tan^{11}x\sec^2x\,dx
  =\int(1+u^2)u^{11}du$$
and so on.