cannot build Caliburn Micro tutorial code. No definition for 'AssemblySource.Select'

Question: I'm trying to get started with Caliburn Micro following the tutorial at http://www.mindscapehq.com/blog/index.php/2012/2/1/caliburn-micro-part-4-the-event-aggregator/
However, the code in the tutorial produces errors. On that page, the following Bootstraper code is provided:
using Caliburn.Micro;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;

public class AppBootstrapper : Bootstrapper<AppViewModel>
{
  private CompositionContainer container;

  protected override void Configure()
  {
    container = new CompositionContainer(new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()));

    CompositionBatch batch = new CompositionBatch();

    batch.AddExportedValue<IWindowManager>(new WindowManager());
    batch.AddExportedValue<IEventAggregator>(new EventAggregator());
    batch.AddExportedValue(container);

    container.Compose(batch);
  }

  protected override object GetInstance(Type serviceType, string key)
  {
    string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
    var exports = container.GetExportedValues<object>(contract);

    if (exports.Count() > 0)
    {
      return exports.First();
    }

    throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
  }
}

I can find no class (generic or otherwise) called Bootstrapper, but I've been able to extend BootstrapperBase instead.
However, I am running into trouble on the line where container is declared.  AssemblySource does not have a method named Select.
So what gives?  Is this a difference between version 2.0 and 1.0?  If so, are there some updated learning materials I can follow?
Answer: There has been some breaking changes between 1.5.2 and 2.0.0. Most of which are outlined in the documentation. Although it appears the change to Bootstrapper is missing. That should be fixed soon.
Instead of inheriting Bootstrapper<T> you should inherit Bootstrapper and add a method like
protected override void OnStartup(object sender, StartupEventArgs e)
{
    DisplayRootViewFor<AppViewModel>();
}

to your Bootstrapper.
The missing method Select is because AssemblySource.Instance is an IObservableCollection and the Select method is the LINQ extension method. Adding a using for System.Linq will correct that error.
Comment: Also, i could not get my app runnig antil I added :
public AppBootstrapper()
        {
            Initialize();
        }
Comment: I believe you meant to inherit from BootstrapperBase and not Bootstrapper.


Quebra de texto por delimitador

Question: Tenho o seguinte texto:
Texto|Texto|Texto|
Quero exibi-lo em um TextView, mas a cada "|" (pipe) ele quebrar a linha.
Desta forma:
String texto = this.textoQuebrado;
String[] array = texto.split("|");
conteudo.setText(Arrays.toString(array));

Sai assim:
|T|e|x|t|o|||T|e|x|t|o|||T|e|x|t|o||
Comment: `texto.replace("|", "\n");`
Comment: @Articuno não tem como sem usar quebra de linha ?
Comment: Na pergunta você diz `mas a cada "|" (pipe) ele quebrar a linha.`.
Comment: É verdade, eu que me perdi por conta de as vezes o \n não ser reconhecido, mas é outra coisa ! Viajei ! Valeu !
Answer: Tente com replace:
String texto = "Texto|Texto|Texto|";
System.out.println(texto.replace("|", "\n"));

Saida:
Texto
Texto
Texto

Veja: https://ideone.com/hp9Jj7
Lembrando que o componente TextView aceita quebras de linhas utilizando o \n normalmente.

Quebra de texto por delimitador


Adding a base field definition in an update hook - it's not appearing

Question: I want to add another base field to a Drupal entity. It used to be possible to just change the code for the entity definition and then update it via the Drupal console. But now it has to be done in an update hook.
I've added the following update hook, done drush updb and the process completes without errors. I then did drush cr to clear the cache, and then opened up the edit form for the entity in question and gave it a hard refresh. But the new field has not appeared. Any idea what I'm doing wrong? Thanks. The code is based on this: https://www.drupal.org/node/3034742, section named "Installing a new field storage definition".
function opencase_entities_update_8002() {
  $storage_definition =  \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
      ->setLabel(t('Date and time'))
      ->setDescription(t('When the activity started.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'datetime_type' => 'date'
      ])
      ->setDefaultValue('2000-01-01')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'weight' => -3,
      ]);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('activity_date_time', 'oc_activity', 'oc_activity', $storage_definition);
}

Comment: Does you have [entity form modes](https://www.drupal.org/docs/8/api/entity-api/display-modes-view-modes-and-form-modes) defined?  Might need to add this new field to them?
Comment: Thanks but no, not using them
Answer: The problem lies in your display options configuration (reference 4k4's answer to #244122).
Try this:
function opencase_entities_update_8002() {
  $storage_definition =  \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
      ->setLabel(t('Date and time'))
      ->setDescription(t('When the activity started.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'datetime_type' => 'date'
      ])
      ->setDefaultValue('2000-01-01')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'datetime_default',
        'settings' => [
          'format_type' => 'medium',
        ],
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'type' => 'datetime_default',
        'weight' => -3,
      ]);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('activity_date_time', 'oc_activity', 'oc_activity', $storage_definition);
}

Edit: Don't forget to update your Entity definition as well!
Comment: would you mind to explain (update entity definition) ? I added new field to custom Entity using hook_update_N, but it didn't appear in UI.


Error Starting Apache Storm Supervisor

Question: I am trying to restart an Apache Storm cluster and I am running into some issues.  I have two supervisors that will not restart.  When I look at the supervisor logs, I see the following error:
java.lang.RuntimeException: java.io.StreamCorruptedException: invalid stream header: 00000000
  at backtype.storm.serialization.DefaultSerializationDelegate.deserialize(DefaultSerializationDelegate.java:56) ~[storm-core-0.9.3.jar:0.9.3]
  at backtype.storm.utils.Utils.deserialize(Utils.java:89) ~[storm-core-0.9.3.jar:0.9.3]
  at backtype.storm.utils.LocalState.deserializeLatestVersion(LocalState.java:65) ~[storm-core-0.9.3.jar:0.9.3]
  at backtype.storm.utils.LocalState.snapshot(LocalState.java:47) ~[storm-core-0.9.3.jar:0.9.3]
  at backtype.storm.utils.LocalState.get(LocalState.java:72) ~[storm-core-0.9.3.jar:0.9.3]
  at backtype.storm.daemon.supervisor$read_worker_heartbeat.invoke.(supervisor.clj:96) ~[storm-core-0.9.3.jar:0.9.3]
  at backtype.storm.daemon.supervisor$read_worker_heartbeats$iter__3992__3996$fn__3997.invoke(supervisor.clj:109) ~[storm-core-0.9.3.jar:0.9.3]
  at clojure.lang.LazySeq.sval(LazySeq.java:42) ~[clojure-1.5.1.jar:na]
  at clojure.lang.LazySeq.seq(LazySeq.java:60) ~[clojure-1.5.1.jar:na]
  at clojure.lang.RT.seq(RT.java:484) ~[clojure-1.5.1.jar:na]
  at clojure.core$seq.invoke(core.clj:133) ~[clojure-1.5.1.jar:na]
  at clojure.core$dorun.invoke(core.clj:2780) ~[clojure-1.5.1.jar:na]
  at clojure.core$doall.invoke(core.clj:2796) ~[clojure-1.5.1.jar:na]
  at backtype.storm.daemon.supervisor$read_worker_heartbeats.invoke(supervisor.clj:108) ~[storm-core-0.9.3.jar:0.9.3]
  at backtype.storm.daemon.supervisor$read_allocated_workers.invoke(supervisor.clj:125) ~[storm-core-0.9.3.jar:0.9.3]
  at backtype.storm.daemon.supervisor$sync_processes.invoke(supervisor.clj:230) ~[storm-core-0.9.3.jar:0.9.3]
  at clojure.lang.Afn.applyToHelper(AFn.java:161) ~[clojure-1.5.1.jar:na]
  at clojure.lang.AFn.applyTo(AFn.java:151) ~[clojure-1.5.1.jar:na]
  at clojure.core$apply.invoke(core.clj:619) ~[clojure-1.5.1.jar:na]
  at clojure.core$partial$fn__4190.doInvoke(core.clj:2396) ~[clojure-1.5.1.jar:na]
  at clojure.lang.RestFn.invoke(RestFn.java:397) ~[clojure-1.5.1.jar:na]
  at backtype.storm.event$event_manager$fn__2467.invoke(event.clj:40) ~[storm-core-0.9.3.jar:0.9.3]
  at clojure.lang.AFn.run(AFn.java:24) ~[clojure-1.5.1.jar:na]
  at java.lang.Thread.run(Thread.java:853) [na:1.7.0]
Caused by java.io.StreamCorruptedExceptionL invalid stream header: 00000000
  at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:885)
  at java.io.ObjectInputStream.<init>(ObjectInputStream.java:348)
  at backtype.storm.serialization.DefaultSerializationDelegate.deserialized(DefaultSerializationDelegate.java:51)
  ... 23 common frames omitted
2015-04-29T10:36:34.096+0000 b.s.util [ERROR] Halting process: ("Error when processing an event")
java.lang.RuntimeException: ("Error when processing an event")
  at backtype.storm.util$exit_process_BANG_.doInvoke(util.clj:325)
  at clojure.lang.RestFn.invoke(RestFn.java:423)
  at backtype.storm.event$event_manager$fn__2467.invoke(event.clj:48)
  at clojure.lang.AFn.run(AFn.java:24)
  at java.lang.Thread.run(Thread.java:853)

I am guessing that this error has to do with data that was assigned to the supervisor that is corrupt now.  What is the best way to handle corrupt data?  I am new to Storm and know only basic info about it.
Storm 0.9.3
Java - IBM J9 VM (build 2.7, JRE 1.7.0 Linux PPC64-64)
Answer: So there were files under the worker directory.  These files were corrupt and I had to delete everything that was under the workers directory.  I then restarted the supervisor and this started working again.
Answer: Just to add a little more info.
In your conf/storm.yaml you will have the location of your storm.local.dir. For me it is set to /var/storm. Inside this dir you will find worker heartbeats, the storm dist files...
Try stopping your storm supervisor, removing all data in the workers dir, and restarting the supervisor again. If this dosnt help try removing all files in the storm.local.dir instead.

Error Starting Apache Storm Supervisor


How to print same pack multiple times on GUI in tkinter

Question: import tkinter as tk

window = tk.Tk()

window.geometry("200x200")

options = tk.Label(text = "Text")

for i in range (3):
      options.pack()

tk.mainloop()

I want this to print "Text" in the gui, 3 times, on 3 different lines. Any help pls?
Answer: import tkinter as tk

window = tk.Tk()

window.geometry("200x200")

for i in range (3):
      options = tk.Label(window, text="test label")
      options.pack()

tk.mainloop()

This will work.


Showing that $\sigma=\prod_{n=1}^{\infty}(n!)^{\frac{1}{2^{n+1}}}$

Question: Somos's quadratic recurrence constant
The Somos's Quadratic recurrence constant is defined by the sequence $g_n=ng_{n-1}$ with initial value of $ g_0= 1$
The value of $\sigma=1.661687...$
An infinite product from maths world $\sigma=\prod_{k=1}^{\infty}k^{\frac{1}{2^k}}$
We found another infinite product involving the factorial numbers by experiments on a sum calculator.
$$\sigma=\prod_{n=1}^{\infty}(n!)^{\frac{1}{2^{n+1}}}$$
Where n! is valid for non-negative integers and defined by
$n!=n(n-1)(n-2)\cdots2\cdot1$
Can somebody help us to prove this
Answer: This is an opportunity to use summation by parts:
$$
\sum _{k=0}^{n} a_kb_k = A_nb_{n}- \sum _{k=0}^{n-1} A_k(b_{k+1}-b_k) \tag1
$$  where $\displaystyle A_n:=\sum _{k=0}^{n} a_k$. Applying it with
$$
a_k=\frac1{2^k},\quad A_n=2-\frac1{2^n}, \quad b_k=\log (k!),\quad b_{k+1}-b_k=\log (k+1),
$$ gives
$$
\begin{align}
\sum _{k=0}^{n} \frac1{2^k} \log (k!) &= \left(2-\frac1{2^n}\right)\log (n!)- \sum _{k=0}^{n-1} \left(2-\frac1{2^k}\right)\log (k+1)
\\& =\left(2-\frac1{2^n}\right)\log (n!)- \sum _{k=1}^{n} \left(2-\frac2{2^k}\right)\log k
\\&=-\frac1{2^n}\log (n!)+2\sum _{k=1}^{n} \frac1{2^k}\log k
\end{align}
$$ that is

$$
\sum _{k=1}^{n} \frac1{2^k}\log k=\sum _{k=0}^{n} \frac1{2^{k+1}} \log (k!)+\frac1{2^{n+1}}\log (n!) \tag2
$$

By letting $n \to \infty$, using $\displaystyle 0\leq\frac1{2^{n+1}}\log (n!)\leq \frac{n\log n}{2^{n+1}}$, then exponentiating both sides one gets the announced result.
Comment: New knowledge for me, excellent thank you!
Answer: Write $n!=\prod_{k=1}^{n} k$ and you have:
$$\begin{align}\prod_{n=1}^{\infty}(n!)^{\frac{1}{2^{n+1}}}&=\prod_{n=1}^{\infty}\prod_{k=1}^{n} k^{1/2^{n+1}}\\
&=\prod_{k=1}^{\infty}\prod_{n=k}^{\infty}k^{1/2^{n+1}}\\
&=\prod_{k=1}^{\infty}k^{\sum_{n=k}^{\infty}1/2^{n+1}}\\
&=\prod_{k=1}^{\infty}k^{1/2^k}\\
&=\sigma
\end{align}$$
Comment: Beautiful, nice one (+1)


How to insert an RTMP url from an adobe streaming server (rtmp://example.com/myvideo.flv) in drupal 7?

Question: I need to create a video gallery and would like some advice on how to view flash videos on drupal 7.
The url I have to insert are rtmp (rtmp://example.com/myvideo.flv).
Any ideas on what modules to install and the steps to follow?
I read on the previous questions about flowplayer but it's only supported on Drupal 6.
Many thanks for your help.
Comment: Can anyone help me on this please?
Comment: http://lmgtfy.com/?q=%22drupal+7%22+embed+flv I'd also advise looking at http://drupal.org/project/media and also http://stackoverflow.com/questions/9065400/what-is-the-best-drupal-module-that-allows-me-to-embedd-videos-from-youtube-or-u may be helpfull
Answer: You can use JWPLAYER , and here is an example for how you setup the streaming
1- in the page header you include the jwplayer js library
2- follow the embedding guide "http://www.longtailvideo.com/support/jw-player/28839/embedding-the-player"
3- use the RTMP changes as it's documented here http://www.longtailvideo.com/support/jw-player/28854/using-rtmp-streaming/
So your simple code will look like this;

 jwplayer("myVideo").setup({
     file: "rtmp://example.com/application/mp4:myVideo.mp4",
     image: "/assets/myVideo.jpg",
     height: 360,
     width: 640
    });


Prove that every number divides itself.

Question: I'm sure these proofs i'm doing are trivial to most of you, but I'm going to persist with these from this book because the aim is to improve the technique of proof writing and mathematical communication. I'm also finding out some properties of numbers I did not realise.
If $d\in \mathbb{Z}$ and  $d|d$, then $\exists k \in \mathbb{Z}$ such that $d\cdot k = d$
The number k exists and is 1.
Would that last line be an acceptable ending of the proof?
Comment: This is the right idea, but: "If $d\in\mathbb Z$ and $d\mid d$ then..." Is a confusing way of writing the proof. You don't want $d\mid d$ implying something, you want something to imply $d\mid d$. So what you should be saying is roughly the reverse: "Since $d\cdot 1=d$ then there is a $k$ such that $d\cdot k=d$, and thus $d\mid d$."
Comment: Indeed. Bucephalus, you had structured a proof along the lines of $\{A\to B~,~ B\}~\vdash A$.  This is not valid.  Thomas gives the correct form: $\{B~,~ B\to A\}~\vdash A$.  (Modus Ponens)
Comment: Oh that's nice @Thomas. Thanks for that.
Comment: But couldn't I be stating "If $d\in \mathbb{Z}$ and  $d|d$, then $\exists k \in \mathbb{Z}$ such that $d\cdot k = d$" as the axiom I will be using to perform the proof. Like a precondition. But then say, what Thomas said, "since $d \cdot 1 = d$ then there is a $k$ such that $d \cdot k =d$, and thus $d|d$." Would you do this, or it's just accepted in the maths community.
Answer: This is the right idea, but: "If $d\in\mathbb Z$ and $d\mid d$ then..." is a confusing way of writing the proof.
You don't want $d\mid d$ implying something, you want something to imply $d\mid d$. So what you should be saying is roughly the reverse:

Since $d\cdot 1=d$ then there is a $k$ such that $d\cdot k=d$, and thus $d\mid d$.

What you've written is a common error in beginning proof-writing. You are reflecting the order of your reasoning: "I want to show $d\mid d$, which means that $d\cdot k=d$, but then $k=1$...."
But that is not the order of the proof, that is the order of your reasoning. The result you want should always be the end of the proof.

Prove that every number divides itself.


Como fazer um site que se ajuste entre 970px e 1300px

Question: Preciso fazer um site que fique com a resolução mínima de 970px, mas que se ajuste até no máximo 1300px de largura.
Pesquisando, eu encontrei algo assim:
<code>.container-fluid {
    margin-left: auto;
    margin-right: auto;
    max-width: 1300px;
}
</code>
Mas quanto ao mínimo? Como poderia ficar? Preciso usar Bootstrap para isso?
Answer: Basicamente acrescentando min-width.
<code>.container-fluid {
    margin-left: auto;
    margin-right: auto;
    max-width: 1300px;
    min-width:  970px;
}
</code>
Considere usar media-queries para atender outros formatos, se for o caso, como neste exemplo:
<code>.div-principal {
    margin-left: auto;
    margin-right: auto;
    max-width: 1300px;
    min-width:  970px;
}

@media (max-width: 970px) {
   .div-principal {
       margin-left: auto;
       margin-right: auto;
       max-width: 970px;
       min-width: 480px;
   }
   ... outras declaracoes adequadas para tamanho < 970 ...
}
</code>

Se não quiser o "efeito" da página esticando, e sim centralizando apenas, ponha o max-width e o min-width na mesma medida.
Comment: Obrigado! Eu não gostaria de versão para celular, nem tablet. No caso seria exibido o site normal em 970px... Preciso mesmo assim usar as media-queries? E no caso poderia abandonar o bootstrap nesse projeto?
Comment: Provavelmente seria exagero usar bootstrap pra algo só em tela de desktop. Essas definições de css básico você pode simplesmente aplicar no  principal da página. Se é só pra desktop, esqueça o @media.
Comment: Muito obrigado amigo! O problema foi resolvido com o uso das Media Queries mesmo!
Comment: @Marcus disponha. Depois experimente as alternativas propostas na questão e dê uma lida geral no assunto, muita coisa você vai ver que o CSS simples resolve pra você numa boa.
Comment: Cuidado ao usar o `@media`. No IE8 não irá funcionar.
Answer: A dica dos media-queries já foi deixada e é o que mais se encaixa no seu problema provavelmente.
 Além do max-width e do min-width, você adicione um width com porcentagem para o seu container se adaptar a tela.
 Uma dica para testar como seu layout vai se adaptar em algumas telas é usar um iframe em uma página e alterar o width dele...
 Mas dependendo do seu objetivo, você talvez nem precise de media-queries.
<code>.container-fluid {
    margin: 0 auto;
    max-width: 1300px;
    min-width:  970px;
    background: #ddd;
    width: 80%;
}
</code>
http://jsfiddle.net/Wagner/LXvAE/2/embedded/result/
Mas se for usar, não é nada difícil adaptar seu layout a outras resoluções, basta dar uma pesquisada a respeito do assunto.
Segue alguns links interessantes:

http://www.w3.org/TR/css3-mediaqueries/
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries
http://css-tricks.com/css-media-queries/


Stop removal of whole table when rows still exist

Question: I have the below code, which does two things:

Checks dates in each table row and removes the row if the date is in the past
If all dates in a table are in the past, remove the entire table

However, the second thing isn't working properly. Instead of only removing the table when all rows of the table have dates in the past, as soon as one row has a date in the past, it is removing the whole table, even if there are multiple rows still with dates in the future.
I've setup a Fiddle so can you see this. http://jsfiddle.net/g6a2nt0k You'll notice there are two dates in the table... one in the past, one in the future, so it should still be showing the one in the future, but instead it hides the entire table.
$(function(){
$('.production-date').each(function(key,value){
    var currentDate = new Date();
    currentDate.setHours(0, 0, 0, 0);
    var date = new Date($(value).text());
    if(date < currentDate){
        var currenttable = $(value).parent().closest('table');
        $(value).parent().remove();
        var count = $(currenttable).children('tr').length;
        if(count<=2) { $(currenttable).remove(); }
    }
});

});
Any advice would be appreciated.
Comment: No need to check inside the loop...do it after
Answer: This line is returning 0:
var count = currenttable.children('tr').length;

Why?  Because the browser adds a tbody tag around the contents of the table, so there are really no tr elements which are children/direct descendands of the table.  That's why this returns 0.
Change it to this:
var count = currenttable.find('tr').length;

Comment: Excellent! Thank you very much!


Como aplicar Pathfinding em uma estrutura de nós?

Question: Eu tenho uma estrutura de nós que representam as minhas páginas e suas ligações, por exemplo, da página A eu posso ir para página B ou página C. Além de que eu posso ter a página A apontando para a B que aponta para C que aponta novamente para A.
O que preciso fazer é determinar uma página de origem e outra de destino, e exibir somente os nós relacionados, por exemplo saindo de A, chegar até H.

Qual algoritmo é utilizado para achar este tipo de caminho?
Answer: Existem vários algorítimos para essa finalidade, dentre eles (tudo em inglês):
Dijkstra's
Eis um exemplo em pseudo-código retirado do link:
<code>function Dijkstra(Graph, source):

       create vertex set Q

       for each vertex v in Graph:
           dist[v] ← INFINITY
           prev[v] ← UNDEFINED
           add v to Q

      dist[source] ← 0

      while Q is not empty:
          u ← vertex in Q with min dist[u]
          remove u from Q

          for each neighbor v of u:
              alt ← dist[u] + length(u, v)
              if alt < dist[v]:
                  dist[v] ← alt
                  prev[v] ← u

      return dist[], prev[]
</code>
D* Algorítimo D-Star
Algorítimo Any-angle path planning
A* Algorítimo A-Star
Comment: @Pagotti a pergunta é tão direta quanto a resposta : "Qual algoritmo é utilizado para achar este tipo de caminho?", e ainda pensado nisso tive o cuidado de transferir o algorítimo do link para minha resposta. No mais, mesmo que os links se quebrem a resposta estará correta, pois essas técnicas são como padrões e sempre estarão presentes para consulta.
Comment: Para mim um link já daria encaminhamento a resposta, mas existe uma discussão interessante sobre isso na comunidade:  http://meta.pt.stackoverflow.com/questions/42/queremos-respostas-que-contenham-somente-links
Comment: O que eu poderia responder ? Se eu colocasse só os nomes, sem os links, tmb estaria correto ao meu ver... Esse tipo de preocupação se dá quando a resposta propriamente dita está no link, o que não é o caso... Mas entendo sua observação, só acho que por ser uma pergunta objetiva, a resposta pode ser também...
Comment: tranquilo, como eu disse, para mim seria suficiente. Eu comentei por ser uma preocupação do SO e também ter tido uma discussão sobre isso aqui no SOpt.


Empty IPv6 address causes DNS error on Macs running Apache Server

Question: For a site I manage, http://archstl.org/, the DNS entry returns an empty (::) IPv6 address when I run $ host archstl.org in the Terminal.
I think the errant IPv6 entry may be the cause of my problem: when a Mac user running Apache Web Server (any flavor) tries to visit archstl.org, they get localhost instead (the Mac seems to pick up archstl.org's IPv6 address rather than the IPv4 address, 126.96.36.199).
Does anyone know how to resolve this issue? I'm not even sure how the IPv6 address is being output for our DNS entry; I don't have any other domain names that return an IPv6 address.
See here for more info on my own troubleshooting: http://archstldev.com/node/74
Answer: :: is the all-zeroes address, similar to 0.0.0.0 in IPv4. This isn't even localhost (::1) — it's guaranteed to make your site unreachable over IPv6. If your web server has IPv6 connectivity, point the AAAA record for archstl.org at its IPv6 address. If it doesn't remove the AAAA record entirely.
Comment: Thanks for the answer - after they removed the AAAA record, everything works great!
Comment: Thanks! I will contact our IT department to see if they can change the AAAA record. I don't actually have the control over this domain name... I'll post back here with the results.
Comment: I have talked to IT, and they said they put in the AAAA record to fix a different issue with IPv6 timeouts they were having. They are looking into possible solutions, and I've filed a support ticket with our hosting provider to see if they have any solutions.


Como pegar o nome e os atributos das tabelas de um banco de dados MySQL?

Question: Como pegar os nomes de todas as tabelas do banco de dados MySQL?
Como pegar os atributos (nome, tipo, etc...) de uma determinada tabela no banco de dados MySQL?
Answer: Para visualizar as tabelas de uma database:
SHOW TABLES;

Para visualizar a estrutura da tabela com nome, tipo, etc.:
DESC nome_da_tabela;

Comment: Se precisar especificar um Banco:
`SHOW TABLES FROM banco`
Comment: **SHOW TABLES** só responde uma parte da pergunta.  Os atributos das tabelas estão no INFORMATION_SCHEMA
Comment: É possível escolher o banco utilizando o comando `USE nomeDoBanco;`, antes do `SHOW TABLES;`
Comment: Sim, você pode utilizar o information_schema para visualizar informações mais completas da tabela, mas, se você precisa apenas de informações básicas como nome, típo, etc. você pode usar o "DESC" (Conforme mencionado nessa mesma resposta) que é mais simples.
Answer: Você pode usar a consulta:
SELECT * FROM information_schema.tables WHERE table_schema = 'nome-do-banco';

Ela mostra os nomes das tabelas e também informações como a engine usada, data de criação, etc.
Answer: O correto é fazer uma consulta no banco INFORMATION_SCHEMA.
Você vai conseguir dados como o type das tabelas, avg do tamanho dos registros, além dos nomes e o Storage Engine.
DESC INFORMATION_SCHEMA.TABLES;

Vai te dar um bom conhecimento do que pode procurar por tabela.
Lembrando que TODO comando "SHOW" tem correlação com tabelas no INFORMATION_SCHEMA
Answer: Pegando os dados das colunas de uma determinada tabela:
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '<tabela>';

Answer: select * from all_tables where tables like '%tabela desejada%'

Comment: Isso é Oracle! Não MySQL!


What does it mean by "geometry" in complex analysis?

Question: I have seen several articles and books describing the geometry of holomorphic functions, although I am not 100% sure what "geometry" means in this case. Those geometric ideas include:

Conformal mapping; automorphism of the unit disc, upper half-plane, etc.
Riemann surfaces

Why exactly are those things called "geometry"? I don't know a lot of geometry, but I think geometry is about "spaces" and "transformations", so it makes sense to say that "automorphisms" are transformations.
The Wikipedia page on "complex geometry" is entirely beyond my understanding of the topic.
Comment: See the discussion here https://math.stackexchange.com/questions/192055/what-is-a-geometry
Answer: I would say that broadly there are three main geometric themes in the classical theory of complex analysis in the plane - here we do not consider Riemann surfaces which are better understood in terms of complex manifolds, 2 or more complex variables or topology per se, just what one would consider fairly basic euclidean and hyperbolic geometry.
We have euclidean stuff that is represented in geometric property of domains like convexity, star like and more intricate stuff (spiral like, convex in one direction etc) and then the theory deals with the strong conditions that are imposed on Taylor series with images domains as above (convex etc) - first we prove results for injective (univalent) holomorphic functions and then we use subordination and quasi-subordination theory to get results in general. Herglotz theorem about holomorphic functions on the unit disc with positive real part (or equivalently positive harmonic functions on the disc) is the typical example one learns first - this usually is called geometric function theory
We have hyperbolic geometric stuff where holomorphic functions from the unit disc to the unit disc are contractions in the hyperbolic metric (this is a fancy way of stating Schwarz lemma) - since the hyperbolic metric is pointwise proportional to the Euclidean metric, angles are same under both metrics so conformality (angle preserving) of holomorphic functions at non critical points belongs to both topics
We have boundary properties of holomorphic functions which belong to both topological (shape) and geometric conditions (areas, lengths..) and usually the first results one learns are topological (eg bounded holomorphic functions on the unit disc have non zero radial boundary limits ae) and then the deeper results are geometric


Getting a substring using method does not work

Question: I am trying to introduce a method in my program which should result into a substring. I wrote the following code but why would not this work?
class testmethod {

   String FQDN = "TEST.domain.local"
   def sname = shortname(FQDN);
   println $sname

     def shortname(Longname)
        {
          shortname1 =  Longname.substring(0, Longname.indexOf('.'))
          return shortname1
        }
     }

Comment: is it part of real code? or just a "pseudocode"? it doesn't look like something real, hard to answer in such form, too many syntax errors here
Comment: Interesting code style convention indeed http://www.myfacewhen.net/uploads/2058-thinking.jpg
Answer: First of all the code should be(for better readability) :-
def shortname(String Longname) not def shortname(Longname).
Also shortname1 =  Longname.substring(0, Longname.indexOf('.')) in this shortname1 is not defined.
Moreover you can try :-
def shortname(String Longname)
        {
          String[] shortnameArr =  Longname.split("\\.");
          return shortnameArr[0];// will return TEST
        }

Comment: @AnkitNigam `def shortname(Longname)` is equal to `def shortname(def Longname)`. It's nice to define actual class as `String` instead of default `def`, some people who will read this code in future will appreciate that, but it's not what @rora asked
Comment: I am saying `String Longname`, not the `def sname` or `def shortname`
Comment: @IgorArtamonov, thanx for clarifying. BTW just offtopic, but i used your FB SpringSecurity. Very Well done.
Comment: @AnkitNigam thanks for using it :) btw, updated answer looks good, I guess original issue was because of undefined `shortname1`, but code in the question is real mess, hard to say what @rora meant
Comment: Sorry Guys. just started with Groovy. coming from perl/vbscript background and have no experience with JAVA.
@IgorArtamonov - you are right. This is not the complete code. currently i have started working on to migrate a VBScript code to Groovy and in this script i have function where a FQDN is changed to hostname by using such function.

the bad thing in groovy is that there are many way to do the same thing.

btw the error i am getting is (Groovy console) is

1 compilation error:

unexpected token: println at line: 5, column: 4
Answer: You're mixing both script and class concepts of the Groovy in one single piece of code.
Just remove the class definition and $ sign to use the script way:
   String FQDN = "TEST.domain.local"
   def sname = shortname(FQDN);
   println sname

     def shortname(Longname)
        {
          shortname1 =  Longname.substring(0, Longname.indexOf('.'))
          return shortname1
        }

Or add class initialization and local variable declaration to use the class way:
class testmethod {
   String FQDN = "TEST.domain.local"
   def sname = shortname(FQDN);

     def shortname(Longname)
        {
          def shortname1 =  Longname.substring(0, Longname.indexOf('.'))
          return shortname1
        }
}

def tc = new testmethod()
println tc.sname


Rails, tinymce-rails multiple images path breaking because of "../../../"

Question: Hi everyone I am trying use tinymce-rails and and also have an upload form. This works really well since I can call the images anywhere. Just about everything is working great. The images upload, the tinymce styles stuff.
Now the weird thing is tinymce keeps adjusting the file paths to add "../../../" and this breaks the photos when editing the text. It would actually work fine if it would just go up one more "../" count on the edit page, the pathing does work on the show page.

Does anyone have any direction they can give me?
Comment: what html you are using to show images?
Answer: As I can't know the source of this, I can provide a workaround.
In your model, let's call it Post, you might need to replace stuff to the field containing the html, let's call it body:
before_save {
    body.gsub!(/(\.\.\/)+/,"..\/")
}

Comment: Thank you very much, I know id hadn't provided much information and your suggestion worked great. In the end this worked

`before_save :fix_photos`

`def fix_photos
   self.description.gsub!(/(\.\.\/)+/,"/")
end`


Domain of essential self-adjointness for $A\otimes 1+1\otimes A$

Question: Let $A$ be an unbounded self-adjoint operator acting on a Hilbert space $H$ (typically $L^2(\mathbb{R}^d)$).
Then, using Stone's theorem, the operator $A^{\otimes 2}:=A\otimes 1+1\otimes A$ defines a self-adjoint operator on $H\otimes H$, the domain of which might be difficult to determine.
Is it however true that if $A$ is furthermore essentially self-adjoint on $\mathcal{C}$, then $A^{\otimes 2}$ is essentially self-adjoint on $\mathcal{C}\otimes \mathcal{C}$ ?
Answer: This is true and in fact even more is true: it is proved in

Theorem VIII.33 (a) of Reed & Simon, Methods of Modern Mathematical Physics I: Functional Analysis, 1980

that

If $\{A_k : \mathcal{H}_k \to \mathcal{H}_k \}$, $1 \leq k \leq N$, is a collection of self-adjoint operators with $D^e_k \subset \mathcal{H}_k$ the domain of essential self-adjointness for $A_k$ and $P \in \mathbb{R}[x_1, \ldots, x_N]$ is of degree $n_k$ in the variable $x_k$, then  $P(A_1^{(1)}, \ldots, A_N^{(N)})$ is essentially self-adjoint on $D^e := \bigotimes_{k=1}^N D^e_k$,

wherein I've used the notation $A_k^{(k)} := I \otimes \cdots \otimes A_k \otimes \cdots I$ (which in the text is written just as $A_k$, overloading the notation).
The specialization to $\sum_{k=1}^N A_k^{(k)}$, which is only slightly more general than your question, is then

Corollary (a) to Theorem VIII.33, ibid.

The proof to your specific form would involve, I believe, essentially the same ingredients as that to Theorem VIII.33 (a).
The natural consequence for the closure of the spectrum is also dealt with in the same place.
Comment: Thank you very much for your help. R&S contains so much information, i will include this reference.


Spring Profiles on method level?

Question: I'd like to introduce some methods that are only executed during development.
I thought I might use Spring @Profile annotation here? But how can I apply this annotation on class level, so that this method is only invoked if the specific profile is configured in properties?
spring.profiles.active=dev

Take the following as pseudocode. How can this be done?
class MyService {

    void run() {
       log();
    }

    @Profile("dev")
    void log() {
       //only during dev
    }
}

Answer: For future readers who don't want to have multiple @Beans annotated with @Profile, this could also be a solution:
class MyService {

   @Autowired
   Environment env;

   void run() {
      if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
         log();
      }
   }

   void log() {
      //only during dev
   }
}

Comment: typo in Enviroment , should be Environment. Also `Arrays.asList(env.getActiveProfiles()).contains("dev")` can be replaced with `env.acceptsProfiles("dev")`
Comment: I prefer the Arrays.asList().contains() solution, acceptsProfiles is not very understandable in this context..
Comment: @funder7, please explain how is creating a new list and calling contains() on it more "understandable" or performant than asking env if it accepts a certain profile?
Comment: I meant that `env.acceptsProfiles("dev")` is more criptic, while the other way is more excplicit: `env.getActiveProfiles` gets the list, and `.contains("dev")` checks if the profile of interest is contained into the active profiles list. It's just a stylistic preference, nothing else. :-)
Answer: AS you can read on http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/Profile.html

The @Profile annotation may be used in any of the following ways:
as a type-level annotation on any class directly or indirectly
  annotated with @Component, including @Configuration classes as a
  meta-annotation, for the purpose of composing custom stereotype
  annotations If a @Configuration class is marked with @Profile, all of
  the @Bean methods and @Import annotations associated with that class
  will be bypassed unless one or more the specified profiles are active.
  This is very similar to the behavior in Spring XML: if the profile
  attribute of the beans element is supplied e.g., , the beans element will not be parsed unless profiles
  'p1' and/or 'p2' have been activated. Likewise, if a @Component or
  @Configuration class is marked with @Profile({"p1", "p2"}), that class
  will not be registered/processed unless profiles 'p1' and/or 'p2' have
  been activated.

So, a @Profile annotation on a class, aplies to all of it's  methods and imports. Not to the class.
What you're trying to do could probably be achieved by having two classes that implement the same interface, and injecting one or another depending on the profile. Take a look at the answer to this question.
Annotation-driven dependency injection which handles different environments
Comment: You would probably want multiple implementation of the same interface where each one will be included in the Spring Context only when a certain profile is active.
From what I gather, you would probably want the production implementation to have an empty implementation for the method in question
Comment: OK so what I want is probably not possible with spring annotations. However, do you have any idea how such a requirement could be implemented?
Comment: I was just writing it.
Comment: How to have a controller handler method being available only if a profile is activated ? A @Profile annotation on the method seems to be ignored.
Answer: @Profile can be used with method and with Java Based Configuration
e.g. separate DB timestamp for PostgreSQL (LocalDateTime) and for HSQLDB (prior to 2.4.0 Timestamp):
@Autowired
private Function<LocalDateTime, T> dateTimeExtractor;

@Bean
@Profile("hsqldb")
public Function<LocalDateTime, Timestamp> getTimestamp() {
    return Timestamp::valueOf;
}

@Bean
@Profile("postgres")
public Function<LocalDateTime, LocalDateTime> getLocalDateTime() {
    return dt -> dt;
}

Have a look also at Spring Profiles example: 3. More…(sample Spring @Profile at method level)
Answer: Just wanted to add that answer saying this is possible with current spring on method-level is blatantly wrong. Using @Profile on methods in general will not work - the only methods it will work on are in the @Configuration class with @Bean annotation on them.
I run a quick test with Spring 4.2.4, where it was seen that

@Profile in @Configuration class bean creation methods work
@Profile in methods of a bean does not work (and is not expected to work - docs are a bit ambiguous)
Class-level @Profile works if and only if it's at the same context as bean definition, in the configuration class or if context-scan is used, there
env.acceptsProfiles("profile"), Arrays.asList(env.getActiveProfiles()).contains("profile") works

Test class:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Arrays;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ProfileTest.ProfileTestConfiguration.class })
@ActiveProfiles("test")
public class ProfileTest {
    static class SomeClass {}
    static class OtherClass {}
    static class ThirdClass {
        @Profile("test")
        public void method() {}
    }
    static class FourthClass {
        @Profile("!test")
        public void method() {}
    }

    static class ProfileTestConfiguration {
        @Bean
        @Profile("test")
        SomeClass someClass() {
            return new SomeClass();
        }
        @Bean
        @Profile("!test")
        OtherClass otherClass() {
            return new OtherClass();
        }
        @Bean
        ThirdClass thirdClass() {
            return new ThirdClass();
        }
        @Bean
        FourthClass fourthClass() {
            return new FourthClass();
        }
    }

    @Autowired
    ApplicationContext context;

    @Test
    public void testProfileAnnotationIncludeClass() {
        context.getBean(SomeClass.class);
    }
    @Test(expected = NoSuchBeanDefinitionException.class)
    public void testProfileAnnotationExcludeClass() {
        context.getBean(OtherClass.class);
    }
    @Test
    public void testProfileAnnotationIncludeMethod() {
        context.getBean(ThirdClass.class).method();
    }
    @Test(expected = Exception.class)  // fails
    public void testProfileAnnotationExcludeMethod() {
        context.getBean(FourthClass.class).method();
    }
}

Answer: Possible in 4.1

The @Profile annotation may be used in any of the following ways:
as a type-level annotation on any class directly or indirectly
  annotated with @Component, including @Configuration classes. As a
  meta-annotation, for the purpose of composing custom stereotype
  annotations. As a method-level annotation on any @Bean method

http://docs.spring.io/spring/docs/4.1.x/javadoc-api/org/springframework/context/annotation/Profile.html
Comment: Also as of 4.0.x: http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/context/annotation/Profile.html
Answer: @Profile can't be used for that, but you might as well code your own @RunOnProfile annotation and aspect.  Your method would look like this:
@RunOnProfile({"dev", "uat"})
public void doSomething() {
    log.info("I'm doing something on dev and uat");
}

Or
@RunOnProfile("!prod")
public void doSomething() {
    log.info("I'm doing something on profile other than prod");
}

Here's the code for the @RunOnProfile annotation and aspect:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RunOnProfile {
    String[] value();

    @Aspect
    @Configuration
    class RunOnProfileAspect {

        @Autowired
        Environment env;

        @Around("@annotation(runOnProfile)")
        public Object around(ProceedingJoinPoint joinPoint, RunOnProfile runOnProfile) throws Throwable {
            if (env.acceptsProfiles(runOnProfile.value()))
                return joinPoint.proceed();
            return null;
        }
    }
}

Note 1: If you expect something in return and the profile does not apply, you would get null.
Note 2: This work like any other Spring aspect.  You need to invoke the autowired bean method, for the bean proxy to kick in.  In other words, you can't invoke the method directly from other class method. If you want that, you need to self autowire the component, on the class and invoke self.doSomething().
Answer: Use acceptsProfiles(Profile)
class Test {

  @Autowired
  Environment env

  public void method1(){
     if(env.acceptsProfiles(Profiles.of("dev")){
        //invoke method
        doStuff();
     }
  }
}

Comment: Hi Sourabh,
Can we write as comma separated values for multiple profiles?

if(env.acceptsProfiles(Profiles.of("dev","test")){
        //invoke method
        doStuff();
 }

Let me know if you think it's the right way.
Thank you!
Answer: Using the Environment profile this can be achieved:
class MyClass {

   @Autowired
   Environment env;

   void methodA() {
      if (env.acceptsProfiles(Profiles.of("dev"))) {
         methodB();
      }
   }

   void methodB() {
      // when profile is 'dev'
   }
}

Profiles.of can be used with logical expressions also:

static Profiles of(String... profiles) Create a new Profiles instance
  that checks for matches against the given profile strings. The
  returned instance will match if any one of the given profile strings
  matches.
A profile string may contain a simple profile name (for example
  "production") or a profile expression. A profile expression allows for
  more complicated profile logic to be expressed, for example
  "production & cloud".
The following operators are supported in profile expressions:
! - A logical not of the profile & - A logical and of the profiles | -
  A logical or of the profiles Please note that the & and | operators
  may not be mixed without using parentheses. For example "a & b | c" is
  not a valid expression; it must be expressed as "(a & b) | c" or "a &
  (b | c)".

Spring Profiles on method level?


PHP removing an array element and inserting it into another array

Question: I have 2 arrays which are in the same form as below; for examples sake, lets call them $array1 and $array2
<code>Array (
    [Element1] => Array
        (
            [id] => 11
            [morethings] => 145
            [somemore] => namehere
        )
    [Element2] => Array
        (
            [id] => 11
            [morethings] => 145
            [somemore] => namehere
        )
    [Element3] => Array
        (
            [id] => 11
            [morethings] => 145
            [somemore] => namehere
        )
)
</code>
What I need to do is take Element2 from the first array and then insert it into array2 as NewElement2
I have the following below but it keeps returning nothing at all in array2
<code>$searchArray = array_search('Element2', $array1);
array_splice($array2, $searchArray, 1, array('NewElement2'));
</code>
Any help would be greatly appreciated.
Comment: your over thinking it `$array2['Element2']=$array1['Element2'];`
Comment: @rtfm wont that kill all the rest of the elements in the array?
Comment: test it and find out
Comment: @rtfm That did indeed work ... Thank you very much
Answer: for assign the value  you can  simply
<code> $array2['Element2'] = $array1['Element2'];
</code>
(this append or repalce the entry for Elemet2 in $array2)
and for remove the value
<code> unset($array1['Element2']);
</code>


Properties of Haar measure

Question: Let $G$ be a locally compact group (but not discrete) and let $m$ be its left Haar measure. Is it true that $\forall \epsilon$ $\exists$ $C$ such that $C$ is a compact neighborhood of the identity and the measure of $C$ is less than$\epsilon$ ?
I have little experience working with Haar measure (basically been told to just assume that it exists) so I'm wary of weird measure theoretic pathologies.
Moreover, if anyone could suggest a reference, it'd be much appreciated.
Comment: If every compact nbd of the identity $e$ has measure $\ge \epsilon$, then (by local compactness) every nbd of $e$ has measure $\ge \epsilon$.  But then (by regularity) the singleton $\{e\}$ has measure $\ge \epsilon$.  NOW: why does that tell you that your group is discrete?
Comment: Consider a discrete group with the counting measure...
Comment: Ah, you added your comment just as I edited to rule out the discrete case.
Comment: Hm... my inbox says there was a comment left here but I don't see it. It starts with "One of the nicest expositions of the existence and," which seems like it would have been helpful. Was it deleted?
Comment: @Grasshopper that comment that disappeard was mine, but it was getting too late to elaborate it into an answer.
Answer: Your technical question on Haar measure was answered in the comments, so I won't elaborate on that (unless you ask me to).

One of the nicest expositions of existence and uniqueness of Haar measure I know is the unpublished manuscript by G.K. Pedersen, The existence and uniqueness of the Haar integral on a locally compact topological group. If you're acquainted with Radon integrals, as discussed e.g. in chapter 6 of Analysis now (and read the part on invariant integration towards the end of said chapter) then you'll know most of the basics that you absolutely need to know for starting out in abstract harmonic analysis.
Alternatively, chapter 2 of
Folland's A course in abstract harmonic analysis contains a thorough account of existence and uniqueness, too, and prepares the ground for further and much deeper study.
I often heard people recommend Nachbin's The Haar integral, but I admit I haven't read it myself.

Added in view of GEdgar's comment:
The basics on Radon measures are well treated in Chapter 6 of Pedersen's book mentioned above and also at the beginning of Rudin's Real and complex analysis.
Two stand-alone manuscripts on integration theory on locally compact spaces (but not specifically for groups) that I liked (I learned the basics from there):

W. Arveson, Notes on Measure and Integration in Locally Compact Spaces.
O.E. Lanford III, Topics in functional analysis, Part 1: The Riesz–Markov theorem.

Some classics you should be aware of:
Hewitt-Ross, Abstract Harmonic Analysis 1, gives an extremely thorough if abstract, lengthy and general treatment of topological groups and integration theory on them. The reference contains most of what you'll ever need.
Further: Loomis,  Reiter and, of course, Weil. They haven't lost their value over time and can be found in every library (I'm not entirely sure that Reiter covers the existence and uniqueness theorem, though).
At some point you should definitely look at the theory of commutative groups, so I should probably also mention Rudin's Fourier Analysis on Groups.

For a quick introduction to some main facts of harmonic analysis I'd recommend George Willis's contribution to H.G. Dales et al. Introduction to Banach algebras, operators, and harmonic analysis,
London Mathematical Society Student Texts, 57. Cambridge University Press, Cambridge, 2003, (e-book version), MR2060440. There are many references for further study in there.

I think that should be enough for the moment.
Comment: Thanks a bunch for the detailed response. I've definitely got enough to work with for a while.
Comment: Maybe I should have mentioned that Haar measure has all the good properties you can dream of... On connected groups it behaves much like Lebesgue measure on $\mathbb{R}^n$.
Comment: These are fine books.  Suitable for someone intending to specialize in related fields.  But I have the impression that the OP wanted a two-page summary or so.
Comment: @GEdgar: That's what the first and last paragraphs are supposed to provide. Grasshopper asked a few questions on abstract harmonic analysis here recently, so I thought I'd give  a bit more than what was asked for. Unfortunately, I don't know of a good Radon-measures-"cheat sheet", but Pedersen Ch. 6 comes close --- or do you think I should send OP to Rudin's real and complex analysis? (that's not a rhetorical question).
Comment: A good source of information on Radon measures (on LCH spaces) is Folland's "Real Analysis: Modern Techniques and their Applications", chapter 6 if I remember correctly. He doesn't assume that the space in question $\sigma$-compact, which some may find as an interesting generalization and others may find as a major annoyance.
Comment: @Mark: thanks for that pointer. I think with all those books and sources I've given, Grasshopper has enough stuff to dig in, so I won't add it to the answer itself.
Comment: The link is dead. Here's an archived one https://web.archive.org/web/20220428004546/https://library.mat.uniroma1.it/mat_cms/materiali/2017-2018/pinzari-26714-Pedersen_Haar_measure.pdf

Properties of Haar measure


Is possible to create a ruby-on-rails migration from a database?

Question: From a previsou existent schema, using modeling tools like mySQL Workbench, The the current database schema is changed.
Is somehow possible for ruby to compare these 2 schemas (before and after modification) and create a propper migration based on these changes?
Answer: You could generate the 'new version' schema by pointing a copy of your app to the new db, then run db:schema:dump.  Then run a "diff" on the old vs new schema - keeping only the parts that changed.  Then use some regex-replacements in your editor (or awk) to change the actions to add_column operations, and put those changes into a migration.
At this point, you still need to change your models, controllers, and views to reflect the db-changes.  The diff could be handy for walking through those changes, as well.


function returning pointer to object in a 2d array

Question: i have a 2d array of struct _tile.
i want a function returning a tile within it.
here is code that i use to generate 2d array of tiles.as i am going to do some path finding and dungeon work.
the function get tile at
enum{normalfloor,door};

tile structure.
     struct _tile{
int type;
bool isSet;
int x,y;
_tile *camefrom;
int index;
bool changeTo(int a){
    if(!isSet){
        type = a;
        isSet = 1;
        return 1;
    }
    return 0;
}
};

dungeon map creation code:
int Mw,Mh;
_tile **tile;
void create(int w = 30,int h = 30){
    Mw=w,Mh=h;
    tile = new _tile *[w];
    for(int a=0,_index=0;a<w;a++){
        tile[a] = new _tile[h];
        for(int b=0;b<h;b++,_index++){
            _tile *C = &tile[a][b];
            C->type = normalfloor;
            //1) Start with a rectangular grid, x units wide and y units tall. Mark each cell in the grid unvisited.
            C->isSet = 0;
            C->x = a;
            C->y = b;
            C->index = _index;
        }
    }
}

i want a function to return a tile at given index.
but for some reason this does not work.
_tile getTileAt(int index){
    int z[2];
    int rem = index/Mh;
    int X = index-(rem*Mh);
    int Y = index - X;
    return *tile[X][Y];
}

when i use this
            _tile *a;
        a = getTileAt(10);
        a->changeTo(door);// here program crashes.

i have been searching over net.but got no satisfactory results.
Comment: Is this really how you format your code?
Comment: "this does not work" Debug it. What happens? What is the result you get? What is the result you expected? Apply critical thinking. Write out the steps on paper and figure out where it diverges. SO is not a helpdesk.
Comment: What exactly is not working? How does the return value of `getTileAt` differ from the expected value?
Comment: it does not return anything.in other words my program gives error of 3221225477.and project1.exe has stopped working.where i am expecting a pointer to the specific element in the array,my program crashes.
Answer: You messed up the remainder computation and computation for X. Try this:
_tile getTileAt(int index){
    int X = index/Mh;
    int Y = index-(X*Mh);
    return *tile[X][Y];
}

You can be even simpler:
_tile getTileAt(int index) {
  return *tile[index/Mh][index%Mh]; //mod returns the remainder
}

Comment: i just used "_tile *a = &tile[index/Mh][index%Mh]" instead of using a function.


label ylab in timeSeries::plot, type = 'o'

Question: How do I label the y-axis, using timeSeries::plot, with Greek letters? i.e. change SB, SP, etc. to \alpha, \beta etc., I'm am aware I need expression(), in some way. However I can't even get to the labels (I normally use ggplot2). Code below.

# install.packages("xtable", dependencies = TRUE)
library("timeSeries")

## Load Swiss Pension Fund Benchmark Data -
   LPP <- LPP2005REC[1:12, 1:4]
   colnames(LPP) <- abbreviate(colnames(LPP), 2)
   finCenter(LPP) <- "GMT"

timeSeries::plot(LPP, type = "o")

It have been pointed out that the object structure, obtained with str(), is quite particular in LPP compared to say this object z
z <- ts(matrix(rnorm(300), 100, 3), start = c(1961, 1), frequency = 12)
plot(z)

If any one has an answer to both or any I would appreciate it. I realize I can convert the data and plot it with ggplot2, I have seen that here on SO, but I am interested in doing in directly on the timeSeries object LPP and the stats  (time-series object) z
Answer: [ REVISION & Edited ]
When plot.type is "multiple", we can't define ylab directly. Both plot(ts.obj) (S3 method) and plot(timeSeries.obj) (S4 method) take colnames(obj) as ylab, and I don't know any methods of using Greek letters as colname. (The difference in structure mainly comes from the difference of S3 and S4; colnames(timeSeries.obj) is equivalent to timeSeries.obj@units; the defaults is Series i and TS.i).
We can step in ylab using the arugument, panel (It wants a function and the default is lines). It is used in for(i in 1:ncol(data)). I couldn't give panel.function a suitable "i" (I guess it can in some way, but I didn't think up), so I got "i" using which col the data matches.
for timeSeries
ylabs <- expression(alpha, beta, gamma, delta)
row1 <- LPP[1,]

timeSeries.panel.f <- function(x, y, ...) {
  lines(x, y, ...)
  mtext(ylabs[which(row1 %in% y[1])], 2, line = 3)
}

plot(LPP, panel = timeSeries.panel.f, type = "o", ann = F)
title("Title")
mtext("Time", 1, line = 3)

 ## If you aren't so concerned about warnings, here is more general.
 ## (Many functions read `...` and they return warnings).
timeSeries.panel.f2 <- function(x, y, ..., ylabs = ylabs, row1 = row1) {
  lines(x, y, ...)
  mtext(ylabs[which(row1 %in% y[1])], 2, line = 3)
}

plot(LPP, panel = timeSeries.panel.f2, type = "o", ann = F,
     ylabs = expression(alpha, beta, gamma, delta), row1 = LPP[1,])
title("Title")
mtext("Time", 1, line = 3)

for ts
ylabs <- expression(alpha, beta, gamma)
row1 <- z[1,]

ts.panel.f <- function(y, ...) {
  lines(y, ...)
  mtext(ylabs[which(row1 %in% y[1])], 2, line = 3)
}

plot(z, panel = ts.panel.f, ann = F)
title("Title")
mtext("Time", 1, line = 3)

Of course you can archieve it using new functions made from the original (mostly the same as the original). I showed only the modified points.
modified plot(ts.obj) (made from plot.ts)
my.plot.ts <- function(~~~, my.ylab = NULL) {
   :
  nm <- my.ylab    # before: nm <- colnames(x)
   :
}

# use
my.plot.ts(z, my.ylab = expression(alpha, beta, gamma), type = "o")

modified plot(timeSeries.obj)
# made from `.plot.timeSeries`
my.plot.timeSeries <- function(~~~, my.ylab = NULL) {
   :
  my.plotTimeSeries(~~~, my.ylab = my.ylab)
}

# made from `timeSeries:::.plotTimeSeries`
my.plotTimeSeries <- function(~~~, my.ylab) {
   :
  nm <- my.ylab      # before: nm <- colnames(x)
   :
}

#use
my.plot.timeSeries(LPP, my.ylab = expression(alpha, beta, gamma, delta), type="o")


Views Taxonomy Term Argument With Multiple Terms

Question: Hello I am having a torrid time creating a views block. Let me try to explain without rambling on about nothing as I usually do.
I have a content type (links) which uses the same vocab as my other content type (posts) When viewing a Post I was hoping to display any links that have the same terms.
Ive set it up with an Argument Taxonomy: Term ID. It all works as hoped when I have just ONE term on a post but when I have more than one term things start to get a bit strange.
Actually I should mention that I am using Load default argument from node page and just doing it on term id. I am not using Allow multiple terms per argument box. this returns no results (for nodes with multiple terms)
If I change the Argument type: to term id's seprated by ....+ etc I do get a return but it only shows links for one of the terms. Funny enough the term results are for the term that I dont want to use. I have changed the term weights and everything to try and change it to show the links for the term I was hoping for but I dont seem to be able to influence what terms results appear in the views box I have made.. Its got me tearing my hair out.
Can anyone understand my gibberish and offer any solutions?
Comment: I'm going to try to reproduce this problem on my dev site. Any way you could take a screenshot of your settings and post a link to make this easier?
Answer: I think I have sort of worked out a solution. It displays correctly in the Views preview but not on the node itself. Maybe this will help though.
View settings:
Create a Block. Configure Block to display on content of type Post. Configure settings of View:
Fields

Content: Title

Filter criteria

Content: Published (Yes)
Content: Type (= Links)

Contextual filters

(field_tags) Content: Title

Using relationship: Term

Relationships

Content: Taxonomy terms on node (term)
Taxonomy term: Content using Tags

Using relationship: term

In my preview, when I enter the title of a Post as the contextual filter, I get a list of all the links tagged with the same tags as the Post. For some reason, when I view the actual Post it doesn't work but that might just be a caching issue or something on my end?


Android extended Spinner is not responding to tap events and missing arrow

Question: I want to use a centered spinner where the width of the spinner is only as wide as the selected item text. From my research it seems that this is not natively supported out of the box with an attribute so I found another StackOverflow question/answer and tried implementing that but ran into some issues with it.
So I took option 1 from this SO response and implemented it in Kotlin and It's not working for me
class DynamicWidthSpinner @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatSpinner(context, attrs, defStyleAttr) {

    override fun setAdapter(adapter: SpinnerAdapter?) {
        super.setAdapter(if (adapter != null) WrapperSpinnerAdapter(adapter) else null)
    }

    inner class WrapperSpinnerAdapter(val baseAdapter: SpinnerAdapter) : SpinnerAdapter {

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            return baseAdapter.getView(selectedItemPosition, convertView, parent)
        }

        override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
            return baseAdapter.getDropDownView(position, convertView, parent)
        }

        override fun getCount(): Int = baseAdapter.count
        override fun getItem(position: Int): Any = baseAdapter.getItem(position)
        override fun getItemId(position: Int): Long = baseAdapter.getItemId(position)
        override fun getItemViewType(position: Int): Int = baseAdapter.getItemViewType(position)
        override fun getViewTypeCount(): Int = baseAdapter.viewTypeCount
        override fun hasStableIds(): Boolean =  baseAdapter.hasStableIds()
        override fun isEmpty(): Boolean = baseAdapter.isEmpty

        override fun registerDataSetObserver(observer: DataSetObserver) {
            baseAdapter.registerDataSetObserver(observer)
        }

        override fun unregisterDataSetObserver(observer: DataSetObserver) {
            baseAdapter.unregisterDataSetObserver(observer)
        }
    }
}

and in my MainActivity I'm doing this from onCreate
        val spinner: DynamicWidthSpinner = findViewById(R.id.global_toolbar_location_spinner)

        val tempLocationList = ArrayList<String>()
        tempLocationList.add("Test1")
        tempLocationList.add("Much longer test string 2")

        spinner.adapter = ArrayAdapter(
            this,
            R.layout.global_toolbar_spinner_item,
            tempLocationList
        )

        spinner.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, arg3: Long) {
                // TODO: do stuff on selection here
            }

            override fun onNothingSelected(arg0: AdapterView<*>) {
                // TODO: do nothing... yet
            }
        }

        spinner.setSelection(0)

and I am using my custom Spinner in the layout xml (ommitting everything else that is not necessary because I am able to get it work just fine using the native <Spinner> or androidx compat Spinner
<com.blablabla.app.ui.DynamicWidthSpinner
        android:id="@+id/global_toolbar_location_spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:spinnerMode="dialog"
        />

What I see is just the first item "Test1" and nothing happens when I tap on it and arrow seems to have disappeared now as well
Answer: I figured out the issue. Turns out that this is one of those cases where the @JvmOverloads doesn't work. Once I converted it to the multiple constructor kotlin syntax it worked without a problem

class DynamicWidthSpinner : AppCompatSpinner {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    ...
}


how to caculate the step response of the second order system with nonzero initial condition, $y¨ + 2ξω_ny˙ +2y = 0, y(0) = 0, y˙(0) = c$

Question: How to caculate the step response of the second order system with nonzero initial condition,$$ \ddot{y}+ 2ξω_n\dot y +2y = 0, y(0) = 0, \dot y(0) = c$$ (where $c$ is a contant)
Question: how to calculate the transfer function of this equation? since the input function is $0$? so  no way to calculate the step response of this equation.
Answer: We have a linear differential equation with constant coefficients:
$$L[y]=y''(t) + 2 \xi  \omega _n y'(t)+2 y(t)$$
In order to solve $L[y]=0$ we try using $y(t)=\exp (\lambda \cdot t)$ and get the characteristic polynomial
$$p_{L}(\lambda)=\lambda ^2+2 \xi \omega_{n} \cdot \lambda  _n+2$$
Then the transfer function is
$$H(s)=\frac{1}{p_{L}(s)}=\frac{1}{s^2+2 \xi \omega_{n} \cdot s+2}$$
For the step response we use the Heaviside $\theta(t)$ unit step function and it's Laplace transform:
$$\mathcal{L}_t[\theta (t)](s)=\frac{1}{s}$$
The step response using inverse Laplace transform then is
$$\sigma(t)=\mathcal{L}_s^{-1}\left[H(s)\cdot\frac{1}{s}\right](t)=\mathcal{L}_s^{-1}\left[\frac{1}{s \left(s^2+2 \xi \omega _n  \cdot s +2\right)}\right](t)$$
The general solution is:
$$\sigma(t)=\frac{\xi  \omega _n e^{t \left(-\sqrt{\xi ^2 \omega _n^2-2}-\xi  \omega _n\right)}}{4 \sqrt{\xi ^2 \omega _n^2-2}}-\frac{\xi  \omega _n e^{t \left(\sqrt{\xi ^2 \omega _n^2-2}-\xi  \omega _n\right)}}{4 \sqrt{\xi ^2 \omega _n^2-2}}-\frac{1}{4} e^{t \left(-\sqrt{\xi ^2 \omega _n^2-2}-\xi  \omega _n\right)}-\frac{1}{4} e^{t \left(\sqrt{\xi ^2 \omega _n^2-2}-\xi  \omega _n\right)}+\frac{1}{2}$$
Example with $\xi=1$ and $\omega_{n}=\frac{1}{2}$:
$$\sigma(t)=-\frac{e^{-\frac{t}{2}} \sin \left(\frac{\sqrt{7} t}{2}\right)}{2 \sqrt{7}}-\frac{1}{2} e^{-\frac{t}{2}} \cos \left(\frac{\sqrt{7} t}{2}\right)+\frac{1}{2}$$
Visualize example:

See also Transfer function
Comment: could you please explain why we could get H(s) using  characteristic  polynomial, as we know that the H(s) is the ration of lapalce transform of output and  lapalce transform of input.
Comment: In fact a transfer function only makes sense with an input like this:

$$y''(t) + 2 \xi  \omega _n y'(t)+2 y(t)=x(t)$$

Then $Y(s)=H(s)\cdot X(s)$
Comment: could you pleae explain more from pL(λ)=λ2+2ξωn⋅λn+2 to get H(s), any priciplels? or any caculation?
Comment: Read this: [Transfer function](https://en.wikipedia.org/wiki/Transfer_function)


JavaScript next sibling?

Question: Could someone show me how to loop through the anchor tags within a div and find the next sibling?
I have this so far.
var menu = document.getElementById('menu');
var links = menu.getElementsByTagName('a');

How do I loop through the links? Can I use .nextSibling to find if the next sibling is a div?
Comment: You'd better use some JavaScrip library, jQuery for example
Comment: The anchor tag. if the tag after the a is a div i need an action to happen.
Comment: I can't in this situation, usually i would. This just show's my dependence on such libraries...
Comment: You will want to use nextElementSibling rather than nextSibling.  nextSibling also includes text nodes and comment nodes.  nextElementSibling ignores text and comments.
Answer: The nextSibling property of DOM nodes works perfectly in all browsers and does exactly what you'd expect. If there is no next sibling, it returns null.
Iterating over a NodeList (which is what getElementsByTagName returns) is identical to iterating over an array using a standard for loop. The following will iterate over the links and alert each time it finds one whose next sibling is a
:
var menu = document.getElementById('menu');
var links = menu.getElementsByTagName('a');

// Iterate over the links
for (var i = 0, len = links.length, link; i < len; ++i) {
    link = links[i];
    if (link.nextSibling && link.nextSibling.nodeName == "DIV") {
        alert("Next sibling is DIV! " + link.innerHTML);
    }
}

Note that in non-IE browsers, whitespace between elements in HTML is considered a text node. You may want to ignore these whitespace nodes when considering what the next sibling of each link is. The following will do that:
function isWhitespace(node) {
    return node.nodeType == 3 && /^\s*$/.test(node.data);
}

// Iterate over the links
for (var i = 0, len = links.length, link, next; i < len; ++i) {
    link = links[i];
    next = link.nextSibling;
    if (next && isWhitespace(next)) {
        next = next.nextSibling;
    }
    if (next && next.nodeName == "DIV") {
        alert("Next sibling is DIV! " + link.innerHTML);
    }
}

Comment: This solution is almost correct. However, it doesn't take the A tags Text node into consideration. Here is a JSFiddle demonstrating: http://www.jsfiddle.net/subhaze/ytCxS/
Comment: @subhaze: Well, I suppose you could say it was incorrect for that reason, but a text node is still a node as much as any other node, even if it does only contain whitespace. The real issue is that IE does not count whitespace text nodes as actual DOM nodes whereas all other browsers do. It's definitely worth pointing out, so I'll amend my answer.
Comment: @subhaze: Amended my answer. I think you'd only want to ignore whitespace text nodes, not any text node (as in your jsfiddle example).
Comment: @Tim Down: I believe what you wrote is correct, which is why I up voted it. But assumed, though I probably shouldn't have, was that they didn't want to take the Text node into consideration. My response was poorly written, I should have just stated "Do this if you wish to bypass the Text nodes" instead of insinuating that your answer was not correct. Sorry about that.
Comment: @subhaze: You made a good point. No need to apologize for anything.
Comment: There's also `nextElementSibling` which doesn't include text-nodes
http://docs.webplatform.org/wiki/dom/traversal/properties/nextElementSibling
Comment: @Vitim.us: Indeed, although it's not supported in IE <= 8 and you may still want to consider non-white space text nodes.
Answer: for(var i=0; i<links.length; i++) {
if (links[i].nextChild.nodeName=="DIV")
    alert("This is a DIV")
}

JavaScript next sibling?


Buzzing amp when input is plugged

Question: I have an orange micro dark that's unusable due to a strong buzz while playing clean, or comes in too early during the decay in a high gain setting.
Clue:
Notably, there's no buzz when the input is unplugged, and because of this im hoping it's not a fault of the tube nor the after market power brick. The tone is still great too - it's just the strong buzz that's the problem, either through speaker outs or headphone outs. Using any other amp does not present this problem at all.
Why does the buzz happen only while the input is plugged?
Any ideas on what might help? Should I replace the power filter cap or something?
Comment: Are you using a properly shielded cable? Guitar amps being high impedance input *can* be a little bit sensible for electromagnetic interference. You might want to try if the problem also occurs if you plug in a shortened plug (without cable). In this case it is most likely your amp that is the problem. If not, it might be the cable, but your amp might also be more sensitive than it should be. In that case I advice you to be very careful with the amp. There can be many sources for unwanted noises in an amp, and we will not be able to pinpoint the cause here on the internet,
Comment: especially without in fact knowing how those noises actually sound. Also handling high power amps can be a bit dangerous, and should only be done if you know what you're doing. Most likely the best bet is to get proper service for the amp. Depending on how old the amp is this might even fall under warranty. (Which is also a point: How old is the amp? Has is worked before?)
Comment: 1st thing I'd do is check or change the cable. It's a process of elimination.
Comment: After checking the cable for shield continuity,  also check the specs on input impedance of amp vs.  output impedance of whatever you have plugged into it.  If they are way out, consider an impedance-matching junction between cable and amp.
Comment: @CarlWitthoft nobody matches impedance in guitar/pedal/amp connections. You can plug a 2 kΩ source in a 500 kΩ amp input no problem, as long as the shielding is ok. In principle it would of course be much more reliable if all connections were balanced low-impedance XLR ones, but it's moot.
Comment: What kind of guitar are you using?  Does it have single-coil pickups (e.g. Stratocaster) or humbuckers (e.g. Les Paul)?
Answer: Absence of buzz when the cable is unplugged doesn't necessarily prove the amp isn't the culprit.  The input jack very likely is designed to short out when there's no plug.  I couldn't find a schematic of the Micro Dark, but here's the input section from a similar product, the Micro Terror.   A shorted input will disguise many issues!
But first try a different cable and a different guitar.
Comment: One way to check this is to plug in a short cable with the tip of the other end wrapped first in sellotape and then aluminium foil around the whole plug. In this case there's no short, but good shielding. (Alternatively, plugging it into the _input_ of any stomp box should give similar results.)

Buzzing amp when input is plugged


Como chamar o mês anterior no R?

Question: Preciso que o R me diga mês anterior ao que estamos, isto é, estamos em "2018-05" e preciso que ele me dê "2018-04". Até o momento a minha solução foi:
format(Sys.Date()-as.integer(format(Sys.Date(), "%d")),"%Y-%m")

Acredito que deva haver uma solução mais "limpa".
Answer: Com lubridate, pode fazer assim:
library(lubridate)
month(today() - months(1))

Answer: Você também pode utilizar o mondate:
library(mondate)

mondate(Sys.Date())-1
# mondate: timeunits="months"
# [1] 05/12/2018

E para formatar somente ano e mês:
format(mondate(Sys.Date())-1, "%Y-%m")
# [1] "2018-05"

Como chamar o mês anterior no R?


Delay / Distortion pedals for electric violin with bridge sensor (Schertler)?

Question: I am playing a violin with a bridge sensor (currently a Schertler STAT-V http://www.schertler.com/homepage_schertler/statv-en.html). I am looking for good ideas for :

Delay pedals
Distortion / Overdrive pedals

Much of the tests available on the web are done with electric guitars and although it can help to see basically how the pedal works, it can produce a very different effect on the violin.
I am looking for:

A pointer to some good tests for pedals and electric violin
List of delay pedals (resp. disto pedals) that could give interesting sounds with a violin input (maybe even designed for violin)

[EDITED to be more specific. Since I believe the topic itself is already quite specific because people are usually asking for guitar effects (very different in terms of attack, impedance, etc...), I think this is enough]
Comment: Consider making your question much more specific than "please give me some general advice on the subject". As it stands it risks being closed as "not a real question". See the FAQ.
Answer: As someone who uses various effects with my electric violin as well as with electric guitars, I can tell you that you don't need any special tests or reviews.

Delay pedals

You are right that without the pick attack, a delay sounds different for a violin than for a strummed guitar, but it does sound very similar to a bowed guitar, or when you use volume shaping, so don't worry about this factor. Concern yourself more with quality of sound, accuracy of echoes etc.
If you prefer analogue delay, use that. If you prefer digital, use that, but above all - test a few to see what you prefer.

Distortion

Very similar guidance here but the source of sound is less important. As you have less strings, you will have less notes clashing with each other, but you have a wider variety of notes as a guitar is mostly fret-based (excluding bends etc)
Play with some pedals - decide whether you like distortion, fuzz, harsh, buzzy, squealing etc etc etc
tl;dr - follow guitar pedal reviews for general quality guidance, then play with some to find out what you prefer, as effects are incredibly subjective
Comment: I'm in agreement with Dr. Mayhem, but want to add:

You won't get the U2/Pink Floyd sound with delay on a violin, because your instrument is all about the sustain, but with say a 300-400ms delay, you can approach the big rock, echo off the back of the the arena sound. And, with distortion, few people use as much as you think they do, so start with the pedal set low, then build to what you need, instead of starting with it dimed. Good luck.
Answer: Many years ago in the 1980s I favoured a cheap Phaser pedal and processing through an old analogue synth to filter the sound. At the time I was pleased with the unique quality I obtained by this novel combination. I recommend experimenting with unlikely combinations of processing but try to keep it subtle.


Obter dados de várias tabelas codeigniter (Array multidimensional)?

Question: Como obter dados de várias tabelas de uma só vez?
Preciso recuperar os dados do seguinte objeto (devedor).
Existem várias tabelas, onde a tabela principal é a tbl_devedor.
Depois disso, vem outras, que são relacionadas a tbl_devedor.
Exemplo:

tbl_devedor
tbl_email
id_contrato
id_telefone
id_endereco

Segue abaixo o array
$dados = array(
    'contratos' => [],
    'id' => '',
    'id_operador' => 0,
    'pessoa_fisica' => array(
          'id' => 0,
          'rg' => '',
          'dt_nascimento' => '',
          'profissao' => '',
          'salario' => '',
          'genero' => '',
        ),
    'pessoa_juridica' => array (
         'id' => 0,
         'nome_fantasia' => '',
         'inscricao_estadual' => ''
    ),
    'nome' => '',
    'cpf_cnpj' => '',
    'emails' => [],
    'enderecos' => [],
    'telefones' => [],
    'crud' => null
);

echo json_encode($dados);

Lembrando que contratos, pessoa_fisicao, pessoa_juridica, emails, enderecos, telefones, vem de tabelas diferentes, até o momento o que tenho é isso:
Controller
$devedor = $this->devedor->obter_por_id($id);

Model
public function obter_por_id($id)
{
    $this->db->from($this->tbl_devedor);
    $this->db->where('id',$id);
    $query = $this->db->get();
    return $query->row();
}

Eu sei fazer o join e obter os dados das outras tabelas, porem não sei como deve ficar a estrutura do array.
Comment: Ok!
Feito isso.
Comment: Wagner você precisa colocar na sua pergunta o diagrama de banco com essas tabelas.
Answer: Mesmo as informações sendo relacionadas, eu faria uma classe Model para cada tabela e depois uma classe Model para gerenciar as outras da seguinte forma:
Exemplo Minimo:
Observação: nesse exemplo simples foi colocado duas dessas tabelas as outras seguem o mesmo layout de programação e a ideia proposta.

class Devedor_model

<?php

    class Devedor_model extends CI_Model
    {

        public function obter_por_id($id)
        {
            $this->db->from('tbl_devedor');
            $this->db->where('id',$id);
            $query = $this->db->get();
            return $query->row_array();
        }

    }

class Devedoremail_model

<?php

    class Devedoremail_model extends CI_Model
    {

        public function obter_por_id_email($id)
        {
            $this->db->from('tbl_devedor_email');
            $this->db->where('devedor_id',$id);
            $query = $this->db->get();
            return $query->result_array();
        }

    }

essas duas classes Model seriam utilizadas agora em uma outra classe Model que iria gerenciar e manipular esses dados de uma vez só e vão gerar o array esperado:
<?php

    class Devedordados_model extends CI_Model
    {
        private $CI;

        public function __construct()
        {
            parent::__construct();
            $this->CI =& get_instance();
            // subindo as classe model coloque todas
            $this->CI->load->model("devedor_model");
            $this->CI->load->model("devedoremail_model");
        }

        public function obter_todos_dados_por_id($id)
        {
            $result = array();
            $result = $this->devedor_model->obter_por_id($id);
            $result['email'] = $this->devedoremail_model->obter_por_id_email($id);
            // insere aqui os outros models
            //$result['enderecos'] =
            //$result['telefones'] =
            return $result;
        }

    }

e finalmente no controller é chamado a classe que gerencia todos os Model, Devedordados_model:
public function de()
{
    $id = 1;
    $this->load->model('Devedordados_model');

    echo json_encode($this->Devedordados_model->obter_todos_dados_por_id($id),
                     JSON_PRETTY_PRINT);

}

o resultado obtido por esse método do Controller:
{
    "id": "1",
    "nome": "Devedor 1",
    "email": [
        {
            "id": "1",
            "email": "email@example.com",
            "devedor_id": "1"
        },
        {
            "id": "2",
            "email": "firstname.lastname@example.com",
            "devedor_id": "1"
        }
    ]
}

e essa seria uma proposta, mediante a sua duvida
Referencias:

Models
Auto-loading Models
Comment: Deu certo desta forma, obrigado..
Comment: só uma outra dúvida, nesta parte `public function obter_por_id_email($id)
        {
            $this->db->from('tbl_devedor_email');
            $this->db->where('devedor_id',$id);
            $query = $this->db->get();
            return $query->result_array();
        }` eu consigo alterar um campo individualmente, antes de retorna-lo ao objeto devedor ?
Comment: tentei assim e não funcionou:
`foreach ($query->result_array() as $row)`
Comment: Cara seja bem especifico que talvez não precise percorrer um array talvez um alias já resolva, mas, me diga na totalidade o que precisa fazer @WagnerFilho
Comment: Porque quando eu obtenho por id, `obter_por_id_email`
Eu pego todos os campos e exibo exatamente o que está no banco de dados.

Estes são os campos da tabela `tbl_devedor_email`, `'id', 'email', 'crud', 'devedor_id', 'id_origem_dados', 'observacao', 'preferencial', 'situacao'`

Se porventura, o campo `crud` tiver um resultado igual a `C`, o objeto recupera `crud: C`.
Eu quero alterar este campo para `crud: R`.
Comment: Olha não entendi a sua duvida está confuso CRud C Crud R não entendi mesmo .... @WagnerFilho só fala o que é pra ser feito, só uma coisa, essa é uma nova duvida se porventurar quiser abra uma nova!
Comment: A finalidade da pergunta era recuperar os dados em geral; quanto a isso OK, está funcionando..

Agora, ao recuperar os dados da tabela email, por exemplo, eu quero alterar o resultado de um dos campos, neste caso, o campo `crud`.
Comment: O campo `crud` que faz parte da `tbl_devedor`, você quer mostrar outro valor no resultdo, ou/e também mudar o valor que está gravado na base salvando o novo valor? @WagnerFilho
Comment: Somente mostrar outro valor no resultado.
Pois quando este valor for recuperado pelo json, o sistema irá entender, que o método a ser utilizado é o R.
Comment: Veja este imagem: https://ibb.co/fSHwU5
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/64758/discussion-between-virgilio-novic-and-wagner-filho).
Comment: Pode me ajudar novamente ?
Se o eu acrescentar um novo campo ao objeto `email`. este campo se chamará, `view` e está `view` deve recuperar dados de outra tabela.
Como posso fazer isso?
Seria algo assim: `view: {id: "1", nome: "admin":}`
Comment: Se poderia abrir outra pergunta @WagnerFilho anexando essa como resposta primária?
Comment: Questão aberta: https://pt.stackoverflow.com/questions/235596/obter-dados-array-multidimensional-codeigniter?noredirect=1#comment482290_235596


When does pg_replication_slot_advance(slot_name name, upto_lsn pg_lsn) function is used?

Question: 1Q Is it called by postgres internally or can it be called by an user.
2Q If it is called by user, then how does he find valid moveto_lsn point in wal records so that after advancing the logical slot...logical decoding continues without error.
3Q If it is called by postgresql internally in what specific use case it is called.
I have read postgres documentation but didn't find proper answers
Comment: I cannot think of a purpose for that function.
Comment: I *think* it's for things like patroni and other replication-management systems that want to be in charge of things.
Answer: 1.It can be called by super user of the database.
2.you have to provide proper lsn which is greater than current confirmed_flush lsn of slot.
3.Main purpose of creating this function is to advance the slot without sending the changes to client.Current use case is,it can be used in standby servers to advance the state of slot based on confirmed_flush lsn of same slot present in master server.This indirectly helps in resuming logical decoding from standby.


Ferramenta para medir desempenho de uma aplicação em html5 em uma plataforma android

Question: Estou interessado em criar uma aplicação em HTML5 para mobile, utilizando a plataforma android. Irei utilizar o Cordova para isso e gostaria de saber se vocês conhecem alguma ferramenta para medir o desempenho dessa aplicação.
Answer: Levando em conta que é html, o desempenho fica à cargo do navegador do celular. Sendo assim, você pode usar plugins como o YSLOW ou Google Page Speed .
Para simular smartphones existe uma extensão para chrome que pode ajudar também.
Ripple
Answer: Aqui nesse site você sabe o que os navegadores móveis suportam e pode ter uma base do que pode fazer: https://html5test.com/
Já verificar o desempenho vai ser meio difícil, porque cada dispositivo Android usa um WebView diferente para executar a aplicação em Cordova. Recomendo para testar seus apps o Phonegap Developr, claro, se vc estiver usando o Phonegap.


Consulta com campo como valor do IN

Question: Estou tentando fazer uma pesquisa usando INNER JOIN na tabela serviço, o campo agenda.serv_id é uma string "vetor" e o valor dele no banco é: '1, 2'
Fiz 3 insert's no serviço, o único problema é que o IN só funciona quando uso (1,2) mas nesse caso eu não posso definir dessa forma pois cada agendamento tem o id de certo serviço

Mesmo convertendo o campo em inteiro o resultado é o mesmo, como não achei nenhuma função de splt no mysql o caso continua sem solução. Caso for necessário fazer o processo em back-end eu estou utilizando a linguagem de programação VisualBasic. Segue o código:
SELECT
    agenda.agen_id,
    agenda.agen_data,
    agenda.agen_turno,
    group_concat(servico.serv_nome),
    agenda.agen_total,
    profissional.prof_comissao,
    agenda.agen_obs,
    profissional.prof_nome,
    cliente.cli_nome
FROM
    agenda
INNER JOIN servico ON servico.serv_id *in (agenda.serv_id)*
INNER JOIN profissional ON agenda.prof_id = profissional.prof_id
INNER JOIN cliente ON agenda.cli_id = cliente.cli_id

Comment: Wendel, conseguiu o resultado??
Answer: No banco de dados você tem algo tipo 1,2,3,4 e precisa pesquisar por apenas um valor, correto?
Realmente o ideal seria isso não acontecer, você poderia ter uma tabela de relacionamento para armazenar o id do serviço e o id da agenda, evitando esse tipo de campo vetor.
Mas como acredito que você não pretende alterar a estrutura, sugiro uma solução alternativa (gambiarra): passe a armazenar o vetor iniciando e finalizando por vírgula, ex ,1,2,3,4,; com isso, pode pesquisar por um número também iniciando e finalizando por vírgula:
SELECT
    agenda.agen_id,
    agenda.agen_data,
    agenda.agen_turno,
    group_concat(servico.serv_nome),
    agenda.agen_total,
    profissional.prof_comissao,
    agenda.agen_obs,
    profissional.prof_nome,
    cliente.cli_nome
FROM
    agenda
INNER JOIN servico ON 1 = 1 --a condição daqui será validada no where
INNER JOIN profissional ON agenda.prof_id = profissional.prof_id
INNER JOIN cliente ON agenda.cli_id = cliente.cli_id
WHERE LOCATE(CONCAT(',',servico.serv_id,','), agenda.serv_id) > 0

Utilizei o CONCAT para alterar o id do serviço apenas na pesquisa e o LOCATE no lugar do in para validar se o código (string) existe no vetor de ids (a função retorna > 0 se existir a substring na string original).
OBS: não indico você pesquisar diretamente o código (id) pois pode retornar dados errados (ex: a pesquisa por 1 retornaria verdade para o id 11)

Consulta com campo como valor do IN


Limit of the series $(2\log3-\log2-\log4) + (2\log5-\log4-\log6) + ...$?

Question: The series $\sum_{k=1}^{+\infty} 2 \log(2k+1) - \log(2k) - \log(2k+2) = (2\log3-\log2-\log4) + (2\log5-\log4-\log6) + ...$ converges to a value approximately equal to 0.242 (obtained computing the partial sum with 10000 terms).
I have been playing around but I can't find an explicit formula or link it with a known constant. Do you have any thoughts or ideas?
It is a series of positive terms that tends to zeros. Interestingly, we cannot split the terms in the following way:
$\sum_{k=1}^{+\infty} 2 \log(2k+1) - \log(2k) - \log(2k+2) = -\log2 + 2\log3 - 2\log4 + 2 \log5 - 2 \log6 + \ldots$
This last series does not converge since the terms are growing larger and larger.
Comment: Are you familiar with telescope series?
Comment: Yes, but the terms do not cancel if I'm correct. I am trying again, using your hint, thanks!
Comment: Yes, I am sorry. I deleted my answer since I realised for myself that I was mistaken. Even [WolframAlpha](https://www.wolframalpha.com/input/?i=sum_(n%3D1)%5E(infinity)+log((2n%2B1)%5E2%2F(4*n*(n%2B1)))) is not able to produce a closed-form solution...
Answer: The hint.
Use $$\frac{\pi}{2}=\prod_{n=1}^{+\infty}\frac{4n^2}{4n^2-1}.$$
I got the following answer:
$$\ln\frac{4}{\pi}.$$
Indeed, since $\ln$ is a continuous function, we obtain:
$$\sum_{k=1}^{+\infty}\left(2\ln(2k+1)-\ln2k-\ln(2k+2)\right)=\sum_{k=1}^{+\infty}\ln\frac{(2k+1)^2}{2k(2k+2)}=$$
$$=\ln\prod_{k=1}^{+\infty}\frac{(2k+1)^2}{2k(2k+2)}=\ln\frac{2}{\prod\limits_{k=1}^{+\infty}\frac{4k^2}{4k^2-1}}=\ln\frac{4}{\pi}.$$
Comment: $$\ln\frac4\pi=0.241~564...$$ That is close to $0.240~941...$ but not right.
Comment: @mrtaurho Can you explain why do you think so?
Comment: Thanks a lot! It works, I will write it down properly. Do you have a reference for this identity?
Comment: @Jonathan D See here: ://en.wikipedia.org/wiki/Infinite_product
Comment: Oh thanks, sorry it was easy to find online
Comment: @MichaelRozenberg Either I am confusing myself right now but according to [WolframAlpha](https://www.wolframalpha.com/input/?i=sum_(n%3D1)%5E(infinity)+%5B2*log(2n%2B1)-log(2n)-log(2n%2B2)%5D) I get about $0.240~941~034...$ for the series but for [$\ln\frac4\pi$](https://www.wolframalpha.com/input/?i=ln(4%2Fpi)) about $0.241~564~475...$ and I would claim these two are different.
Comment: @mrtaurho Which says that your WolpramAlpha is wrong. See please my solution.
Comment: I think WolframAlpha does a finite sum to compute the value. When computing the partial sum of the 10'000 terms, it returns 0.24153
Comment: @MichaelRozenberg I would be pleased to see a whole solution since honestly speaking I do not know how to apply the given product in this case and hence I am confusing myself right now with the decimal approximation I am not convinced by your value.
Comment: Let me write it down in an answer below!
Comment: @MichaelRozenberg I apologize for my doubts caused by an invalid numerical approximation. Manually setting the upper limit for the partial sum at 1'000'000 [gives the value $0.241~564~225...$](https://www.wolframalpha.com/input/?i=sum_(n%3D1)%5E(1000000)+%5B2*log(2n%2B1)-log(2n)-log(2n%2B2)%5D) which agrees nicely with your solution.
Comment: @mrtaurho I added something. You can see a full solution.
Comment: Since the terms are $\Theta(1/n^2)$ I'd expect the error from truncating the sum at $N$ to be $\Theta(1/N)$ - so for truncating after 10000 terms the error would be roughly on the order of 0.0001 (and that's ignoring accumulation of rounding errors but if the calculation is using double-precision numbers I'd expect that contribution to be significantly less).


Existence of solutions of $\Delta u = f$ such that $|u|_{L^\infty} < \infty$ if $|f|_{L^\infty} < \infty$.

Question: I am struggling with figuring out the details of proposition 7.1. in the paper Curvature and Uniformization - R. Mazzeo and M. Taylor.
Setting is as follows.

Let $\Omega$ be a noncompact Riemann surface with compatible Riemannian metric $g_0$, and let take a sequence $(\Omega_\nu)_\nu$ of compact, smoothly bounded subsets $\Omega_0 \subset \subset \Omega_1 \subset \subset \ldots$ exhausting $\Omega$ (i.e. for any compact $K \subset\Omega$ there exists $\nu$ such that $K \subset \Omega_\nu$).
Let $u_\nu \in C^\infty(\Omega_\nu)$ denote the solution to PDE
  $$\Delta u_\nu = e^{2u_\nu} + k(x) \ \ \ \ \ \ \ \ (\star),$$
  where $k(x)$ is a Gaussian curvature associated to the metric $g_0$.
  (We get the existence of $u_\nu$ by a results established in preceding sections. They satisfy $u_\nu|_{\partial\Omega_\nu} = +\infty$, and moreover these solutions are monotonically decreasing in a following sense: $\forall \nu \ u_\nu \ge u_{\nu+1}$ on $\Omega_\nu$)
Proposition 7.1: For every such $\Omega$ one of the following must happen:

$u_\nu \searrow u \in C^\infty(\Omega)$, where $u$ satisfies PDE $(\star)$, or
$u_\nu \searrow -\infty$ on $\Omega$.

Now I will try to go through the proof, and emphasize the parts which I don't understand.
By a results from preceding sections we know that the case 1. holds if there exists a function $v : \Omega \to \mathbb{R}$ which is locally bounded such that $\forall \nu$ we have $u_\nu \ge v$. So we'd like to assume that there is no such $v$ and show that it implies that 2. must hold. There is no such $v$ if we can find a sequence $(p_\nu)_\nu \subset \mathcal{O} \subset \subset \Omega_N$ for some open set $\mathcal{O}$ and $N \in \mathbb{N}$, such that $$u_\nu(p_\nu) \to -\infty \ \ \text{as} \ \ \nu \to \infty.$$
From now on let's assume that $\nu \ge N+1$, then we have a following uniform bound (w.r.t. indices $\nu$) on $u_\nu$'s by a monotonicity:
$$u_\nu \le A_N := \sup_{x \in \bar \Omega_N}{u_{N+1}(x)} < \infty \ \ \text{for} \ \ \nu \ge N+1.$$
And similarly we may define a uniform bound
$$|e^{2u_\nu}+k| \le A_{2n} := \sup_{x \in \bar \Omega_N}{|e^{2u_{N+1}(x)}+k(x)|} < \infty \ \ \text{for} \ \ \nu \ge N+1.$$
My question is: now the authors claim that hence we can find $v_\nu \in C^1(\bar \Omega_N)$ for $\nu \ge N + 1$, such that
$$\Delta v_\nu = e^{2u_\nu} + k \ \ \text{on} \ \Omega_N, \ |v_\nu|_{L^\infty(\Omega_N)} \le A_{3N}.$$
How do we know that? Reference to the result implying this will be enough.
Answer: In fact, we just solve the Dirichlet problem$$\nabla v = e^{2u_\mu} + k \text{ on }\Omega_\nu, \quad u = 0 \text{ on } \partial \Omega_\nu,$$then we know that on $\Omega_N$ which is a compact set of $\Omega_\nu$ we have all the estimate we need by standard elliptic theory. Then $v - u_\nu$ is harmonic and satisfies a Harnack inequality which ensures the dichotomy of the behavior. You can also have a look at this paper of Brezis and Merle on that type of result.


Implementing python code for grouping purchase based on genre

Question: I have the following table(df) having following attributes
 id      purchase date    genre(music, drama, horror..)
23      1/1/2020          music
23      1/2/2020          horror
24      5/2/2020           drama

I want to generate table having
id      count of purchases     no.of purchasesin music     no.ofpurchasesin horror  noofpurchasedrama
23             2                   1                                1                    0
24             1                    0                               0                     1

I have tried the following code:
a = df.groupby('id').agg({'purchasedate': lambda a: a.count()})
 But how to get new attributes of genre?

Answer: Does it really have to be columns for the count values? What if other genres are added in the future? That would change the column count of your result table, and depending on how you did it, maybe you'd even have to change your code.
Instead you could do the following, which gives you one row per occuring id and genre combination with the number of purchases of that setting added:
df.groupby(['id', "genre"]).size().reset_index(name="purchases")

   id   genre  purchases
0  23  horror          1
1  23   music          1
2  24   drama          1

And for the total values, use a second query
df.groupby('id').size().reset_index(name="total_purchases")

   id  total_purchases
0  23                2
1  24                1

It's a bit different in structure from what you asked for, but it scales well with a growing list of genres in your database.


Does POSTGRES have a "autocomplete" query?

Question: I have a question about Postgres. For example I want to query a column but I only fill in the first letters. Am I able to get all the results with these letters?
Comment: Automatically completing column names in a query, if that's what you're talking about, would be a feature of the client software you use to connect to PostgreSQL, not a feature of PostgreSQL itself.
Comment: Exactly what are you looking for? Autocompleting elements of your query, or performing a prefix-search on a column?
Answer: If you are using postgres enterprise manager tool, I think you can see the suggestions using ctrl+spacebar