Why does the arrow notation of categorical limit go from right to left?

Question: Whilst studying some category theory, I was blindly using the notation $\lim_\leftarrow D$ for the limit of a diagram $D$ in some category $\mathcal{C}$ (as they are notated in MacLane, Awodey, my lectures etc.).
Why does the arrow go from right to left?
Is it because we think of the limit of a diagram as sitting on the left of the diagram (where the arrows in our diagram go from left to right)?
I sometimes think of a terminal object as being to the far right of a category, because everything can map into it. If limits had an arrow from left to right (like in analysis), I think I could justify this by saying "Well a limit is a terminal object in the category of cones, so it sits on the right". This makes me think that my 'reason' above is nonsense.
Any thoughts are appreciated. Thanks!
Answer: I don't know the reason for sure, but here is my guess.
The most basic (and historically important) examples of limits and colimits are those indexed by the natural numbers, ordered by $\geq$ (resp. $\leq$). In the case of limits, one takes diagrams of the form
$$\dotsc \dotsc \to A_2 \to A_1 \to A_0$$
and the limit goes to the left direction and therefore(?) is denoted by $\varprojlim A_i$.
Dually, the colimit of
$$B_0 \to B_1 \to B_2 \to \dotsc \dotsc$$
goes to the right direction and therefore(?) is denoted by $\varinjlim B_i$.
Notice that the limit of $A_0 \to A_1 \to \dotsc$ is $\varprojlim A_i = A_0$, which is "because" $A_0$ is already on the left.
Comment: \varprojlim and \varinjlim
Comment: also how do you Tex that $lim_\leftarrow$ so nicely?
Answer: The universal property of the limit has certain arrows go into the limit.
Similarly,  the universal property of colimits has certain arrows come out of the colimit.
Comment: I didn't know that this is the reason for the notation. Do you have a reference for this or is this just your mnemonic? Often one writes $\varprojlim$ (resp. $\varinjlim$) and here it is not clear if the arrow goes out or into the limit (resp. colimit).


Strawberry Perl - Error Message: This package requires a C compiler

Question:
I have Strawberry Perl May 2016 (5.24.0) 32bit PortableZIP edition. I have only unzipped it; there are no changes otherwise.
When i want to install modules with cpan i got the follow error:
C:\Fhem\perl\bin>cpan -i Net::SSLeay
Loading internal null logger. Install Log::Log4perl for logging messages
CPAN: CPAN::SQLite loaded ok (v0.211)
Database was generated on Tue, 13 Dec 2016 13:41:47 GMT

Running install for module 'Net::SSLeay'
CPAN: LWP::UserAgent loaded ok (v6.15)
CPAN: Time::HiRes loaded ok (v1.9733)
Fetching with LWP:
http://cpan.strawberryperl.com/authors/id/M/MI/MIKEM/Net-SSLeay-1.78.tar.gz
CPAN: YAML::XS loaded ok (v0.62)
CPAN: Digest::SHA loaded ok (v5.95)
Fetching with LWP:
http://cpan.strawberryperl.com/authors/id/M/MI/MIKEM/CHECKSUMS
CPAN: Compress::Zlib loaded ok (v2.069)
Checksum for C:\Fhem\cpan\sources\authors\id\M\MI\MIKEM\Net-SSLeay-1.78.tar.gz ok
CPAN: Archive::Tar loaded ok (v2.06)
CPAN: File::Temp loaded ok (v0.2304)
CPAN: CPAN::Meta::Requirements loaded ok (v2.140)
CPAN: Parse::CPAN::Meta loaded ok (v1.4417)
CPAN: CPAN::Meta loaded ok (v2.150005)
CPAN: Module::CoreList loaded ok (v5.20160507)
Configuring M/MI/MIKEM/Net-SSLeay-1.78.tar.gz with Makefile.PL
Unresolvable missing external dependency.
This package requires a C compiler.
NA: Unable to build distribution on this platform.
No 'Makefile' created  MIKEM/Net-SSLeay-1.78.tar.gz
  C:\Fhem\perl\bin\perl.exe Makefile.PL -- NOT OK
Stopping: 'install' failed for 'Net::SSLeay'.

Seems to be no compiler found. What must I do to fix this?
Comment: Aren't there any post-install scripts to run when using a ZIP version of Strawberry?
Comment: @VesaKarjalinen: No. The whole point of the *PortableZIP* version is that there is no installation process. It provides a command file which opens a new command prompt window with all the necessary settings enabled just for the life of that window.
Answer: Presumably you are running perl and cpan directly from the command prompt?
You should read the contents of the README.txt file in the distribution, where it tells you to run
c:\myperl\portableshell.bat before using any of the utilities
I hope it's clear that you must change c:\myperl to the folder where you unzipped the distribution
There are three subdirectories of the unzipped volume which need to be in the PATH before everything will work, and the .bat file will set those up temporarily for you. If you want something more permanent then the README.txt file explains how to  do that, but you should probably run a proper installed version instead
Comment: Ty very much, made my day :-). Sry for not reading readme...Next time i will do first! Followed your guide and the readme and it really works ;-).
Comment: @l05443: You can make things a whole lot easier by selecting `portableshell.bat` in File Manager, then using a *right-click* to drag and drop it to the desktop. If you then select `Create shortcuts here` from the context menu then you will have a desktop shortcut that you can double-click to start the portable Perl environment. Highlight the shortcut and press `F2` to rename it to something more useful.


Basic Example of Yoneda Lemma?

Question: I have been digging the whole internet and books on category theory trying to understand the Yoneda Lemma. I have read the Tom Leinster's "Yoneda Lemma: Whas is it all about?", and watched the talk of Steve Awdoey on that subject as well. Both of them did help me a lot, and I'm starting to understand the matter.
However, most of the examples I could find always relate to things on mathematics that I haven't had any touch with (such as Rings, Groups, Topos, ...). I'm a Computer Science Student, and I know the very basics of Category Theory (Sets, Posets, Sets and Partial Functions, Graphs, all seen as a category).
Is there any example you can give me (or know of) that uses the Yoneda Lemma and basic knowledges of category theory? I'm interested on an example of the application of the Lemma or the Embedding to solve or prove something.
Answer: Computer scientists do use quite a few algebraic structures, they are just slightly different from the ones mathematicians usually focus on.  Computer scientists tend to care about monoids, semigroups, semirings, and seminearrings.  For example, the free monoid on some set $\Sigma$ is just the list $\Sigma^*$.  A deterministic finite state automaton is just a monoid action of the free monoid on a finite set.  Relatedly, the operators of regular expressions form a star semiring.  In fact, many things in CS form a star semiring which leads to surprising connections.
Anyway, when you hear about the Yoneda lemma, you invariably hear about it's corollary, the Yoneda functor is full and faithful.  All this means is $$\text{Nat}(\text{Hom}(\_,A),\text{Hom}(\_,B)) \cong \text{Hom}(A,B)\text{ and} \\ \text{Nat}(\text{Hom}(A,\_),\text{Hom}(B,\_)) \cong \text{Hom}(B,A)$$ natural in $A$ and $B$.  A key general result is a fully faithful functor reflects isomorphisms.  That is, if $F$ is fully faithful and $FX \cong FY$ then $X \cong Y$.  You should prove this. (All functors preserve isomorphisms.)  Specializing, this means if $\text{Hom}(A,X) \cong \text{Hom}(A,Y)$ natural in $A$, then $X \cong Y$, and similarly for the other argument of $\text{Hom}$.  For example, here's a proof that left adjoints preserve coproducts (basically the same proof will show that left adjoints preserve all colimits).  Assume $F \dashv U$, i.e. $\text{Hom}(FA,X) \cong \text{Hom}(A, UX)$ natural in $A$ and $X$.  The defining property of a coproduct is the following $\text{Hom}(A+B,\_) \cong \text{Hom}(A,\_)\times\text{Hom}(B,\_)$.  The proof:
$$\begin{align}
\text{Hom}(F(A+B),\_) &\cong \text{Hom}(A+B,U\_) \\
&\cong \text{Hom}(A,U\_)\times\text{Hom}(B,U\_) \\
&\cong \text{Hom}(FA,\_)\times\text{Hom}(FB,\_) \\
&\cong \text{Hom}(FA+FB,\_)
\end{align}$$
By Yoneda, we have $F(A+B) \cong FA + FB$.  This use of Yoneda is so ubiquitous that it is usually used tacitly. (As a side note, I highly recommend this chain-of-isomorphisms style of doing category theory which is driven by the notion of a representable functor.  Combined with (co)ends, huge swathes of categorical proofs become this easy.)
Monoid actions have a particularly nice representation in category theory, since monoids can be viewed as one-object categories.  Let $M$ be a monoid viewed as a category.  A (left) $M$-action is a functor $M \to \mathbf{Set}$. Call the one object $\star$.  (A right $M$-action is a functor $M^{op}\to\mathbf{Set}$.) By definition $\text{Hom}(\star, \star) = M$ where here we're viewing $M$ as just a monoid.  When we have a $M$-action, $\phi$, on a set $X$, we mean $\phi(\star) = X$.
The Yoneda lemma then states that for a $M$-action, $\phi$, each element $x\in\phi(\star)$ corresponds to a function $h_x : M \to \phi(\star)$ which satisfies $h_x(m_1 m_2) = \phi(m_1)(h_x(m_2))$ and $h_x(1)=x$. Since the Yoneda lemma, $\text{Nat}(\text{Hom}(C,\_),F)\cong FC$, is also natural in $C$, we have that monoid action $\phi$ is essentially the same thing as the collection of functions $\{h_x\mid x\in X\}$ with the constraint that $h_x(m_1 m_2) = h_{\phi(m_2)(x)}(m_1)$ which follows from the properties of the $h_x$.  The Yoneda lemma is thus the statement that the representation of a monoid action as a monoid homomorphism into an endofunction monoid, which is what the functor view essentially is, is equivalent to the more typical representation as a function $M\times X \to X$ satisfying certain properties. The universal property of the free monoid $A^*$ is that a monoid homomorphism, $A^*\to M'$ is corresponds to an arbitrary function $A\to M'$. (This is a special case of a free category generated from a directed (multi)graph.) With this representation of $A^*$-actions, one direction of the Yoneda lemma is essentially the right fold operation (though most of the work is being done by freeness). For automata, right $\Sigma^*$-actions make more sense than left ones. The same calculation will produce a left fold in that case.
A lot of category theory can be considered a categorification of order/lattice theory ideas.  Decategorifying a categorical concept usually produces a useful concept in order theory.  Abstract interpretation is one area in CS where order theoretic ideas are used heavily.  Instead of viewing posets as special categories, I like to view them as $\mathbf{2}$-enriched categories or, equivalently, as (0,1)-categories.  This may sound intimidating, but actually makes things much simpler and clearer. (I wish someone had suggested that I view the Sub functor as an indexed (0,1)-category.)
The upshot is instead of having a family of hom-sets, we have a single hom-relation.  In this context, often the notion of an upward-/downward-closed set is used.  Let $\mathbf{2}\equiv\{\bot,\top\}$ with the ordering $\bot\leq\top$.  An upward closed subset of a poset $X$ can be identified with a monotonic function $X \to \mathbf{2}$ which can be made in a poset by using the point-wise ordering.  You can check that if $f : X \to \mathbf{2}$ is monotonic and we define $U = \{x\in X\mid f(x)=\top\}$, then $U$ is upward-closed, i.e. if $x\in U$ and $x\leq y$ then $y \in U$.  Furthermore, the pointwise ordering on functions corresponds to the subset ordering.  Write $\text{Up}(X)$ for the set of upward-closed subsets of $X$ with the subset ordering.  Write $\text{Down}(X)\equiv\text{Up}(X^{op})$ for the set of downward-closed sets.  The Yoneda embedding is then $\mathcal{Y}(x) = \{y\in X\mid y \leq x\}$ and $\mathcal{Y} : X \to \text{Down}(X)$ is a monotonic function.  The Yoneda lemma is then the statement for $U \in \text{Down}(X)$: $$x \in U \iff \forall y\in X.y\leq x \Rightarrow y \in U$$ The co-Yoneda lemma then says $$x \in U \iff \exists y\in X. x\leq y \land y \in U$$
Comment: Clearly a very complete example. I'll take some time to appreciate it and understand everything in details. But it will help me, thank you :)
Answer: Programming with continuations
You may have seen the continuation-passing style of programming. Starting with a subroutine like this:
function f (x, y, z) {
  return [result]
}

...you alter it so that instead of returning its result directly, the subroutine returns another subroutine that allows you to process that result before returning it:
function f (x, y, z) {
  return function(CONTINUE_FN) {
         return CONTINUE_FN([result])
  }
}

That is, instead of returning result directly, it returns another subroutine; you pass a function $g$ to that subroutine and it returns $g(result)$.  For example, if you pass the identity function g(x){return x}, it'll just return the result directly.
This paradigm is useful for when you want to decide how to further process/handle return values at a later, asynchronous time. It is useful for event handling, exception handling, and co-routines, for example.

The Yoneda lemma proves that the direct style of programming and the continuation-passing style of programming are equivalent (naturally isomorphic).
Indeed, consider the datatypes returned by the direct and continuation-passing  variants. Say the direct subroutine returns objects of type $\mathsf A$.  The continuation subroutine instead returns a function. That function takes in a continuation $\mathsf A \rightarrow \mathsf R$, where $\mathsf R$ can be any data type, and returns a result of type $\mathsf R$.
The fact that these return structures are equivalent is an isomorphism:
$$\mathsf A \cong (\mathsf A \Rightarrow \mathsf R) \Rightarrow \mathsf R$$
This equivalence, as can be made precise, is an application of the Yoneda Lemma in the case where the functor is just the identity functor:
$$\mathrm{Nat}( \hom(\mathsf{A}, -), \mathrm{id}) \cong \mathrm{id}(\mathsf A)$$
Comment: You have to be more careful. What Yoneda states is more like $A\cong\forall R.(A\Rightarrow R)\Rightarrow R$. This isomorphism certainly doesn't exist for a fixed $R$ in general. What this produces is the codensity monad (at $Id$) which is weaker than the continuation-passing style monad which is what makes this equivalence possible.

Basic Example of Yoneda Lemma?


Dúvida em diagrama de classe

Question: estou desenvolvendo meu diagrama de classe de um projeto e fiquei com a seguinte dúvida:

Como eu indico que somente o ADM pode cadastrar um contribuinte?
Tenho que indicar já isso no Diagrama de Classe?
Obrigado
Tem algum método pra conseguir visualizar as classes que posso ter? Porque nessa fase me sinto meio perdido por não sabe se o que eu penso é uma classe ou não! Obrigado!
Comment: Salvo engano `ADM pode cadastrar um contribuinte` seria função do diagrama de caso de uso. Com o diagrama de caso de uso fica mais fácil definir as classes, assim, você não fica `meio perdido por não sabe se o que eu penso é uma classe ou não`.
Comment: Te entendo cara... É que meu Caso de Uso também não tá dos melhores.. Vou ter que refazer ou implementá-los! Vlw pela dica @rubStackOverflow
Answer: Neste seu caso não se faz necessário esta representação no diagrama de classes, pois essa mesma representação poderá ser feita no diagrama de Máquina de Estados. Pois não vou te afirmar com 100% de certeza, mas creio que o diagrama de classes não tem recursos para este procedimentos, então fiz algumas pequenas modificações no de classes e possível representação de máquinas de estados.
1. Diagrama de Classe
Neste foi adicionado um novo atributo referente ao tipo de usuário se vai ser comum ou administrador, bem como os métodos para CRUD e somente uma anotação referente a restrição de somente o administrador pode fazer o cadastro do contribuinte.

2. Diagrama de Máquina de Estados
Na representação do diagrama de máquinas de estados é representado o cadastro do contribuinte, onde será analisado o tipo de usuário, caso ele seja administrador será realizado o cadastro do contribuinte e logo após finalizado o processo, se o usuário for do tipo comum será então tido o processo como finalizado já que ele não pode realizar este procedimento.
Comment: Devo fazer uma pequena anotação referente ao relacinamento de Contribuinte com Usuario, onde o Contribuinte é na verdade uma herança de Usuario.
Comment: Matou a pau Joaquim... me esclareceu muita coisa, tenho que ser mais específicos nas classes! Não sei se a professora exigirá o Máquina de Estados... mas mesmo assim ajuda a entender o processo!
Obrigado pelo help! Abração!

Dúvida em diagrama de classe


Arvore Binária de Busca vs Lista Ordenada

Question: Considere um árvore binária de busca não balanceada e uma lista vetorial ordenada. Qual das duas estruturas é mais indicada para realizar uma busca por qualquer elemento.
Answer: O algoritmo mais eficaz para encontrar um elemento qualquer em ambos os casos é o mesmo: busca binária. Ele tem complexidade média O(log n).
O problema é que em árvores binárias não balanceadas, o cenário de pior caso é O(n). Por exemplo, imagine que estou procurando 5 na árvore abaixo:
1
 \
  2
   \
    3
     \
      4
       \
        5

O algoritmo vai percorrer todos os elementos da árvore achar o 5. Já com listas ordenadas, o pior caso continua sendo O(log n). Tendo os mesmos itens como exemplo:
[1,2,3,4,5]
O algoritmo vai percorrer apenas o 3, 4 e 5 até encontrar o resultado. Desta forma é preferível usar uma lista ordenada.
Answer: Árvore ABB.
        A complexidade da árvore é O(log n) e a complexidade da lista ordenada é O(n), então a busca em uma árvore ABB é mais eficiente que a busca na lista.
Comment: Se voce tem uma lista ordenada, você pode usar algoritmos melhres que uma busca linear.


How to delete mailbox from database and release the storage?

Question: I need to delete some user mailboxes from exchange 2013 database to release the storage. Each of those mailbox has 40-50G of data. Those mail boxes have been exported as backups. There is a retention period of 14 days by default that all deleted items will still be hold in database. The situation is that I need space right now and I want to bypass this retention period and have those mailboxes removed from the hard drive imminently.
Is there a way to do this? I could not find the solution online....
Note: They are disconnected mailboxes, User accounts will still be in AD.
Answer: Deleting the mailboxes isn't going to reduce the size of the mailbox database file. You need to perform an offline defrag of the mailbox database to shrink the file. You might be better off moving all mailboxes to a new mailbox database and removing/deleting the original mailbox database, if you have enough disk space to do so.
Comment: The problem is the space .......I don't have any extra space on my SAN...all taken by exchange.....OMG....what am i gonna do? No budget to buy any drives....
Comment: How much disk space is being taken up by the Exchange transaction logs?
Comment: The first thing you should do is not panicking :) Then follow Joe's advice. :) If you have a backup if your Exchange, the defraging and compacting the dB should be safe. Have not done it more than 6-7 times, but I never had a problem. Although, start the defrag after work.
Comment: A defrag will NOT free space if the retention period is not over. So you first have to change the retention period to 0 day, wait for the next maintenance (or modify the maintenance schedule) and check the log to ensure the mailboxes have been marked deleted, then you can perform the defrag.
Answer: List out mailboxes and remove
Get-Mailbox  -Database <database>

You can do something fast like
Get-Mailbox  -Database DB02 >> C:\MailboxesToDelete.txt

and then
$users=Get-Content C:\MailboxesToDelete.txt
foreach ($user in $users) {
    Try{
    #Print to screen user mailbox to delete
    Write-Host "User: $($User)"
    #Mark Mailbox for delete
    Disable-Mailbox -Identity $user
    #Success
    Write-Host Success -foregroundcolor green
    "$($User),Pass" | Add-Content $logfile
    }

You also need to perform offline defrag
https://blogs.technet.microsoft.com/rmilne/2013/08/23/offline-defrag-and-dag-databases-oh-my/
Answer: Offline defrags? Is it 2005?
Create a new database and move the mailboxes. Zero risk, zero downtime - unlike an offline defrag.
If you really don't have the space, then another option would be to stand up a temporary Exchange server, move those mailboxes you want to delete to that temporary server and delete them from there. That should give the white space back to the database much quicker than anything else.
Finally, there is another technique to remove those mailboxes using remove-storemailbox. It is outlined in this blog posting:
http://blog.enowsoftware.com/solutions-engine/bid/131820/Moving-Exchange-2010-Mailboxes-to-Create-White-Space
Comment: Sadly also not usable given that there seems to be no space available at all. The OP has nicely put himself into a corner - no magic bullets.
Comment: An offline defrag isn't going to be possible either. If there is space to do an offline defrag then there is space to build a temporary server.
Comment: This looks like a doable solution. Fight for budget first.


Trying to delete the records if greater then 25?

Question: I am trying to delete all records so I only have the last 25 records. I am trying to figure this out but I can't seem to figure out, my MySQL version doesn't support the DELETE LIMIT OFFSET that most suggest, so I am trying to do
DELETE FROM
    account_versions
WHERE
    account_versions_id < (
        SELECT
            account_versions_id
        FROM
            account_versions
        ORDER BY
            account_versions_id
        DESC
        LIMIT 24, 1)
 AND
     account_id = 1

But I can't seem to get it to work. I want to only have the last 25 records for account_id = 1
Comment: the `account_versions_id` is an autoincrement?
Comment: Yes it is primary and auto increment.
Answer: So, as you said that account_versions_id is an autoincrement. Here is what you need:
DELETE FROM account_versions
 WHERE account_id = 1
   and account_versions_id IN
      (select account_versions_id
         from
         (SELECT account_versions_id, @id:=@id+1 as rn
            FROM account_versions,
                 ( select @id:=0 ) a
           ORDER BY account_versions_id DESC) x
        where rn > 25)

Now it should work.
Comment: Is there anyways to not use a LIMIT in subquery I get `This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'`
Comment: Didn't see the `account_id = 1` part of the problem. I've fixed it.


What will be the playing position of Thomas Muller? Will he play as CF?

Question: Thomas Müller of Germany was a midfielder in the last World Cup in 2014.
In this World Cup some news on the Internet claim that Müller will play as a forward. So, what will be his position during the tournament?
Comment: As the first match has [shown](https://youtu.be/6wGCEAw5Ptw?t=30s), Thomas Müller is playing as a right winger.
Answer: He mainly plays center forward or right winger, although he is often listed as striker. (source)
His last games for Germany he played midfielder as well with Timo Werner or Mario Gomez being the only striker (for example here and here).
It's pretty safe to assume that he'll play on that position in the World Cup as well, but who knows what Joachim Löw got up his sleeve.


Trying to call a method within a function

Question: I get test is not defined when calling the stop() method
http://jsfiddle.net/n4mKw/1766/

var rotate = {
    quoteIndex: -1,
    duration: 500,
    delay: 3000,
    play: true,
    quotes: [],
    init: function (quotes) {
        this.quotes = quotes;
        this.showNextQuote();
    },
    showNextQuote: function () {
        this.quoteIndex = (this.quoteIndex + 1) % this.quotes.length;
        if (this.play) {
            $("#rotator").html(this.quotes[this.quoteIndex])
                .fadeIn(this.duration)
                .delay(this.delay)
            .fadeOut(this.duration, this.showNextQuote.bind(this));
        }
    },
    stop: function () {
        this.play = false;
    }

};

var test = rotate.init(["example1", "example2", "example3"]);
test.stop();

Comment: `rotate.init` returns nothing, thus `test` is `undefined`
Answer: You may want rotate.stop() instead. test is not an instance of rotate because init does not return the object, or anything for that matter.
Answer: Your functions aren't returning the instance of the rotate object as the previous answer specified. However, the way that you can fix this is by returning the instance of the object to the test variable.
var rotate = {
    quoteIndex: -1,
    duration: 500,
    delay: 3000,
    play: true,
    quotes: [],
    init: function (quotes) {
        this.quotes = quotes;
        this.showNextQuote();
        return this;
    },
    showNextQuote: function () {
        this.quoteIndex = (this.quoteIndex + 1) % this.quotes.length;
        if (this.play) {
            $("#rotator").html(this.quotes[this.quoteIndex])
                .fadeIn(this.duration)
                .delay(this.delay)
            .fadeOut(this.duration, this.showNextQuote.bind(this));
        }
        return this;
    },
    stop: function () {
        this.play = false;
        return this;
    }

};

var test = rotate.init(["example1", "example2", "example3"]);
test.stop();

I have updated the code to return the object in the function. Please test it in the fiddle.
Answer: Every JavaScript function returns something, if you dont specify a return value, it would return undefined by default. What you are doing currently is assigning that undefined value to test and calling stop() which is invalid. If you are trying to chain objects just return this from the init function.
var rotate = {
  quoteIndex: -1,
  duration: 500,
  delay: 3000,
  play: true,
  quotes: [],
  init:function()
  {
     this.quotes = quotes;
     this.showNextQuote();
     return this;
  },
  showNextQuote: function () {
    //showNextQuote stuff.....
  },
  stop:function(){
     this.play = false;
  }

}
Be careful of how you use the "this" keyword though..it would mean something else in a different context.


Can terminal close itself after stop debug in VSCode?

Question: I recently use VSCode to debug node.js program on Linux, is it a way to configure the terminal to close itself after I stop debug
Comment: Great question this just started as of v0.5.0 I think.
Answer: I think this should do what you are looking for:
<code>"debug.console.closeOnEnd": true
</code>


phpmyadmin database getting deleted automatically

Question: I am using aws ec2 t2 instance. Where I created few database as per my requirement.
For last few day I noticed new databases which I create getting deleted automatically. Is there any possibility of automatically getting deleted?
Current I have not put any password on phpmyadmin. Also no one other then me knowing IP of this server.
Any clue why it is getting deleted and tips to secure it?
Comment: "also no one other then me knowing IP of this server"  thats not true. If its a public ip, its there for everyone with a port scanner tool.
Comment: Two key things 1) Change the database admin user / password 2) Ensure that no-one on the internet can access the database using security groups. AWS or security training would help.
Comment: @MrZach: Yes, i just checked, someone created new databse in it with Warning that they have deleted all database and asking for bitcoin. How do they attack and how to secure from them, any idea?
Comment: A single actor can scan every IPv4 address on the Internet in a few hours. You cannot rely on "no one other then me knowing IP of this server". Automata will try to break in every hour of every day. You have to be secure from the first moment you start your server.
Comment: @user3449212 If the response below answered your question please upvote and accept it. That's the ServerFault way of saying Thanks :)
Answer:
Thoroughly read Making MySQL Secure Against Attackers and implement the recommendations.
Restrict access to the EC2 through Security Group

Only permit access to the database (port 3306) from the IP addresses where your web application lives (if it's on the same server don't open access to port 3306 at all).
Only permit access to phpMyAdmin and SSH from your IP (e.g. your home connection).

Set password for phpMyAdmin
Use HTTPS to access phpMyAdmin, e.g. use free LetsEncrypt certificate.
Consider using Adminer which is similar to phpMyAdmin and enforces some basic security.
Read or get some training about security essentials - both general and cloud-related.

Hope that helps :)


Base number converter from 10 base with recursive function - C

Question: I try to convert any number base from 10 base. After I multiply two numbers that the same base, but the function should be recursive.
<code>    double convert(int number,int base)
{
    int digit = 1;
    double sum=0;
    int i=0;
    int figure;
    double end;
    if(base==10)
        return number;

    else
    {
        figure = (digit % (digit * 10) - number % digit) / digit;
        end=pow(base,i);
        sum+=figure*end;
        ++i;
        digit *= 10;

        convert(figure,base);

    }
return sum;
}
</code>
But I'm confused in else, it doesn't work. How can I fix it? Any offers?
Thanks..
Comment: Please don't just say "it doesn't work".  Post exact inputs, outputs and expected outputs, and describe what debugging you've done so far.
Comment: Firstly I try to convert to any base from 10 base with recursive function..
Answer: E.g.
<code>#include <stdio.h>

int convert(int number,int base){
    if(number == 0 || base==10)
        return number;

    return (number % base) + 10*convert(number / base, base);
}

int main () {
    int i;
    for(i=2;i<=10;++i)
        printf("%d is %d base(%d)\n", 100, convert(100, i), i);
    return 0;
}
</code>
Comment: yes, thank you, otherwise e.g. I need to convert to 10 base from 6 base, I'll try it with that you help. :)
Comment: @physee , Processing is similar.
Answer: <code>static string ToBase(int n, int @base)
    {
        Func<int, string, string> x = null;
        return (x = (i, j) =>
        {
            if (i == 0)
            {
                return j;
            }
            return x(i / @base, i % @base + j);
        })(n, string.Empty);
    }
</code>
Comment: Wrong programming language. This is C, not C# (or whatever that is).


"Drush sqlc < myfile.sql" doesn't return the site to previously working state. Are there files to be deleted?

Question: I've backed up my drupal 8 database via the CLI using drush sql-dump > myfile.sql.
I make some changes to the site and break it, then I try to restore it via drush sqlc < myfile.sql.
It works for a bit, until I click something and it messes up again as if there was something written to the files causing it and it is not just the database alone that is the culprit. I get this error:

The website encountered an unexpected error. Please try again later.

A totally vague error as I'm not sure what is causing it.
Are there any files that are written to the Drupal directory that has to be deleted as well when doing a drush sqlc < myfile.sql restore?
Answer:
The website encountered an unexpected error. Please try again later.

There was an error on PHP that Drupal couldn't handle.

If you have your install set to log errors, check the report.
Another option, on your settings.php add:
$config['system.logging']['error_level'] = 'verbose';

To show the errors.
Comment: this helped showed me where the culprit was.
Answer: All drush sqlc does is apply the mysqldump to your database.  If the target has tables that are not known of by the source those tables will not be dropped by the dump file before being replaced.
You should take a backup, then run drush sql-drop first, clearing the way for your replacement database.
For example,
drush sql-dump > /location/to/backup-file
drush sql-drop
drush sql-cli < /location/of/myfile.sql


"X_FORWARDED_FOR" Header Doesn't Present In The Request

Question: In my web application I need to extract the real ip address for clients behind proxy, after searching I found that the possible method to do that is to read the content of "X_FORWARDED_FOR" header , I am using java servlet and the headers of the incoming request doesn't contain "X_FORWARDED_FOR" header , So why the header doesn't included in the request?
I am using java 1.7 , tomcat v7 , proxy server :TMG and configured to use "X_FORWARDED_FOR" header .
Please advice.
Thanks in advance.
Comment: Please show your tomcat configuration where XFF is set.
Answer: TMG doesn't support X-Forwarded-For out of the box; you need to add a third party web filter such as Winfrasoft X-Forwarded-For for TMG to gain this capability in your TMG reverse proxy.
Answer: The Winfrasoft one is 4,500 per server.  Try a free, open source one:
https://github.com/ramonsmits/XFF-Filter4TMG

“X_FORWARDED_FOR” Header Doesn't Present In The Request


Tranformar Multiplos arrays em apenas um array

Question: Em determinado processo do meu sistema, eu recebo como retorno de uma função um array de characteristics e esse array pode conter diversas informações, inclusive outros arrays com nomes diferente para cada tipo de informação. Ex:
Apartamento:
Characteristics => [
 ["external_area"]=>
    array(5) {
      [0]=> "varanda"
      [1]=> "lavanderia"
      [2]=> "piscina"
      [3]=> "muros"
      [4]=> "area_serviço"
    }
    ["bedroom"]=>
     array(12) {
      [0]=> "piso_frio"
      [1]=> "alvenaria"
      [2]=> "azulejo_teto"
      [3]=> "massa_corrida"
      }
   ]

Casa:
Characteristics => [
 ["internal_area"]=>
    array(5) {
      [0]=> "mesa de madeira"
      [1]=> "area"
    }
    ["options"]=>
     array(12) {
      [0]=> "2 andares"
      [1]=> "banheiro externo"
      }
   ]

e eu preciso que tudo fique dentro de um array só, por exemplo de apartamento, ficaria:
Characeristics => [
   [0]=> "varanda"
   [1]=> "lavanderia"
   [2]=> "piscina"
   [3]=> "muros"
   [4]=> "area_serviço"
   [5]=> "piso_frio"
   [6]=> "alvenaria"
   [7]=> "azulejo_teto"
   [8]=> "massa_corrida"
]

EDIT: Lembrando que eu não sei os nomes dos arrays que vem dentro de Characteristics
Comment: Pode haver repetições?
Comment: Não. Tanto arrays quanto os elementos do array não se repetem no mesmo tipo.
Answer: Uma vez precisei disso e usei esta solução.
function flatten($array) {
    $return = array();
    array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
    return $return;
}

Essa forma funciona independente do número de sub-arrays que você tenha e também independente das chaves. Ex.: https://eval.in/671144
Comment: Funcionou perfeitamente. Obrigado.
Answer: Podes usar a função array_walk_recursive:
array_walk_recursive($array, function ($item, $key)
{
    global $Characeristics;
    if (! is_array( $item ) ) $Characeristics[] = $item;
});

$result = array( "Characeristics" => $Characeristics );

Ou seja, se o valor em que está a passar no momento não for um array (será a tua string de característica) é adicionado a um novo array.
A funcionar o ideone
Answer: Exemplo de como pode fazer:
$arr = array(
    0 => array(1, 2, 3),
    1 => array(4, 5, 6)
);

$rs = array();
foreach ($arr as $v) {
    $rs = array_merge($rs, array_values($v));
}
unset($arr);

print_r($rs);

Esteja ciente de que isso é um exemplo. O array original da pergunta possui um nível a mais, porém, pode resolver com a mesma lógica.
Para o seu caso deve ficar algo assim:
$rs = array('Characteristics' => array()); // Esse array serve para guardar o resultado final

foreach ($arr['Characteristics']['external_area'] as $v) {
    //aqui mescla os valores
    $rs['Characteristics'] = array_merge($rs, array_values($v));
}
unset($arr); // Se não precisar mais desses dados, apague-os

print_r($rs);

Nomes das chaves
Caso o nome da primeira chave seja desconhecida, pode obtê-la com a função key()
$arr['a']['b'] = array();
echo key($arr['a']);
// retorna 'b'

Para o seu caso específico:
$arr['Characteristics']['external_area'] = array();
echo key($arr['Characteristics']);
// retorna 'external_area'

Implementando no código de exemplo
$rs = array('Characteristics' => array()); // Esse array serve para guardar o resultado final

$k = key($arr['Characteristics']); // obtém o nome da primeira chave

foreach ($arr['Characteristics'][$k] as $v) {
    //aqui mescla os valores
    $rs['Characteristics'] = array_merge($rs, array_values($v));
}
unset($arr); // Se não precisar mais desses dados, apague-os

print_r($rs);

Comment: Eu não tenho como saber o nome do array do segundo nivel. 'external_area' pode ter qualquer nome ou pode não existir.
Comment: adicionei a resposta
Answer: Desenvolvi uma função que percorre o array e vai mesclando os array, dê uma olhada, considerei o array $characteristics como o primeiro que você postou na pergunta, espero que ajude
var_dump(getAllCharacteristics($characteristics));
die;

function getAllCharacteristics($characteristics) {
    $newArray = [];
    foreach ($characteristics as $characteristic) {
        if (is_array($characteristic)) {
            $newArray = array_merge($newArray, getAllCharacteristics($characteristic));
        } else {
            $newArray[] = $characteristic;
        }
    }
    return $newArray;
}

A saída da função var_dump seria:
array(9) {
  [0]=>
  string(7) "varanda"
  [1]=>
  string(10) "lavanderia"
  [2]=>
  string(7) "piscina"
  [3]=>
  string(5) "muros"
  [4]=>
  string(13) "area_serviço"
  [5]=>
  string(9) "piso_frio"
  [6]=>
  string(9) "alvenaria"
  [7]=>
  string(12) "azulejo_teto"
  [8]=>
  string(13) "massa_corrida"
}


Is it possible to view data as it is being imported in Teradata?

Question: I'm trying to import data from a txt file and keep getting a 'Wrong number of data values in row xxx' error. Looking at the text file, everything looks fine but I can't tell what/how Teradata is interpreting it.
So is there a way to view or preview the data from Teradata's perspective? I tried running a SELECT statement, but since the import doesn't finish, nothing is even imported. Which brings me to my next question, is there a way to limit an external-file import to a certain # of rows? Like import just the first 50 rows from the text file?
Comment: Which tool do you use for import? One of the Teradata supplied load tools like BTEQ/FastLoad/MLoad/TPT? Is this a comma delimited text file?
Comment: I honestly haven't been able to figure out what tool I'm using, but I've been just using the default one under File - Import Data. While searching for help, I found [this link](http://forums.teradata.com/forum/tools/difference-between-load-export-utilities) and BTEQ seems to fit the description of what I'm using, but I'm not 100% sure. Even for importing a few thousand rows, it's very slow. I can see TD processing 1 row at a time
Comment: Seems you're not using any of those utilities :-)  Do you run a **INSERT ... VALUES(?,?,?)** from within SQL Assistant? Goto Tools-Options-Import and increase the maximum bath size to at least 100 and check "Silently discard rows that cause constraint violations". This might load at least some rows. Can you show a input row from that file?
Comment: Yep, I'm using INSERT ... VALUES(?,?,?) from within SQL Assistant. I've already increased the batch size to 1000 yet it still has been running about the same speed as before. When I run the import, it will get to about row #900 and then give the error I mentioned before. After that error, when I run a select query, I see nothing but the table grain/definition
Comment: If the table is empty you probably load your table within a single transaction, which means your session is in ANSI mode. Try changing the session mode from ANSI or ystem Default to Teradata, in ODBC it's in the Options, in .NET on the Advanced tab. How many rows are you trying to load? Maybe you should switch to a 'real' load tool :-)
Comment: What text editor are you using to view the file which you are attempting to import?
Comment: dnoeth: how exactly do I open up ODBC? Is it another program/application? And I would use a 'real' load tool, but we're getting rid of the only one we had since it was expensive.
Comment: Rob: I'm just using Notepad. Does this make a big difference as to which text editor I use?
Answer: May I suggest you obtain a copy of Notepad++ or Sublime Text, both of which are free to download, to view the text file. This will allow you to open the text file and identify what in the records is causing you trouble loading the file. You will be able to display non-printable characters and use advanced search techniques to traverse the files looking for problems with the data.
It is possible there is an embedded carriage return, line feed, or other non-printable character that is being interpreted during the import and generating this error.


Attempting to update AWS secret isn't saving in AWS

Question: I'm on Mac Monterrey.  Using the AWS CLI, I want to update a secret's value, so I did this
aws secretsmanager update-secret --secret-id 'development/database' --description '{"adapter": "mysql2", "encoding": "utf8", "host": "host.docker.internal"}'

And I get back
{
    "ARN": "arn:aws:secretsmanager:us-east-1:1234678901234:secret:development/database-4walfE",
    "Name": "development/database"
}

However, when I go to see the value of my secret, it is unchanged
$ aws secretsmanager get-secret-value     --secret-id 'development/database'
{
    "ARN": "arn:aws:secretsmanager:us-east-1:1234678901234:secret:development/database-4abcdE",
    "Name": "development/database",
    "VersionId": "378861d2-c5f0-48a4-a965-13877321da62",
    "SecretString": "{\"adapter\": \"mysql2\", \"encoding\": \"utf8\", \"host\": \"127.0.0.1\"}",
    "VersionStages": [
        "AWSCURRENT"
    ],
    "CreatedDate": "2022-04-11T12:00:43.029000-05:00"
}

What gives?  What am I missing?
Answer: If you're updating the value of the secret, you should use --secret-string
aws secretsmanager update-secret --secret-id 'development/database' --secret-string '{"adapter": "mysql2", "encoding": "utf8", "host": "host.docker.internal"}'


Deleting SSL certificate from Windows Server 2008

Question: I want to permanently delete SSL certificate from Windows Server 2008. What I did is open up the mmc window and selected the certificate from the machine store and click delete. This removed the certificate from the certificate store. I just want to know if this action deleted the certificate completely from the machine and want to make sure that its private key is also deleted. The action I did is correct or not?
Answer: Yes, the key will be deleted with the certificate. You would need to export them first if you want to be able to restore them at some point.
Comment: When I import certificate, a file is created under C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys.   But when I delete certificate it does not delete file from that location.
Comment: I mean is it safe to leave the files in C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys once I delete certificate from mmc.
Comment: That file is a container for keys. The actual key will be removed from the container when the key is deleted.


Existe algum seletor jQuery que pegue o html de sua própria tag e também o conteúdo?

Question: Exemplo:

Quadro de horários

Se eu utilizar $("#quadro").html() eu só obtenho o h1, porém quero o html do h1 e da própria div.
Estou precisando de algo dinâmico, que independa de ter "parentes" ou filhos definidos.
Comment: primeiramente acredito que o correto seria assim $(".quadro").html(), pois você está tratando uma classe e um não um id
Comment: Beleza, foi so uma distração na hora de formular. Vou corrigir.
Answer: jQuery não tem essa função, mas é possível utilizar a propriedade Element.outerHTML, como é uma propriedade do objeto javascript (e não jQuery) é preciso pegar o elemento com .get(0) ou como array (no exemplo) para pegar o primeiro elemento selecionado.
Dessa forma fica:
$(".quadro")[0].outerHTML

Ainda é possível fazer com javascript puro, utilizando querySelector():
document.querySelector('.quadro').outerHTML;

Answer: Se você utilizar
$(".quadro") nesse momento você tem todos os elementos que contém essa classe dentro do mesmo, e com isso você consegue navegar no elemento e nos seus childs.
se você utilizar o método .html(), você vai conter apensar o html dos seus childs(string), o que você realmente precisa, do elemento dentro do selector, ou do html em string ?


Spanning of Vectors on the Plane

Question: Problems:
Evaluate all the vectors that span the set of all vectors on the plane $2x+3y-z=0$.
Are all the vectors linearly independent? Give the explanation.
Attempt (source from my friend):
This plane is 2-dimensional hence cannot be spanned by a single vector but is spanned by any set $\{p,q\}$ where $p,q\in V$ are independent.
Actually I need more explanation for this problems.
Thanks for your help.
Comment: I can't figure out what are you asking? What is "brief" here?
Comment: Where is " brief " here?
Comment: I have edited it
Answer: The plane is nothing more than
$$\begin{align}
\textsf{W} &= \{(x,y,z)\in \mathbb{R}^3:\, 2x+3y-z=0\} \\
&= \{(x,y,z)\in \mathbb{R}^3:\, z=2x+3y\} \\
&= \{(x,y,2x+3y):\, x,y\in \mathbb{R}\} \\
&= \{x(1,0,2)+y(0,1,3):\, x,y\in \mathbb{R}\}
\end{align}$$
that is, any vector in the plane can be written as a linear combination of the vectors $(1,0,2)$ and $(0,1,3)$. Now verify that the set formed by these vectors is linearly independent, that is, if $$a_1(1,0,2)+a_2(0,1,3)=(0,0,0)$$ for some scalars $a_1,a_2$, necessarily implies that $a_1=a_2=0$ (which is clear).

Spanning of Vectors on the Plane


PHP PDO Query with a number of conditions taken from the array

Question: I have a few conditions that I want to do in a single query. The base query:
<code>$query = "select * from table1
    inner join
        table2 on table1.id=table2.id
    where
        ".$condition."
    limit 0,100;";
</code>
I have array of values to query:
<code>$Var = array(
    1 => array('name' => 'somename1','value' => 'somevalue1'),
    2 => array('name' => 'somename2','value' => 'somevalue2'),
    3 => array('name' => 'somename3','value' => 'somevalue3'),
    4 => array('name' => 'somename4','value' => 'somevalue4')
)
</code>
Now in loop
<code>foreach($Var as $Array){
    $condition .= '(T1_column1 = '.$Array['name'].' and T2_column1 = '.$Array['value'].') or ';
}
</code>
Final result:
<code>$query = "select * from table1
    inner join
        table2 on table1.id=table2.id
    where
        (T1_column1 = somename1 and T2_column1 = somevalue1) or
        (T1_column1 = somename2 and T2_column1 = somevalue2) or
        (T1_column1 = somename3 and T2_column1 = somevalue3) or
        (T1_column1 = somename4 and T2_column1 = somevalue4)
    limit 0,100;";
</code>
Is there a way to do the same thing using PDO: prepare,bindvalue,execute ? or bindValue in foreach loop has the same effect? how can I do this?
Answer: This is a duplicate of PDO bind unknown number of parameters?
For your convenience, this is code from Paystey's answer modified to fit your example:
<code>$sql = 'SELECT * FROM table1
    INNER JOIN table2 ON table1.id=table2.id
    WHERE ';
foreach($Var as $Array)
{
    $sql .= '(T1_column1 = ? and T2_column1 = ?) or ';
    $binds[] = $Array['name'];
    $binds[] = $Array['value'];
}
$prep = $db->prepare(substr($sql,0,-3) . 'limit 0,100');
$i = 0;
foreach($binds as $bind){
   $prep->bindValue(++$i, $bind);
}
$prep->execute();
</code>
Not tested.


LassoLarsCV: different results after removing variables with coef=0

Question: I am using LassoLarsCV from sklearn on a dataset with around 100 variables. After fitting the model around 80 of them have a coefficient of 0. I want to remove those variables from my dataset because it requires unnecessary load to the DB and network to request them every time during prediction.
After refitting LassoLarsCV with the same settings on the reduced dataset I get different coefficients and R2 score on my test dataset.
Is this behavior expected? What would be a better approach to not change the actual model, can i remove manually the 0-coefficients from the model object or would it have side effects on the internal model structure?
Answer:
Is this behavior expected?

Yes.  By removing the variables, you are changing the loss function, and so the optimization will be different.

What would be a better approach

You could pass the full data to the model.  This would be the easiest but it seems you aren't interested in doing that.  Because the Lasso is a linear model, it would not be so hard to write your own function to compute the predictions.  That way, you only need to pull the data you need and the computation is just a matrix vector product.
Comment: If there is no other solution I will try to change and overwrite the coef_ array manually, knowing that it's not a very clean solution. But mathematically it should be identical to the fitted model then.


Interactive drawing in C#

Question: I need to draw a large, interactive tree structure in C# WinForms - a corporate hierarchy.
Aside from the algorithm which will arrange the blocks in the tree which is probably going to be quite complex, I'm not really sure about how to go about implementing the actual canvas and drawing code.
At first glance, I could create a giant Image (or a matrix of largeish images), and use a Graphics or BufferedGraphics to render a small region given where the user is zoomed into. This would give the zooming and panning effect you might see on Google Maps.
As for interactivity, what can be done here? I'd like the user to be able to highlight certain people (people in a particular cost centre, people who are contractors, etc...). Also, it would be pretty cool if the tree showed progressively more information about the staff as the user is zoomed in more. Should I just be doing hit testing with the MouseMove event and programatically add/remove/alter the things which make up the picture on the canvas?
Is this something that I should avoid using GDI for and maybe using DirectDraw instead? I don't want to go overkill - I just want to be able to visually represent the structure and give users the option to print it.
Alternatively, is there a (freeware?) library available which allows zooming and panning with interactivity? I might be asking a bit much, but maybe one which also can handle tree structures?
I have experience with each individual concept on a smaller scale, however nothing brought together in a largeish structure like this. I predict that if I do something wrong, it can turn into something very slow, laggy, and memory-hogging.
I've only dabbled in WPF. I almost exclusively use WinForms in .Net - is there something in WPF which would make this task significantly easier?
Answer: I don't know if this even is an answer, but I do a lot of interactive graphical work using GDI+ and I feel that I can work very effectivly with it. Both when it comes to tree structures exacly as the one you describe as well as versatile layout editors and over to browsing photos etc.
What you do not want is painting everything on a large bitmap. Avoid large bitmaps. :-)
So either you use double buffered graphics as provided by the framework or you design it on you own. This may not be perfect if you want to run your app remotely, however: http://blogs.msdn.com/b/oldnewthing/archive/2006/01/03/508694.aspx
Basically you just put everything you want to draw in a list and update it with inforamtion on exactly where it ended you on screen so that you can hit-test for it in OnMouseDown/OnMouseMove/OnMouseUp. You'll soon notice the need for keeping an enum for which state the interaction is in (eg.g DraggingObject, MakingSelection, Scrolling etc) and a Point _lastMousePosition.
The logic is pretty simple. Making it flicker-free and responsive may not be that simple.
Comment: Like I said, I am familiar and practised with each individual concept, but have never brought it together into one large, interactive display like this. I can assure you that your advice was certainly helpful! Thanks.
Answer: Assuming that you are staying with WinForms, one option would be to create your own custom control for each item that needs to expose interactions.
Then create another custom control that will house them and the master canvas. Give it a canvas (e.g. Panel) and a couple of scroll bars.
When the scroll bars are used, dynamically create and remove the child controls as needed. Beyond a certain zoom level you may need to switch from controls to directly drawn, non-interactive images.
This model assumes that users won't be interacting with more than one control at a time. If you offer a lasso that lets them select multiple items things get hard fast.
Comment: P.S. Good luck. What you want is possible, but it isn't going to be easy.

Interactive drawing in C#


Openstack nova-compute service is not recognized as compute service in controller node (probably rabbitmq connection problem)

Question: I was following the tutorials on Openstack docs website for a minimal deployment of the Stein release (I am installing it on Ubuntu 18.04 instances). I installed the nova services and made the required configuration. Then I reached this stage and ran the following command on the controller node.
openstack compute service list --service nova-compute

I was expecting to see a nova-compute service running on a compute host as the result, but I get nothing.
I looked at the nova-compute.log file on my comupte node (/var/log/nova/nova-compute)
and I have this error:
.
.
.
2022-04-25 06:33:46.682 4015 ERROR oslo.messaging._drivers.impl_rabbit [req-313f4c65-0f63-4d8b-8682-6295770701af - - - - -] Connection failed: timed out (retrying in 32.0 seconds): socket.timeout: timed out
2022-04-25 06:34:23.745 4015 ERROR oslo.messaging._drivers.impl_rabbit [req-313f4c65-0f63-4d8b-8682-6295770701af - - - - -] Connection failed: timed out (retrying in 32.0 seconds): socket.timeout: timed out
2022-04-25 06:35:00.803 4015 ERROR oslo.messaging._drivers.impl_rabbit [req-313f4c65-0f63-4d8b-8682-6295770701af - - - - -] Connection failed: timed out (retrying in 32.0 seconds): socket.timeout: timed out
2022-04-25 06:35:37.860 4015 ERROR oslo.messaging._drivers.impl_rabbit [req-313f4c65-0f63-4d8b-8682-6295770701af - - - - -] Connection failed: timed out (retrying in 32.0 seconds): socket.timeout: timed out
2022-04-25 06:36:14.920 4015 ERROR oslo.messaging._drivers.impl_rabbit [req-313f4c65-0f63-4d8b-8682-6295770701af - - - - -] Connection failed: timed out (retrying in 32.0 seconds): socket.timeout: timed out
.
.
.

Apparently, it has a problem connecting to the rabbitmq service. I searched a lot but I couldn't find anything of use in my case. I've been stuck on this for quite some time now. I'd be very happy if someone could give me an answer.
Comment: First, check `rabbitmq` status and listening port. Then verify that whether the `rabbitmq`'s port works or not.
Answer: As Victor Lee suggested in the comments, I checked rabbitmq's port and nothing was wrong there. It was running with no problem. Turned out my firewall didn't allow incoming traffic through rabbitmq's port. So I added a rule to allow it.


Tchaikovsky symphony No1 movement 1 time 2/4

Question: I'm busy with the first symphony of Peter I. Tchaikovsky. In movement 1 the time signature is 2/4. Can someone explain the choice of putting 2/4 instead of 4/4. If it goes with the feel I don't feel 2/4 more then 4/4? Or there are other parameters that made him choose 2/4.
Comment: Even if it's not 100% clear to all listeners, it is likely that Tchaikovsky intended musicians and conductors to have a march mentality while performing the movement. Whether the movement is so fast that it's very hard to hear the difference may not matter. One thing that helped me understand 2/4 versus 4/4 was learning how clearly 6/8 (compound 2/4) is different from 12/8 (compound 4/4). To me, the differences between the compound time signatures is a lot more audible.
Comment: @Todd with the 6/8 I feel it alright. But I never thought of taking it to 12/8 that's a good idea.
Answer: In general a (classical) 4/4 signature emphasises the first and third beat, with the first beat being emphasised slightly (but noticeable) more than the third beat.
In a 2/4 signature, the first beat is emphasised in each bar to give it a march feel.  Think 1 2 1 2.
If one was to rewrite a 2/4 as a 4/4 then one would lose the equal emphasis on every first beat in the bar, replacing alternate 1's with a slightly less emphasised third beat.
Comment: @Nachmen I've just had a quick listen to it and you're right that the march feel is subtle and really only felt when the full string complement enters after about a minute, and even then only intermittently.  There is a lot of dynamics layered on top of the underlying string ground which make the march feel, at times, far from evident.  The march of winter in a blizzard of sounds.
Comment: I got the gist of what you're saying. But the tempo is so fast it's q=132 I almost don't feel nothing? What I do feel is the musical sentence and that gives me the feeling of 4/4.
Comment: Thank for reaffirming my doubts. It's the  don't know  feeling. I'm still making sense.
Comment: I took a metronome and sang the tune as best to my ability, you do see a difference. When the metronome is on 2/4 it fits in more naturally.


HTML Textbox not typing

Question: I need help. My form in my page looks like below however when I click on the text box the cursor won't appear and I can't type
<form name="input" action="postblog.php?name=<?PHP echo ($_GET['name']); ?>" method="post">
    Post: <input type="text" name="text2">
    <input type="submit" value="Submit">
</form>

Comment: Because there's not more code than just these few lines, which are working perfectly, I guess you have JavaScript on your site which blocks the user input. Please give us more code so we can spot the real error.
Answer: There's probably an error that's not being displayed on your screen because it's appearing inside the HTML tags. Make sure to check if $_GET['name'] is set first:
<form name="input" action="postblog.php?name=<?php echo ($_GET && isset($_GET['name'])) ? $_GET['name'] : 'No_Name_Value_From_GET'; ?>" method="post">
  Post: <input type="text" name="text2" />
  <input type="submit" value="Submit" />
</form>

In this instance, if $_GET['name'] is not set, the value for ?name= will be No_Name_Value_From_GET (but you can change it to whatever you want).
HTH... :)

HTML Textbox not typing


How to get particular element from an array

Question: I am getting following output from running a php code, now i want to get "url" field from the following array, how can i get this?
Array (
    [data] => Array (
        [0] => Array (
            [id] => xxxxx
            [from] => Array (
                [id] => xxxxxx
                [name] => abc
            )
            [start_time] => 2012-04-28T07:49:17+0000
            [end_time] => 2012-04-28T07:49:17+0000
            [publish_time] => 2012-04-28T07:49:17+0000
            [application] => Array (
                [id] => 389407107765872
                [name] => Ki News Social Reader
            )
            [data] => Array (
                [article] => Array (
                    [id] => 10150703062718596
                    [url] => http://example.com
                    [type] => kinewssocialreader:article
                    [title] => story
                )
            )

Thanks in advance!
Comment: How to access arrays should be basic knowledge: http://php.net/manual/en/language.types.array.php
Comment: See the multidimensional arrays [here](http://www.w3schools.com/php/php_arrays.asp).
Answer: Index it like any other array. Looking at the actual source of print_r can be much more helpful than seeing it all strung together in one line.
$arr['data'][0]['data']['article']['url']

Answer: $url=$myArray['data'][0]['data']['article']['url']; //assuming $myArray is array

Answer: Use this
$array['data'][0]['data']['article']['url']

if your array variable is called $array.
Answer: If you want to access the array with its key:
$array["key_name"] , $array[$key_name]

If you want to access the array with its element order:
$array[0], $array[1]

If the result of the selection is array, you can continue to use [] to go deeper:
Assume $array["key"] is containing an array, and the array has "another_key" keyed value;
$array["key"]["another_key"]

will work too.
Answer: Assuming that I'm reading the data structure correctly, it would be:
$variableName['data'][0]['data']['article']['url']

Where $variableName is the name of the top level array.  The parentheses don't balance, so I can't be 100% sure of the structure.
I've drawn out the structure to look like this.  If this matches your structure, the naming above will work.
Array (
  [data] => Array (
    [0] => Array (
      [id] => xxxxx
      [from] => Array (
        [id] => xxxxxx
        [name] => abc
      )
      [start_time] => 2012-04-28T07:49:17+0000
      [end_time] => 2012-04-28T07:49:17+0000
      [publish_time] => 2012-04-28T07:49:17+0000
      [application] => Array (
        [id] => 389407107765872
        [name] => Ki News Social Reader
      )
      [data] => Array (
        [article] => Array (
          [id] => 10150703062718596
          [url] => http://example.com
          [type] => kinewssocialreader:article [title] => story
        )
      )
    )
  )
)


Swatch Internet time in python

Question: I have this code :
from time import localtime, timezone

def itime():
    """Calculate and return Swatch Internet Time

    :returns: No. of beats (Swatch Internet Time)
    :rtype: float
    """

    h, m, s = localtime()[3:6]
    beats = ((h * 3600) + (m * 60) + s + timezone) / 86.4

    if beats > 1000:
        beats -= 1000
    elif beats < 0:
        beats += 1000

    return beats

But it doesn't take in account the timezone.
How to choose a timezone for choosing zurich as timezone ?
The server is in the usa but the internet time is based in Swiss
Comment: `localtime()` should already take timezone into account, by subtracting `timezone` you're counting it twice.
Comment: @toti08 the server is in the usa but the internet time is based in Swiss
Comment: Doesn't the following post answer your question? https://stackoverflow.com/questions/1398674/display-the-time-in-a-different-time-zone
Comment: `pytz` I think this covers your issue, along with removing DST, as Swatch time doesn't observe DST. https://stackoverflow.com/questions/48321362/pytz-convert-time-to-utc-without-dst
Answer: There are no time zones in Swatch Internet Time; instead, the new time scale of Biel Meantime (BMT) is used, based on Swatch's headquarters in Biel, Switzerland and equivalent to Central European Time, West Africa Time, and UTC+01. ref https://en.wikipedia.org/wiki/Swatch_Internet_Time
But you can achieve this using following steps:
1) - Get the current time in UTC. (Now you dont need to be worried about server location and its time)
2) - Convert the that time to Zurich time, (Zurich time is UTC+2).
3) - Convert Zurich time to datetime.timetuple().
Previously, datetime.localtime was returning you the timetuple object of local time.
from datetime import datetime
from dateutil import tz

def itime():
    """Calculate and return Swatch Internet Time

    :returns: No. of beats (Swatch Internet Time)
    :rtype: float
    """
    from_zone = tz.gettz('UTC')
    to_zone = tz.gettz('Europe/Zurich')
    time = datetime.utcnow()
    utc_time = time.replace(tzinfo=from_zone)
    zurich_time = utc_time.astimezone(to_zone)

    h, m, s = zurich_time.timetuple()[3:6]

    beats = ((h * 3600) + (m * 60) + s) / 86.4

    if beats > 1000:
        beats -= 1000
    elif beats < 0:
        beats += 1000

    return beats

print itime()

Hope this helps :)

Swatch Internet time in python


How to call a puppet filetemplate twice with different parameters without using define?

Question: i try to create two different files with one template, because they only diff by one line.
file
{
    "/tmp/bootstrap-raid.sh":
    content => template("pxe/bootstrap.sh.erb"),
}

file
{
    "/tmp/bootstrap-noraid.sh":
    content => template("pxe/bootstrap.sh.erb"),
}

bootstrap.sh.erb:
<% if ??? == "???" %>
-r yes \
<% else %>
-r no \
<% end %>

i can't pass a variable by defining it twice like $raid=yes file{} $raid=no file{}, so i tried to define the variable inside each file{} with no effort. then i thought about using the targetfilename inside the template like <% if filename == "/tmp/bootstrap-raid.sh" %> which is also not possible.
how to work call a template twice with different "parameters"
my target is to not defining and calling an extra function in the manifest file, or making two templates. any ideas?
are there any predefined default variables in a template like the filename of the targetfile, the templatename,...?
edit:
another example would be having two php.ini files like in debian, one for the command line and one for the webserver. i want only to exchange the memory limit. but each server needs both php.ini files.
i am looking for a way to pass a hardcoded parameter to the template file or a way that i can if/then/else based upon the targetfilename.
of course i know that i am able to create a new define, which i can call twice. but i am looking for an easier way.
Answer: Perhaps you should do this with a define?

class bootstrap {
 define conf ( $israid= undef ) {
  $loc = $name
  file {
    "$loc":
      content => template(blah.erb);
  }
 }
}

then call it with

include bootstrap
  bootstrap::conf {
    "/loc":
      israid => '-r yes \';
    }
  bootstrap::conf {
    "/otherloc":
      israid => '-r no \';
    }

your template will need to handle the israid variable you can just use an include and keep the logic out of the template (or at least less of the logic in there
 <%= israid %>

Comment: a (pseudocode) `template("templatename.erb",'myvar' => 12)` looks more handy to me than having to add a define for each template i want to use twice. i think there must be a simple way to access the targetfilename or to easily pass a variable in.
Comment: thank you for answering, but its not what i am looking for. added clearification.
Comment: Why don't you want to use a define?
Answer: You can't get the resource name (it seems), but you can get the class. For example:
class bootstrap-raid {
    file {
        "/tmp/bootstrap-raid.sh":
        content => template("/root/bootstrap.sh.erb"),
    }
}
class bootstrap-noraid {
    file {
        "/tmp/bootstrap-noraid.sh":
        content => template("/root/bootstrap.sh.erb"),
    }
}

And for the template:
<% if name == "bootstrap-raid" %>
-r yes \
<% else %>
-r no \
<% end %>

There's also title available, which usually means the same thing (at least, I never saw them differ).
Comment: thank you for the answer, you solution is not i am looked for, but your answer is correct, ist simply not possible. for getting it run i switched to defines.


Group acting on its set of subgroups by conjugation

Question:
I'm pretty sure for the first $H$, the Stabiliser is all of $S_4$ due to the normality of $V_4$, and so the Orbit is just $V_4$.
For the second $H$, I have that the Stabiliser is $H$, as $4$ has to be left invariant. By Orbit-Stabiliser theorem, the Orbit must be a set of 4 subgroups, which I understood to be the 4 different symmetric groups of 3 elements within $S_4$.
However $H = \langle(1234)\rangle$ is giving me a real headache. I can't seem to get the Stabiliser as easily this time around, as nothing appears to work besides the identity.
Comment: If aou have problems with the stabilizer, maybe first determine the orbit (so that you know how large the stabilizer should be)
Comment: Hints: Well, the stabilizer of $H$ in this action always contains $H$. In the case here, $H = \langle (1234) \rangle$ it is actually  slightly larger than $H$.
Answer: Conjugacy classes in the symmetric group correspond to cycle-types. Thus, for $H = \langle (1234)\rangle$, the conjugacy class of $(1234)$ is just $\{(1234),(1243),(1324),(1342),(1423),(1432)\}$. We see that the cycles $(1234),(1432)$ generate the same group. Similarly, so do the cycles $(1243),(1342)$, and also the cycles $(1324),(1423)$.
Thus, the orbit of $H = \langle (1234)\rangle$ are the three groups $H, \langle (1243)\rangle,\langle (1324)\rangle$.
By orbit-stabilizer, the stabilizer $S$ is thus a subgroup of index 3, hence order 8. Clearly $S$ contains $H$, so to describe $S$, it suffices to find an element of $S$ not in $H$.
Note that every element of $H$ commutes with itself. On the other hand, we know that $(1234)$ and $(1432)$ are conjugate, so they must be conjugate by an element of $S_4$ not in $H$. Finding this conjugating element comes down to realizing that given two permutations $\sigma,\tau$, if $\tau(a) = b$, then $(\sigma\tau\sigma^{-1})(\sigma(a)) = \sigma(b)$. Thus, the cycle notation of $\sigma\tau\sigma^{-1}$ is precisely just $\sigma$ applied to the cycle notation of $\tau$. From this we see that the transposition $(24)$ has the property that $(24)(1234)(42) = (1432)$. Thus, the stabilizer $S$ is the group generated by $(1234)$ and $(24)$.
Comment: Thanks for reminding me, I'm still quite new to this


Programmatically disable the permission "this input method may be able to collect all the text you type ." in customed android soft keyboard

Question: I am developing a custom keyboard.I am following this Link to make this Keyboard
https://code.tutsplus.com/tutorials/create-a-custom-keyboard-on-android--cms-22615
As a beginner in android developing ,I have changed some design and add color in this keyboard.But when i try this in my android device and enable this keyboard , it takes appear a ATTENTION
This input method may be able to collect all the text that you type, including personal data like passwords and credit card numbers. ....
As i am not taking any data from user , i want to disable this.I have disable all the permission in AndroidManifest.xml file .but it is not works,
how can i disable this in programmatically and disable this permission ?
Comment: The warning is there not because you are doing it, but because you could.  Any keyboard could-  just dump all the text typed to a file.  As such, the OS warns you about turning on a highly dangerous application.  This is a good thing for the user and should not be removed (and can't be, short of a custom OS).
Comment: Thanks but many android keyboard i found that does not show this warning or Attention, is there any way to disable this warning, it seems dangerous for the user who used my developed keyboard -@Gabe Sechan
Comment: Every keyboard has this warning when you set it as the default IME, with the possible exception of pre-installed keyboards.  There is no way to disable this warning, and there should be no way to disable it.
Comment: Tnx a lot for your kind reply .Sir  would u plz tell me abot SwiftKey Keyboard.when i install this the below link https://play.google.com/store/apps/details?id=com.touchtype.swiftkey.it does not  show any warning , how they managed this ?- Gabe Sechan
Answer: Fortunately, that is not possible. Otherwise, malware authors would simply disable this warning.
Comment: @buddhobaniksagor: "how can i disable this warning" -- you can't. "it seems dangerous for the user who used my developed keyboard" -- then do not distribute the keyboard to users. This message is not unique to your app. It will appear for any keyboard app that the user installs and attempts to enable.
Comment: how can i disable this warning , it seems dangerous for the user who used my developed keyboard -CommonsWare
Comment: Thanks a lot  for your useful reply  but many android keyboard i found and install in my mobile that does not show this warning or Attention, then how can they do or they hide this warning . Is there any way to do this ? - CommonsWare
Comment: @buddhobaniksagor: Perhaps the issue is with your device. The device manufacturer can disable this warning for any keyboards that they pre-install, and perhaps they have marketing deals with some of those others that you test.
Comment: Apple actually gives the developer the option not to request Full Access. But yeah, not an option on Android.


How to fire onmouseup event outside stage when doing free draw in react-konva

Question: I am implementing free draw function through react-konva. It starts drawing with the mousedown event and continues drawing with the mousemove event. The mouseup event terminates the drawing operation. However, the mouseup event works normally within the stage area, but does not work outside the canvas area. How can I make the mouseup event work even outside the stage area?
    <Stage
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
    >

Answer: Instead of listening mouseup/mousemove on stage, you can listen on global window object. In react you can do something like this:
const App = () => {
  const handleMouseUp = React.useCallback(() => {
    // your code here
  }, []);
  React.useEffect(() => {
    window.addEventListener('mouseup', handleMouseUp);
    return () => {
      window.removeEventListener('mouseup', handleMouseUp);
    }
  }, [handleMouseUp]);
  return (
    <Stage
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
    >
  );
}


Can precision and recall of both classes in a binary classification be compared?

Question: While I was going through the question How to interpret classification report of scikit-learn? with the following metrics -

I saw following claim (in the accepted answer) -

you cannot compare the precision and
the recall over two classes. This only means you're classifier is
better to find class 0 over class 1.

I am not able to understand this statement. Shouldn't, in theory atleast, we be striving to get as high score as possible for both the classes separately? Also, this example is for a balanced class problem. What about imbalanced classes? I am assuming that we have a single binary classifier that is estimating P(Y=1|X) only. Could you please help? Thanks
Answer: The cited comment makes no sense and is contradictory on its face: if you cannot compare them, then there is no "it only means".  I notice that a user has sought clarification from the person who posted the answer, but no clarification has been forthcoming.  Interpreting charitably, I suspect that the answerer is alluding to the fact that a binary classification algorithm might overestimate the frequency of one class, making its precision in correctly identifying that class higher than the precision in correctly identifying the other class.  This doesn't really mean that you can't compare the two precisions --- it just means that caution is needed in interpreting what a disparity in precision means.  In any case, just ignore the comment in that answer; at best it is a poorly worded allusion to an unexplained principle.


Using method of an extended class in a class

Question: I'm trying to use a method of an extended class in the extended one (this is probably not really clear but look at the example below and you will understand).
My module is made in typescript :
export default class Test1 {
  private storedCond: string;

  public cond = (cond: string) => {
    this.storedCond = cond;
    return this.storedCond.length;
  };
  public getStoredCond = () => this.storedCond;
}

And then i want to use is some how like so in a js file :
import Test1 from './modules/Test1';

class Test2 extends Test1 {
  // this line is not working, how can i make it work ?
  this.cond('a futur dynamic string');

  final = () => `${this.getStoredCond()} is ${this.getStoredCond().length} length`;
}

const test = new Test2();

console.log(test.final());

My Test1 module is a little bit like a store, i could do something like this : sotredCond = this.cond('a futur dynamic string'); in my Test2 class but this is not what i want to do. I want to give a string (cond) in my Test2 class and store it in my Test1 module.
Comment: If you wanting this to automatically run the `this.cond` you will want to put that in the constructor..
Comment: you can't rich that result with extend class, you should create an instance of Test1 on your Test2 class and call function with binding to Test1 class. and if you want to use that cond for other modules you should create you Test1 class as singleton
Answer: You can use a constructor in your class Test2
import Test1 from './modules/Test1';

class Test2 extends Test1 {

  constructor(cond: string) {
    this.cond(cond);
  }

  public final = () => `${this.getStoredCond()} is ${this.getStoredCond().length} length`;
}

const test = new Test2('a futur dynamic string');

console.log(test.final());

Each time you call new Test2(arg) the constructor will be executed.
See documentation here
Comment: this is wrong answer he just want to give a string (cond) in Test2 class and store it in Test1 module.
Answer: The @Nathan Bruet's answer works but this is not what i really want to do.
But the comment of @Keith is right.
The the final code of my Test2 class is :
class Test2 extends Test1 {
  constructor() {
    super();
    this.cond('a futur dynamic string');
  }

  final = () =>
    `${this.getStoredCond()} is ${this.getStoredCond().length} length`;
}


How to install a module which includes a different version of Symfony?

Question: I am a developer and maintainer for the CiviCRM project. We've been trying to make a Drupal 8 version CiviCRM, and have a come a long way. We're beating our heads against our collective keyboards trying to figure a major blocker for the project.
CiviCRM has used Symfony for a while, and the version that is included is different than what ships with Drupal.
We can get CiviCRM installed with Drupal 8, but after you install it, we cannot install any other Drupal module.
I believe it boils down to a situation where somehow the CiviCRM version of Symfony loads before the Drupal version, and this causes problems.
Does anyone know of a Drupal 8 module that includes a different version of Symfony than the one that ships with Drupal?
Recently I ran across the Ludwig project. This module allows the registering of namespaces in a class that extends ServiceProviderBase.
Would it be possible for the Drupal 8 version of the CiviCRM module to include a CivicrmServiceProvider.php file, which defines a CivicrmServiceProvider class,  and a register() method that adds a container namespace to allow this to work?
Many CiviCRM files have use statements like Drupal starting with Symfony, like here.
We actually put CiviCRM Core into Drupal doc_root/libraries folder, and use the libraries module.
This is the repo for the CiviCRM Drupal module 8.x version, if somebody wants to look at what we got so far. If somebody has the magic elixir for this, I can tell you there would be many happy folks in our community. So if you know how to help us, please do.
CiviCRM does install, and the CiviCRM pages do work. What doesn't work is that after CiviCRM is installed, we can't install other modules via the admin/modules page. As far as I know that's the only thing that is broken. Also installing modules with Drush, after installing CiviCRM, does work.
Trying to install another module after CiviCRM is installed causes the following error:

PHP Fatal error: Call to undefined method Symfony\Component\DependencyInjection\Definition::setFactory() in /var/www/html/civi-for-d8/core/lib/Drupal/Core/DependencyInjection/YamlFileLoader.php on line 206

That's in Drupal 8.3.5. Trying to install CiviCRM for Drupal 8 into a clean Drupal 8.4-dev instance causes the following error:

Drupal\Component\Serialization\Exception\InvalidDataTypeException: The reserved indicator "@" cannot start a plain scalar; you need to quote the scalar at line 8 (near "arguments: [@string_translation, @civicrm.page_state]"). in Drupal\Component\Serialization\YamlSymfony::decode() (line 40 of /var/www/html/drupal84/core/lib/Drupal/Component/Serialization/YamlSymfony.php).
Comment: I don't think this is possible. Drupal 8.4 actually already switched to Symfony3 although there are still similar discussions related to drush, which has the same problem. It's not possible to load two different symfony versions, either you break your integration or you break Drupal. Maybe symfony3 will not be in 8.4 yet, but the security support for symfony2 will end before Drupal8 security support, so at some point, we will have to switch
Comment: @Berdir that might make a good answer?
Comment: On mobile, but what version of Symfony? 8.4 will use 3.x, a jump from v2.
Comment: We're at version 2.5.0 in CiviCRM
Comment: Some documentation of the issue: https://issues.civicrm.org/jira/browse/CRM-17652 .... One person reports he didn't see the problem, but I'm not sure about that, everyone else that tries get an error like reported there
Comment: I'll give a read over tomorrow. See how I can help!
Comment: very much appreciated :)
Comment: The Drupal-ites of CiviCRM hang out here: https://chat.civicrm.org/civicrm/channels/drupal , it's CiviCRM's Mattermost chat site
Comment: Might, except it's not a positive answer, but it's all the answer I can provide. Added some links and posted as answer.
Answer: So, I think if CiviCRM were installed into Drupal 8 via composer (ie. composer require civicrm/civicrm-core in the Drupal root) and CiviCRM's use of Symfony was compatible with Symfony 2.8 or 3.x (ie. not using deprecated functionality), this could work.
This would get everything installed in Drupal's vendor directory, rather than having two, and it'd mean that CiviCRM would use the Symfony version in Drupal 8. But if CiviCRM was compatible with later Symfony versions (even if it bundled an older version for Drupal 6 & 7 and other CMS's) it should be fine.
I think?
UPDATED: Yes, it works - I tried it. :-) I originally posted the below in the CiviCRM issue queue (CRM-17652), but re-posting here for completeness.
The big idea:
Since composer is pretty new to a lot of people, I'm going to attempt to go step by step, from some high-level composer stuff all the way to one way it could be done in CiviCRM:

Composer allows applications to require the libraries it needs (and libraries, of course, can require other libraries).
Libraries have a composer.json file which says what other libraries it needs and what versions it's compatible with (but not necessarily a specific single version - usually a range of versions, like ^2.4.3 which says a minimum of 2.4.3 and up to (but not including) 3.0.0)
Applications have a composer.json which similarly describes needed libraries and compatibility with a range of versions, but the range is really to help with updating. An application will also have a composer.lock which is a specific set of individual versions
Libraries can also have a composer.lock for their own testing or distribution (like building the release tarball with the dependencies bundled), but this is ignored when an application requires the given library (see https://getcomposer.org/doc/02-libraries.md#lock-file)
When an application wants to require a new library, composer finds an intersection of version compatibility between all the things the application requires (including all the libraries already installed and their dependencies) and the new library, possibly doing some updates to make everything line up (or erroring out if it can't find a compatible mix of versions)
In this case, CiviCRM is a library, and a particular Drupal 8 site is the application (Drupal core itself is a library)
CiviCRM could say it "requires" Symfony ^2.5 in its composer.json which means it is compatible with versions 2.5.0 up to (but not including) 3.0.0
When a Drupal 8 site wants to use CiviCRM, the site admin uses composer require civicrm/civicrm-core to require the CiviCRM library and all it's dependencies. If CiviCRM is compatible with Symfony 2.8 (like used in Drupal 8.3.x) everything will install and work fine, using the single Symfony 2.8 from Drupal. All the dependencies end up in Drupal's vendor directory.
However, CiviCRM could keep Symfony 2.5 in its composer.lock, which means the tests would use that, and the tarballs for Drupal 6 & 7 and other CMS's would bundle Symfony 2.5

The proposal:

Update the composer.json of CiviCRM so it can be used as a library by composer-based CMS's like Drupal 8 (but probably others could move that way in the future - composer is getting quite popular)
Make sure CiviCRM core is compatible with Symfony 2.8 and 3.0 (used by Drupal 8.3.x and 8.4.x respectively) but keep the "officially supported" version (currently Symfony 2.5) in the composer.lock for testing and the tarball for distribution. Being compatible with multiple Symfony versions may not be as hard as it sounds - there's a number of libraries out there compatible with both Symfony 2.8 and 3.0. It may just be a matter of avoiding deprecated methods/classes/features! The composer.json will need to be updated to reflect this
Use composer to install the CiviCRM library on Drupal 8 rather than copying into the libraries directory. This is becoming the normal way of installing 3rd party PHP libraries in Drupal 8 (this is used extensively by Drupal Commerce, for example)

For composer-based CMS's, I really think this is The Right Way. While this issue is currently affecting Symfony and Drupal, as the PHP community starts using more and more 3rd party libraries via composer, this could very well affect other CMS's with other version conflicts.
Some working code to test:
So, as promised, I actually got this to work to a limited degree :-) I'm totally coming at this from a Drupal/Composer/Symfony perspective -- I don't have a ton of CiviCRM experience, so there's probably some better ways to do my process below. I welcome any advice!

Download and install Drupal 8.3.5 (or the latest dev of Drupal 8.4.x!)
Go into the root directory in the shell and run these commands to install CiviCRM via composer: https://gist.github.com/dsnopek/56311dbea347874e75180883efabb620
If you use Apache, remove the vendor/.htacess file. This is a security measure from Drupal, which prevents resources like CSS/JS being loaded. This will need some collaboration with the Drupal project to figure out a proper solution because removing this file altogether is a bad idea on production. See: vendor/.htaccess blocking CSS/JS assets from composer libraries.
Go into the /modules directory and do git clone https://github.com/dsnopek/civicrm-drupal.git --branch composer-library
Go to the "Extend" page (/admin/modules) and install the CiviCRM module
Clear drupal cache via Drush (drush cr)
Log out and log back in again per CRM-19878
CiviCRM works! :-)

After all of this, CiviCRM is using Symfony 2.8 from Drupal and the dependencies in Drupal's vendor directory, and isn't loading anything from it's own vendor directory. Huzzah!
I tested enabling the "Telephone" module which failed before these changes (see my steps to reproduce), but works fine with them. :-)
Comment: "using composer....is it possible to have one package use Symfony 2.8, and another package use Symfony 3.2" -> No, PHP can't have two classes with the same name. This isn't really a composer thing.
Comment: So here's a question related to all of this, using composer....is it possible to have one package use Symfony 2.8, and another package use Symfony 3.2 ....
Comment: There's pretty difficult institutional resistance to CiviCRM being required to always use what version of Symfony that Drupal 8/9 does.
Comment: "There's pretty difficult institutional resistance to CiviCRM being required to always use what version of Symfony that Drupal 8/9 does" -> All that would be required of upstream CiviCRM core is that the code is *compatible* with the later Symfony used in Drupal. It wouldn't have to bundle it or use it by default, just be compatible, ie. avoid deprecated methods/classes/features.
Comment: I get why one would be interested in running the two major versions of Symfony side-by-side -- SemVer sorta implies the necessity. But I think it's important that large swaths of Symfony components are similar in v2/v3, and that Civi's integration of v2 has been pretty modest. So I'm optimistic about having or achieving PHP code which is compatible with both. IMHO, the real work is updating the distribution-channel and directory structure.
Answer: I don't think this is possible.
Drupal 8.4 actually already switched to Symfony 3 although there are still similar discussions related to drush, which has the same problem. see Drush 8.x doesn't install Drupal 8.4.x and Drush master doesn't install Drupal 8.3.x and Symfony components are updated to 3.2.6
It's not possible to load two different symfony versions, either you break your integration or you break Drupal. Maybe symfony3 will not be in 8.4 yet, but the security support for symfony2 will end before Drupal8 security support, so at some point, we will have to switch.
Comment: Also, security support for Symfony 2.5 ended in 2015 according to http://symfony.com/roadmap?version=2.5#checker, which means CiviCRM is built on an insecure and outdated symfony version. That alone should be enough to convince them that an update is necessary, at least to version 2.8, it's not just about Drupal8.
Comment: You can not load two different versions of the same class at the same time, that is not possible. The error sounds exactly like what I'd expect to happen. You managed to load the 2.5 version of the Definition class first and then Drupal breaks because it expects a method to exist that actually doesn't. And the differences will get bigger as Drupal switches to Symfony 3. I don't quite understand why you are stuck with 2.5, 2.8 is a minor update and should be backwards compatible (but not the other way round as you found out). So you should be able to update CiviCRM to require 2.8?
Comment: As I mentioned in my comment, I assumed that you wouldn't like me answer, but that doesn't change it. None of those projects you mention use symfony (joomal seems to use a handful of components that might not conflict but possibly will eventually), so you can't compare that. Is is technically impossible to load two conflicting versions of the same class, nothing can change that. That's why dependencies is a complex business and why composer exists. Instead of using libraries, you should probably look into using composer and making CiviCRM compatible with multiple symfony versions
Comment: @DavidSnopek right, what you wrote in your answer is basically what I mentioned in my comments as well, but as long as composer.json of CiviCRM specifices "~2.5.0" for its symfony components, that's not going to work. See https://github.com/civicrm/civicrm-core/blob/master/composer.json. So my answer "you can not use two different versions" is still correct IMHO, you can only improve/update the version contraints in civicrm and then install it through composer and use the same version.
Comment: Well.....Everything works except installing modules from admin/modules....installing modules with Drush does work...All the CiviCRM pages do work. So I'm not convinced its impossible.  Why would it be impossible?
Comment: I've updated my question with more information
Comment: Civi actually has 2.5, and the method seems to exist in 2.8;
Comment: CiviCRM works in Drupal6, Drupal7, Wordpress, Joomla, and Backdrop.  Only some people care about D8, and I am one of them.  The powers that be don't want to have to upgrade Symfony, just because D8 does. I'm trying to figure a way to have cake, eat it too, and then give some to my girl.
Comment: The CiviCRM folks could probably stomach an upgrade to 2.8, but for 8.4 needed 3.x, there may be resistance, and then they don't want to necessarily be tied to whatever version D8.4, 8.5, 9.x uses
Comment: .. then composer will do its best to combine compatible versions together.
Comment: yeah its in the works to upgrade civi to a supported 2.x version, but probably not 3.x and we need to figure out how to make it all work and not be tied to whatever version Drupal is....I do appreciate you taking the time to answer, but I need a solution to this, no matter what form that takes...
Comment: So, I don't want to down vote @Berdir (and I didn't :-)), but I think it is possible. See my answer elsewhere on this page.
Comment: @Berdir you may be technically correct about not being able to use a different version of Symfony in a module.  That being said DavidSnopek came in and spent significant time in solving our actual problem.  For this reason he gets the accepted answer and the bounty
Comment: Berdir is right.  You can't have two versions of a composer library, it's a composer/php limitation.  This question and its answers have a lot of text to essentially say, "Just update your version," and the only way to get around it is to do something hackish (which can work fine, depending on your project) where you call an external application which has its own, separate autoloader.
Answer: Theoretically the only issues here are the file location and class namespace. Unfortunately the only tools I know of in composer for doing that don't let you specify per VERSION, just per package name.
Have you tried setting it up as a completely separate autoloader?
Comment: Can you explain in more detail what you mean?
Comment: https://getcomposer.org/doc/faqs/how-do-i-install-a-package-to-a-custom-path-for-my-framework.md is how to do the custom location. I've seen people fork a project just to make this possible... Also https://getcomposer.org/doc/06-config.md#prepend-autoloader for the option to keep composer's autoloader separate.  In the end the autoloader is just a php file, so you could write your own autoloader that decides which one to include depending on whatever factors you like.
Comment: Also relevant: https://stackoverflow.com/questions/30000063/one-shared-vendor-with-two-projects
Comment: Do be clear, ATM there is no composer based installation method to install Civi with D8.  I had though maybe that was one way to accomplish this. That was what the ServiceProvider object mentioned in the question was about, like adding a PSR-4 namespace to Drupal to point to the CiviCRM library...If I did this, would Civi need to change all of its files from 'use Symfony\....' to 'use Civicrm\Symfony\..' ? Pardon my ignorance of composer pls.


Term or Stat for when a baseball pitcher is responsible for the team's win, both offensively and defensively?

Question:
Is there a term or a recorded statistic for when a baseball pitcher is
  responsible for winning the game both defensively and offensively?

i.e...
1. The pitcher batted and had an RBI/Run, which was either the only run scored or the winning/last run scored

They pitched well enough to keep the opposing team's score lower than their own (producing a win)

Thanks in advance!
Answer: WPA (Win Probability Added) does what you are looking for, although with some limitations. WPA takes the difference in win expectancy for each team for each play and assigns it to the pitcher (for the defense) and the batter (for the offense). Since both pitching and hitting components are measured, a pitcher's contributions both on the mound and at the plate can be considered. I'm not aware of any site that actually combines those two numbers, but it's easy enough to just add it up.
The highest offensive WPA contribution for a pitcher of 2015 was Steven Matz's game on June 28 against the Reds (according to Baseball Reference Play Index). He went 3-for-3 (2 singles and a double) driving in four, which added up to 41% WPA. He also pitched 7.2 innings giving up two runs, which accounts for another 12% WPA. So total, he contributed 53% WPA to the Mets that game. Not bad for a Major League debut.
A couple of things to keep in mind about WPA. On the defense side, all of the value is attributed to the pitcher. So if a fielder makes a great play, the pitcher gets all of the credit. Also, it's all about context, so closers tend to have really high WPA values because they come into games that could go either way (~50% win expectancy), and if they close out the victory (100% win expectancy), the WPA will be ~50%. In a blowout, it's difficult to gain (or lose) WPA because the outcome of the game is largely determined already.
See Fangraphs for a good summary of WPA.
Answer: "Player of the Game" (joking). There is no ACTUAL stat for what you are asking, it is just a great game played by the pitcher. The pitcher can get offensive stats for "walk offs", and they can get defensive stats such as a "win" towards their pitching stats. But there is not a stat that combines the pitcher's offensive and defensive performance.
Answer: There is an expression for this - though as mentioned, no stat.  The expression that is most commonly used is (and this is definitely an artful expression rather than a statistical one)  is "helping themselves".   Another common way this is referred to is "doing it all".
Those are both normal phrases, and probably wouldn't be worth mentioning if not for the fact that their use is ubiquitous enough to give them some sort of standardization.
Incidentally there is also something called "the shut 'em out / home run club" ( a highly exclusive club ) for pitchers who have homered while pitching a complete game shutout. Kershaw is the most recent. See the list.


How is posterior inference an alternative to bootsrap?

Question: From https://people.maths.bris.ac.uk/~sw15190/mgcv/tampere/mgcv-advanced.pdf:

This sounds very vague to me. What, exactly, is posterior inference, and how is it an alternative to the bootstrap?
I would use bootsrap to e.g. test how good our estimated confidence interval is.
So, does it mean that given the estimates of $\beta$ and their covariance-matrix, I would... do, what, exactly, to test that confidence interval, and why would that work?
Answer: Posterior inference is a Bayesian approach to quantifying uncertainty in your parameter estimates. Boostrapping is a non-Bayesian approach to the same question.
I won't re-hash Bayesian inference in this answer, but I suggest you google it. Posterior inference works by positing a distribution over possible parameter values (i.e., we model our parameters as being randomly chosen from some prior distribution). Then, we develop the sampling model (i.e., what is the statistical model for our data) that goes with our parameters. We combine these with Bayes' Theorem to get the posterior probability distribution for our parameters given our observed data.
Bootstrap has many flavors, but it essentially treats your sample as a proxy for your population and proceeds to calculate sampling errors under this assumption. The end result is an estimate of the distribution of estimation errors about the "true" value.
So, two very different ways of attacking the same thing. I would challenge the author's statement the posterior is always fast, although there are certainly cases where one approach beats the other.
However, they are calculating different things as well...Bayes gives credible regions whilst boostrap tries to estimate confidence regions. Read up on the difference between these concepts to see that they are different.