How to substitute a pattern in Makefile.am

Question: I have an application with several subdirectories, which I want to compile non-recursive. For this I have seperated all sorucefiles from the subdirectories into several variables, which I then use in the final collection of sources. Something like this:
GUI_SOURCEFILES = Gui/MainWindow.cc \
                  Gui/StatusBar.cc
...
foo_SOURCES = $(GUI_SOURCEFILES) \
              $(DATABASE_SOURCEFILES) \
              main.cc

Now however this forces me to write Gui/ for all gui sourcefiles and Db\ in front of all database files. I think it should be possible to create this prefix automaticall, but I cannot find a way to do this correctly. I tried the usual make way:
GUI_SOURCEFILES = MainWindow.cc \
                  StatusBar.cc
...
foo_SOURCES = $(GUI_SOURCEFILES) \
              $(patsubst %,Gui/%,$(DATABASE_SOURCEFILES)) \
              main.cc

But autotools will not compile this Makefile.am at all.
Is there a way to get autotools to do this for me?
Comment: @LiKao: Some traditional makefile constructs like suffix substitution also work in automake. However, I don't know a *prefix* method.
Comment: What about `$(addprefix Gui/, $(DATABASE_SOURCEFILES))`?
Comment: @dma_k: this has the same problem: `src/Makefile.am:12: addprefix Gui/, $(GUI_SOURCEFILES: non-POSIX variable name` `src/Makefile.am:12: (probably a GNU make extension)`. I think there must be a very specific autotools/m4 way to do this, but I have never used either to a great extend. All Makefile ways are probably out of question.
Comment: You issue is also mentioned in [this post](http://stackoverflow.com/questions/4167887). I am surprised as well. General advise is: update `autotools` to latest version and make sure that `make` is the only one and it is GNU make. Looking [here](http://gcc.gnu.org/svn/gcc/branches/cilkplus/libgomp/Makefile.am) and [there](http://caca.zoy.org/browser/libpipi/trunk/ThePimp/Makefile.am?rev=2940) I think you have an environment issue. Are you running Linux?
Comment: @dma_k: Yes, I am on kubuntu 11.4 using autotools version 2.67 from 2010. Seems rather recent to me. There is no other make installed, so this should not confuse autotools. I think with the examples you linked to the parts where `addprefix` or `patsubst` are used are passed to the final Makefile and not processed by autotools.
Answer: There is no way here, all filenames must be available at automake time, and that precludes certain make-time like functions (non-portable at that).
Comment: automake could expand *$(addprefix...)* provided the argument is constant and known at AM time, just like it does with *include*, but alas, it does not do it currently, which leads to "if you can cook up a patch, you can try submitting".
Comment: The filenames are fully available. I just don't want to explicitly add the directory prefix each time. That is all. I guess I am out of luck with autotools for this.


Calculating sampling weights when I have sampled from a known population

Question: I have a very large data (100+ million records)and I am estimating a complex random coefficients model and I can only comfortably use a million or so records. Iam interested in details in time and space so I have sampled on these attributes so that each  space-time cell has 10 records. Consequently some cells are overrepresented compared to the population and some are underrepresented. I also have several other variables -all of them categorical and because I can compare the obtained sample with the know frequencies in the population I can evaluate the under and over representation  of these types too.
I want to use sampling weights to rebalance the sample as in the population on a number of attributes simultaneously. Can I use a model whether the dependent variable is in sample or not and predictor variables based on type to derive these weights?
Any help much appreciated.
Comment: How many attributes did you sample on? How many are going to be part of the model.?
Comment: I think I have at the minimum of  4 categories by 2 by 2  if I take interactions into account but this could increase considerably if I take into account time on a month by month bases as  a main effect it would be 12 months by 12 year. So if I took into account all of this it would be with interactions  4 * 2 *2 *12 * 12 - but I have a lot of records! Thanks for answering.
Comment: Describe the random coefficients model.  From what you've described so far, your sampling method would make difficult any analysis.  For example if you have  repeated observations on individuals, so that coefficients vary with individual,  I'd think that a valid sampling method would have to start with a sample of individuals.
Comment: I am quite comfortable with the problem as listed - the level 1 units are not repeatedly measured - they are however repeated measures of higher level units - but I think I know how to calculate higher level weights and how to use them. What i was looking for was help on the fixed effects ts and how to estimate suitable weights that will overcome the mis-representation of the level 1 units. Thank for taking the time to resdpond
Comment: What was the sampling design for the higher level units?
Comment: I have all the higher level units - there are 5 levels of them and they are all there. However the level 1 units have been sampled to a maximum number per week in each of the lowest higher level so that in some periods - the boom times - this represents a lower sampling ratio than in others.
Answer: I'll answer your question based on the information you've already provided. I don't see how these weights can be used in a random effects model, but that's not what you asked for.
1- Constructing sampling Weights
The cells in which you selected 10 observations each are known as   "sampling strata". You have 4 x 2 x 2 x 12 x 12 = 2,304 of them. Number  for convenience from $i = 1\ldots 2304$. You know $N_i$,
    the number of records in cell $i$.  Then the probability of
    selection for records  in cell $i$ is $f_i=\dfrac{10}{N_i}$, and the
    sampling weight is
$$
w_i = \frac{1}{f_i} =  \frac{N_i}{10}
$$
These are the "design" or "sampling" weights.
2-  Balancing on other categorical variables  known for the entire population.
The standard method for doing this is variously known as "raking", "ratio raking" or "sample balancing".  with the first common in the survey literature.  The technique is an application of interative proportional fitting (IPF). The commands take the design weights and alter them so them that the resulting weighted totals for categories match the known totals.
References:
L Anderson and R Fricker "Raking: an important and often overlooked survey analysis tool"
http://faculty.nps.edu/rdfricke/docs/RakingArticleV2.2.pdf
Battaglia, Michael P, David Izrael, David C Hoaglin, and Martin R Frankel. 2004. Tips and tricks for raking survey data (aka sample balancing). Abt Associates 4740-4744.
http://www.amstat.org/sections/srms/Proceedings/y2004/files/Jsm2004-000074.pdf
Software:
SAS macros
http://abtassociates.com/Expertise/Surveys-and-Data-Collection/Raking-Survey-Data-%28a-k-a--Sample-Balancing%29.aspx
Stata:

ipfraking (Stas Kolenikov)   "findit ipfraking"
survgwt rake (Nicholas Winter) "ssc install survwgt"

R package survey (Tom Lumley) https://cran.r-project.org/web/packages/survey/index.html
Comment: Thanks that is really helpful -on the use of weights in multilevel modelling see http://support.sas.com/documentation/cdl/en/statug/66859/HTML/default/viewer.htm#statug_glimmix_examples23.htm
Comment: You're very welcome.  Since you've found the answer useful, please "accept" it.  And thanks for the SAS link;  I hadn't seen it and I like the simulation.  Stata has added similar survey weighting options to most of  its multilevel mixed effects commands see, e.g.. p. 21 of  http://www.stata.com/manuals14/memeglm.pdf.
Comment: And for more completion MLwiN also has this weighting facility :  http://www.bristol.ac.uk/media-library/sites/cmm/migrated/documents/weighting.pdf


opendkim - how to take action on incoming messages that should be signed?

Question: How can I configure opendkim to quarantine or reject (incoming) unsigned messages that instead should be signed because a key is present in the DNS?
opendkim.conf(5):
On-NoSignature (string)
   Selects the action to be taken when a message arrives unsigned.
   Possible values are the same as those for On-BadSignature.
   The default is accept.

I guess this is not the correct option to set, because it does not specify that the message was supposed to be signed (key present in the DNS), it just seems to refer to each "generic" unsigned message. (Am I wrong?)
Comment: It's not a standard way. Better to use DMARC (`opendmarc` milter), it was made *exactly* to solve the general problem you have in mind. DMARC is used by domain owner to tell you that it expects message to be either DKIM-singed or SPF-transferred, and in both cases to check the `From` header spoofing. Presence of DKIM records is not itself an obligation that all messages will be DKIM-signed.
Comment: No DMARC record = "I allow my outgoing emails spoofed". Same for DMARC `p=none` record. If some domain has DKIM record, this means they already started to walk in a right direction, don't punish them for that! Maybe they got stuck implementing opendkim or other such software.
Comment: I can use DMARC with my own domains, but 90% of incoming emails have no DMARC set in their DNS, so in the meantime, I need to find a way to quarantine (or to tag, at least) messages with no DKIM signature that should instead be signed, for later review. Any ideas?
Comment: You are absolutely right, but I just need a way to put those unsigned emails in the users' junk folder, so they will be able to review them and in case restore false positives. Of course DMARC would take precedence, but to my experience, most of unsigned emails (with DKIM in the DNS but no DMARC set) are actually junk.
Comment: ...and if somebody, a normal user, uses a third party mail relay/webmailer for perfectly legit emails under this domain you will filter it out as SPAM. Do you see the error here?
Answer: Using the On-NoSignature parameter is only for taking an action when no signature is present and will not achieve your goal of quarantining messages that are not signed but have DKIM records.
Your goal is likely not achievable for general incoming mail because the DKIM TXT record is configured per key with a unique selector in the host of the DNS record. Therefore a receiving server has no way to determine whether the domain an unsigned email is from expects there to be a DKIM record when being sent by the sending server (there may be multiple servers sending on behalf of a domain).


Multiple eventListener and innerHTML data text not working well?

Question: I am trying to create an interactive map with svg paths from what you can see in my codepen(at the end) js code every time I am clicking a country I would like to display in a modal the name of their force, year and country name, until now I added to UK and France an eventListener -click-
So when I am clicking one of them the eventListener call the function text which should take the arguments from an array which is in my code and pass it to the parameters of the function which contain 3 getElementById with the innerHtml.
The problem is that only the one of France eventListener pass the text data in the modal which appear at the center of the page and work but the strange thing if I will remove the evetListener of it in the js file the one of the UK start to work and pass the text data after i reload the page.
Plese have a look on my codepen(at the end) click on both countries which their Id's have eventListeners(click) in javascript but only the text of the last eventListener(France) in js will work.
So the main point is that I would like to click the countries and display different informations about them by creating different eventListeners, maybe is wrong to do it like this but I am very new to js and untill now I cannot go deeper maybe.
codepen
For a first look my js code here:
<code>     //Variable and eventListener 1
var RoyalAirForce = ["Royal Air Force", "1 April 1918", "United Kindom"];

document.getElementById("gb-gbn-5").addEventListener("click",
 text(RoyalAirForce[0],RoyalAirForce[1],RoyalAirForce[2],RoyalAirForce[3])

);

//Variable and eventListener 2 (**Only this one is working, when removed the other one start to work**)
var France = ["France","France2","France3"];

document.getElementById("fr-7").addEventListener("click",
 text(France[0],France[1],France[2])

);

//Functions which should pass parameters
function text(param1, param2, param3){

  document.getElementById("name").innerText = param1;
      document.getElementById("founded").innerHTML =param2;
  document.getElementById("country").innerHTML = param3;

}
</code>
I forgot to tell that the modal will appear if you click anywhere on the page but will have the same informations I want to have different when I click different countries.
Answer: Vanilla Javascript does handle arguments being passed into eventListener call functions.  Basically the event listeners for GB/FR were never being called, only the btn.onclick to display the modal was being called.  A work around is to define a new variable / function which calls the function you want with its parameters. Replacing the following fixes your problem:
<code>document.getElementById("gb-gbn-5").addEventListener("click",
    gbnFunc = function({text(RoyalAirForce[0],RoyalAirForce[1],RoyalAirForce[2])}
);

document.getElementById("fr-7").addEventListener("click",
    frFunc = function(){text(France[0],France[1],France[2])}
);
</code>
Comment: Why are you assigning to a variable in the callback argument to `addEventListener`? And in your first function, you're missing the argument list of the function.
Comment: This one is working, thank you just forgot a ")" in the second line of code near function, can you plese tell me why this one is working and mine no?


Proving $\lVert x \rVert_3$ is smaller than euclidean norm

Question: Is there a simple way to show that $\lVert x \rVert_3\leqslant \lVert x \rVert_2$ for vectors in $\mathbb{R}^2$? I've used the result in another problem but can't figure out where to get it from.
Answer: Let's look at general $p<q$. Since the inequality
$$ \lVert x \rVert_p \geqslant \lVert x \rVert_q $$
is homogeneous (i.e. it is unchanged by $x \mapsto \lambda x$ for scalar lambda), we can assume $\lVert x \rVert_p = 1$ (the inequality's trivial for $x=0$, of course). Therefore every component, $x_i$, of $x$, satisfies $\lvert x_i \rvert<1$, so $\lvert x_i \rvert^{q-p} \leqslant 1 $. Hence
$$ 1= \lVert x \rVert_p^p = \sum_{i} \lvert x_i \rvert^p \geqslant \sum_{i} \lvert x_i \rvert^q = \lVert x \rVert_q^q, $$
because we multiplied each term by something that is at most $1$.


lp is not working in a bash script

Question: I have a test script that contains the following:
lp -d HP ~/cap/alpha/error

HP is a designated printer on my wireless network and ~/cap/alpha/error is the full file path to the file containing the report from a python unit test.
The command works from the terminal window but not from the script called test.
I can't figure out why this is not working?
Comment: Are you using `lp` with its full path from inside the script or just `lp`?
Comment: Replace `~` with `/home/$USER`
Comment: there is a standard unix command named `test`. Get in the habit of making your test scripts with names like `myTest`, or `testR` to eliminate a whole class of debugging problems. ALSO, please be more specific about "does not work". Good luck.
Comment: Thanks I got it working.
Answer: How to pipe stdout while keeping it on screen ? (and not to a output file) (answer by jilliagre):
echo 'ee' | tee /dev/tty | foo

This answer worked for me as follows:
$ python3 "mytest.py" | tee /dev/tty/ | lp -d brother

printing to both my terminal and my printer.
Comment: With a bit more rep, [you will be able to flag duplicate questions like this](https://stackoverflow.com/privileges/comment). Until then, posting links as answers is not really ideal, and they will generally be deleted.

lp is not working in a bash script


How to use a 61-keys digital piano?

Question: Yesterday I bought a Casio CTK-1200 keyboard. It was listed as a digital piano on Amazon, but it is really a keyboard I guess. Anyway, when I pressed couple keys it didn't really sound like the sound of a real piano.
The problem is that I've never used a keyboard before or learned music. So I'm a COMPLETE beginner and I have absolutely no idea how and where to start learning. I can't afford a teacher of course since I'm a poor student, so I need to learn alone. My main purpose is to learn how to play piano. So I bought this cheap keyboard to learn how to play in general for one year and then probably upgrade to a decent digital piano.
I tried Google and YouTube and then I found this; however it assumes having an 88-kes piano. But I only have 61 keys, so I'm not sure what to do.
I also have no idea what chords, tempo, rhythms, etc. are.
My question:

Can you please give me good places to start learning? Tutorials ... etc? Or even proper Google terms since I'm not a native English speaker.
Also a tutorial that demonstrates the features of a keyboard like mine or a digital piano.
Comment: You don't need a full 88 keys to get started with basic skills.  For example Twinkle Twinkle Little Star played in the lesson you linked to - could be played on a keyboard with only ten keys.  Most of the beginning lessons will use less than the 61.  Your 61 keys is like a slice out of the center of the 88 keys so you will be missing the lowest and highest notes but won't need those in the beginning.  It looks to me like you found a good place to start learning on YouTube.  That video even links to a music theory tutorial.  I would start with those YouTube lessons if I were you.
Comment: I'm guessing it still has the ABC [Auto Bass Chord] switched on, so the bottom maybe 12 notes will play bass &/or chords when you press them. Have to figure out from the manual how to switch it off. Start at http://www.casio-intl.com/asia-mea/en/emi/standard/ctk1200/spec/ if you don't have the manual
Comment: @RockinCowboy aha! Then that is why the sound sounds different when I press the left most key and then compare it to the sound of the left most key from that video. So I'm missing those keys then.
Comment: @Tetsujin I'm not sure what you mean because I'm a complete beginner. But I found that the left most key is the C note.
Comment: My last comment still stands - if the lower notes make a different sound, you have to figure out how to switch off the ABC
Answer: I will aim at the original question: How to play things on a shorter keyboard. The positioning of the keys for various sizes of the keybed is the following (click to enlarge):

(Note that some 73 or 76 keyboards can be slightly shifted.the) That's how you should position your music on the keyboard. The red key is "the middle C" (I made it C3 here, but it's commonly known as C4, and also as C1 on some countries, it's also C1 in LilyPond):

As other say, you likely won't miss the outer keys. If you missed them:

For the high notes (ottava 6), there's not much you can do. Only if it's an isolated figure that is only played there, you can simply shift it by one ottava down.
For the low notes (ottava -1 and 0), you mostly play only bass notes there, and frankly, not many people notice if you play them in the lowest ottava of your keyboard. I mean, you can shift the lowest notes up by 1 ottava in most cases.
Comment: @Mr.Boy Ah, probably yes. Well, it's the C1 in my country, so it confuses me always. I'll redo the picture.
Comment: @Mr.Boy Ok, I made a remark that "you never know which C is C4", I think it should be fine now.
Comment: this is helpful indeed, because I thought my keyboard starts with note A!
Comment: @JackTwain It is possible that it's shifted by couple keys, especially for the 6-ottava (73 to 76 keys) it's quite common. But according to images I checked on the internet, your Casio CTK-1200 starts with C1 as I indicate here.
Comment: Isn't middle C C**4**?
Comment: Well my keyboard _does_ have C3 as middle C but I don't think this is normal - it got me very confused trying to figure out my vocal range!
Comment: @Mr.Boy you could try to use something like https://play.google.com/store/apps/details?id=com.bork.dsp.datuna to determine which key actually produces which sound. For vocal ranges, it's okay-ish to get an idea, but whether you can actually sing the outermost tones that äpp shows your vocal chords are able to produce is another question ;) But it at least gives you an idea.
Comment: Many 61-key keyboards have controls that can set them to play the pitches shown, or an octave up, or an octave down.  When configured an octave up, they can reach all the upper notes of an 88-key piano (but not the lower notes).  When configured an octave down, they can reach all but the bottom four keys (which sound like "mud" on all but the best pianos).  They can thus handle a wide range of music unless it uses high and low notes simultaneously.
Comment: @supercat Sure, but not both ways at once, right? :)
Comment: Middle C is `c'` in LilyPond not C1.
Answer: The number of keys is not everything.
From the product website it is very questionable if CTK-1200 has velocity sensitive keys (nothing is written about) and also looks like it does not have any pedals even between optional parts. Your expression will suffer significantly with such a keyboard regardless of the number of keys.
Thinking positively, maybe the keyboard can be a safe, cost efficient way to check if you actually like playing piano enough. The number of keys probably does not matter for that. After a year at most, probably earlier, the teacher will probably suggest you to buy a more high end instrument.
Comment: For the record, the OP says the question asker cannot afford a teacher.

How to use a 61-keys digital piano?


pip install cssselect Weird Error

Question: I need help with the following error message below.
Thanks,
Mittervi.
<code>Username-MacBook-Pro:~ usernameremoved$ pip install cssselect
Collecting cssselect
  Using cached cssselect-0.9.1.tar.gz
Installing collected packages: cssselect
  Running setup.py install for cssselect
    error: could not create '/Library/Python/2.7/site-packages/cssselect': Permission denied
    Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/86/t2qqsky97xzgsl4kvhgsr1jh0000gn/T/pip-build-DP_x6t/cssselect/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/86/t2qqsky97xzgsl4kvhgsr1jh0000gn/T/pip-psclw0-record/install-record.txt --single-version-externally-managed --compile:
running install

running build

running build_py

creating build

creating build/lib

creating build/lib/cssselect

copying cssselect/__init__.py -> build/lib/cssselect

copying cssselect/parser.py -> build/lib/cssselect

copying cssselect/tests.py -> build/lib/cssselect

copying cssselect/xpath.py -> build/lib/cssselect

running install_lib

creating /Library/Python/2.7/site-packages/cssselect

error: could not create '/Library/Python/2.7/site-packages/cssselect': Permission denied

----------------------------------------
Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/86/t2qqsky97xzgsl4kvhgsr1jh0000gn/T/pip-build-DP_x6t/cssselect/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/86/t2qqsky97xzgsl4kvhgsr1jh0000gn/T/pip-psclw0-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/86/t2qqsky97xzgsl4kvhgsr1jh0000gn/T/pip-build-DP_x6t/cssselect
</code>
Answer: I fixed it using.
sudo pip install cssselect

pip install cssselect Weird Error


Slow speeds on Raid 10?

Question: I'm getting slower than what I would have expected on an external raid box (https://www.scan.co.uk/products/4-bay-icy-box-ib-rd3640su3-external-raid-system-for-35-sata-hdd-with-usb-30-plus-esata-host)
I have connected via Sata on a sata card (https://www.scan.co.uk/products/lycom-pe-130-port-multiplier-aware-2x-sata-iii-6gbps-low-profile-pcie-20-host-adapter) connected to a 1x PCIe slot. I was thinking this was the bottleneck as im capping out at 250MB/s no matter if im using Raid 0, Raid 5 or Raid 10.
I tried connecting over usb 3.0 to make sure that its not the PCIe slot that is the bottle neck but im getting the same speeds.
Is this normal, is there anything i can check?
with 4x 2TB barracua 7200rpm drives I was expecting more like 500-600MBS

RAID 0 - SATA

RAID 5 - SATA

RAID 10 - SATA

RAID 10 - USB

RAID 0 - USB

Copying from SSD to Raid 10 SATA
Answer: With 4x 2TB barracua 7200rpm drives your measured speed is excellent in RAID10.
Your expected values for RAID 0 in a best-case scenario, but still there is some clear limitation preventing your array to get more speed. You should of had 400MB/s at minimum.
Note that the SATA card you linked was not designed for RAID, therefore it may be limited.
Also, on USB 3 you will never hit specified speeds, there are many factors that can limit them. You should test RAID 0 with USB 3, though. You might get more speed.
If you want to use RAID 0, you should get a SATA adapter that actually supports 4 ports in any RAID configuration and you should have no limitation and make the RAID directly from the adapter, not from the OS.
Otherwise, RAID 1 speed is fine. If you want to keep RAID 1, keep it as-is. You can't get more speed out of that one.
Comment: Thanks for the advise, Ill wipe the array again and test on USB three, if thats expected for RAID 10 I may end up using that so I have a backup of my virtual machines, the array is primarily used for that. Thanks
Comment: Yes, in RAID1 / 10 you get max double the speed of a single drive. But do the USB RAID 0 test, it would be interesting to see how much it can handle on your system.
Comment: I have uploaded a test of Raid 0 on USB 3, seems a bit slower than SATA, CPU is at about 10% during the test. Just wanted to test for completeness
Comment: Just uploaded a pic copying from SSD to RAID 10 on sata, this is going at 472 MB so its certainly capable of faster speeds!
Comment: That can be cached writing. Use HD Tune to test read speeds (or even write speeds if the drives are empty).

Slow speeds on Raid 10?


Fisher information matrix of two parameter exponential distribution

Question: Is it possible to find the Fisher Information matrix of the two parameter (scale and  location) exponential distribution?
Any hint?
Answer: Adding the location parameter $\mu$ in the derivation in https://stats.stackexchange.com/a/263124/14346 and modifying the change of variable as $z=\frac{x-\mu}{\sigma}$, you can show that the information matrix  of for any location-scale distribution is of the form:
$$
I(\mu,\theta) = \frac{1}{\sigma^2} K_f
$$
where $K_f$ depends on the distribution.


How do I change a field with hook_node_presave()?

Question: In Drupal 7, I was using hook_node_presave() to update some hidden fields in a node.
function mymodule_node_presave($node){
    if ( CONDITIONS ) {
        $node->field_fieldname['und'][0]['value'] = importantfunction();
    }
}

In Drupal 8 I cannot do the same thing. Looking into the object I tried this:
function mymodule_node_presave($node){
    if ( CONDITIONS ) {
        $node->values['field_fieldname'][0]['value'];
    }
}

It won't work though. I am aware that a lot have changed in Drupal 8 and I am studying it, but I did not find an answer to this yet.
Answer: A bit outdated but still a great resource:
http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet
Also the documentation on drupal.org: https://www.drupal.org/node/1795854
In short, fields are lists of objects that use property and array access magic methods to simplify reading and writing values to them:
// Set a value, the field class will decide what to do with it, usually write to the primary property...
$entity->field_fieldname = importantfunction();

// The default property is often called value, but for reference fields, it is target_id, text fields also have a format for example
$entity->field_fieldname->format = 'full_html';

// By default, you access delta 0, you can also set other deltas.
$entity->field_fieldname[1] = importantfunction();

// You can also append a new item, without hardcoding the delta.
$entity->field_fieldname->appendItem(importantfunction());

// Note that when accessing fields, you must always specify the property:
print $entity->field_fieldname->value;
print $entity->field_fieldname[1]->value;

// What basically happens internally for the above is:
$entity->get('field_fieldname')->get(0)->get('value')->getValue();

Comment: That's much better!
Answer: Probably late here but if anyone is still looking then:
function mymodule_entity_presave(EntityInterface $entity){
    $entity->set( 'field_fieldname',importantfunction() );
}

Answer: I don't know if this is a best practice, but I've come to this solution:
function mymodule_node_presave(EntityInterface $node){
    $node->field_fieldname->set(0, importantfunction() );
}

Answer: This is a very late answer.
With \Drupal\node\NodeInterface interface, I'm using that snippet to achieve your needs :
/**
 * Implements hook_node_presave();
 *
 * @param \Drupal\node\NodeInterface $node
 */

function module_name_node_presave(\Drupal\node\NodeInterface $node) {
    if($node->get('field_name')->getString() != 'search') {
        $node->set('field_name', 'new field value');
    }
}

Comment: This does not work


How to add discount field to add divs script?

Question: this is what i have so far.
https://jsfiddle.net/thvinic/0g8pnqk2/
I would like an input field to add the discount and it returns the discount value in

var total = $('.somar').get().reduce(function(tot, el) {
    var numero = el.innerHTML.split('.').join('').split(',').join('.');
    return tot + Number(numero);
}, 0);
$('#resultado').html(total.toLocaleString(undefined, {minimumFractionDigits: 2}));

500

1.000

1.000

tank's for helps! ^^
Answer: I would recommend you to try on your own and ask for help with specific issues or errors you encounter along the way.
Here is your solution:

Added a input field with the id discountInput is added to enter the
discount value.
Added a button with the id calculateDiscount is added to trigger the
discount calculation. When the button is clicked, it retrieves the discount value from the input field and subtracts it from the total.

 $(document).ready(function () {
        var total = $('.somar')
            .get()
            .reduce(function (tot, el) {
                var numero = el.innerHTML.split('.').join('').split(',').join('.');
                return tot + Number(numero);
            }, 0);

        $('#resultado').html(total.toLocaleString(undefined, { minimumFractionDigits: 2 }));

        $('#calculateDiscount').click(function () {
            var discountValue = parseFloat($('#discountInput').val() || 0);
            var discountedTotal = total - discountValue;

            if (discountedTotal < 0) {
                discountedTotal = 0;
            }

            $('#discount').html(
                'Discounted Total: ' + discountedTotal.toLocaleString(undefined, { minimumFractionDigits: 2 })
            );
        });
    });

500

1.000

1.000

    Enter Discount:
    <input type="number" id="discountInput"/>
    <button id="calculateDiscount">Calculate Discount</button>

Hope this helps!
Comment: you were amazing my friend! it was exactly what I needed!


CreateProcess error=206, The filename or extension is too long when running gwtCompile

Question: My application is a springboot gradle application. Part of my application involves legacy gwt compile using gradle. It works fine but today when I run the below gradle task, it shows CreateProcess error=206, The filename or extension is too long.  What might be went wrong? as it worked before. Any suggested changes to the code below to resolve this issue?
    task compileGwt(dependsOn: classes, type: JavaExec) {
    //ext.buildDir = "${project.buildDir}/resources/main/static"
    ext.buildDir = "${project.rootDir}/src/main/webapp"
    //ext.buildDir = "${project.buildDir}"
    ext.extraDir = "${project.buildDir}/extra"
    ext.generatedDir = "${project.buildDir}/generated"

    inputs.source sourceSets.main.java.srcDirs
    inputs.dir sourceSets.main.output.resourcesDir
    outputs.dir buildDir

    // Workaround for incremental build (GRADLE-1483)
    outputs.upToDateSpec = new org.gradle.api.specs.AndSpec()

    doFirst {
        file(buildDir).mkdirs()
        //classpath.each { println it.name}
    }

    main = 'com.google.gwt.dev.Compiler'

    classpath {
        [
                sourceSets.main.java.srcDirs,           // Java source
                sourceSets.main.output.resourcesDir,    // Generated resources
                sourceSets.main.output.classesDir,      // Generated classes
                sourceSets.main.compileClasspath,       // Deps
        ]
    }

    args =
            [
                    'com.company.application.UI', // Your GWT module
                    '-war', buildDir,
                    '-logLevel', 'INFO',
                    '-style', 'DETAILED',
                    '-localWorkers', '2',
                    '-compileReport',
                    '-gen', generatedDir,
                    '-extra', extraDir,
                    '-draftCompile' // Speeds up compile with 25%
            ]
    maxHeapSize = '1024M'

}

war.dependsOn compileGwt
war {
    from compileGwt.buildDir
}

Below is the updated build.gradle with pathingJar, when I run compileGwt, it gives error saying:Could not find or load main class com.google.gwt.dev.Compiler
apply plugin: "build-app"
apply plugin: 'war'
apply plugin: 'java'

dependencies {

    compile("javax.validation:validation-api:1.1.0.Final")
    compile("javax.validation:validation-api:1.1.0.Final:sources")
    compile("net.sourceforge.javacsv:javacsv:2.0")

    compile("org.springframework.boot:spring-boot-starter-security")
    compile("org.springframework.security:spring-security-ldap")
    compile("org.apache.directory.server:apacheds-server-jndi:1.5.5")
    compile("org.springframework:spring-web")
    compile("com.fasterxml.jackson.core:jackson-databind")

    compile("javax.servlet:javax.servlet-api:3.1.0")

    compile("com.google.gwt:gwt-user:2.5.1")
    compile("com.google.gwt:gwt-servlet:2.5.1")
    compile("com.google.gwt:gwt-dev:2.5.1")
    compile("com.google.gwt.inject:gin:1.5.0")

    compile("com.googlecode.mvp4g:mvp4g:1.4.0")
    compile("com.googlecode.mvp4g:mvp4g:1.4.0:sources")

    compile("com.sencha.gxt:gxt:3.0.1")
    compile("com.sencha.gxt:gxt:3.0.1:sources")

    compile("org.atmosphere:atmosphere-gwt-client:1.1.0.RC5")
    compile("org.atmosphere:atmosphere-gwt-server:1.1.0.RC5")
    compile("com.fasterxml.jackson.datatype:jackson-datatype-hibernate4:2.1.2")
    compile("org.bouncycastle:bcpg-jdk16:1.46")
    compile("org.jsoup:jsoup:1.7.2")
    compile("org.eclipse.jetty:jetty-continuation:9.3.5.v20151012")
    compile("org.springframework.boot:spring-boot-starter-aop")
    compile("com.googlecode.lambdaj:lambdaj:2.3.3")
    compile("org.apache.poi:poi:3.9")
    compile("org.apache.poi:poi-ooxml:3.9")
    compile("commons-fileupload:commons-fileupload:1.3.1")
    compile("org.springframework.security:spring-security-core:4.0.3.RELEASE")
    compile("com.google.guava:guava:18.0")
    compile("com.google.guava:guava-gwt:18.0")
    compile("org.springframework.integration:spring-integration-core:4.2.4.RELEASE")
    compile("org.samba.jcifs:jcifs:1.3.3")
    compile("org.springframework.integration:spring-integration-file:4.2.4.RELEASE")
    compile("org.springframework.integration:spring-integration-ftp:4.2.4.RELEASE")
    compile("org.springframework.integration:spring-integration-sftp:4.2.4.RELEASE")
    compile("org.springframework.integration:spring-integration-flow:1.0.0.RELEASE")
    compile("org.springframework.integration:spring-integration-java-dsl:1.1.0.M1")
    compile("org.atmosphere:wasync:2.1.2")

    compile libs.quartz
    compile libs.spring_jms
    compile libs.spring_jpa
    compile libs.jdbc_sybase

    runtime files("src/dist/conf")
    runtime files("src/dist/env/local")

    configurations {
        all*.exclude group: '', module: 'servlet-api'
    }
}

task createDirs << {
    sourceSets*.java.srcDirs*.each { it.mkdirs() }
    sourceSets*.resources.srcDirs*.each { it.mkdirs() }
    webAppDir.mkdirs()
}

task initProject << {
    File oldSource = file("./src")
    File tmpSource = file("./tmp")
    tmpSource.mkdirs()

    oldSource.listFiles().each { File f -> f.renameTo new File(tmpSource, f.name) }

    sourceSets*.java.srcDirs*.each { it.mkdirs() }
    sourceSets*.resources.srcDirs*.each { it.mkdirs() }
    webAppDir.mkdirs()

    File newSource = file(sourceSets.main.java.srcDirs.iterator().next())

    tmpSource.listFiles().each { File f -> f.renameTo new File(newSource, f.name) }

    tmpSource.delete()
}

task pathingJar(type: Jar) {
    dependsOn configurations.runtime
    appendix = 'pathing'

    doFirst {
        from "${project.buildDir}/classes"
        manifest {
            attributes "Class-Path": configurations.compile.files.join(" ")
        }
    }
}

task compileGwt(dependsOn: pathingJar, type: JavaExec) {

    //ext.buildDir = "${project.buildDir}/resources/main/static"
    ext.buildDir = "${project.rootDir}/src/main/webapp"
    //ext.buildDir = "${project.buildDir}"
    ext.extraDir = "${project.buildDir}/extra"
    ext.generatedDir = "${project.buildDir}/generated"

    inputs.source sourceSets.main.java.srcDirs
    inputs.dir sourceSets.main.output.resourcesDir
    outputs.dir buildDir

    // Workaround for incremental build (GRADLE-1483)
    outputs.upToDateSpec = new org.gradle.api.specs.AndSpec()

    doFirst {
        file(buildDir).mkdirs()
        //classpath.each { println it.name}
    }

    main = 'com.google.gwt.dev.Compiler'
    classpath {
        [
                pathingJar.archivePath,
                sourceSets.main.java.srcDirs,           // Java source
                sourceSets.main.output.resourcesDir,    // Generated resources
                sourceSets.main.output.classesDir,      // Generated classes
                //sourceSets.main.compileClasspath,       // Deps

        ]
    }

    args =
            [
                    'com.company.application.UI', // Your GWT module
                    '-war', buildDir,
                    '-logLevel', 'INFO',
                    '-localWorkers', '2',
                    '-compileReport',
                    '-extra', extraDir,
                    // '-draftCompile' // Speeds up compile with 25%
            ]
    maxHeapSize = '1024M'

}

war.dependsOn compileGwt
war {
    from compileGwt.buildDir
}

Comment: I'm trying to use the pathingJar to resolve the issue, but I encountered another issue after modifying my gradle.build.(See modified section above)
Answer: I fixed a similar issue with this gradle plugin : https://github.com/viswaramamoorthy/gradle-util-plugins
buildscript {
    dependencies {
        classpath "com.github.viswaramamoorthy:gradle-util-plugins:0.1.0-RELEASE"
    }
}
...
apply plugin: 'ManifestClasspath'

Answer: See https://github.com/steffenschaefer/gwt-gradle-plugin/commit/087a94377fbd83cab938ffffe51ce8fab871be35 which applies a fix for the gwt-gradle-plugin which had the same issue.
instead of setting classpath, you should be able to do something like the following
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                javaExecSpec.environment("CLASSPATH", classpath.getAsPath());
            }

Answer: I fixed this issue based on info from fix for long classpath

create the following task:
        task pathingJar(type: Jar) {
    dependsOn configurations.runtime
    appendix = 'pathing'
    doFirst {
        manifest {
           attributes "Class-Path": configurations.runtime.files.collect {
               it.toURL().toString().replaceFirst(/file:\/+/, '/')
           }.join(' ')
  }
}

}
use this task in bootRun
task bootRunDev(type: org.springframework.boot.gradle.tasks.run.BootRun,
dependsOn: 'build') {
dependsOn pathingJar
group = 'application'
jvmArgs = [
    "-agentlib:jdwp=transport=dt_socket,server=y,address=8000,suspend=n"
]
doFirst() {
    main = bootJar.mainClassName
    classpath = files(sourceSets.main.output.files, pathingJar.archivePath)
    systemProperty 'spring.profiles.active', 'development'
}

}
Answer: I was trying to run stand alon java program. Changing the below in run configuration fixed my issue
Answer: This is a simplified version of @GLK's pathingJar solution that works in gradle4.10:
task pathingJar(type: Jar) {
    dependsOn configurations.runtimeClasspath
    appendix = 'pathing'

    doFirst {
        manifest {
            Set<File> classPathJars = configurations.runtimeClasspath.files
            attributes "Class-Path": classPathJars.collect {it.toURI().toURL().toString().replaceFirst("file:/", '/')}.join(" ")
        }
    }
}

bootRun {
    dependsOn pathingJar
    doFirst {
        classpath = files(sourceSets.main.output.files, pathingJar.archivePath)
    }
}

My sourceSets.main.output.files (in a groovy build) resolves to:
[<projectRoot>\build\classes\java\main, <projectRoot>\build\classes\groovy\main, <projectRoot>\build\resources\main]


Test ads are shown in real device but not in emulator

Question: The emulator was working perfectlty showing test ads but in the last 2 days the test ads are not shown in the emulator. It is not a problem of the code because before it was showing the test ads and I have not changed the implementation of the ads, but now they are not shown in the emulator but they continue to be shown in a real device. What could be happening with the emulator?
Edit: The internet connection is still working fine because if I search something on Google in the emulator it is working fine.
Edit2: I have tried to log the ad when it is loaded and suddenly after waiting 2 minutes the log has appeared and the ads are shown. Why it has take so long to load the ad in the emulator but in a real device it just takes some seconds?
Answer: try logging to be sure, since ad mob has AdListener, u can easily log them
Comment: I don´t understand anything, I have logged it when the ad is loaded, and after 2 min the log has appeared and it is working fine. It is like if in the emulator the ad is loaded really slowly and in a real device the ad is loaded faster...


Simulation to estimate a conditional expectation

Question: Let X and Y be independent and identical exponential random variables with parameter $\theta>0$. Compute $P[X \leq x | X+Y]$ for $x\geq0$.
I tried to solve this theoretically here (https://math.stackexchange.com/questions/4508874/conditional-distribution-function-of-one-random-variable-given-the-sum-of-two) and I wanted to verify it through simulation as I'm waiting a response.
Any suggestion?
Comment: @Xi'an I am surprised at such a negative prognosis.  I know you know of many efficient ways to generate $(X,Y)$ values conditional on some event.  Any way that does not rely on the analysis used to compute the conditional distribution would serve as a useful check of that analysis.
Comment: I would like some sort of a runnable example that generically solves the problem. E.g. I would like to fix the sum of X+Y to 5, $\theta=1$ and obtain a result. Do you think it is possible to get the solution in an answer here? Thank you.
Comment: This could be fine. Could you give me some references so I can write down some code? Thank you.
Comment: Sorry for being not clear enough: imho one cannot verify the theoretical result since one need exploit the theoretical result to simulate from the conditional. The only verification one could make is to simulate from the marginal of $X+Y$ then $X$ given $X+Y$ and check that the marginals of $X$ and $Y$ are indeed both Exp$(\theta)$.
Comment: So there is no way to simulate two exponential distributed and independent samples and obtain an estimate for that probability in a "Monte Carlo" style? Probably I am a bit rusty in these topics after 5 years of not using them anymore.
Answer: Unless the conditional density varies rapidly with the conditioning event, a brute-force rejection sample works.
Let's state the general problem.  You wish to study the distribution of some function $f(X,Y)$ conditional on an event $\mathscr E$ which is either extremely rare or, as in this case, has zero probability (but positive density).
The idea is that with some care--there are geometric and probabilistic subtleties here (that are partially explored below)--you can "thicken" $\mathscr E$ by an amount $\delta$ to an event $\mathscr E^\prime = \mathscr E(\delta) \supset \mathscr E$ that has positive probability.  Generate $(X,Y)$ from its joint distribution and reject any results not in $\mathscr E^\prime,$ then examine the empirical distribution of $f(X,Y)$ and compare it to what you expected theoretically.
This works provided the probability of $\mathscr E^\prime$ is not so small that it takes forever for randomly-generated $(X,Y)$ to fall within it.  To obtain a sample of size $n,$ you will need (on average) to generate $N = n/\Pr(\mathscr E^\prime)$ values of $(X,Y).$  I recommend starting with a modest value of $N,$ generating values, and observing what $n$ turns out to be.  Extrapolate from that to determine how many values you have time to generate.  If it's too small, you will have to thicken $\mathscr E$ more -- and you can make a reasonable guess about how much more is needed based on this preliminary study.

Let's use your problem as an example. $X$ and $Y$ are independently Exponentially distributed.  Because the parameter only establishes the unit of measurement, we may take it to be $1$ with no loss of generality.  The function is $f(X,Y) = X+Y.$
A quick and dirty R implementation mirrors the strategy.  This one examines the distribution of $X$ conditional on $X + Y \approx 0.5,$ using an amount $\delta = 0.05$ to thicken $\mathscr E:$
x <- rexp(1e4)
y <- rexp(1e4)
z <- x + y                                    # z = f(x,y)
i <- abs(z - 0.5) <= 0.05                     # Thicken E to E'
X <- data.frame(x = x[i], y = y[i], z = z[i]) # Reject results outside E'

Here is what the empirical $(x,y)$ scatterplot might look like:
with(X, plot(x, y))

The line $x+y=0.5$ is plotted for reference: it corresponds to the conditioning event $\mathscr E.$  The gray area (comprised of thousands of generated points) more or less fills out $\mathscr E^\prime.$
With such a simulation in hand, you can explore the conditional distribution of any $f(X,Y)$ in all the familiar ways, such as with a histogram

(the dashed line is the theoretical value) or an empirical CDF (ECDF)

The (faintly visible) dashed blue line is the theoretical distribution, shown for reference.
There are clear edge effects near $X = 0.5$ but those are understandable consequences of the fact that $Y \lt 0$ is not possible, thereby reducing the probability at that corner of $\mathscr E^\prime.$  (This is why examining the first scatterplot is helpful: it alerts you to such problem regions and helps you interpret the results.)

I mentioned the need for care. Let's illustrate that by showing what happens when the event $\mathscr E$ is thickened differently, using the same three figures.

I have allowed $\mathscr E^\prime$ to be thicker at smaller $X$ values than at larger ones, thereby relatively oversampling the smaller $X$ values.  (This has a rationale: it eliminates the edge effects near $X = 0.5$)  The histogram

and the ECDF

reflect that.  They clearly differ from the theoretical result.
The moral of this example is that you need to understand what you're doing when you compute distributions conditional on events with zero probability!
Comment: This is a great answer. I learned a lot from your post.
Comment: I appreciate your answer whuber.  If I am right, my theoretical result seems confirmed by what you found examining the ecdf of X|X+Y.
Comment: I have plotted your theoretical result in the histograms and ECDFs.  There is good agreement :-).
Comment: My dotted line is a little less than $2$ to account for the edge effects near $0.5:$ it represents the uniform distribution on the interval $[0, 0.5+0.05].$  The theoretical answer is given in several other threads here, including https://stats.stackexchange.com/questions/252692 (where yours is the special case $n=2$).  Using uniform order statistics it's easy to show $X/(X+Y)$ has a Uniform distribution and that's exactly what your result says.
Comment: Good, I'm waiting someone to validate them from a mathematical point of view. One question: shouldn't the conditional density of X|X+Y be equal to 2 in the plot? Thank you.
Answer: We could approach the problem using inverse transform sampling: generate random samples from the standard uniform distribution ($U$) and, given $X+Y$ that we specify, solve for $X$ and $Y$ for each $U$ using the hypothesized CDF. Then test whether $X$ and $Y$ are iid exponential variates.
Equivalently, we can reverse that approach by generating random $X$, $Y$ pairs, where the same exponential distribution is used within each pair. Then use the hypothesized CDF to transform them to $Z=\frac{X}{X+Y}$ (basically inverse transform sampling in reverse). Then simply test if $Z\sim U(0,1)$.
In R:
set.seed(94)
n <- 1e7L
X <- rexp(n)
Y <- rexp(n)
z <- X/(X + Y)
ks.test(z, "punif")
#>
#>  One-sample Kolmogorov-Smirnov test
#>
#> data:  z
#> D = 0.00029162, p-value = 0.3629
#> alternative hypothesis: two-sided

Check that the results hold while allowing the rate parameter to vary with each $X$, $Y$ pair:
theta <- runif(n)
X <- rexp(n, theta)
Y <- rexp(n, theta)
z <- X/(X + Y)
ks.test(z, "punif")
#>
#>  One-sample Kolmogorov-Smirnov test
#>
#> data:  z
#> D = 0.00037478, p-value = 0.1205
#> alternative hypothesis: two-sided

Or plot the ECDF:
set.seed(94)
n <- 1e6L
X <- rexp(n)
Y <- rexp(n)
plot(ecdf(X/(X + Y)))

theta <- runif(n)
X <- rexp(n, theta)
Y <- rexp(n, theta)
plot(ecdf(X/(X + Y)))

Comment: The initial idea is great (for this specific problem), but checking it with moments is poor: why not just explore the entire distribution of $X/(X+Y)$? If you want to be formal, conduct a KS test: it's simple and powerful (it's the analog of visually comparing the ECDF to the theoretical CDF).
Comment: Point taken. See updated answer.
Comment: Cool approach, thank you jblood94.
Comment: My confusion is how to get from establishing empirically that  $X/(X+Y)\sim\mathcal U(0,1)$ to deriving the conditional distribution of $X$ conditional on $X+Y$.
Comment: Yes, of course. This approach would not be useful for deriving the conditional distribution, only for testing an existing hypothesized distribution. The OP has a hypothesized distribution, so this approach seemed appropriate.


fadeOut CSS não some

Question: Tenho o seguinte código, porém o problema é que ele deveria sumir de vez, mas após um tempo ele volta e fica estático.
Queria que sumisse, que o elemento fosse removido, como posso fazer?

@keyframes fadeOut {
  0% {
    opacity:1;
  }
  100% {
    opacity:0;
  }
}

@-moz-keyframes fadeOut {
  0% {
    opacity:1;
  }
  100% {
    opacity:0;
  }
}

@-webkit-keyframes fadeOut {
  0% {
    opacity:1;
  }
  100% {
    opacity:0;
  }
}

@-o-keyframes fadeOut {
  0% {
    opacity:1;
  }
  100% {
    opacity:0;
  }
}

.afo {
  width: 270px;
  height: 30px;
  padding: 20px 0;
  color: black;
  background: lightblue;
  font-weight: bold;
  border-radius: 5px;
  animation: fadeOut ease 5s;
  -webkit-animation: fadeOut ease 5s;
  -moz-animation: fadeOut ease 5s;
  -o-animation: fadeOut ease 5s;
  -ms-animation: fadeOut ease 5s;
}

  Usuário ou senha inválidos.

Comment: Você quer dizer  quando a animação acabar, o elemento `span` seja removido do DOM ou apenas que ele fique transparente (invisível)?
Comment: Tem de ser removido
Answer: Para definir como inicia ou terminar o efeito de fade, pode usar o atributo animation-fill-mode
Como deseja que o efeito fique permanente, ou seja, ao terminar mantenha como ficou o último quadro de animação, precisa setar o animation-fill-mode como forwards:
animation-fill-mode: forwards ou no próprio atributo de fade: animation: fadeOut ease 5s forwards:

forwards The target will retain the computed values set by the last keyframe encountered during execution.

Ou seja, vai manter os valores do último keyframe da animação.

@keyframes fadeOut {
  0% {
    opacity:1;
  }
  100% {
    opacity:0;
  }
}

@-moz-keyframes fadeOut {
  0% {
    opacity:1;
  }
  100% {
    opacity:0;
  }
}

@-webkit-keyframes fadeOut {
  0% {
    opacity:1;
  }
  100% {
    opacity:0;
  }
}

@-o-keyframes fadeOut {
  0% {
    opacity:1;
  }
  100% {
    opacity:0;
  }
}

.afo {
  width: 270px;
  height: 30px;
  padding: 20px 0;
  color: black;
  background: lightblue;
  font-weight: bold;
  border-radius: 5px;
  animation: fadeOut ease 5s forwards;
  -webkit-animation: fadeOut ease 5s forwards;
  -moz-animation: fadeOut ease 5s forwards;
  -o-animation: fadeOut ease 5s forwards;
  -ms-animation: fadeOut ease 5s forwards;
}

    Usuário ou senha inválidos.

Comment: Ainda não vou dar um +1 porque não sei se resolve a dúvida do AP. Eu tinha entendido que ele queria remover o elemento do DOM, mas ao ponto de não afetar o layout. Ou afetar mesmo, algo como `display: none` ou remover literalmente do DOM usando JS.
Comment: eu entendi, eu respondi baseado no *"mas após um tempo ele volta e fica estático"*, o que me leva a crer que ele queria que ao terminar o fade, ficasse "escondido", mas entendo o que disse, essa perte *"Queria que sumisse, que o elemento fosse removido"* deixa meio em dúvida, mas não faria sentido remover o label para ter de adicionar depois se quiser reexibir a mensagem ;)

fadeOut CSS não some


Grafana - How to add elasticsearch as a datasource when username and password are available for ES?

Question: I set up x-pack, to provide an extra layer of security to Elasticsearch and now I am unable to use elasticsearch as a data source anymore. All I can see is a red alarming signal, showing that grafana failed to add the elasticsearch as a data source.
I provided the URL as, http://elastic:changeme@localhost:9200
Answer: There shouldn't be a problem to connect to an elasticsearch instance with Basic Auth from Grafana. Grafana even provides the possibility to enter the credentials by checking the Basic Auth field.
What probably could cause problems in your setup is the way of providing basic auth credentials via direct access, so your browser directly issues the requests against the elasticsearch instance, which usually only works when you enable the matching CORS settings in elasticsearch. But since grafana also allows to use its backend as a proxy for the calls, my suggestion is to use this way instead of opening elasticsearch to cross-origin calls.
For details, please see the grafana docs on the elasticsearch datasource.
So, please try to add your credentials in the grafana settings for Basic Auth and switch to proxy access instead of direct in the http settings section.


Derivative of L1 norm of Hadamard product

Question: I am trying to find the derivative of  $f(B)=\lambda\Vert W \bigodot B \Vert_1 + \frac{\rho}{2}\Vert A-B \Vert_F^2 + tr(\Delta^T(A-B))$ with respect to B.
where B is (n×n)matrix, W is (n×n)constant matrix, A is (n×n)constant matrix. $\lambda$ and $\rho$ are scalars. $tr$ is the trace of the matrix. $W \bigodot B$ is the Hadamard product of W and B.
I am troubled in finding the derivative involving Hadamard product and L-1 norm. Therefore, I first replaced $W \bigodot B$ with T.
$$T=W \bigodot B$$
$$B=W^{-1} \bigodot T$$
where $W^{-1}$ is the element-wise inverse. $W \bigodot W^{-1}=I$.
$$f(T)=\lambda\Vert T \Vert_1 + \frac{\rho}{2}\Vert A-W^{-1} \bigodot T  \Vert_F^2 + tr(\Delta^T(A-W^{-1} \bigodot T))$$
I do not konw what to do next.
Thank you in advance for any help you can provide.
Answer: Let's use a colon to denote the trace/Frobenius product,
i.e. $\;A:B = {\rm Tr}(A^TB)$
The cyclic property of the trace allows such products to be rearranged in many different ways, e.g.
$$\eqalign{
A:B &= A^T:B^T &= B:A \\
A:BC &= AC^T:B &= B^TA:C \\
}$$
Together, the Frobenius and Hadamard products form a scalar/triple product, whose terms commute.
$$A:(B\odot C) = (A\odot B):C$$
Using these products and the element-wise sign function, we can calculate the differential and subgradient of the troublesome term.
$$\eqalign{
\phi &= \lambda \|T\|_1 \\
 &= \lambda\operatorname{sign}(T):T \\
d\phi
 &= \lambda\operatorname{sign}(T):dT \\
 &= \lambda\operatorname{sign}(T):W\odot dB \\
 &= \lambda W\odot\operatorname{sign}(T):dB \\
 &= \lambda W\odot\operatorname{sign}(W)\odot\operatorname{sign}(B):dB \\
\frac{\partial\phi}{\partial B}
 &= \lambda W\odot\operatorname{sign}(W)\odot\operatorname{sign}(B) \\
}$$
Introducing an element-wise absolute value function,
we can write this as
$$\eqalign{
\frac{\partial\phi}{\partial B}
  &= \lambda\operatorname{abs}(W)\odot\operatorname{sign}(B) \\
}$$
Comment: This is so amazing. I am so grateful for your help and  the thorough explanation.


Neighbors with very different labels

Question: The cells of a square $2011$ by $2011$  array are labelled with the integers $1,2,\dots, 2011^2$ in such a way that every label is used exactly once. We identity the top and bottom edges and the left and right edges to wrap the array to form a torus or donut shape.
What is the largest positive integer $M$ such that, no matter which labelling we choose, there exist two neighboring cells with the difference of their labels at least $M$?
Two cells are neighbors if either their $x$ or $y$ coordinates are the same and the other coordinate is  $\pm 1$  when taken modulo $2011$.
Answer: This is Problem 6 from the 4th Romanian Master of Mathematics Competition.
Its solution is here.
Comment: Thanks. It's a very nice problem it turns out.

Neighbors with very different labels


How to map fields from content type to user Profile

Question: I am using a content type named application
There are some fields I like to map to the users profile to use them with panels.
For example there are fields called:

name -->textfield
nickman-->textfield
birthday--> date
about-->text with summery
etc

Now I would like to map the content of these fields to the same fields used in the users profile to display the information the users had entered in their applications.
How could I do that? Where to start to find more about field mappings?
Thank you guys and gals!
Answer: If you want the content of the fields in application to be saved in the user entity, I can think of a couple of approaches:

Use Rules module to copy the values to the user entity when the application content is saved.
Write a custom module and use hook_node_update() to add the values to the user entity.
Comment: The rules  approach  is working  perfectly. Thanks!


These lines of code gets me out this error and i cannot understand it

Question: $number_to_keep = db_select('variable', 'va')
    ->fields('va.value')
    ->condition('va.name', 'dblog_row_limit', '=')
    ->execute();

And it gets me out that errors:
Notice: Undefined index: table in SelectQuery->preExecute() (line 1245 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: table in SelectQuery->compile() (line 1079 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: table in SelectQuery->compiled() (line 1097 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: arguments in SelectQuery->arguments() (line 1024 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: table in SelectQuery->arguments() (line 1028 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: table in SelectQuery->compiled() (line 1097 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: table in SelectQuery->__toString() (line 1531 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: table in SelectQuery->__toString() (line 1538 of /var/www/html/drupal/includes/database/select.inc).
Notice: Undefined index: alias in SelectQuery->__toString() (line 1543 of /var/www/html/drupal/includes/database/select.inc).
Answer: The signature for SelectQuery::fields() is:
public SelectQuery::fields($table_alias, array $fields = array())

So you need:
$number_to_keep = db_select('variable', 'va')
  ->fields('va', array('value'))
  ->condition('va.name', 'dblog_row_limit', '=')
  ->execute();

Comment: Oh my god!! I am new in drupal and I am sorry about that... Thank you!


How to parse this multi-dimensional array properly

Question: I have tried everything I know and I have failed totally to parse this multi dimensional array so that I can get the "symbol" keys and corresponding values of "contractType" , but I can't seem to get it.
The array is generated here: https://fapi.binance.com/fapi/v1/exchangeInfo
So I am doing the following:
<code>    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    $data = curl_exec($curl);
    curl_close($curl);

    $results = [];
    foreach ($data['symbols'] as $info) {
        $results[] = $info['symbol'];
    }
    print_r($results);
</code>
I tried a foreach loop, for loop, tried various offsets eg. $data[0]['symbols']..
to $data[9]['symbols'] etc. but can't seem to get the correct array offset.
<code>10000"}],"symbols":[{"symbol":"BTCUSDT","pair":"BTCUSDT","contractType":"PERPETUAL","deliveryDate
</code>

I'm trying to loop through the "symbols" offset within this main array, and get 1. the "symbol" 2. its corresponding  "contractType"

Ty..
Comment: It's hard to answer this when you've only posted a partial of the array structure. Without knowing the full structure, we can only make unfounded guesses.
Comment: try to decode the json response you get from the CURL, `$data = json_decode($data);`. and now $data is an object that you can have accesses like `$data->symbols`
Answer: It doesn't work because the CURL result is in JSON.
You got to convert it to an array before you can loop through it.
<code>$data = json_decode($data, true);
</code>
Comment: @metokitt the `$data` in your original question is a string, this works with that code.
Comment: Warning: json_decode() expects parameter 1 to be string, array given ...
Answer: It looks like you need to convert the JSON response into an array before you loop over it.
<code>    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    $data = curl_exec($curl);
    curl_close($curl);

    $results = [];
    $data = json_decode($data);
    $i = 0;
    foreach ($data->symbols as $info) {
        $results[$i]['symbol'] = $info->symbol;
        $results[$i]['contractType'] = $info->contractType;
        $i++;
    }
    print_r($results);
</code>
Comment: Warning: Invalid argument supplied for foreach() in /data/www/.....
Comment: My bad, I posted the concept without testing. I have updated the answer for you now.
Answer: Yes. Thankyou.. (didn't understand answer properly.)
<code>    $url = 'https://fapi.binance.com/fapi/v1/exchangeInfo';
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    $data = curl_exec($curl);
    curl_close($curl);

    $data = json_decode($data, true);

    $results = [];
    $symbols = $data['symbols'];
    $i = 0;
    foreach ($symbols as $info) {
        $results[$i]['symbol'] = $info['symbol'];
        $results[$i]['contractType'] = $info['contractType'];
        $i++;
    }
    print_r($results);

</code>
Much appreciated, ty..


Servable not found for request: while loading an older version of the model

Question: I've a model, let's say mymodel and two different data sets: setA, setB.
After training(in my local machine) setA and setB separately, tensorflow serving created two different directories: 100, 200 for setA and setB respectively.
To host the model inside docker
root@ccb58054cae5:/# ls /serving/model/
100 200
root@ccb58054cae5:/# bazel-bin/tensorflow_serving/model_servers/tensorflow_model_server --port=9000 --model_name=mymodel --model_base_path=/serving/model &> log &

Now when I do the inference for setB, I'm successfully able to get the response, as tensorflow serving by default loads 200 because it thinks this is the latest model.
Now I want to query for setA, so I need to mention in the code which version of the hosted model to hit and that would be 100.
In terms of code: request.model_spec.version.value = 100
for completeness here is the other relevant client code:
host, port = FLAGS.server.split(':')
channel = implementations.insecure_channel(host, int(port))
stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
request = predict_pb2.PredictRequest()
request.model_spec.name = 'mymodel'
request.model_spec.signature_name = signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
request.model_spec.version.value = 100

I got to know about request.model_spec.version.value = 100 from here. But I got unlucky, I'm getting:
Traceback (most recent call last):
  File "C:\Program Files\Anaconda3\lib\site-packages\grpc\beta\_client_adaptations.py", line 193, in _blocking_unary_unary
    credentials=_credentials(protocol_options))
  File "C:\Program Files\Anaconda3\lib\site-packages\grpc\_channel.py", line 492, in __call__
    return _end_unary_response_blocking(state, call, False, deadline)
  File "C:\Program Files\Anaconda3\lib\site-packages\grpc\_channel.py", line 440, in _end_unary_response_blocking
    raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with (StatusCode.NOT_FOUND, Servable not found for request: Specific(mymodel, 100))>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\Anaconda3\lib\site-packages\flask\app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Program Files\Anaconda3\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Program Files\Anaconda3\lib\site-packages\flask_cors\extension.py", line 188, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "C:\Program Files\Anaconda3\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Program Files\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Program Files\Anaconda3\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Program Files\Anaconda3\lib\site-packages\flask\app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "mymodel.py", line 63, in json_test
    response =  main.main(ser, query = que)
  File "D:\mymodel_temp\temp\main.py", line 23, in main
    return json_for_inference(model.inference(query), query, service_id)
  File "D:\mymodel_temp\temp\src\utils.py", line 30, in wrapper
    outputs = function(self, *args, **kwargs)
  File "D:\mymodel_temp\temp\src\model.py", line 324, in inference
    result = stub.Predict(request, 10.0) # 10 seconds
  File "C:\Program Files\Anaconda3\lib\site-packages\grpc\beta\_client_adaptations.py", line 309, in __call__
    self._request_serializer, self._response_deserializer)
  File "C:\Program Files\Anaconda3\lib\site-packages\grpc\beta\_client_adaptations.py", line 195, in _blocking_unary_unary
    raise _abortion_error(rpc_error_call)
grpc.framework.interfaces.face.face.AbortionError: AbortionError(code=StatusCode.NOT_FOUND, details="Servable not found for request: Specific(mymodel, 100)")

Answer: You are getting Servable not found for request: Specific(mymodel, 100) error, because there is no model loaded with this specific version number.
root@ccb58054cae5:/# bazel-bin/tensorflow_serving/model_servers/tensorflow_model_server --port=9000 --model_name=mymodel --model_base_path=/serving/model &> log &

When you run above command on docker for serving models, it will load model according to Version Policy mentioned here in Git Code of Tensorflow Serving. By default only one version of model will be loaded and that version will be Latest one (Higher version number).
If you want to load multiple versions or multiple models, you need to add --model_config_file flag. Also remove --model_name and --model_base_path flags as we will be adding them in model config file.
So now your command will be like this :-
root@ccb58054cae5:/# bazel-bin/tensorflow_serving/model_servers/tensorflow_model_server --port=9000 --model_config_file=mymodel.conf &> log &

Format of model config file will be like this :-
model_config_list: {

    config: {
        name: "mymodel",
        base_path: "/serving/model",
        model_platform: "tensorflow"
        model_version_policy: {all{}}
    }
}

So you can set Version Policy other than latest (By Default) to all and specific. By selecting all , you can load all versions of model as servables and then you can easily access specific version using   request.model_spec.version.value = 100 in client code. If you want to load more than one models, you can do that in same config file by appending model config for those models.


Como converter numeros 2.15600e+03 (euler) para tipo numerico?

Question: Estou com o seguinte problema: tenho que ler um arquivo que contém vários números muito grandes conforme exemplo abaixo.

Ao tentar ler eles e mandar pra uma variável double/long/int, da erro acusando que é uma string. Gostaria de saber como converter esse tipo de número em double/long/int (o que for aplicável neste caso).
Answer: Use a classe Double para fazer a conversão:
Para long:
long longVar = Double.valueOf("2.15600e+03").longValue();

Para double:
double doubleVar = Double.valueOf("2.15600e+03").doubleValue();


What are the obstruction rules in squash?

Question: I've been struggling to find anywhere that speaks in detail of the rules of obstruction in squash.
How close does the player have to be to the squash ball for it to be considered obstruction?
Is it obstruction whenever one player has to run around the other to reach the ball?
Answer: This is broken down into 3 rulings

"Let" - Your opponent is making their best effort to clear, and there's minimal obstruction. If the referee calls let, the point can be re-played.
"No let" - If you could have safely played the ball, but chose not to. In this case, your opponent wins the point.
"Stroke" - It's unsafe for you to play the shot without striking your opponent with the ball or racket. You will win the point in this case.

There are no specific rules about how close an opponent must be to cause a Stroke call, so we just use the term "safe to return".
When I'm playing a game with a friend without a referee, we usually default back to "Let", and go again.
Note - I have (inadvertently) hit an opponent with a ball, and I've also been struck with a ball. It's a risk of playing an aggressive racket ball game, in a closed arena.


How to install CMake on FreeBSD without Sphinx

Question: CMake recently (September 2014 I guess) started to depend on py27-Sphinx port for its documentation. I actually don't use python on my server, but CMake builds and installs it and its 9 other dependencies just to build its documentation, even though I chose not to build and/or install the documentation.
This is really annoying, have to keep 9 ports up to date just so CMake can build its own documentation that I won't ever read.
I can't get rid of the CMake, as it is needed to build mysql. I just want to get rid of the Sphinx and its dependencies. All help will be highly appreciated.
Comment: There is a patch for this: https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=193259 Unfortunately it is not committed for a long time.
Answer: I have figured this out thanks to @citrin's comment.
Adam Weinberger reported this as a bug here.
He also provided two patches for two different desirable options: pre-building the man pages, or building cmake without them. I opted for the latter one.
The attachment here includes little fixes to the Makefile and pkg-plist of the corresponding port. I just updated my cmake Makefile and pkg-plist with the new lines, and voila! There was another config option for manpages, and after I chose not to build with manpages, the dependency disappeared.
Answer: In the latest port of cmake you can de-select building the man-pages and sphinx will not get pulled in.
<code>cd /usr/ports/devel/cmake
make config
</code>
I had the same issue.


How to add content in custom menu block?

Question: I have own menu type "Footer menu". When I add new content, "Footer menu" is not display in Menu setings. Where is the problem?
Answer: It's in the Content Type's settings screen under "Menu settings", you have to tick the Footer Menu to make it available for selection.
Comment: thx, it`s work!
Comment: is possible to add one content type to more menu blocks?


understanding a proof of a function lying in the closure of a polynomial space

Question:
Show that $f(x) = |x|$ lies in the closure of $\mathcal{P}[-1, 1]$ in $\mathcal{C}[-1,1]$ (using the supremum metric), where for $a,b\in\mathbb{R}, \mathcal{P}[a,b]$ is the set of polynomials on $[a,b]$ and $\mathcal{C}[a,b]$ is the set of continuous functions on $[a,b].$

Below is a proof of this proposition.

I understand most of it, except the claim that $|\frac{g^{(n+1)}(t)}{(n+1)!}(x-1)^{n+1}| \leq \dfrac{1\cdot 3 \cdots (2n-1)\cdot a^{2n-1}}{2^{n+1}{(n+1)!}}.$ Can someone explain why this inequality holds?
Comment: Interesting exercise. I am not sure that the reasoning is solid (see the answer below) and am not sure that any clever case-specific reasoning would be more valuable to understand than a general proof of the Stone-Weierstrass theorem. https://en.wikipedia.org/wiki/Stone%E2%80%93Weierstrass_theorem
Answer: The Lagrange form of the remainder of the Taylor series is
$$R_n(x) =  \frac{g^{n+1}(t(n,x))}{(n+1)!}(x-1)^{n+1}  = \frac{r_n \cdot (x -1)^{n+1}}{(t(n,x)+a^2)^{(2n+1)/2}}$$
where $r_n = \dfrac{1\cdot3 \cdot \ldots \cdot (2n-1)}{2^{n+1}(n+1)!}$ and $t(n,x) \in (x,1)$. We want to show that
$$d_n := \sup_{x \in [0,1]} \lvert R_n(x) \rvert \to 0$$
as $n \to \infty$. But certainly
$$\sup_{x \in [0,1]} \lvert R_n(x) \rvert \ge  \lvert R_n(0) \rvert = \frac{r_n}{(t(n,0)+a^2)^{(2n+1)/2}} .$$
As long as we do not know anything about $t(n,0) \in (0,1)$, we cannot exclude that there exists $b < 1$ such that $t(n,0) + a^2 \le b^2$ for all $n$. In that case
$$d_n \ge \frac{r_n}{b^{2n+1}} .$$
But we have
$$r_n  \ge \dfrac{2 \cdot 4 \cdot \ldots \cdot (2n-2)}{2^{n+1}(n+1)!} = \dfrac{2^{n-1} (n-1)!}{2^{n+1}(n+1)!} = \dfrac{1}{4n(n+1)}$$
and therefore
$$d_n \ge \frac{1}{4n(n+1)b^{2n+1}} .$$
The RHS diverges to $+\infty$.
This does not necessarily mean that the claim $d_n \le \dfrac{1}{2(n+1)}$ is false, but a proof would require to know something about $t(n,0)$, for example that $t(n,0) + a^2 \ge 1$ for all $n$. I doubt that.


The Barassi Line and Australian winter sports today

Question: The Barassi Line is an imaginary line that divides Australia into two parts based on the popularity of Australian Rules Football vs the rugby codes.
Essentially, Aussie Rules is more popular in Victoria, Tasmania, South Australia, the Northern Territory and Western Australia, whereas rugby is more popular in New South Wales, the ACT and Queensland.
Does this hold true even today, with AFL teams in Sydney, Brisbane and the Gold Coast, and an NRL team in Melbourne?
Also, is it true that for most rugby fans in Australia, rugby league would be more popular than rugby union, and that the latter is only really followed during the World Cup and other similar international events?
Answer:
Does this hold true even today, with AFL teams in Sydney, Brisbane and the Gold Coast, and an NRL team in Melbourne?

Yes.
Out of the 18 AFL teams, four of them are north of the Barassi Line - Sydney, GWS, Brisbane, and Gold Coast. Let's look at the common metrics of popularity used for sports teams to see how they fare:
Crowds
Average home crowd in 2019 [1]

Richmond (VIC), 59,987
Collingwood (VIC), 58,975
West Coast (WA), 53,513
Essendon (VIC), 47,733
Carlton (VIC), 46,730
Adelaide (SA), 44,514
Fremantle (WA), 40,896
Port Adelaide (SA), 33,950
Geelong (VIC), 33,405
Hawthorn (VIC), 31,077
Sydney (NSW), 31,070
Melbourne (VIC), 28,968
Western Bulldogs (VIC), 26,747
St Kilda (VIC), 25,401
Brisbane Lions (QLD), 24,741
North Melbourne (VIC), 20,808
Greater Western Sydney (NSW), 12,267
Gold Coast (QLD), 11,417

All four teams above the Barassi line are in the bottom half of the competition for attendance, including three of the four worst-attended clubs in the league. Even Sydney, one of the most consistently strong teams over the last decade and a half, is significantly behind the league average attendance of 35,122.
Notably, Gold Coast's highest ever "home" crowd actually occurred in Perth, as part of a scheme where they hosted a "home" game interstate while their actual home ground was being renovated for the 2018 Commonwealth Games.
Membership
AFL-audited membership numbers for 2020. Some clubs self-report much higher membership figures by including things like their email lists, but this list is for paying memberships only. [2]

West Coast (WA), 100,776
Richmond (VIC), 100,420
Collingwood (VIC), 76,862
Hawthorn (VIC), 76,343
Carlton (VIC), 67,035
Essendon (VIC), 66,686
Geelong (VIC), 60,066
Adelaide (SA), 54,891
Fremantle (WA), 51,577
St Kilda (VIC), 48,588
Sydney (NSW), 48,322
Port Adelaide (SA), 46,820
Melbourne (VIC), 40,571
Western Bulldogs (VIC), 38,876
North Melbourne (VIC), 38,667
Greater Western Sydney (NSW), 30,841
Brisbane Lions (QLD), 29,277
Gold Coast (QLD), 16,236

This is even worse reading for the clubs north of the Barassi Line. Sydney is in the same spot and still a fair chunk off the league average of 55,159, but the other three clubs occupy the lowest three spots on the leaderboard, and by a very large margin. And this is despite GWS and Gold Coast both recording club record membership figures this year, in a year that had a slightly more than 6% downturn league-wide (likely due to economic hardship)!

The NRL
The NRL is much less interesting to look at, with only one team south of the Barassi Line, Melbourne Storm. Melbourne does admittedly draw very good crowds (18,230) and membership numbers (22,221) - 4th in the league for each - but both of these figures are lower than the worst Victorian-based team in the AFL, despite 10 AFL teams splitting the attention in Victoria, while Melbourne Storm has the Victorian NRL market all to itself. [3] [4]
It's also telling that this there's more clubs in a different country (New Zealand) than in NT, WA, SA, and Tasmania combined. In the 1990s the Adelaide Rams went defunct after two seasons in the NRL, and the Western Reds (based in Perth) lasted only three. I live in Adelaide, and anecdotally I can tell you that most people here are barely even aware that the NRL exists, let alone that we ever had a team participating in it.

League versus Union

is it true that for most rugby fans in Australia, rugby league would be more popular than rugby union, and that the latter is only really followed during the World Cup and other similar international events?

Yes, but with slightly more of an asterisk.
It's unequivocally true that League is more popular in Australia as a whole, and you're right that Union typically only receives mainstream coverage during the Rugby World Cup. Unfortunately I'm not quite familiar enough with Union to get the most reliable sources for this, but most of the dodgy sites I'm finding with Google seem to suggest that League has about 3x the participation and viewership of Union in Australia as a whole.
However, you may see minimal differences outside of the eastern seaboard, particularly in Perth where the Western Force participated in the Super 14/Super Rugby competitions for over a decade during a period where there was no local presence in any League competitions of note.

Sources
[1] AFL Tables - Crowds 2019
[2] The Age - AFL club membership tally falls for first time in 20 years
[3] RL Tables - Attendances 2019
[4] League Unlimited - 2020 NRL Membership Tracker
Comment: @Student The ACT is probably the only place in the country where it's hard to answer that question. All three codes have a fairly large cultural presence in the territory, but Union probably holds the best claim to the region on account of the Brumbies existing.

As for a sport that unites the country, cricket is absolutely the top pick there (and your friend who doesn't know who Steve Smith was is *seriously* out of touch with the national sporting scene), but multi-sport events like the (Summer) Olympics and Commonwealth Games fit the bill as well.
Comment: Great answer! So going by your last para, I would assume that in the rugby strongholds of NSW and Queensland, League rules the roost. However, this may not hold in the small pockets of rugby fanhood that exist outside these places. Perth may be one example, could the ACT be another? See here: https://en.wikipedia.org/wiki/Sport_in_the_Australian_Capital_Territory
Comment: Would it be correct to say that cricket is the only sport that unites the country? Though I met someone from Perth who didn't know who Steve Smith was. Whereas everyone in a truly cricket-mad country like India would know who Virat Kohli is.
Comment: Right....and again in NSW/QLD overall, Union may still have an edge over the AFL even domestically (i.e. not counting the Wallabies popularity as mentioned), despite neither being too well-followed.
Comment: Also, going by your comments about the Melbourne Storm.....the high figures are interesting....this would imply that there are teams in NSW and QLD who have lower attendance figures than a team in VIC, wonder why that is the case.


How to get the opened document using UNO?

Question: I'm writing an add-on that opens a dialog and I need to access the currently opened text document but I don't know how get it.
I'm using the OpenOffice plug-in in NetBeans and I started from an Add-on project. It created a class that gives me a XComponentContext instance but I don't know how to use it to get a OfficeDocument instance of the current document.
I've been googling for some time and I can't find any example that uses an existing, opened, document. They all start from a new document or a document that is loaded first so they have an URL for it.
I gave it a try based on the OpenOffice wiki (https://wiki.openoffice.org/wiki/API/Samples/Java/Office/DocumentHandling) and this is what I came up with:
private OfficeDocument getDocument() {
  if (this.officeDocument == null) {
    try {
        // this causes the error
        XMultiComponentFactory xMultiComponentFactory = this.xComponentContext.getServiceManager();

        Object oDesktop = xMultiComponentFactory.createInstanceWithContext("com.sun.star.frame.Desktop", this.xComponentContext);
        XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, oDesktop);

        String url = "private:factory/swriter";
        String targetFrameName = "_self";
        int searchFlags = FrameSearchFlag.SELF;
        PropertyValue[] propertyValues = new PropertyValue[1];
        propertyValues[0] = new PropertyValue();
        propertyValues[0].Name = "Hidden";
        propertyValues[0].Value = Boolean.TRUE;

        XComponent xComponent = xComponentLoader.loadComponentFromURL(url, targetFrameName, searchFlags, propertyValues);

        XModel xModel = UnoRuntime.queryInterface(XModel.class, xComponent);
        this.officeDocument = new OfficeDocument(xModel);
    } catch (com.sun.star.uno.Exception ex) {
        throw new RuntimeException(ex);
    }
  }
  return this.officeDocument;
}

But there is something strange going on. Just having this method in my class, even if it's never been called anywhere, causes an error when adding the add-on.
(com.sun.star.depoyment.DeploymentDescription){{ Message = "Error during activation of: VaphAddOn.jar", Context = (com.sun.star.uno.XInterface) @6ce03e0 }, Cause = (any) {(com.sun.star.registry.CannotRegisterImplementationException){{ Message = "", Context = (com.sun.star.uno.XInterface) @0 }}}}

It seems this line causes the error:
XMultiComponentFactory xMultiComponentFactory = this.xComponentContext.getServiceManager();

I have no idea how to preceed.
I posted this question on the OpenOffice forum but I haven't got a response there. I'm trying my luck here now.
Answer: Use this in your code to get the current document:
import com.sun.star.frame.XDesktop;
...
XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, oDesktop);
XComponent xComponent = xDesktop.getCurrentComponent();

I opened the BookmarkInsertion sample in NetBeans and added this code to use the current document instead of loading a new document.
As far as the error, there may be a problem with how it is getting built.  A couple of things to check:

Does the Office SDK version match the Office version?  Check version number and whether it's 32- or 64-bit.
Make sure that 4 .jar files (juh.jar, jurt.jar, unoil.jar, ridl.jar) are shown under Libraries in NetBeans, because they need to be included along with the add-on.

If you get frustrated with trying to get the build set up correctly, then you might find it easier to use python, since it doesn't need to be compiled.  Also python does not require queryInterface().


When making a pickup, does the orientation of the magnetic field relative to the winding matter?

Question: The instrument I want seems to be hard to get hold of in my country, so I'm building one. I won't say which instrument, so that the answer will be more generally useful.
I have sourced a magnet that's wide enough to span the width between two strings, and I'll probably use a wire from some cheap headphones (easy to source and usually have a thin layer of insulation). Now, I understand basic digital electronics but I have no intuition as to why a pickup is even going to work. So I don't know which way to arrange the magnet or anything either.
Does North need to face outward or into the body of the instrument? Or even toward either end of the string?
Comment: I really think that you should tell us the type of instrument and what the strings will be made of.  There are  pickups that detect string movement for solid-bodied guitars but this requires steel strings. For acoustic instruments and instruments that don't have metal strings, you need a different kind of pickup. Also you don't have to buy the whole instrument to get a pickup. They can be bought separately. Please tell us the instrument with a photo if possible.
Comment: @chasly-supportsMonica Maybe you are right. I'll tell you then. It's the dombra, from central Asia. I've got these steel cello strings I'm planning to use but I'm not married to that idea.
Answer: The magnet poles should be in the direction perpendicular to the plane of the strings.
For an individual single coil pickup the polarity of the magnet doesn't matter. If you use several magnets, they all should have the same polarity.
Polarity starts to matter when you combine several single coil pickups. The most common humbucker configuration uses two pickups with opposite polarity and opposite coil connections.
Note that typical guitar pickups have thousands of winds in the coil, so cable from headphones might be too short.
Comment: The more winds, the higher overall sensitivity of the coil, but also the higher inductance of the coil, which leads to dampening of the high frequencies, so one has to find some compromise. Still, length of a headphone cable seems to be far away from what most would call a compromise.
Comment: Yeah also it seems the core is merely to alter the electric magnetic permutivity the medium or something. What's important is the coils and increasing the turns would seem to improve the signal i suppose.
Comment: @marshalcraft From my research there appears to be a trade-off with the number of windings. Increasing improves the signal strength, but according to some sources this can lead to a loss in sensitivity. With *coil-tapping*, an extra set of windings can be switched in/out of the circuit to make adjustments on this axis.
Comment: "it seems the core is merely to alter the electric magnetic permutivity the medium or something" I'm not sure what makes it seem that way to you. Did you ever wonder why magnets are used instead of just steel/iron/ferrite slugs? It's because it's necessary for the strings to be magnetized ("made magnetic"), and they get this property imparted to them by the field from the magnets.
Answer: Others have addressed the magnet orientation, so just to add one additional point.
The cable from headphones will be magnitudes too thick for this task. You will barely get a couple of dozen winds even if your cable is long enough. You need about 1,000 or so. The wind count & layout will vastly affect the resulting pickup. Pickups are wound by machine, even if the machine is hand-powered, because this is not really one of those tasks humans are good at. Imagine taking all the cotton off a sewing bobbin, then putting it all back again, neatly.
You can buy pickup wire, it's actually really cheap - e.g. https://www.wires.co.uk/acatalog/gpw.html - but if you can't stretch to that, then another source would be wound voltage transformers from power supplies. They use the same type of wire.
Pickup (& any transformer winding) is extremely thin copper wire with a microscopic thickness of insulation. Nothing else can be substituted.
I also found this on the differences wire types & winding can make - https://mwswire.com/guitarpickup/
Answer: With single cool pickups, like with Telecasters, if you wind one with reversed windings and reversed polarity, aka RWRP, your serial position will be noise-free, like a humbucker. With Stratocasters, there is no neck-and-bridge option, the middle is made RWRP so the 2 and 4 positions are noiseless.
Comment: This is a poor answer in my opinion, because the asker gave a minimum degree of specifity, namely the exact 3d orientation of the field/coil. That said, what you are talking about does sound interesting, but to me it is not concrete for what was asked. Let's stop beating around the bush.
Answer: I think normally you would use six magnets, one for each string, or you whole use one large magnet in the shape of a plate that spans all six string and have six pole pieces for each string that are ferrous and screw into the big magnet.
Either way the magnetic field should be perpendicular to the body of the guitar, but it doesn't matter whether north or south is pointing out of the guitar, as long as all the magnets have north in the same direction.
One thing you might want to do before building your first pickup is build a simple battery powered electromagnet and see how that works. A pickup is like six electromagnets combined into one thing except instead of the magnetic field being created by electricity in the coil, the field is created by the magnetic metal and the that sort of makes electricity in the coil.
Answer: The OP has revealed in a comment that the instrument is a dombra.

This is a traditional instrument with two strings, from central Asia.
Traditional strings are gut or nowadays nylon as shown here.

It might seem obvious but I'll point out that these won't work with an electric guitar pickup. For that the strings should be steel.
The sound hole of the dombra is very small and so not suitable for an acoustic-guitar-type pickup.

Traditional solution
If you want to stay traditional then I suggest a surface-mounted Piezo Transducer Pickup as used for violin, ukulele, or cigar-box guitar. These detect the vibration of the soundboard of the instrument. They can be bought online from China and are very cheap.

Steel string solution
If you are not worried about being traditional then you can use steel strings and even a solid body if you wish.
In that case here is what you need to know:

Source of pictures
These pictures and the full text are available at How Does a Guitar Pickup Really Work?.


Rank of matrix with cosine entries

Question: Find the rank of the matrix $\def\rank{\operatorname{rank}} [\cos(i-j)]_{1 \le i,j \le n}$.
\begin{align}
\rank[\cos(i-j)] &= \rank[\cos i \cos j + \sin i \sin j] \\
&\le \rank[\cos i\cos j] + \rank[\sin i\sin j]
\end{align}
The latter two have rank 1 by row reduction. So the rank is at most 2. Take the first and last rows of the matrix, they are linearly independent since $$\cos(n-1)-\cos 1\cos n = 0 \implies \sin 1\sin n = 0$$ which is not possible because $n$ is an integer.
Comment: What have you tried?
Comment: I have an answer ready to post, but only after you edit the question to show your personal effort and for whatever context you need this in. Otherwise for now, I am voting to close this question.
Comment: I think the answer is rank = n (from smaller cases) but don't know what to use  to prove it
Comment: Please edit your post to include all of the scratch work or guess work you have done. As an aside I can tell you that $n$ is incorrect.
Comment: Ok I think I got it, am I right?
Comment: You have the right answer, see my solution now
Answer: Using the angle difference identity we have that
$$\cos(i-j) = \cos i \cos j + \sin i \sin j$$
So define the following two (linearly independent) vectors
$$\mathbf{c} = \begin{bmatrix} \cos 1 \\ \vdots \\ \cos n\end{bmatrix} \hspace{24 pt} \mathbf{s} = \begin{bmatrix} \sin 1 \\ \vdots \\ \sin n\end{bmatrix}$$
meaning your matrix can be factored as
$$A_{ij} = \cos(i-j) \implies \mathbf{A} = \mathbf{cc^T} + \mathbf{ss^T}$$
which makes the rank of the matrix $=\min(2,n)$

Rank of matrix with cosine entries