How do I load .class files into a variable?

Question: I'm working on a text-based game as a practice project.
I already managed to write an engine that displays information and handles user input. It draws the games content from custom Scene classes. More precisely, I have a Scene superclass and create child-classes, like EvilDungeon extends Scene, for the actual playable levels.
All scenes are located in a "Scenes"-folder, but I want to be able to make game expansions later on by dropping additional .class files of new scenes into said folder.
My plan was to use loadClass when the game is started to add them to a Scene-array, but it requires the class names which I can't know, since there can a any random combination of scenes in the Scenes-folder.
How can I load all scenes in the folder without knowing which scenes exactly are present? Can I retrieve the class name somehow?
Comment: Can't your game depend on the source of those Scene subclasses? Instead of using reflections to load .class at runtime you could recompile the project with new Scene subclasses.
Answer:
My plan was to use loadClass when the game is started to add them to a Scene-array, but it requires the class names which I can't know, since there can a any random combination of scenes in the Scenes-folder.

That's what Service Provider Interfaces are for. Just define an interface for your plugins and use ServiceLoader to get an instance of each plug-in.
The plug-in needs to provide a text-file in /META-INF/services named after the interface and containing the class which implements that interface (both names must be fully qualified). You'll find the details in the documentation of ServiceLoader.
This gives you the ability to add plugins to the class-path. E.g. you can run your application using something like java -cp myapp.jar;plugins/* my.app.Main, then all the plugin-Jars in folder plugin will be added to the class-path and are available to your application (for more information on the asterisk, see this answer).
If you want to load plug-ins at runtime, you can use a URLClassLoader, e. g. read this question or this tutorial on how to use the URLClassLoader.
Comment: SPI is intended for such extendibility. You can list the available scenes. Make an interface (needed for SPI), Scene, and rename your old scene class something like AbstractScene or BaseScene or DefaultScene.
Comment: Thanks for your answer! It was very helpful!
But there's still a part I don't understand: How do I create the instance of my scenes? If I turn my `Scene` superclass into an interface or abstract class I can't create a `new` object from them, right?
Now I'd do something like this: (with `defaultScene` being the interface)
`list allScenes = new arraylist;

ServiceLoader loader = ServiceLoader.load(defaultScene.class);
 for (defaultScene myScene : loader) {
  allscenes.add(myScene);
        }`
Would this still run the constructor of the individual scenes?
Comment: The ServiceLoader creates instances of the implementations, therefore each implementation of the Service needs to provide a public no-args constructor. Of course, you can define a Service which is able to create instances of the Scene in question.
Comment: Oh, and of course the no-args constructor will be used.


What would a change of basis matrix look like between the abstract vector spaces of $\cos^k(x)$ and $\cos(kx)$?

Question: My friend mentioned that creating this matrix is possible and useful for difficult integrals with high power cosine functions. However, I am having trouble actually creating it.
My thoughts are to use the formula: $$\cos(2x)=2\cos^2(x)-1$$
But that is the end of it. I imagine there is some simple pattern I am missing. If someone could highlight it that would be great!
In case my wording is confusing, I am imagining some abstract vector space W where the first entry is the coefficient on $\ \cos^0(x) $, the second entry is the coefficient on $\ \cos^1(x) $, the third entry is the coefficient on $\ \cos^2(x) $, etc. and another abstract vector space H where the first entry in any vector is the coefficient on $\ \cos(0x) $, the second entry is the coefficient on $\ \cos(1x) $, the third entry is the coefficient on $\ \cos(2x) $, etc. The matrix I am trying to find, but currently failing at, is the change of basis matrix from W$\ \rightarrow$ H.
This would make integrals with high cosine powers easier to integrate, since a linear u-sub is extremely simple.
Comment: One way round is writing down the coefficients of Chebyshev polynomials.
Comment: You might want to have a look at the Chebyshev polynomials: https://en.m.wikipedia.org/wiki/Chebyshev_polynomials
Answer: To find that matrix, you may use the Euler's formula to help you.
$$ e^{ix} = \cos(x) + i\sin(x)$$
Since $ e^{inx}=\cos(nx)+i\sin(nx)$
And we know that $e^{inx} = {e^{ix}}^n = {(\cos(x) + i\sin(x))}^n $
So $$\cos(nx)+i\sin(nx) = {(\cos(x) + i\sin(x))}^n $$
If we take $n=2$ , using the binomial theorem on RHS, and taking the Real Part on both sides. After comparing, you can find that $\cos(2x)=2\cos^2(x)-1$.
For $n=3,4,\dots$ you can use the same technique to find out what $\cos(kx)$ is, in terms of linear combination of $1,\cos(x),\cos^2(x),\dots,\cos^k(x)$
So you can find out more columns of the change of coordinate matrix now.
And this video from Dr.Peyam may be useful. 1
Answer: The main fact is that $\cos(n\theta)=T_n(\cos(\theta))$ where $T_n$ is the $n$th degree Chebyshev polynomial of the first kind. There's no simple closed form for these polynomials but you can compute them by the recursion $T_0(x)=1,T_1(x)=x,T_{n+1}(x)=2xT_n(x)-T_{n-1}(x)$.
Thus the coefficients of $T_n$ enter the coefficient matrix mapping $\cos(n\theta)$ into $\cos^n(\theta)$, which is the opposite of the transformation you would usually want to do in trig integration. Inverting this matrix lets you go the other way.


15/8 blues playing live?

Question: I am writing a bluesy piece. I tried a 15/8 and it works great. It sounds interesting but i don't think the band will be able to play it in that time signature. I was wondering if there is a good solution to play it 15/8 live. Any ideas?
Comment: I'm intrigued by the idea of a blues with a non-standard time signature... would like a link to any recording of this!
Comment: It's going to depend entirely on how the melody line and/or rhytmic pattern is formed, could be as simple as 3 lots of 4/8 then a 3/8. Could be 3 lots of 5/8. If they can't manage 5 time, they'll never manage 15.
Comment: at what point does it not just become jazz with blues influence?
Comment: @topomorto Once I have it recording, if we manage to play it, I'll drop a link here.
Comment: Gotta try 5/8 with the band
Comment: They may end up in 4 or 6! If so, you have an answer either way. But, yes, 5 is a lovely time sig to play in.
Comment: https://www.youtube.com/watch?v=mqgyD_yTWCU
Comment: Rufus, an odd time signature doesn't make blues become jazz...
Comment: https://www.youtube.com/watch?v=k7KUYAwI-ig for an example in 11.
Comment: @SovereignSun I'm intrigued.  What are the groupings? if it's 3+3+3+3+3 then it's probably easier just to think of it as a slow 5/4 shuffle; in the way something like this https://www.youtube.com/watch?v=dNr_eIgP0tI can be thought of as as slow 4/4 shuffle or 12/8 depending on your perspective.
Comment: If you've written something in 15/8, and it works well, you should be able to play it to the band and just get them to copy the sound. How do you picture the drums sounding in your head?  When I show a new song, I often sort of beatbox a rough drum pattern to give the drummer a feel for what I'm picturing. Also, I am not a drummer, but for complex or unfamiliar timings I'll smack my hands on a desk in time, and sing the melody/guitar part/whatever so the band can hear how it all fits together. I don't play drums AT ALL, but if you know the groove of a song you should be able to do this.
Comment: Is there any chance of you posting a vocaroo or something of you just roughly outlining how your song idea sounds with just you and your guitar?  I'm really curious to hear a 15/8 blues...
Comment: @Some_Guy Actually, I play keyboard. Unfortunately, my band is paused for quire a time and we didn't even start playing it. However, I managed to save the main idea in Guitar Pro.
Answer: Tim's comment is great. I just wanted to add that 15/8 can also be understood as compound quintuple meter. As he pointed out it depends on the rhythmic structure of the melody and a complex time like this could be broken into several different smaller rhythmic groupings. If it turns out that the melody mostly fits into five pulses with triplet division then I would suggest practicing it as the meter I described above. If this is the case then it could be useful for your group to learn take five by the bruebeck quartet in order to solidify your familiarity with 5/4 time. It should be easier to do compound quintuple after getting good at simple quintuple and the swing of take five can justifiable give it a compound feel making for even better preparation. If you have questions about harmonizing or arranging this song for your groups instruments please feel free to contact me at email@example.com or find me on Facebook as Guy Gastineau. I've arranged it for solo guitar and for a four piece. It's also a great song to have in the rep to play before breaks.
Answer: The final arrangement will very much depend on the positioning of accents in the parts you have right now. As evidenced by the comments on your question, there's a number of ways to subdivide 15/8 time and the final choice will very much depend on which approach you will take.
There are several standard approaches, however, that I'd like to mention - as a jumping off point:
The 5/4 shuffle
Since it's a bluesy piece, the time signature suggests a triplet subdivision, possibly with a shuffle feel. If that is the case, the underlying rhythm can be viewed as 12/8 + 3/8 - essentially a four-beat shuffle (4/4 with triplet subdivision) with an extra beat tacked on the end.
The 10/4 shuffle
Essentially the same approach, but with a rhythm pattern that stretches for two bars of the basic time signature. It might alternatively be read as 12/8 + 12/8 + 6/8. The advantage of this approach is that the drummer can keep an alternating kick and snare every dotted quarter, which keeps the underlying beat easy enough to follow.
Depending on how the accents are distributed in the main parts, some hits may have to be moved around, but otherwise this would appear to almost be a standard even beat, so that the listener would really have to be paying attention to notice there's something strange going on. I consider this to be a benefit: overemphasis of the fact we're playing odd timings seems to me a cop-out.
The truncated 16/8
This even subdivision works out as 8/8 + 7/8 - two bars of 4/4, less an eighth note. It does require the band (especially the drummer) to be capable of playing 7/8 time.
Straight 60/8
This approach involves the rhythm section keeping a straight beat, extending over four bars of the underlying time signature. Again, accents may need some moving around, but this should feel more like syncopation than a non-standard time signature. It is equivalent to 7 bars of 4/4 (56/8) + 2/4 (4/8). As you can see, here - as in the 10/4 shuffle - the drummer can keep an alternating kick/snare pattern (this time falling on the quarter notes), whilst all the tricky compound stuff is happening over the top.

I've purposefully avoided more convoluted approaches, since you mention the band having trouble with compound time signatures. The 10/4 shuffle and straight 60/8 should be well within reach of just about any rhythm section.

15/8 blues playing live?


Poisson-gamma posterior mean expectation

Question: Let's have a gamma prior $\lambda\sim \operatorname{Gamma}(a,b)$ (mean: $\frac{a}{b}$)
With Poisson data $Y\mid \lambda\sim \operatorname{Pois}(N\lambda)$ (mean: $N\lambda$)
The posterior is $\lambda\mid Y\sim \operatorname{Gamma}(a+Y,b+N)$
The posterior mean is $E(\lambda\mid Y)=\frac{Y+a}{N+b}$.
What is its expectation? $E(E(\lambda\mid Y))=\frac{\tfrac{a}{b}+a}{N+b}$? How is this estimator called?
(I would be interested in, when I repeatedly sample from a Poisson, given samples from a gamma distribution, what will be the mean of this samples.)
Thank you very much.
Answer: From your first two lines, your prior implies $E[Y] = N\frac{a}{b}$
So with $E(\lambda\mid Y)=\frac{Y+a}{N+b}$, you have $E\left[E(\lambda\mid Y)\right] =E\left[\frac{Y+a}{N+b}\right]=\frac{E\left[Y\right] +a}{N+b}= \frac{N\frac{a}{b}+a}{N+b} = \frac{a}{b}$
which is what you might have thought from your first line and the law of total expectation
Comment: Thank you very much!!! That is excellent.


Virtual Server: RDP under attack?

Question: My newly acquired windows 2008 virtual server now has 3.500 entries (in three days) in its security log, most of which are of event ID 4625: "An account failed to log on".
The login attempts appear rather quick - about 10-20 attempts per second. I guess this is an attack - is that correct?
It does not appear as if the attacker (I'll just use this name) was successful in logging in and brute-forcing the password should not be easy since it is long and complicated...
However, I wonder whether there is something I can do systematically? How about changing the port of rdp? A hardware firewall will probably help?
Moreover, the server now hosts only a single website which is not even public yet, so I didn't expect any traffic of this kind so soon. A little vague: will this get much worse when the site goes online?
Answer: Could be. Then again it could also be an application trying to log on under credentials where the password has been changed or expired.
You should look closer at the events and establish:
 - What kind of logon is occuring? See if it's RDP, or some other kind of access
 - What account names are being attempted (If it's random account names you don't recognize, or running through A-Z of names, then definitely an attack)
Outside of that, verify that RDP to your server is accessible publically. If so, do you really need that? If your virtual server is within your organisation, lock down your public firewall to prevent this (or ask the admin in charge of the firewall to do so). If it's out in the cloud, the provider should provide interfaces for controlling network access (virtual firewalls).
You have a pretty major security problem if you have servers available on the net that are not sitting behind a proper firewall. The boxes should be available exclusively on only the ports that are needed for operation, so a basic web serving box should only have firewall rules outbound for ports 80, and 443 if SSL is served.
Security should never be approached from the other direction (start all-permissive, then lock down only specific items). Likewise, moving to a non-standard port gives only a very minor increase in security.
Comment: Thanks for the hint. Names are {Administrator, Admin, IUSR, user, server, etc.} - looks like an attack. LogonType is alwasy "NetworkCleartext". According to MSDN that is typically an IIS login attempt? LogonProcess is always "advapi". I found this link http://blogs.msdn.com/puneetgupta/archive/2007/08/20/unknown-username-or-bad-password-inetinfo-exe-advapi.aspx but it seems to be a little over-engineering for my small vps.
Comment: Worth checking what kinds of authentication IIS is configured to pass-through from clients. If your site doesn't need external users to authenticate with a windows account, turn off non-anonymous authentication methods.
Comment: Anonymous and Forms authentication are turned on - the website uses forms login. However, I didn't establish what is being attacked here: IIS or RDP. From what MSDN says, it rather seems to be IIS. However, what is being attacked in IIS then? I'm a little confused. I guess my initial question is badly formulated because it might essentially not even have to do with RDP - will try to investigate further. Thanks!
Comment: To help establish what's going on a bit more, perhaps fire up [Wireshark](http://www.wireshark.org/) to see if you can explicitly see the packets and what port they're coming in from.
Answer: Chances are your IP was scanned and RDP was detected and someone decided to try and brute force it. Once your website goes online, the amount of attempts might grow, though there's no way of telling the future.
You should be able to change the RDP port from HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp under the PortNumber key.
Be careful not to lock yourself out when installing a firewall. From what I know you may be able to set up a maximum number of login attempts from by configuring the Account Lockout Policy.
Answer: I've got the same problem with my VPS - alongside RDP they are also trying to hack into SQL Server remotely. As a consequence, over a period of a few months they were gradually filling up my disk space with ever expanding logs!
My solution was to restrict who can connect in via IP addresses - these requests now fall at the first hurdle.
As has already been mentioned, you can also change the ports for each service - it might be worth doing this in conjunction with IP addresses - you can't be too secure!
I'd also second Chris's endorsement of the Principle of Least Privilege... Lock everything down, and gradually open things up - but as little as possible.

Virtual Server: RDP under attack?


Create a view of users to show their profile visits

Question: I need to track the IP address in order to have a good idea on how many users visit each profile. This report will be available only to the admin.
I have used User Visits Advanced module
The problem is that even user can also see his profile visits by using this module.I was also trying to figuring out how to create view of recent visitors using this module but finally unsuccessful.
I just want to create view report of users and their respective profile visits .
Comment: What about https://www.drupal.org/project/visits
Answer: You can achieve this by simply creating a rule for profile clicks and add an action i.e. a counter that accepts +1 everytime the event occurs (Rules module).
To create a profile click action, all you need is the uid (user ID) which can be like this example.com/user?q=uid.
create a field in my accounts which stores this value and keep it hidden with display suite. In views, show the profile as fields and choose the uid and your recent field to display profile visits. Style it with css. sorry for bad english I am spanish


Site UUID in source storage does not match the target storage

Question: When I run drush cim -y on my staging instance of my site I get the following error:

Drupal\Core\Config\ConfigImporterException: There were errors
  validating the config synchronization. in Drupal\Core\Config\ConfigImporter->validate() (line 728 of /var/www/xeno/docroot/core/lib/Drupal/Core/Config/ConfigImporter.php).
  The import failed due for the following reasons: Site UUID in source storage does not match the target storage. Entities exist of type Paragraph and Paragraph type Image. These entities need to be deleted before importing.

This is what I did:

Copied the database from staging and pulled the latest code
Ran drush cex -y
Committed configuration
Went to staging and pull latest code
Ran drush cim -y and get the error stated above

When I run drush cget system.site uuid on local and staging I get the same uuid so I am not sure why I am getting this error.
How can I fix the error?
Answer: You can fix this by changing your local site UUID, with Drush, as described in one of the answers for How can I import the configuration on a different site?
I also needed to run a mix of drush entity-updates -y and installing specific modules with drush en <module_name> -y before the configuration objects would be imported on a new fresh database.
As per Support for automatic entity updates has been removed, you shouldn't use drush entity-updates -y anymore.
Answer: Traditionally, you would use the following before importing config:
drush cset system.site uuid "6ba9bxxx-xxxx-438x-9c8x-e5x7x3d0x347"

Or with drupal console:
$ drupal config:override

Enter configuration name []:
> system.site

Enter the configuration key [uuid]:
> uuid

Enter the configuration value:
> 6ba9bxxx-xxxx-438x-9c8x-e5x7x3d0x347

A more generic solution
For people getting tired of doing this all over again. I finally got a fix on how to do this automatically. You would have to add a pre-command for config:import with drush to set the uuid. Read all about it here: https://stefvanlooveren.me/blog/fixing-systemsite-uuid-config-import-problem-drupal-8
Answer: Actually, I was using SFTP deploy and the system.site.yml file wasn't present on the staging site. I just redeployed all files and the issue went away.
Answer: Use drush config-set "system.site" uuid <UUID value>. You can confirm the value has been changed with drush cedit system.site.
To fix the shortcut error during the configuration import, use drush ev '\Drupal::entityTypeManager()->getStorage("shortcut_set")->load("default")->delete();'.
Manually edit the system.site.yml file, changing the UUID to match.
After that, the configuration import ran successfully on my port.
Answer: Solved!
Using the Drush command. Get the site uuid from existing site the Set the UUID. That's it.
Get UUID from Source:
drush cget system.site uuid

Set UUID to target:
drush cset system.site uuid "c6a99459-912d-4502-b9d3-07dc6e5a240d"

Answer: Get UUID using: uuid:
drush cget system.site uuid

One need to paste the YML file back again to include UUID, this will resolve : /admin/config/development/configuration/single/import


Windows file server permissions mistake - Everyone denied !

Question: I just made a big mistake. I set the Everyone group Deny permissions on a folder shared..
How do I recover that ?
Please help..
Comment: Share permissions, or on the directory? Sounds like the directory on the local filesystem...
Comment: Yes it's on the directory itself..
Comment: I have the samilar problem, I just set a file permission everyone denied. and I can't edit its permission or delete it even as an administrator.
Answer: Take ownership of the folder. Remove the deny entry.
Comment: Yes indeed. It is the only way.
Comment: I'm already folder's owner (Administrator), but how to remove the deny entry ?

When trying to access the Security tab, I have a message : "You do not have permission to view the current permission settings for XXXXXX, but you can make permission changes.", then the list of users/group with associated permissions is empty !
Comment: Then I try to Add the Everyone user, I modify the permissions to Full control Allow but it refuses with : "Unable to save permission changes on XXXXX. Access is denied".
Comment: Ok, there is something strange. When I first check the owner it was set to Administrator as I said. But I closed the window and reopened it, and now it was "Don't have the permission to display the owner" or something like that. I was able to get back the ownership and correct the permissions.

Thank you
Comment: @ack__ Ensure you are re-taking the ownership correctly.  On the Ownership tab, reselect Administrator in the Change to section. Click Apply.  This should allow you to delete the Everyone entry on the Security tab.


How to set edges styles of Graph based on it's weights in Wolfram?

Question: I set my custom graph with vertex names like ell, poll, novi etc. (not numbers, but symbolic names). And I set vertexes and edges weights (weights can be positive or negative). I want to set different style parameters of vertexes and edges based on those weights. How can I do that? Thank you.
Graph[
 {
  Labeled[
   Property[
    vat, {VertexSize -> (.567 + .7)/3,
     VertexStyle -> Hue[.567/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    elch, {VertexSize -> (-.608 + .7)/3,
     VertexStyle -> Hue[-.608/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    ion, {VertexSize -> (-.025 + .7)/3,
     VertexStyle -> Hue[-.025/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    kar, {VertexSize -> (-.167 + .7)/3,
     VertexStyle -> Hue[-.167/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    kos, {VertexSize -> (-.400 + .7)/3,
     VertexStyle -> Hue[-.400/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    lap, {VertexSize -> (.408 + .7)/3,
     VertexStyle -> Hue[.408/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    mas, {VertexSize -> (-.050 + .7)/3,
     VertexStyle -> Hue[-.050/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    novi, {VertexSize -> (.258 + .7)/3,
     VertexStyle -> Hue[.258/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    novo, {VertexSize -> (-.033 + .7)/3,
     VertexStyle -> Hue[-.033/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    pod, {VertexSize -> (-.083 + .7)/3,
     VertexStyle -> Hue[-.083/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    pol, {VertexSize -> (.142 + .7)/3,
     VertexStyle -> Hue[.142/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    sar, {VertexSize -> (.025 + .7)/3,
     VertexStyle -> Hue[.025/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    sok, {VertexSize -> (-.142 + .7)/3,
     VertexStyle -> Hue[-.142/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    sut, {VertexSize -> (.067 + .7)/3,
     VertexStyle -> Hue[.067/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    ust, {VertexSize -> (-.050 + .7)/3,
     VertexStyle -> Hue[-.050/3 + .75, 1, 1]}], ""],
  Labeled[
   Property[
    ell, {VertexSize -> (.117 + .7)/3,
     VertexStyle -> Hue[.117/3 + .75, 1, 1]}], ""]
  }
 ,
 {
  Property[vat -> elch, EdgeWeight -> -9],
  Property[vat -> kar, EdgeWeight -> 3],
  Property[vat -> kos, EdgeWeight -> -4],
  Property[vat -> lap, EdgeWeight -> 5],
  Property[vat -> mas, EdgeWeight -> -1],
  Property[vat -> novi, EdgeWeight -> 1],
  Property[vat -> novo, EdgeWeight -> 1],
  Property[vat -> pod, EdgeWeight -> -2],
  Property[vat -> pol, EdgeWeight -> 4],
  Property[vat -> sut, EdgeWeight -> 2],
  Property[kar -> vat, EdgeWeight -> 9],
  Property[kar -> elch, EdgeWeight -> -9],
  Property[kar -> ion, EdgeWeight -> -1],
  Property[kar -> lap, EdgeWeight -> 1],
  Property[kar -> mas, EdgeWeight -> -2],
  Property[kar -> novi, EdgeWeight -> 4],
  Property[kar -> novo, EdgeWeight -> 1],
  Property[kar -> sar, EdgeWeight -> 1],
  Property[kar -> sok, EdgeWeight -> -4],
  Property[kar -> ust, EdgeWeight -> -2],
  Property[sok -> vat, EdgeWeight -> 2],
  Property[sok -> elch, EdgeWeight -> -4],
  Property[sok -> ion, EdgeWeight -> -3],
  Property[sok -> kar, EdgeWeight -> -4],
  Property[sok -> kos, EdgeWeight -> -3],
  Property[sok -> lap, EdgeWeight -> 3],
  Property[sok -> novi, EdgeWeight -> 1],
  Property[sok -> novo, EdgeWeight -> 1],
  Property[sok -> pod, EdgeWeight -> -1],
  Property[sok -> pol, EdgeWeight -> -3],
  Property[sok -> sar, EdgeWeight -> 2],
  Property[sok -> sut, EdgeWeight -> 2],
  Property[sok -> ell, EdgeWeight -> 7],
  Property[novo -> vat, EdgeWeight -> 6],
  Property[novo -> elch, EdgeWeight -> 3],
  Property[novo -> ion, EdgeWeight -> -2],
  Property[novo -> kar, EdgeWeight -> -2],
  Property[novo -> kos, EdgeWeight -> -3],
  Property[novo -> lap, EdgeWeight -> 1],
  Property[novo -> pod, EdgeWeight -> -1],
  Property[novo -> sok, EdgeWeight -> -2],
  Property[novo -> sut, EdgeWeight -> 1],
  Property[novo -> ust, EdgeWeight -> -3],
  Property[novo -> ell, EdgeWeight -> 2],
  Property[sut -> vat, EdgeWeight -> 7],
  Property[sut -> elch, EdgeWeight -> -3],
  Property[sut -> kar, EdgeWeight -> -6],
  Property[sut -> kos, EdgeWeight -> -6],
  Property[sut -> lap, EdgeWeight -> -1],
  Property[sut -> novi, EdgeWeight -> 6],
  Property[sut -> novo, EdgeWeight -> -1],
  Property[sut -> pol, EdgeWeight -> 4],
  Property[novi -> vat, EdgeWeight -> 3],
  Property[novi -> elch, EdgeWeight -> -3],
  Property[novi -> kar, EdgeWeight -> 2],
  Property[novi -> kos, EdgeWeight -> -7],
  Property[novi -> lap, EdgeWeight -> 6],
  Property[novi -> mas, EdgeWeight -> 1],
  Property[novi -> novo, EdgeWeight -> -1],
  Property[novi -> pol, EdgeWeight -> 3],
  Property[novi -> sut, EdgeWeight -> -2],
  Property[novi -> ust, EdgeWeight -> -1],
  Property[novi -> ell, EdgeWeight -> 3],
  Property[lap -> vat, EdgeWeight -> 8],
  Property[lap -> elch, EdgeWeight -> -2],
  Property[lap -> ion, EdgeWeight -> 1],
  Property[lap -> kar, EdgeWeight -> 1],
  Property[lap -> kos, EdgeWeight -> -3],
  Property[lap -> mas, EdgeWeight -> -3],
  Property[lap -> novi, EdgeWeight -> 4],
  Property[lap -> novo, EdgeWeight -> -1],
  Property[lap -> sar, EdgeWeight -> -4],
  Property[lap -> sok, EdgeWeight -> -2],
  Property[lap -> ell, EdgeWeight -> 1],
  Property[ell -> vat, EdgeWeight -> 3],
  Property[ell -> elch, EdgeWeight -> -8],
  Property[ell -> kar, EdgeWeight -> 1],
  Property[ell -> kos, EdgeWeight -> -2],
  Property[ell -> lap, EdgeWeight -> 6],
  Property[ell -> mas, EdgeWeight -> -3],
  Property[ell -> novi, EdgeWeight -> 1],
  Property[ell -> novo, EdgeWeight -> -2],
  Property[ell -> pol, EdgeWeight -> 5],
  Property[ell -> sok, EdgeWeight -> -3],
  Property[ell -> sut, EdgeWeight -> 2],
  Property[ust -> vat, EdgeWeight -> 6],
  Property[ust -> elch, EdgeWeight -> -8],
  Property[ust -> ion, EdgeWeight -> 2],
  Property[ust -> kos, EdgeWeight -> -7],
  Property[ust -> lap, EdgeWeight -> 2],
  Property[ust -> novi, EdgeWeight -> 2],
  Property[ust -> pod, EdgeWeight -> 1],
  Property[ust -> pol, EdgeWeight -> 2],
  Property[ust -> sok, EdgeWeight -> -2],
  Property[ust -> sut, EdgeWeight -> 2],
  Property[mas -> vat, EdgeWeight -> 3],
  Property[mas -> elch, EdgeWeight -> -9],
  Property[mas -> kar, EdgeWeight -> -2],
  Property[mas -> kos, EdgeWeight -> -5],
  Property[mas -> lap, EdgeWeight -> 8],
  Property[mas -> novi, EdgeWeight -> 1],
  Property[mas -> pod, EdgeWeight -> -2],
  Property[mas -> pol, EdgeWeight -> 1],
  Property[mas -> sar, EdgeWeight -> 4],
  Property[mas -> ell, EdgeWeight -> 1],
  Property[sar -> vat, EdgeWeight -> 5],
  Property[sar -> elch, EdgeWeight -> -7],
  Property[sar -> kar, EdgeWeight -> -3],
  Property[sar -> kos, EdgeWeight -> -4],
  Property[sar -> lap, EdgeWeight -> 8],
  Property[sar -> mas, EdgeWeight -> 2],
  Property[sar -> novi, EdgeWeight -> 3],
  Property[sar -> pod, EdgeWeight -> -4],
  Property[ion -> vat, EdgeWeight -> 9],
  Property[ion -> elch, EdgeWeight -> -1],
  Property[ion -> kar, EdgeWeight -> -9],
  Property[ion -> kos, EdgeWeight -> -4],
  Property[ion -> lap, EdgeWeight -> 6],
  Property[ion -> novi, EdgeWeight -> 2],
  Property[ion -> novo, EdgeWeight -> -1],
  Property[ion -> pod, EdgeWeight -> -1],
  Property[ion -> pol, EdgeWeight -> 1],
  Property[ion -> sok, EdgeWeight -> -2],
  Property[pod -> vat, EdgeWeight -> 7],
  Property[pod -> elch, EdgeWeight -> -9],
  Property[pod -> ion, EdgeWeight -> -2],
  Property[pod -> kar, EdgeWeight -> -1],
  Property[pod -> lap, EdgeWeight -> 4],
  Property[pod -> novi, EdgeWeight -> 6],
  Property[pod -> novo, EdgeWeight -> -1],
  Property[pod -> sok, EdgeWeight -> -2],
  Property[pod -> sut, EdgeWeight -> 1]
  },
 EdgeShapeFunction ->
  GraphElementData[{"CarvedArrow", "ArrowSize" -> .01}],
  GraphLayout -> "CircularEmbedding",
 EdgeStyle ->
  Thread[a ->
    Transpose@{Dashing /@ ((b + 0.5)/10), Hue /@ (b + 0.5),
      Thickness /@ ((b + 0.5)/100)}]
 ]

Answer: You didn't give much info about your graph, but this is a way to let the different EdgeStyle characteristics be defined by EdgeWeight.
Graph[a = {"a" <-> "b", "b" <-> "c", "c" <-> "a"},
 EdgeWeight -> (b = RandomReal[{-.5, .5}, 3]),
 EdgeStyle ->
  Thread[a ->
    Transpose@{Dashing /@ ((b + 0.5)/10), Hue /@ (b + 0.5),
      Thickness /@ ((b + 0.5)/100)}]]

Edit:
name = {vat, elch, ion, kar, kos, lap, mas, novi, novo, pod, pol, sar,
    sok, sut, ust, ell};
vSize = {.567, -.608, -.025, -.167, -.4, .408, -.05, .258, -.033, \
-.083, .142, .025, -.142, .067, -.05, .117};
hue = {.567, -.608, -.025, -.167, -.4, .408, -.05, .258, -.033, \
-.083, .172, .025, -.142, .025, -.142, .067, -.050, .117};
props = Labeled[
     Property[
      name[[#]], {VertexSize -> (vSize[[#]] + .7)/3,
       VertexStyle -> Hue[hue[[#]]/3 + .75, 1, 1]}], ""] & /@
   Range[Length[name]];
a = {vat -> elch, vat -> kar, vat -> kos, vat -> lap, vat -> mas,
   vat -> novi, vat -> novo, vat -> pod, vat -> pol, vat -> sut,
   kar -> vat, kar -> elch, kar -> ion, kar -> lap, kar -> mas,
   kar -> novi, kar -> novo, kar -> sar, kar -> sok, kar -> ust,
   sok -> vat, sok -> elch, sok -> ion, sok -> kar, sok -> kos,
   sok -> lap, sok -> novi, sok -> novo, sok -> pod, sok -> pol,
   sok -> sar, sok -> sut, sok -> ell, novo -> vat, novo -> elch,
   novo -> ion, novo -> kar, novo -> kos, novo -> lap, novo -> pod,
   novo -> sok, novo -> sut, novo -> ust, novo -> ell, sut -> vat,
   sut -> elch, sut -> kar, sut -> kos, sut -> lap, sut -> novi,
   sut -> novo, sut -> pol, novi -> vat, novi -> elch, novi -> kar,
   novi -> kos, novi -> lap, novi -> mas, novi -> novo, novi -> pol,
   novi -> sut, novi -> ust, novi -> ell, lap -> vat, lap -> elch,
   lap -> ion, lap -> kar, lap -> kos, lap -> mas, lap -> novi,
   lap -> novo, lap -> sar, lap -> sok, lap -> ell, ell -> vat,
   ell -> elch, ell -> kar, ell -> kos, ell -> lap, ell -> mas,
   ell -> novi, ell -> novo, ell -> pol, ell -> sok, ell -> sut,
   ust -> vat, ust -> elch, ust -> ion, ust -> kos, ust -> lap,
   ust -> novi, ust -> pod, ust -> pol, ust -> sok, ust -> sut,
   mas -> vat, mas -> elch, mas -> kar, mas -> kos, mas -> lap,
   mas -> novi, mas -> pod, mas -> pol, mas -> sar, mas -> ell,
   sar -> vat, sar -> elch, sar -> kar, sar -> kos, sar -> lap,
   sar -> mas, sar -> novi, sar -> pod, ion -> vat, ion -> elch,
   ion -> kar, ion -> kos, ion -> lap, ion -> novi, ion -> novo,
   ion -> pod, ion -> pol, ion -> sok, pod -> vat, pod -> elch,
   pod -> ion, pod -> kar, pod -> lap, pod -> novi, pod -> novo,
   pod -> sok, pod -> sut};
b = {-9, 3, -4, 5, -1, 1, 1, -2, 4, 2, 9, -9, -1, 1, -2, 4, 1,
   1, -4, -2, 2, -4, -3, -4, -3, 3, 1, 1, -1, -3, 2, 2, 7, 6,
   3, -2, -2, -3, 1, -1, -2, 1, -3, 2, 7, -3, -6, -6, -1, 6, -1, 4,
   3, -3, 2, -7, 6, 1, -1, 3, -2, -1, 3, 8, -2, 1, 1, -3, -3,
   4, -1, -4, -2, 1, 3, -8, 1, -2, 6, -3, 1, -2, 5, -3, 2, 6, -8,
   2, -7, 2, 2, 1, 2, -2, 2, 3, -9, -2, -5, 8, 1, -2, 1, 4, 1,
   5, -7, -3, -4, 8, 2, 3, -4, 9, -1, -9, -4, 6, 2, -1, -1, 1, -2,
   7, -9, -2, -1, 4, 6, -1, -2, 1};
Graph[props, a, EdgeWeight -> b,
 EdgeShapeFunction ->
  GraphElementData[{"CarvedArrow", "ArrowSize" -> .01}],
 GraphLayout -> "CircularEmbedding",
 EdgeStyle ->
  Thread[a ->
    Transpose@{Dashing /@ ((b + 9)/2000), Hue /@ ((b + 9)/20),
      Thickness /@ ((b + 9)/2000)}]]

Comment: Your solution did not work for me. Am I doing something wrong? I post my whole code to the Q.
Comment: @DmitriyKorobkov Guess it's the season, I've edited your code in my answer.
Comment: Thank you very much! It is what I need.


Is there a way to estimate ridge regression regularisation parameter from OLS output

Question: When performing ridge regression there is a regularisation parameter to choose. Can a good approximate value be estimated from output from standard OLS.
Intuitively these factors seem important:
- the larger the sample N the larger the regularisation needs to be
- the more unexplainable error in fitted variable the larger the regularisation needs to be
- the amount of correlation in the explanatory variables maybe an important factor
How to combine these from OLS( and other factors) to make an estimate would be useful if it was possible. Is it possible without using a solver to minimise some objective function?
Comment: *the larger the sample N the larger the regularisation needs to be* -- did you mean the opposite?
Comment: What criterion are you proposing for selecting the regularization parameter?  We need some specific target if we're to have any hope of knowing what an approximate answer might be.
Comment: @whuber the criterion am looking to minimise by using regularisation is prediction error. So if we later do cross validation of sum of squared errors this was close to a good choice.
Comment: @RichardHardy I am adding regularisation by adding additional samples to the standardised training set/explanatory variables with response variable equal to zero. So if there are a lot of samples before adding this regularisation they need to be larger or they will be drowned out.
Answer: Yes, you can obtain a rough estimate of the penalty parameter from standard OLS output. People in the old days used to compute
$$ \lambda = \frac{ k \hat{\sigma }^2} {||\hat{\boldsymbol{\beta}}||^2}, $$
where $k$ is the number of slope coefficients, $ \hat{\sigma }$ is an estimated residual scale and $\hat{\boldsymbol{\beta}} $ is the vector of estimated slopes. This formula may be found in the old papers of Hoerl and Kennard from the 70s. My guess is that modern  crossvalidation methods produce better estimates but this may be good enough for simple problems.
Comment: I think that might be a little misleading: if it works for standardized coefficients, then in any case where the columns are not close to standardized it's likely *not* to work and can be arbitrarily bad. Thus, it's important to be clear about what $\hat\beta$ is.
Comment: I'm having trouble seeing why this would work.  Are you perhaps assuming the betas are the *standardized* coefficients?
Comment: @whuber sorry for the late response. This indeed works best for standardised coefficients.
Comment: @JohnK thanks for this idea I will try out, I am using standardised coefficients.


How to disable "related videos" from an embedded youtube playlist

Question: I need to embed a Youtube playlist on an iframe. I don't want the user to be able to exit this playlist, so I need to disable the "related video" and "more video" features (the one that shows more videos when the video is stopped and the one that shows them when the video is finished).
I've tested some workarounds but they only used to work for single videos (not playlist) and most of them stopped working after they changed the way ?rel=0 behaves. Is there any way to do this?
This is my code:
.rep {
   position: absolute;
   top: 0px;
   left: 0px;
   width: 1280px;
   height: 640px;
   z-index: 6;
}

EDIT: The videos must be shown in order, therefore I can't use rel to display only videos from the playlist. Plus, if you click on them a youtube page outside of the iframe will appear.
Comment: The behavior for the rel parameter is changing on or after September 25, 2018. The effect of the change is that you will not be able to disable related videos. However, you will have the option of specifying that the related videos shown in the player should be from the same channel as the video that was just played. https://developers.google.com/youtube/player_parameters#showinfo
Comment: Yeah, thats exactly what I answered you on the answer you just deleted. I'm looking for a workaround
Comment: I'm confused, I just tried `` and it prevents the More video when paused as well as removes related video at the end. Thats what you wanted right?
Comment: It doesnt for me. Did you add the css? If you didnt, the player will be way too small for it to show the related videos. Regarding the videos at the end, they will only be shown after the last video of the playlist.
Comment: Yes you are right, once i added the css the problem occurs.
Answer: If I look through the YouTube Embedded Players and Player Parameters docs, there is no such thing to order the more videos section if you pause the video.
The two parameters I suggest to get near as possible to your goal is:
You can add:

listType=playlist
rel=0 to turn off related videos from the more videos section.

Note: The behaviour of rel=0 will be removed after September 25, 2019.

Conclusion:
It seems like what you want to achieve is not possible. With the default embed iframe of YouTube.
You might want to consider to look to other players with playlist options. Something like JW Player note that you need a licence for this player, JW Player playlist docs. I did some reading on JW Player as well, they currently don't support YouTube videos.
But maybe there are other players that have the same functionally for free.
Comment: I tried today and rel=0 is still working.
Answer: If you add &rel=0 at the end of playlist link - in related videos will be showed only videos from your playlist. Example:

If you remove &rel=0 from the link, it show random videos from youtube
Comment: I need to make it so the user can't skip videos, which means I cannot use the new rel at all. Also, doing that opens a youtube page (if you click the related videos) and I do not want that to happen.
Answer:
Update for 2021

Youtube now seems to have a loop function that can be used to git rid of "related videos". What it does basically is that when your video ends, it restarts again instead of showing (un)related videos. It worked perfectly in my case. Here is the code:
https://www.youtube.com/embed/VIDEO_ID?playlist=VIDEO_ID&loop=1

Please make sure to replace both VIDEO_ID in the code with your video ID. N̲o̲ N̲e̲e̲d̲ for creating a playlist
Example of full iframe code with player controls being enabled

Example of full iframe code with player controls being disabled

Comment: Does not work, keeps suggesting videos at the end (with/without player controls)...
Comment: It works if you also add `listType=playlist`
Answer: Here is a work around not the best but it will stop them annoy recommendations. It loops the playlist never giving youtube a chance to stop and give you there recommendations to get users back to youtube. This has worked well for me. If you see it plays my list in the loop and then plays the next, all without ever bringing up the recommendations. if you stop it it just stays there. Hope it helps they key is 0&loop
https://codesandbox.io/s/adoring-tereshkova-nwv8i
<!DOCTYPE html>

    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />

Answer: It can not be done after September 25, 2018. The effect of the change is that you will not be able to disable related videos. Below is the YouTube official post link of it.
Official Link: https://developers.google.com/youtube/player_parameters#release_notes_08_23_2018
Thanks
Answer: I just found a great website that found a fix for your problem. The code is a bit long, but I think it works. They have an example if you scroll up a bit. https://www.maxlaumeister.com/blog/hide-related-videos-in-youtube-embeds/#hideyt-embed-code

        <iframe width="640" height="360" src="https://www.youtube.com/embed/`**YOUR VIDEO ID HERE**`?rel=0&enablejsapi=1" frameborder="0">

Comment: Unfortunately, that doesn't work with playlists and it doesnt work on the browser I want to display it on.
Comment: Please place the code here instead of a link, since link may close or be dead at any time.
Answer: In my case this is working you can try this :
https://www.youtube-nocookie.com/embed/{videoId}?rel=0&showinfo=0

Answer: Unfortunately, external CSS or JS can't be applied to iframe videos or iframe contents in a webpage.
For now, you can add rel=0 parameter to the video URL in iframe code. As per youtube documentations, rel=0 parameter will be disabled after Sep 25 2019.
Here is an example with rel=0 parameter

You can also use the playlist feature or parameter. See example below:

Above code is taken from Official Youtube Support documents. You can add only one video in the list so that it does not play any other video after the current video finishes.
Comment: It was disabled Sep 25 2018, as I stated in my question. It no longer disables related videos, instead shows them from the same channel.
Comment: Sorry, I have checked it again and missed the year in date. I will look for another solution and update it here.
Answer: Based on the work of Maximillian Laumeister hideyt I forged a JS which can be included anywhere and autoamtically wraps its magic around every embedded youtube iframe you have.
hideYTrel.js
"use strict";
if (document.readyState !== 'loading') init();
else document.addEventListener('DOMContentLoaded', init);

function init() {
    if (window.runOnce) return;

    if (typeof YT === 'undefined') {
        var tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    }

    var iframes = [];

    for (var iframe of document.querySelectorAll("iframe[src]")) {
        var src = iframe.getAttribute("src");
        if (src.includes("youtube.com/embed/")) {
            if(!src.includes("enablejsapi=1"))
                if(src.includes("?"))
                    iframe.setAttribute("src", src + "&enablejsapi=1");
                else
                    iframe.setAttribute("src", src + "?enablejsapi=1");

            iframes.push(iframe);
        }
    }

    var overlayStyles = {
        display: "none",
        content:"",
        position: "absolute",
        left: 0,
        right: 0,
        cursor: "pointer",
        backgroundColor: "black",
        backgroundRepeat: "no-repeat",
        backgroundPosition: "center",
    };

    window.onYouTubeIframeAPIReady = function() {
        iframes.forEach(function(iframe) {
            var overlay = document.createElement('div');
            for (var style in overlayStyles) {
                overlay.style[style] = overlayStyles[style];
            }

            var wrapper = document.createElement('div');
            wrapper.style.display = "inline-block";
            wrapper.style.position = "relative";

            iframe.parentNode.insertBefore(wrapper, iframe);

            wrapper.appendChild(overlay);
            wrapper.appendChild(iframe);

            var onPlayerStateChange = function(event) {
                if (event.data == YT.PlayerState.ENDED) {
                    overlay.style.backgroundImage = "url(data:image/svg+xml;utf8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjgiIGhlaWdodD0iMTI4IiB2aWV3Qm94PSIwIDAgNTEwIDUxMCI+PHBhdGggZD0iTTI1NSAxMDJWMEwxMjcuNSAxMjcuNSAyNTUgMjU1VjE1M2M4NC4xNSAwIDE1MyA2OC44NSAxNTMgMTUzcy02OC44NSAxNTMtMTUzIDE1My0xNTMtNjguODUtMTUzLTE1M0g1MWMwIDExMi4yIDkxLjggMjA0IDIwNCAyMDRzMjA0LTkxLjggMjA0LTIwNC05MS44LTIwNC0yMDQtMjA0eiIgZmlsbD0iI0ZGRiIvPjwvc3ZnPg==)";
                    overlay.style.backgroundSize = "64px 64px";
                    overlay.style.top = 0;
                    overlay.style.bottom = 0;
                    overlay.style.display = "inline-block";
                } else if (event.data == YT.PlayerState.PAUSED) {
                    overlay.style.backgroundImage = "url(data:image/svg+xml;utf8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEiIHdpZHRoPSIxNzA2LjY2NyIgaGVpZ2h0PSIxNzA2LjY2NyIgdmlld0JveD0iMCAwIDEyODAgMTI4MCI+PHBhdGggZD0iTTE1Ny42MzUgMi45ODRMMTI2MC45NzkgNjQwIDE1Ny42MzUgMTI3Ny4wMTZ6IiBmaWxsPSIjZmZmIi8+PC9zdmc+)";
                    overlay.style.backgroundSize = "40px 40px";
                    overlay.style.top = "40px";
                    overlay.style.bottom = "50px";
                    overlay.style.display = "inline-block";
                } else if (event.data == YT.PlayerState.PLAYING) {
                    overlay.style.display = "none";
                }
            };

            var player  = new YT.Player(iframe, {
                    events: {
                        'onStateChange': onPlayerStateChange
                    }
                });

            wrapper.addEventListener("click", function() {
                var playerState = player.getPlayerState();
                if (playerState == YT.PlayerState.ENDED) {
                    player.seekTo(0);
                } else if (playerState == YT.PlayerState.PAUSED) {
                    player.playVideo();
                }
            });
        });
    };
    window.runOnce = true;
}

Jsfiddle: https://jsfiddle.net/pv75zjoh
Answer: I found out that if the youtube channel the video is from has less than (I don't know how many exactly but definitely  more than 20 and less than 40) videos and the iframe youtube url has the rel=0 attribute, it won't show the related videos section at all.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32783032)
Answer: URL parameter rel=0 is working fine to stop the appearance of related videos.
e.g. https://www.youtube.com/embed/fMTfFNihqfM?autoplay=1&rel=0


Cannot get theme_links__system_main_menu($variables) to fire now matter what

Question: i've added the code below to my theme's template.php file. i've cleared the cache too. but this just isn't firing no matter what. i'm not getting any errors either.
anyone have any experience with this function? i am using a sub-theme of the Adaptive theme. don't know if that has anything to do with it.
function spn_at_links__system_main_menu($variables) {
 echo '';
 $html = "
";
 $html .= "
";
 foreach ($variables['links'] as $link) {
   $html .= "
".l($link['title'], $link['path'], $link)."
";
 }
 $html .= "
";
 $html .= "
";

 return $html;
}

yes my theme name is spn_at with an underscore. i have other theme related function working just fine in the template.php file. big thanks for any help w/ this
Comment: How is your main menu rendered?
Answer: The Adaptive theme never calls links__system_main_menu from its page.tpl.php file, hence providing an override has no effect and it falls back to theme_links. If you want to override it you will have to provide your own theme suggestion in preprocess hook function.
Look here for more info: THE DEFINITIVE GUIDE TO DRUPAL 7
Comment: $variables['theme_hook_suggestions'][] = 'spn_at_links__system_main_menu';
Comment: obvious maybe, it did not work. actually it made all my menus disappear!, til i removed and cleared the cache


Graph Theory: (Open) Ear Decomposition Has Number of Ears Equal to Circuit Rank / Nullity / Cyclomatic Number

Question:
The Wikipedia article on 'Circuit rank' tells me that 'In any biconnected graph with circuit rank $r$, every open ear decomposition has exactly $r$ ears.'
It refers to Whitney's 1932 paper 'Non-separable and planar graphs' - especially Theorem 18 - to make that connection.
Theorem 18. If $G$ is a non-separable graph of nullity $N>1$, we can remove an arc [edge] or suspended chain [internally disjoint path] from $G$, leaving a non-separable graph $G'$ of nullity $N-1$.
Unfortunately, I cannot deduce from the theorem the connection between circuit rank and number of ears in an ear decomposition.
Answer: Both the circuit rank and the number of ears in an ear decomposition can be computed from the number of vertices and edges in the graph.
Suppose the graph $G$ is $2$-connected, and has $n$ vertices and $m$ edges.

The maximum number of edges in an acyclic graph on $n$ vertices is $n-1$, and we can reach that by deleting all edges outside a spanning tree of $G$. If we do that, we are deleting $m-(n-1) = m-n+1$ edges, so the circuit rank is $m-n+1$.
Suppose that $G$ has an ear decomposition that begins with a cycle and adds $k-1$ more ears. In the cycle, the number of vertices equals the number of edges. Adding an ear of length $\ell$ adds $\ell$ edges and $\ell-1$ vertices, increasing the difference $|E|-|V|$ by $1$. Therefore after adding $k-1$ ears, the difference is $k-1$; but we know the difference is $m-n$. So $k-1 = m-n$, or $k = m-n+1$.


Redirect Apache just for specific site

Question: is it possible to have a redirect for a specific URL. I mean the following.
Redirect to an other site. On this site there are images under http://www.examples/images
ProxyPass /content http://www.example/content
ProxyPassReverse /content http://www.example/content

But images are not loading, so I try to add.
ProxyPass /images http://www.example/images

But there are also images on the proxy under http://www.proxy.com/images where I try to redirect.
So it is possible to redirect the images just for the example.com site when they needed?
I hope somebdy understand what I mean :)
Comment: If I understand you correctly rather than a ProxyPass you need to use mod_rewrite. You can set a rewrite condition such that when the requested resource does not exist as a file a rewrite rule with a proxy target gets triggered. This answer might apply http://serverfault.com/a/656001/37681
Answer: Use the Redirectdirective in mod_alias, see the documentation here.
This should help you:
# Redirect to a URL on a different host
Redirect "/content" "http://www.example/content"

Comment: Hi, the simple redirect is working, but when I type http://www.myproxy/content/test/, I get an redirect to http://www.example/content.
Comment: Is it maybe possible to use just the exact path? So when I type http://www.myproxy.com/content/ I want the redirect but when I type http://www.myproxy.com/content/test/test/test I do not want a redirect.
Comment: RedirectMatch will set you up. Please take a look at the documentation i linked before further inquiry.
Comment: RedirectMatch "^/Images/(.*)" "http://new.example.com/Images/$1"
I add this one for my images, but is doesnt work.
What I am doing wrong.
Answer: If you want to link a specific URL pattern to another site, then this question has been answered here using mod_rewrite instead of ProxyPass :
https://stackoverflow.com/a/1701992/1725739
Comment: Consider mod_alias with redirect instead. Also see https://httpd.apache.org/docs/2.4/rewrite/avoid.html
Answer: I tried an other solution so far.
    RewriteEngine On
    RewriteCond %{REQUEST_URI} !myproxy.com/content/$ [NC]
    RewriteRule ^ htpp://www.example.de%{REQUEST_URI} [L,NE,P]

But everything is redirect to www.example.com
How can I change this?

Redirect Apache just for specific site


UTF8 combination PHP/MySql

Question: My sql database have utf8_unicode_ci collation and HTML have utf8 (meta charset="utf-8").
when i write in PHP:
$query = "SELECT * FROM  `subjects` WHERE  `year` = '$year'";
$result = $mysqli->query($query);

while($row = mysqli_fetch_array($result)){
    echo "<option value='" .  $row['name'] . "'>" . $row['name'] . "</option>";
}

instead čćšđ i am getting some crazy values like: ?�...
Answer: Add
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET 'utf8_general_ci'");

before
$query = "SELECT * FROM  `subjects` WHERE  `year` = '$year'";

Comment: @PauliusMarčiukaitis after the `mysql connection` place the queries will work as a GLOBAL to mysql
Comment: So it's 2 more queries... Use them only once, then delete...
Answer: Encode your HTML or PHP file to UTF-8. Possible with most editors. What is more about your code, if you want to make it with less code use (I think you need only ASSOC values)
while($row = $result->fetch_assoc())

instead of
while($row = mysqli_fetch_array($result))

Comment: +vote for pointing this `while($row = $result->fetch_assoc())` out

UTF8 combination PHP/MySql


QuotaExceededError using Ionic Storage with a few strings

Question: I'm having this issue with Ionic Storage, this is the complete stack trace:
core.es5.js:1084 ERROR Error: Uncaught (in promise): QuotaExceededError:
at c (polyfills.js:3)
at c (polyfills.js:3)
at polyfills.js:3
at t.invokeTask (polyfills.js:3)
at Object.onInvokeTask (core.es5.js:4140)
at t.invokeTask (polyfills.js:3)
at r.runTask (polyfills.js:3)
at o (polyfills.js:3)
at IDBTransaction.invoke (polyfills.js:3)

I'm using the settigs servis as recommended in Ionic super template.
this is happening testing on browser (Chrome)
Comment: For Chrome try this: https://stackoverflow.com/a/52635590/7752468
Answer: By chance, tonight I discovered that the hard disk of my windows PC was almost full, which was generating problems of virtual memory, and specifically in chrome problems with the local storage
Comment: I have the same problem on Mac if I have less than 1Go free on my hard disk.
Comment: same issue on ubuntu 14.04. Guess it affects every os
Comment: same on the Windows 10 (900 MB) :p
Comment: It didn't work for me. I use ionic-native-storage to solve this problem.
Comment: correct answer.. local storage set value end with error... when i delete some file app works fine...
Comment: my laptop was running out of space too. :/
Answer: I had the same issue and discovered that my hard disk running short of space. Cleared the memory and it worked fine.
Answer: Did you try this:
IonicStorageModule.forRoot({
  name: '__mydb',
  driverOrder: ['sqlite', 'websql', 'indexeddb']
})


Usando formula em SQL

Question: Olá, estou com uma dúvida e não acho exemplos para progredir, seguinte:
select
    'disponivel' as TIPO
    , COUNT(distinct dp.ds_nome) as qtd
FROM
    dm_pessoa_treino dp
union ALL
select
    'em_uso' as TIPO
    ,COUNT(distinct nm_cpf) as qtd
FROM
    ft_pessoa_treino fp

Resultado:
|tipo       |qtd |
|disponivel |2845|
|em_uso     |2848|

Proposição:
Quero poder exibir um resultado com a seguinte equação: N(disp.) * 100 / N(uso)
usando como base os resultados de COUNT.

Answer: Retirei o campos que você coloca como Tipo, separei os dois selects e fiz um select que ja faz a conta com o outro select.
No firebird ficaria assim:
select
    (
    (select
       COUNT(distinct dp.ds_nome) as qtd
    FROM
        dm_pessoa_treino dp  ) *100)
     /
    (select
        COUNT(distinct nm_cpf) as qtd
    FROM
        ft_pessoa_treino fp)
    )
from
    rdb$database

Answer: Flavio, não sei qual banco de dados você está utilizando, mas segue uma sugestão para testes:
with CTE_Qtds as
(
  select
    'disponivel' as TIPO
    ,COUNT(distinct dp.ds_nome) as qtd
  FROM dm_pessoa_treino dp

  union ALL

  select
    'em_uso' as TIPO
    ,COUNT(distinct nm_cpf) as qtd
  FROM ft_pessoa_treino fp
)

select *
from CTE_Qtds

union all

select
  'resultado',
  100.0 * d.qtd / u.qtd
from CTE_Qtds as d
cross join CTE_Qtds as u
where
  d.tipo = 'disponível' and
  u.tipo = 'em_uso'

Espero que ajude

Usando formula em SQL


Regular expression rules for union and concatenation with $\epsilon$ and $\emptyset$

Question: I have four rules here that are true and I wanted to make sure I have a general intuition as of why. These aren't meant to be rigorous proofs, but rather simple explanations.
Suppose $R$ is a regular expression. Then,
$R\cup \emptyset = R$. This is because $\emptyset$ is empty. This is straightforward.
$R\cdot\emptyset = \emptyset$. This is because concatenation is defined as $A\cdot B = \{xy | x\in A \texttt{ and } y\in B\}$. Nothing is in $\emptyset$, so our second requirement is not fulfilled, and never will be, so we get $\emptyset$.
$R \cdot\epsilon = R$. This is because $\epsilon$ doesn't change the regular regular expression in any way. (My explanation is lacking, and is not that convincing).
$R\cup \epsilon \neq R$. Suppose some machine $M$ recognizes RE $R$. This machine does not accept $\epsilon$. Then clearly this machine will not accept $R\cup\epsilon$, so $R\cup \epsilon \neq R$.
Do these generally sound right?
Answer: First of all, you make a confusion between regular expression and regular languages. That said, the formulas $R \cup \emptyset = R$ $R\emptyset = \emptyset$ and $R\varepsilon = R$ hold for every language $R$ (regular or not), but the formula $R \cup \varepsilon \neq R$ does not hold in general: just take $R = \varepsilon$ for a counterexample.


Get docker-compose.yml file location from running container?

Question: I have a few running docker containers created by executing docker-compose up.
Is there any way to get the exact file path of the corresponding docker-compose.yml file used to start these containers, just by inspecting the running containers?
As far as I can see, docker inspect CONTAINER_NAME does not provide this information, nor does docker-compose provide a method to get compose-related information from a running container.
What I'd like to do in a script:

list certain running containers on a docker host
get the corresponding docker-compose.yml file locations
use docker-compose to restart all containers of the corresponding docker-compose projects at once
Answer: The answer to this question seems to have changed with new versions of docker-compose.
There is a label "com.docker.compose.project.working_dir": "/var/opt/docker", that points to the directory where I started docker-compose. I have not checked if that is pwd or the actual location of the docker-compose.yml file.
This got me interesting information about docker-compose:

samuel@vmhost1:~$ docker inspect fc440a1afbaa | grep com.docker.compose
                "com.docker.compose.config-hash": "89069285a4783b79b421ea84f2b652becbdee148fbad095a6d9d85aab67ececc",
                "com.docker.compose.container-number": "1",
                "com.docker.compose.oneoff": "False",
                "com.docker.compose.project": "docker",
                "com.docker.compose.project.config_files": "docker-compose.yml",
                "com.docker.compose.project.working_dir": "/var/opt/docker",
                "com.docker.compose.service": "jenkins",
                "com.docker.compose.version": "1.25.0"
samuel@vmhost1:~$

I'm running docker-compose.yml configuration version 3.6
Comment: The working_dir is the context specified in the compose file, it doesn't point to location of compose file
Comment: @at54321 The context and the compose file are not the same thing.  The context can be located in a different location to the compose file
Comment: this should be the answer
Comment: @RobBlanchard the context is defined inside the compose file (i assume if it's not defined it will take same dir).  try to set the context to a different location inside the compose file and see if it still works for you.  I keep my compose files together in a separate location and it didn't work for me when setting a context location inside compose file.
Comment: @Guerrilla: What do you mean?
Comment: @Guerrilla I agree with you. But it seems that it works as if. `docker-compose -f subdir/docker-compose.yml up` will indeed show `/path/to/context/subdir` in `com.docker.compose.project.working_dir`
Answer: You can identify it using the inspect command, as follow:
docker inspect <container_id> | grep compose

Comment: Simple command and it works!
Comment: Didn't work with compose 1.17.1.
Answer: It is not currently possible.
As an alternative might find the following helpful:

Use docker ps -a | grep <certain_container>
Use locate docker-compose.yml and find the one that you want
Use docker-compose restart (do docker-compose to see option)
Comment: As of 2022, with Docker 20.10, I was able to run `cd /` and `find . -name "docker-compose.yml"` and locate my missing compose files (just `cat` the returned paths).
Answer: Update: Since this was asked, docker compose v2 was released, which is written in Go and accessible from docker compose instead of docker-compose (there may also be a shim directing docker-compose to this new version depending on your install). This version now embeds the directory into the image labels that you can retrieve with:
docker container inspect ${container_name_or_id} \
  --format '{{ index .Config.Labels "com.docker.compose.project.working_dir" }}'

This isn't perfect for the OP's request since there may be more than one compose file, the file could be located in a different directory from where compose was run, and it doesn't capture things like environment variables or profiles that may modify how compose starts the project. However I suspect it gets most people close enough to find the source.
If you're using an older version of compose, you can use one of the options in the original answer below:

As far as I can see, docker inspect CONTAINER_NAME does not provide
this information, nor does docker-compose provide a method to get
compose-related information from a running container.

From an already running container that you do not control, the information is not there. You can infer the location using bind mount directories if the container creates any host mounts to relative directories. Otherwise, it's possible to deploy containers without compose, and it's possible to use compose without a compose file on the filesystem (piped via stdin), and compose does not store these details on running containers for you.

What I'd like to do in a script:

list certain running containers on a docker host
get the corresponding docker-compose.yml file locations
use docker-compose to restart all containers of the corresponding docker-compose projects at once

If you just want to run a restart on all containers in the same project, you don't need the first two steps, or even docker-compose. Instead, you can run:
docker ps --filter "label=com.docker.compose.project=${your_compose_project}" -q \
| xargs docker restart

Which uses a label docker-compose adds to each project it deploys.

If you want to proactively store the compose file location for later use, you can inject that as a label in your compose file:
version: '2'
services:
  test:
    image: busybox
    command: tail -f /dev/null
    labels:
      COMPOSE_PATH: ${PWD} # many Linux shells define the PWD variable

If your shell does not set a ${PWD} environment variable, you can start compose with:
PWD=$(pwd) docker-compose up -d

Then you can later inspect containers for this label's value with:
docker inspect --format '{{.Config.Labels.COMPOSE_PATH}}' ${your_container_id}

And you can chain a filter and inspect command together to find the path for a specific project:
docker ps --filter "label=com.docker.compose.project=${your_compose_project}" -q \
| xargs docker inspect --format '{{.Config.Labels.COMPOSE_PATH}}'

Comment: @Utopiah that's compose v2, it didn't exist when I first answered this.
Comment: Bad idea. With `pwd` you can never user `docker-compose -f ...`
Comment: @A.B. the point of the `pwd` section was that you can inject a label into your containers with the details you want later. If you override the compose file, inject that as a label that you manage.
Comment: You can an its even there by default. I was going to suggest `curl --unix-socket /var/run/docker.sock  http://localhost/containers/json | jq .[].Labels | grep com.docker.compose.project.working_dir | uniq` but it's the same idea as your answer.
Answer: you know, your question turns to be a useful answer to the same issue I have.
I used docker inspect <containerID> and then it gave me the location that I should look into. specifically in these lines:
HostConfig": {
            "Binds": [
....
...
],

Answer: If you mounted a local volume, e.g ./data then inspecting the container will give you the path, e.g docker inspect peertube_peertube_1 | jq .[0].HostConfig.Binds. It doesn't work for containers without volumes but it's rare enough.


Why does the DCGAN output degrade with an increase in the kernel size?

Question: Thank you for the explanation on the kernel size.
I have been experimenting with the sample Generative Adversarial Network (GAN) code from the book on Deep learning with Python by François Chollet, Section 8.5.3 Page 308. I noticed that when I happen to increase the kernel size in the keras.layers.Conv2D function, the output of the generator model degrades while decreasing the kernel size improves the performance of the generator. Could you help me in better understanding this?
Answer: By decreasing the size of the convolutional kernel, you're changing the number of parameters in the model (as well as what scales it looks at the data in). The optimization process for models like DCGAN is somewhat unstable, not super well-understood, and needs a very careful balance between the generator and discriminator; especially if you change one and not the other, it could throw all kinds of things off in the ability to actually optimize the model.


What's Wrong with This UBOUND?

Question: Suppose the values of A1, A2, and A3 are 1, 2, and 3. I wrote the following code.
function uboundout(reference)
uboundout=ubound(reference)
end function

And I put =uboundout(A1:A3) in B1 expecting 3, but Excel displays #VALUE!. There is no problem when I try worksheetfunction.count rather than ubound. What's wrong here? Thanks for your reading.
Comment: It doesn't work too. The manual says the default is already 1.
Answer: Declare reference as a Range and use .value:
Function uboundout(reference As Range)
If reference.CountLarge = 1 Then
    uboundout = 1
    Exit Function
End If
uboundout = UBound(reference.Value)
End Function

Comment: Further hint to `Ubound()` function: c.f. [help reference](https://docs.microsoft.com/de-de/office/vba/language/reference/user-interface-help/ubound-function?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev11.query%3FappId%3DDev11IDEF1%26l%3Dde-DE%26k%3Dk(vblr6.chm1009050)%3Bk(TargetFrameworkMoniker-Office.Version%3Dv16)%26rd%3Dtrue) stating:  *"Returns a Long data type containing the largest available subscript for the indicated dimension of an **array**." - So applying `UBound` to a range only instead to 2-dim 1-based array created via `.Value` or `.Value2`, OP gets an error message.
Comment: @BigBen - sure, edited.
Comment: Fails with something like 2344 in A1, or anything longer than one character. Oh and of course I made a mistake, you can simplify to `If reference.CountLarge = 1`, the `Cells` is redundant.
Comment: @T.M. that is why I proposed that edit, yep, thanks for the link.
Comment: Oh I just understood the function of `countlarge` here. Thank you.
Comment: I wouldn't use `Len`. Maybe `If reference.Cells.CountLarge = 1 Then`.
Comment: @BigBen - Done!  Just curious, what might I not have thought about when using `Len()`?
Comment: Thanks. I changed `=ubound(reference)` to `=ubound(reference.value)` and this worked.
Comment: @JunyongKim note that you need more of a change than that. Try what you have with `=uboundout(A1)`. It will fail. You need the handle the instance of when `reference` is a single cell.

What's Wrong with This UBOUND?


Likelihood of Global Catastrophe - Surely it cant be 80%?

Question: I'm not a mathematician, but I'm trying to wrap my head around this statistical problem ...
An Oxford 2008 study guessed the likelihood of global extinction at 0.2%pa, which by my calculation is roughly 20% in the next 100 years, no?  The Stern review reckons half that.  But either way this is total extinction, not simply a catastrophe, which is what I'm trying to quantify here.  This report defines a global catastrophe as 10% of the world dying, which is 2-4x worse than the worst thing that happened last century (spanish flu), but good enough as a benchmark if that's what the experts are focussing on.
Now, my questions are:

If it's 0.2% likely that we'll lose 100% of our population in the next year, then is it correct to calculate the likelihood of losing 10% of our population in the next year to be 10x as likely, or 2.0%?

How can I extrapolate that out to the likelihood of it happening in my lifetime, say, the next 40 years?  Is it as simple as just multiplying it by 40, making it 80%?

Reference Article (page 24)
Comment: You should understand the underlying logic to derive the 0.2%. They may talk about the extreme event lying in the fat tail. You cannot simply do the extrapolation as any distribution is highly non-linear.
Comment: Thanks Kevin. This is a good question which is rather beyond me. But I can tell you than its an aggregate of a range of very different risks (eg: pandemic, asteroids, climate change, etc) each of which were calculated differently.
Answer: Check the reference for the figure mentioned by the report:

Sandberg, A. & Bostrom, N. (2008): "Global Catastrophic Risks Survey",
Technical. Report #2008-1, Future of Humanity Institute, Oxford
University: pp. 1-5.

It explains where does the number comes from and what it means:

At  the  Global  Catastrophic  Risk  Conference  in  Oxford  (17‐20
July,  2008)  an  informal  survey  was  circulated  among
participants,  asking  them  to  make  their  best  guess  at  the
chance that there will be disasters of different types before 2100.
This report summarizes  the main results.

On the first page it mentions the number for "Overall risk of extinction prior to 2100" to be 20%. First, notice that this is just a survey, so subjective opinions of people. Second, the question asked the participants to guess the number for the period till the year 2100. I don't think you can use this number to interpolate or extrapolate. For example, if we consider risk due to something like climate changes, this risk would probably grow incrementally in an exponential fashion, so it would be low in the next few years, but then start rapidly growing--so it would not grow linearly. Third, humans perceive numbers, and probabilities in particular, on subjective scales, that not necessarily correspond to their actual "raw" numeric values. I wouldn't do math on guessed numbers.


Fm7 Drop 2 1st inversion confusion

Question: I'm reading a guitar book that has started to describe drop voicing and inversions (both of which I'm already familiar with their concepts).
My concern is that I think my understanding of the concepts are slightly off (or not as nuanced as maybe the author's understanding).
He starts...
"Let's begin by learning the four voicings for a drop 2 Fm7 chord played on the top 4 strings (squares being the root)".
When discussing the Drop 2 voicing for Fm7 he provides a set of chord diagrams (one for each inversion: root, 1st, 2nd and 3rd).
But the second diagram, "Fm7 Drop 2 1st inversion", I noticed as not looking quite as I expected:

The Fm7 chord should be:

♮1: F
♭3: A♭/G♯
♮5: C
♭7: E♭/D♯

The 1st inversion of Fm7 would be:

♭3: A♭/G♯
♮5: C
♭7: E♭/D♯
♮1: F

Notice the ♭3 has been dropped into bass position
  So the 1 is shifted up an octave, while the other notes follow the ♭3

This would then suggest the Drop 2 voicing of Fm7 1st inversion to be:

♭7: E♭/D♯
♭3: A♭/G♯
♮5: C
♮1: F

Notice the second highest note ♭7 has been dropped into bass position
  While the other notes stay in their current ordering

But looking at the diagram the notes being played are:

♭3: A♭/G♯
♭7: E♭/D♯
♮1: F
♮5: C

Which (based on my earlier understanding of inversions and drop voicings) doesn't look to be correct, if he wanted to play a Drop 2 of the Fm7's 1st inversion?
Answer: Your confusion lies in the fact that you believe that the 1st inversion of the close voicing will result in a 1st inversion drop-2 voicing when the second note from the top is dropped one octave. This is not the case. As already pointed out by Tim, the lowest note in the voicing determines the inversion, regardless of the sequence of the other notes.
It turns out that the 3rd inversion of a close voicing of a four-part chord (e.g., Fm7) results in the 1st inversion of a drop-2 voicing:

3rd inversion close  =>    1st inversion drop-2

Eb - F - Ab - C      =>     Ab - Eb - F - C

The drop-2 voicing is in the 1st inversion because its lowest note is the (minor) third of the chord, i.e., the note Ab. The 1st inversion of the close voicing also has the third as the lowest note, but the sequence of the other three notes is different (Ab - C - Eb - F instead of Ab - Eb - F - C).
In a similar manner you can figure out the following relations:

root close     => 2nd inv. drop-2
1st inv. close => 3rd inv. drop-2
2nd inv. close => root drop-2

You have to look at the second note from the top of the close voicing, because this will become the bass note of the corresponding drop-2 voicing. And the latter determines which inversion you get.
Answer: An inversion is called with regard to the lowest note. Thus 1st inv. would have Ab as its lowest note. On piano, it's very easy to follow on with the rest of the notes going up sequentially, but, due to the tuning of the guitar, it's often not possible to keep the order. So, as long as the other three notes are present, their order is said not to be important, only that for the inversion, the correct note is at the bottom - Root =root=F. 1st inv. =b3 =Ab, 2nd inv. = 5 = C, and 4th inv. = b7 = Eb.
Drop 2 voicing for root is R,5,b7,b3, and the one in question, 1st inv. is b3,b7,R,5 - as Ab,Eb,F,C. So it looks like it's correct.
Comment: Your answer has confused me. I was of the understanding that a drop voicing was dropping the nth highest note by an octave. So if you had `1,3,5,7` then surely a drop 2 would be `5,1,3,7` and not `1,5,7,3` as you've described in your answer?
Comment: Also, your answer states that the order of the notes (for guitar at least) doesn't really matter, as long as the bass note has changed as per the requirement for the inversion. Does the same principle apply to drop voicings? So I was of the understanding that a first inversion was moving the next note (e.g. the 3rd) into bass. You're saying that with `1,3,5,7` the 1st inversion could be any of the following `3,5,7,1` or `3,7,5,1` or `3,5,1,7` or `3,1,7,5` or `3,7,1,5` etc. If drop 2 voicing order also don't matter then it seems there are also multiple drop 2 variations possible
Comment: Since drop 2 means the second highest note in a triad, or four note chord is dropped down a complete octave, while the other 2 (or 3) notes stay the same, it's going to be dependent on what the original voicing is, I think.

Fm7 Drop 2 1st inversion confusion


How to find out whether or not a page is cached?

Question: I have some serious problems with the performance of my Drupal website and I think that the problem may caused by the fact, that the pages are not cached. How can I find out whether or not a page was cached and if not, how can I find out why the page is not cached?
I am using varnish for my page.
Answer: Whether a page is cached
You can enable logging and use varnishlog, varnishstat, etc. See Debugging Varnish for a bit more information. There's also a lot of information on Pantheon's Working with Varnish, I'd highly recommend reading that.
Why it is not cached
That's a much bigger, harder question to answer. It's entirely down to your server/application logic. Your server's VCL files, in conjunction with response headers sent from your Drupal application, will determine whether or not a page is cached.
There may be other environmental factors affecting things, but again those would be specific to your server and your sysadmin (or whoever installed/set up the server) should be able to tell you about them.
There's a pretty decent tutorial available that walks through setting up Varnish with Drupal, I'd recommend reading through that and comparing your own set up to that known-to-be-working one.


Replace custom listview layout while clicking button in android

Question: I am having two buttons in one screen,When I click first button I am showing a list in custom listView in next screen. And when I click second button I need to replace the custom listview with another layout in next screen(which is same for both buttons )
Answer: Please use below logic when you press buttons:
<code> Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("is_show_custom_view",true);//pass false when you press second button
 startActivity(intent);
</code>
Now you have to get that boolean and appy logic like :
<code>if(getIntent().getBooleanExtra("is_show_custom_view")){
//Add here your code for custome view
}else{
//Add here your code for normal view
}
</code>


Qualification decision in group stages when everything is equal

Question: Consider a football (soccer) tournament has a group stage, where for example teams are divided into groups of four and the first and second teams will qualify to the next round. If all games end with 0-0 score, every metric for all four teams will be the same. Which teams will qualify now? Is there a rule set by FIFA in this case?
Comment: I personally think rule G is a shocker as football shouldn't be decided by a lottery. At least with a penalty shootout it's decided on the pitch fairly.
Comment: What happens if all the three teams playing in a tournament have the equal points and goals and everything?
Comment: Iam confused for group D of the African Cup of Nations since all of them have the same points and same goal differences. What next?
Comment: I know this is a old thread but surely all these scenarios could be avoided by simply having a low pressure penalty shoot out in any drawn game in the group stages creating a winning draw that would only count if everything is level and the end of the group stage. It would be good entertainment for the crowd, good practice for the players and no injuries should occur for the players.
Comment: Can you please provide any sources?
Answer: As you say "a tournament", be aware that different competitions use different rules for tie breaking. When you mention FIFA, the tournaments organized directly by FIFA use the rules described by Dor Cohen; e.g. the official FIFA World Cup 2014 Regulations state in rule 49, paragraph 5:

The ranking of each team in each group shall be determined as follows:

a) greatest number of points obtained in all group matches;
b) goal difference in all group matches;
c) greatest number of goals scored in all group matches.

If two or more teams are equal on the basis of the above three criteria, their rankings shall be determined as follows:

d) greatest number of points obtained in the group matches between the teams concerned;
e) goal difference resulting from the group matches between the teams concerned;
f) greater number of goals scored in all group matches between the teams concerned;
g) drawing of lots by the FIFA Organising Committee.

However, UEFA (the European football association) uses a different system in its competitions, where results from the matches between the teams concerned are given more importance than the results from the rest of the group matches (plus, there are more auxiliary criteria when everything else fails). See e.g. the official Regulations of the UEFA European Football Championship 2012 which state in the rule 8.07:

If two or more teams are equal on points on completion of the group matches, the
  following criteria are applied, in the order given; to determine the rankings:

a) higher number of points obtained in the matches among the teams in question;
b) superior goal difference in the matches among the teams in question (if more
  than two teams finish equal on points);
c) higher number of goals scored in the matches among the teams in question (if
  more than two teams finish equal on points);
d) superior goal difference in all the group matches;
e) higher number of goals scored in all the group matches;
f) position in the UEFA national team coefficient ranking system (see Annex I,
  paragraph 1.2.2);
g) fair play conduct of the teams (final tournament);
h) drawing of lots.

And, there is an additional interesting rule 8.08 (which is a recent addition):

If two teams which have the same number of points, the same number of goals
  scored and conceded play their last group match against each other and are still
  equal at the end of that match, the ranking of the two teams in question is
  determined by kicks from the penalty mark (Article 16), provided no other teams
  within the group have the same number of points on completion of all group
  matches. Should more than two teams have the same number of points, the criteria
  listed under paragraph 8.07 apply.
Comment: I don't think it has ever come up on UEFA-organized tournaments. However, in [Group F of the 1990 FIFA World Cup](http://en.wikipedia.org/wiki/1990_FIFA_World_Cup#Group_F), Ireland and the Netherlands were "completely" tied, and their positions had to be decided by drawing of lots (won by Ireland). (Might be interesting also to point out to [1907–08 Football League](http://en.wikipedia.org/wiki/1907%E2%80%9308_Football_League), which had tied 14th place, with two teams finishing with identical records.)
Comment: Interesting, I was curious about a case where all teams are equal. So it would be simply drawing lots in FIFA World Cup or deciding on ranks and fair play and then drawing lots in UEFA. Have you seen a case that these parts of rules used in action?
Answer: The answer is drawing of lots by the FIFA Organising Committee.
The ranking of each team in each group will be determined as follows:

a) greatest number of points obtained in all group matches;
b) goal difference in all group matches;
c) greatest number of goals scored in all group matches.
If two or more teams are equal on the basis of the above three
  criteria, their rankings will be determined as follows:
d) greatest number of points obtained in the group matches between the
  teams concerned;
e) goal difference resulting from the group matches between the teams
  concerned;
f) greater number of goals scored in all group matches between the
  teams concerned;
g) drawing of lots by the FIFA Organising Committee.

You can see an example (Given by @mormegil), in Group F of the 1990 FIFA World Cup, Ireland and the Netherlands were "completely" tied, and their positions had to be decided by drawing of lots (won by Ireland). - http://en.wikipedia.org/wiki/1990_FIFA_World_Cup#Group_F
Comment: This is a good answer, but I don't see a way to d) e) and f) work.. In fact unless there was a rule change somewhere that I didn't realize, from c you just jump to g... I think d e and f are using on other sports.
Comment: @gbianchi Example. Suppose teams A,B,C,D. D looses all, A beats B (2-0), B beats C (3-1) and C beats A (4-2). D looses from all. A 1-3, B 2-4, C 0-2. Then they all end with 6 points and 7-5 in goals. You end up with a case f where C wins. It is unlikely to happen however
Comment: @Bernhard I understand the system, but I think that is not used on football...
Answer: In line with the above case,the two teams had the same point, goal for,goal against,then each competition has rules which have to be determine by competition organizers and should be spelt out clearly before the commencement of the competition so that all teams will be aware of it.


Proof: Each linear subspace of $\Bbb R^n$ (or $\Bbb Q^n$) is also the intersection of finitely many linear hyperplanes

Question: I am currently in the process of reading Theory of Linear and Integer Programming by Alexander Schrijver and encountered the following theorem and proof:

Theorem 3.1. Each linear subspace of $\Bbb R^n$ (or $\Bbb Q^n$) is generated by finitely many vectors, and is also the intersection of finitely many
  linear hyperplanes.
Proof. The proof is well-known from linear algebra. If $L$ is a linear subspace of $R^n$, then any maximal set of linearly independent
  vectors in $L$ is finite and generates $L$. Similarly, $L$ is the
  intersection of finitely many linear hyperplanes $\{x|a_ix = 0\}$,
  where the $a_i$ form a maximal set of linearly independent vectors
  generating $L^* $$:=$ $\{z|zx =0$ for all $x$ in $L\}$.

Although I understand the first part of the proof, I have trouble understanding why every linear subspace is the intersection of finitely many linear hyperplanes.
Answer: Hint: extend a basis $b_1, \ldots, b_l$ for $L$ to a basis $b_1, \ldots, b_l, \ldots b_n$ for $\Bbb{R}^n$. Consider the hyperplanes $H_k$ comprising the points $\sum_i x_ib_i$ where $x_k = 0$. $L$ can be expressed as the intersection of some of the $H_k$.
Answer: The book's proof can be expanded to be more explicit: it is, for every subspace $L$, defining a subspace usually known as $L^{\perp}$ perpendicular to the original in the sense that $z\in L^{\perp}$ if and only if for every $x\in L$ we have that the inner product $z\cdot x = 0$ - i.e. that $z$ is "perpendicular" to every $x\in L$.
The idea is that if you let $z_1,\ldots,z_k$ be a basis for $L^{\perp}$, then you can define hyperplanes $H_i$ to be the set of $x$ such that $z_i\cdot x = 0$. The claim is that the fact that $z_1,\ldots,z_k$ is a basis for $L^{\perp}$ implies that $H_1\cap H_2\cap \ldots \cap H_k$ must equal $L$ and therefore that $L$ is a finite intersection of hyperplanes.
For instance, if you had the subspace $L=\{(0,t,t) : t\in\mathbb R\}$ in $\mathbb R^3$, one would find that $L^{\perp}$ could be described as $\{(x,y,-y):x,y\in\mathbb R\}$ which has a basis $\{(1,0,0),(0,1,-1)\}$ which then says that $L$ is the intersection of the two hyperplanes defined by the tuples $(x,y,z)$ such that $x=0$ and $y-z=0$.
This does subtly rely on the nontrivial fact that $L^{\perp\perp} = L$.

Though it's not necessary to understand this proof, the idea behind it is encapsulated in the notion of duality which is basically a method in linear algebra in which one transforms lines (which can be represented by vectors!) into hyperplanes and spanning sets into intersections of hyperplanes. The motivation for the proof in the book is to apply this reasoning (i.e. to look at $L^{\perp}$) to try to get a new statement out of our preexisting knowledge of bases.
Comment: Thank you so much Milo! This is just the explanation I was looking for.  The example was super helpful too!


Problemas com injeção de dependêcias em testes unitários Angular

Question: Estou tentando realizar testes unitários no Angular, porém tenho alguns problemas com a injeção de dependências nos services. Na aplicação existem vários services que dependem um do outro, por exemplo:

Service A tem como dependência o Service B
Service B tem como dependência o Service C
Service C tem como dependência o Service D
Service D tem como dependência o HttpClient e o Router do Angular

Devido a esses múltiplos níveis de dependência não consigo realizar a injeção dos providers na classe de teste.
Foi levantada a possibilidade de criar mocks para os services, mas devido a quantidade de dependências seria necessário criar um mock para cada service.
Existe alguma maneira de facilitar a injeção de dependências nos services?
Comment: vc ta usando jest ou o karma?
Comment: Estou usando karma
Answer: Você pode usar o useValue ou useClass para usar algo que seria um stub ou um mock do seu serviço. Por exemplo, vamos supor que você tem um serviço que retorna um usuario via http:
providers:[{
     provide: SeuServico,
     useValue: { getUser: (userId) => of({ name: 'Joao', idade: 13 }) }
}]

Assim você tem um serviço que não tem nenhuma depedência, acabando com esse ciclo.


Dynamic add MediaStream's into current.srcObject into a list of useRef for  [React]

Question: As MediaStream() needed to use useRef to work in video:
const videoRef = useRef();
// ... some code until add MediaStream() to ref
videoRef.current.srcObject = event.stream;
// ... some more codes until the render function
return (
  <video ref={videoRef}></video>
)

What if I need multiple video streams? I can duplicate it like this.
This works:
const VideoConferencing = () => {
  let [videosContainer, setVideosContainer] = useState([]); // to store video information

  // yikes i know
  const videoRef0 = useRef();
  const videoRef1 = useRef();
  const videoRef2 = useRef();
  const videoRef3 = useRef();
  const videoRef4 = useRef();
  const videoRef5 = useRef();
  // what if i need more videoRef in real time?

  // ... some more codes until defining each incoming stream to its ref

    if (num_streams === 0) {
      videoRef0.current.srcObject = event.stream; // event.stream is a MediaStream()
    } else if (num_streams === 1) {
      videoRef1.current.srcObject = event.stream;
    } else if (num_streams === 2) {
      videoRef2.current.srcObject = event.stream;
    } else if (num_streams === 3) {
      videoRef3.current.srcObject = event.stream;
    } else if (num_streams === 4) {
      videoRef4.current.srcObject = event.stream;
    } else if (num_streams === 5) {
      videoRef5.current.srcObject = event.stream;
    }

  // more codes until the render

  return (

      {videosContainer.map(function (video, i) {
        return (

            {video.videoIndex === 0 ? (
              <video
                ref={videoRef0}
                autoPlay
                playsInline
                controls
              ></video>
            ) : (
              ""
            )}
            {/* ... so on and so forth ... */}
            {video.videoIndex === 5 ? (
              <video
                ref={videoRef5}
                autoPlay
                playsInline
                controls
              ></video>
            ) : (
              ""
            )}
            {/* what if i needed more in real time? */}

        );
      })}

  );
};

Defining it like this by copy and pasting is simply dirty, and it is not dynamic (what if the 7th stream comes in?). How can this converted to something more dynamic, where new streams received will create a new useRef, and then assign the stream into its current.srcObject?
Answer: What I would do is to create an array of stream and render the videos dynamically using .map()
    const VideoConferencing = (arrayStream) => {
  let [videosContainer, setVideosContainer] = useState([]); // to store video information

  return (

      {arrayStream.map(function (stream, i) {
        return (

              <video
                ref={video => video.srcObject = stream}
                autoPlay
                playsInline
                controls
              ></video>

        );
      })}

  );
};