Manipular uma List dentro de um foreach em uma view

Question: tenho uma duvida que deve ser simples resolver, mas não estou conseguindo desenvolver uma logica, ou até mesmo possa estar fazendo da forma errada.
Bem, tenho uma tabela na qual eu percorro uma tabela chamada de "categorias" dentro desta tabela eu tenho um relacionamento com outra denominada "destinos" como vocês podem notar abaixo no bean:
Destination.java
@Entity
@Table(name="destination")
@Multitenant
@TenantDiscriminatorColumn(name="tenant_id", discriminatorType=DiscriminatorType.INTEGER, contextProperty=PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
@NamedQuery(name="Destination.findAll", query="SELECT d FROM Destination d")
public class Destination implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_destination")
    private Long idDestination;

    @Column(name="tenant_id", insertable=false, updatable=false)
    private Long tenantId;

    @Column(name="appear_website")
    private Boolean dtAppearWebsite;

    @Lob
    @Column(name="description")
    private String dtDescription;

    @Column(name="highlight_website")
    private Boolean dtHighlightWebsite;

    @Column(name="name")
    private String dtName;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_streetview")
    private StreetView streetView;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_video")
    private Video video;

    @ManyToOne(cascade=CascadeType.REFRESH)
    @JoinColumn(name="fk_category")
    private Category categories;

    //Getters and Setters

Category.java
@Entity
@Table(name="category")
@Multitenant
@TenantDiscriminatorColumn(name="tenant_id", discriminatorType=DiscriminatorType.INTEGER, contextProperty=PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
@NamedQuery(name="Category.findAll", query="SELECT c FROM Category c")
public class Category implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_category")
    private Long idCategory;

    @Column(name="ct_active")
    private int ctActive;

    @Column(name="ct_name")
    private String ctName;

    @Column(name="tenant_id", insertable=false, updatable=false)
    private Long tenantId;

    @OneToMany(mappedBy="categories")
    private Set<Destination> destination;

    //Getters and Setters

Certo! Em minha view tenho um campo no qual exibi o numero de destinos vinculados a cada categoria:
<c:forEach items="${category}" var="c">

        ${c.ctName}

        ${categoryHasDestination}
        <c:choose>
            <c:when test="${c.ctActive=='1'}">
                Ativo
            </c:when>
            <c:otherwise>
                Desativo
            </c:otherwise>
        </c:choose>

</c:forEach>

Logo, criei um metodo no qual me retorna as categorias e também uma lista do numero de destinos vinculados em cada categoria.
@RequestMapping("category")
public String getMenuCategory(Model mv) {
    List<Category> category = dashboardFacade.getCategoryList();
    List<Integer> size = new ArrayList<Integer>();

    for (Category categories : category) {
        Set<Destination> destinationList = categories.getDestination();
        int s = destinationList.size();
        size.add(s);
    }

    /Retorna uma lista com o numero de destinos para cada categoria
    mv.addAttribute("categoryHasDestination", size);

    //Me retorna todas as categorias
    mv.addAttribute("category", category);
    return "category/categoryList";
}

O problema é que na minha view eu tenho um foreach, ou seja, para cada registro a lista é retornada e não o numero em si. A imagem abaixo ilustra o que estou querendo dizer:

Agradeço a todos a ajuda
Abraço!
Comment: Já tentou usar o atributo `var` do `forEach` para indexar a lista `categoryHasDestination`? Acredito que ficaria `${categoryHasDestination[i]}` sendo `i` o `var` do `foreach`. A forma como o utluiz citou é mais correta do ponto de vista OO.
Comment: Oi Wakin. Sim a alternativa se duvida é a correta, mas estou usando multi-tenant e acarreta alguns problemas se eu faço dessa forma. Poderia me esplicar melhor a sua alternativa? Muito obrigado
Comment: Olhando melhor a documentação do `forEach`, é a variável `varStatus` que fornece o índice do item na lista. Vou elaborar uma resposta para ver se resolve seu problema.
Answer: Crie um método getDestinationSize na sua classe Category que retorne o size do atributo destination.
Aí no seu JSP, basta acessar o método ${c.destinationSize}.
Comment: apenas uma ressalva da qual esqueci de comentar. Seu blog e fera! Estava dando uma olhada aqui e os artigos são show de bola. Pode ter certeza de que vou utilizar muito alguns dos artigos publicados.Parabéns!!!
Comment: utluiz, fiz desta forma, mas como estou usando multi tenant ele me da alguns erros que no momento é complicado de se resolver. Gostaria de alguma alternativa no meu controller para que possa passar como atributo para a view. Muito obrigado pela ajuda.
Comment: @JoãoManolo Não entendi qual o problema com *multi tenant*. O atributo está no model e o escopo dele é da requisição, não vai afetar outros usuários.
Comment: na verdade deu certo sim! O que ocorreu é que no meu mapeamento de destination estava como padrão LAZY. Acabei colocando como EAGER e funcionou tudo perfeitamente. A questão do multi tenant, e que sempre quando ocorre uma consulta no banco eu tenho que passar o tenant_id para saber com qual inquilino estou manipulando. Logo com lazy ele dava problema pois eu não passava o tenant corrente. Como serão poucos registros cadastrados creio que não vai onerar muito o desempenho do meu sistema. Muito obrigado pela sua ajuda abraço e sucesso!
Comment: @JoãoManolo Legal, não sabia dessa questão do *lazy*, mas é interessante saber. Abraço!
Comment: @JoãoManolo Se tiver sugestões pode escrever pra mim por lá :D
Answer: Usando o forEach da jstl existe o atributo varStatus que expõem um objeto do tipo javax.servlet.jsp.jstl.core.LoopTagStatus no escopo da iteração, que fornece alguns dados sobre o objeto que está sendo iterado.
Nesse caso estou usando o index para indexar sua lista de categoryHasDestination para ter o dado que precisa.
<c:forEach items="${category}" var="c" varStatus="status">

        ${c.ctName}

        ${categoryHasDestination[status.index]}
        <c:choose>
            <c:when test="${c.ctActive=='1'}">
                Ativo
            </c:when>
            <c:otherwise>
                Desativo
            </c:otherwise>
        </c:choose>

</c:forEach>

Para ver os outros atributos de uma olhada na documentação do LoopTagStatus
Comment: Oi Wakim. Obrigado pela sua contribuição. Na verdade por fim acabou dando certo a sugestão do nosso companheiro utluiz. Mas bem legal esse recurso de LoopTagStaus. Acabei lendo algumas informações e achei bem interessante essa abordagem. Um abraço!


How do I add a fade effect to this slideshow?

Question: I have a slideshow here that I would love to give a fade effect.
Not sure how to do it, I am not very familiar with JavaScript, all I know is how to copy and paste a code ( even then I make mistakes)
The page is here:
http://lazlo.us/bw/getimages.html
I am using a PHP script to pull images from the directory to create the slideshow.
The JavaScript that creates the slideshow is very straightforward ( I found it on the the net):
var curimg = 0;
function rotateimages()
{
    document.getElementById("slideshow").setAttribute("src", "" + galleryarray[curimg]);
    curimg = (curimg<galleryarray.length - 1)? curimg + 1 : 0;
}

window.onload = function()
{
    setInterval("rotateimages()", 3500);
}

Anyone could help me to put the fade effect into it?
Lazlo
Answer: Instead of updating the src of the image, you'll need to insert a second element, and then fade that in.
Here's a simple fiddle I threw together that uses CSS to handle transitions on opacity.
Basically, it will:

Create an image element
Insert before the existing image element
Wait 100ms, and then set opacity of the old image to 0

An image preloader would be helpful to properly kick off the animation as well. Good luck!
Comment: As for the recommendation by brenzy, you're facing a similar issue where the script tries to call an animation but the element isn't there. In addition, it'll only call it once. Here's an new fiddle with the jquery version (wrapped with jQuery's onload/ondomready shortcut handler): http://jsfiddle.net/1uav7dhm/ It's a different effect (because you're working with just one image - a fade out to white instead, rather than a transition/fade into the new image) - Also, I removed the CSS additions I made since jQuery uses JavaScript to animate the style property over time.
Comment: Thanks you Jack. I am going to give it a try.
Comment: You could also try the solution suggested at [http://stackoverflow.com/questions/7723727/add-fadein-and-fadeout-effect-to-image-lightbox-jquery/#7724796](http://stackoverflow.com/questions/7723727/add-fadein-and-fadeout-effect-to-image-lightbox-jquery/#7724796), which might be a bit simpler to implement
Comment: Thank you Jack and Brenzy for looking into this. Unfortunately none of the above solutions worked for me. Maybe it has got something to do with the fact that the images are pulled in from the directory via a PHP. script (getimages.php). Jack's solution would work if I specified the image names. I couldn't get Brenzy's solution to work at all,but that could be because of might have the wrong CSS syntax ( not sure).. Here are the links to the two different solutions you guys provided:  http://lazlo.us/bw/getimages3.html and  http://lazlo.us/bw/getimages4.html
Comment: Hi @Lazlo for getimages3.html, you will need to move the script to the bottom of your page (before the closing `` tag). Right now there's an error being thrown because the script tries to query the element before it's available. You can also wrap the script in a `window.onload` handler, as well. Like this: http://jsfiddle.net/u94kcys5/1/
Comment: Jack, this one works like a charm. Thank you so much for your help !


What is a roman numeral analysis of the chords from Coldplay's "God put a smile upon your face"?

Question: I'm trying to apply Roman numeral analysis to some pop songs and am a little stumped on Coldplay's "God put a smile upon your face".
The chords, as I understand them, are:
Section A:
D♭, E6, E♭7, Dmaj7
Section B: Amaj7, E6, F♯add9
Any help would be greatly appreciated!
Comment: This question does not conform to the title: You are not asking about _underlying harmonic analysis_  - you're simply asking for the chords to the song. That is not _underlying harmonic analysis_. Unfortunately, it is also off topic on this site. If you google for the chords to the song, more than likely you'll find them.
Answer: In some cases, Roman numerals aren't all that helpful, and this piece might be one of them.
In my opinion, Section A is best understood by considering two simultaneous actions:

The chromatic descent in the bass from E, through E♭ and D, to the tonic D♭.
And the constant presence of the tonic D♭ in all four of the chords. The D♭ is obviously the root of D♭, it's the 6 of E6 (spelled as C♯), the 7 of E♭7, and the maj7 (again spelled as C♯) of Dmaj7.

These two aspects make it very clear that D♭ is tonic, and that's ultimately what drives the harmonic motion: tension and resolution to that D♭.
The B Section is less clear, but there are two things to consider: B Sections often go somewhere else tonally, and here it seems to be rooted in A, which is enharmonic to ♭VI (B♭♭), a relatively common move dating back almost two centuries. Note also that the overall tonic D♭ is still present in every single chord, though now always spelled as C♯: it's the third of Amaj7, the sixth of E6, and the fifth of F♯add9.
In other words, Coldplay makes clear what the tonic is by playing it in every single chord of the song. If you try to sing a D♭ throughout the song, you'll see that it fits everywhere!
Answer: I tried listening to the song and the progression in the A section is pretty non-functional which means there are going to be some ambiguities when doing the analysis.
The B section sounds like I-V-VI-I in the key of A (I'm not sure about the tensions, but if you're right then Imaj7-V6-VIadd9).
If I'm hearing it right each chord in the A section is played on the guitar by moving the open C chord shape around but leaving the open stings open, so each chord has an E and G though I think you got the basic movement down. We could interpret this section to also be in the key of A as III#9#11-V#9-bVb9-IVadd11 with the G and/or E providing the tensions on each, but I think you could make an argument for analyzing this in Db/C# since during the verse the bass is alternating between B and C# throughout. Either way there are many non-diatonic tones throughout. I like the interpretation in A since the III chord could be thought of as a sort of substitute for the I.


How can the custom files copied by code to the private directory be accessible through URL for authenticated users?

Question: In my project, I am using headless Drupal with .Net on the front end.
I have to use private and encrypted file systems for the project requirements. The files which I am uploading through Drupal private file field from content type are accessible through URL, but as encrypted files aren't accessible through direct URL, I thought of copying the decrypted files from the encrypted folder to the private folder so they become accessible. Strangely, these files aren't accessible for authenticated users, who get access denied for this particular case.
I can't copy these files to the public folder as it is accessible to anonymous users too.
So here I am facing two problems:

Is there any way to restrict public files(sites/default/files/*) to authenticated users only so that anonymous users can't view them? I tried the rewrite rules in the .htaccess file, but it isn't restricting the URL to particular users, and it redirects users to a private URL.
Is there any way to access the copied files from the private folder via URL?

These files aren't uploaded through Drupal private file field, but they are copied from the encrypted folder to the private folder through custom code.
Answer: I would suggest using a Controller whose route parameter(s) can be used to specify the desired file. Then your controller (either directly or by delegating to another service) can access the file, decrypt it, then return the contents. The route that you define for your controller supports permissions, so you can easily apply access control.
Drupal console is a fantastic resource for generating Drupal assets, such as controllers. To generate a new controller with Drupal console: drupal generate:controller.


Abrir janela modal automaticamente ao abrir a página

Question: Estou tentando usar a função .load do jquery, substituindo a .click. Porque a intenção é que a lightbox abra ao carregar a página e não clicando.
JS PARA ABRIR A JANELA MODAL AO CLICAR NUM LINK
  $(document).ready(function(){
    $("a[rel=modal]").click( function(ev){
      ev.preventDefault();

      var id = $(this).attr("href");

      var alturaTela = $(document).height();
      var larguraTela = $(window).width();

      //colocando o fundo preto
      $('#mascara').css({'width':larguraTela,'height':alturaTela});
      $('#mascara').fadeIn(1000);
      $('#mascara').fadeTo("slow",0.8);

      var left = ($(window).width() /2) - ( $(id).width() / 2 );
      var top = ($(window).height() / 3) - ( $(id).height() / 3 );

      $(id).css({'top':top,'left':left});
      $(id).show();
    });

    $("#mascara").load( function(){
      $(this).hide();
      $(".janelao").hide();
    });

    $('.fechar').click(function(ev){
      ev.preventDefault();
      $("#mascara").hide();
      $(".window").hide();
    });
  });

JS PARA ABRIR A JANELA MODAL COM O CARREGAMENTO DA PÁGINA
Nessa parte alterei o $("a[rel=modal]").click por $(window).load e FUNCIONOU! Porém só abre o fundo preto e não a div #janelao
   $(document).ready(function(){
    $(window).load( function(ev){
      ev.preventDefault();

Daí em $("#mascara").click( function(){ tentei inserir o .load e $(window).load no lugar do .click e .show no lugar de .hide e NÃO funcionou
     $("#mascara").load( function(){
      $(this).show();
      $(".janelao").show();
    });

Então o meu problema é carregar a div janelao que não carrega, só carrega o fundo preto
Answer: Seu problema está na variável id
Ao trocar de $("a[rel=modal]").click( para $(window).load( você altera o valor do this e, por isso, ao realizar a operação var id = $(this).attr("href"); essa variável fica com valor alterado.
Altere essa atribuição para var id = $("a[rel=modal]").attr("href"); que irá funcionar.
Comment: Obrigada pela resposta Felipe. Por fim eu utilizei essa solução http://wbruno.com.br/jquery/abrir-modal-tuto-maujor-automaticamente-ao-carregar-pagina-jquery/
Comment: valeu amigo.. é isso mesmo.. esta dica me ajudou muito


What are the steps for rebasing an issue fork of core to the latest code plus 'patch'?

Question: It appears the current version of Drupal outside the issue fork needs to be added as a remote repository, but i'm getting tripped up on creating it as a branch i can rebase against.
Hoping the answer to this is a link to documentation, but https://www.drupal.org/docs/develop/git/using-git-to-contribute-to-drupal/rerolling-patches does not mention the issue fork workflow.
Answer: This seems to do it, where '3029545' is the issue number which is forked, these steps are presumed to have happened first:
git clone firstname.lastname@example.com:issue/drupal-3029545.git
cd drupal-3029545

And now rebasing on most recent Drupal core:
git checkout 3029545-add-route-exists # check out the branch in development
git remote add drupal firstname.lastname@example.com:project/drupal.git
git fetch drupal
git rebase drupal/9.2.x # current core branch


Integral formula for the local L factor of a base changed automorphic representation

Question: Let $\Bbb A$ the ring of rational adeles and let $\pi=\bigotimes_{p\leq\infty}\pi_p$ be an automorphic (cuspidal) representation of ${\rm GL}_2(\Bbb A)$. Fix a quadratic extension $K\supset\Bbb Q$. Then there exists an automorphic representation $\pi_K$ of ${\rm GL}_2(\Bbb A\otimes_{\Bbb Q}K)$ (known as the base-change of $\pi$ to $K$) which is characterized by the identity
$$
L(\pi_K,s)=L(\pi,s)L(\pi\otimes\eta_K,s)
$$
of $L$-functions, where $\eta_K$ is the character of $\Bbb A^\times$ attached to $K$, namely that corresponding to the Hecke character taking value $1$ at split primes and vale $-1$ at inert primes.
So if I understand things correctly when $p$ is a prime which is unramified both for $\pi$ and $K$ the local $L_p$ factor is explicitely given by
$$
L_p(\pi_K,s)=\begin{cases}
\left(\frac1{1-\mu_1(p)p^{-s}}\right)^2\left(\frac1{1-\mu_2(p)p^{-s}}\right)^2 & \text{if $p$ splits in $K$}\\
\frac1{1-\mu_1(p)^2p^{-2s}}\frac1{1-\mu_2(p)^2p^{-2s}} & \text{if $p$ is inert in $K$}
\end{cases}.
$$
where $\pi_p\simeq\pi(\mu_1,\mu_2)$ as a principal series.
Now, I came across the formula
$$
L_p(\eta_K,2s)^{-1}L_p(\pi_K,s)=\int_{\Bbb Z_p-\{0\}}
\frac{\mu_1(ap)-\mu_2(ap)}{\mu_1(p)-\mu_2(p)}|a|^{s-{\frac12}}d^\times a
$$
given very matter-of-factly but I am not sure how to derive it. Can anyone give a hint?
Comment: @user1952009: The Dedekind zeta of $K$ factors as $\zeta_K(s)=\zeta(s)L(\eta_K,s)$  but I see no direct link between the two situations.
Comment: has your integral at the end  any equivalent in the case of [Dedekind zeta functions](https://en.wikipedia.org/wiki/Dedekind_zeta_function) ? (the rest does)
Answer: This is too long to fit into the comment section - but really is one... Does the following agree with your calculations?
Doing the obvious, and evaluating (as you probably have done) the integral... Call the integral $I(s)$.
Assume that $\mu_1$ and $\mu_2$ are unramified at $p$.
$$
\begin{align}
I( s  ) &=   \int_{ \mathbb Z_p - \{0\} } \frac { \mu_1(ap)-\mu_2(ap) } {   \mu_1(p)-\mu_2(p) } |a|^{s-1/2} \, d^*a \\
  &=   \frac {1} {  \mu_1(p)-\mu_2(p) }  \left( \mu_1(p)J_{\mu_1}(s) - \mu_2(p) J_{\mu_2}(s) \right), \\
\end{align}
$$
where
$$
\begin{align}
 J_{\mu} (s) &= \int_{\mathbb Z_p - \{0\}} \mu(a)|a|^{s-1/2}\, d^*a \\
    &= \sum_{k=0}^\infty \int_{p^k\mathbb Z_p^*} \mu(a)|a|^{s-1/2}\, d^*a \\
       &= \sum_{k=0}^\infty \int_{\mathbb Z_p^*} \mu(p^ka)|p^ka|^{s-1/2}\, d^*a. \\
\end{align}
$$
The last equality holds because $d^*a$ is multiplicative Haar measure.
Now, if $a$ a unit,  $ |p^ka| = p^{-k} $, and  $\mu (p^ka) = \mu(p)^k$ for $\mu$ unramfied. Therefore, the integrand(s) does not (do not) depend  on $a$.
So, since $d^*a$  gives the units volume $1$, one has
$$
\begin{align}
 J_\mu(s) &= \sum_{k=0 }^\infty \left( \frac{\mu(p) } { p^{s-1/2}} \right)^k \cdot \int_{\mathbb Z_p^*} \,d^*a\\
    &= \sum_{k=0 }^\infty \left( \frac{\mu(p) } { p^{s-1/2}} \right)^k\\
    &= \frac{1 } {  1 - \frac{\mu(p) }{ p^{s-1/2} } }.\\
\end{align}
$$
Therefore
$$\begin{align}
I(s) &=   \frac {1} { \mu_1(p)-\mu_2(p)}   \left( \frac{\mu_1(p) }{ 1 - \frac{\mu_1(p)}{  p^{s-1/2} } } - \frac{\mu_2(p) }{1 - \frac{\mu_2(p) }{ p^{s-1/2} } }  \right) \\
  &=   \frac{1 }{  1 - \frac{\mu_1(p) }{ p^{s-1/2} } } \cdot \frac{1}{1 - \frac{\mu_2(p)} { p^{s-1/2} } }.
\end{align}
$$
The claim is that
$$ L_p(\pi_K, s) = I(s) L_p(\eta_K,2s). $$
Now, suppose $p$ is inert.
Then, one should have
$$ \frac{1}{ 1-\frac{\mu_1(p)^2}{p^{2s} } } \cdot \frac{1}{ 1-\frac{\mu_2(p)^2}{p^{2s} } }\overset{?}{=}
\frac{1 }{  1 - \frac{\mu_1(p) }{ p^{s-1/2} } } \cdot \frac{1}{1 - \frac{\mu_2(p)} { p^{s-1/2} } }
\cdot \frac 1 {1+ \frac{1}{p^{2s}}}.
$$
I don't see how this can be - if I haven't made a mistake. Anybody care to comment?
Where did the claim appear?


Exposing Spring services as SOAP webservice

Question: I have a quite extensive Spring 3.0 service architecture (the typical architecture; a bunch of model objects and a bunch of services that do stuff with these objects). I would like expose some of these services as SOAP web services.
We have developed SOAP web services before, but these have always been relatively simple and dedicated, and we have always used Axis 2. I found Axis 2 a bit heavy on the dependency and implementation side, and I'm a bit worried that this will bloat my current project something awful.
I have looked around and apparently using Apache CXF this would seem quite easy. So I'm looking for some advice on this. Does anyone have any practical experience with this? Pros and cons?
Comment: Preferably code first, since this code already exists (I already have the Spring services, I just want to expose some of them).
Comment: What sort of web service development style do you want? "code-first", or "schema-first"?
Answer: We are using spring with CXF for soap services and it goes very smooth. Following the CXF tutorial makes it straightforward to use by simply using the jaxws xml namespace.
Comment: I have found a good example on this: http://united-coders.com/phillip-steffensen/developing-a-simple-soap-webservice-using-spring-301-and-apache-cxf-226
Answer: I haven't really tested any other webservice frameworks - always been going with CXF and am quite happy with that.
If you're using Netbeans (even if not, it's still useful I'd say), check out this tutorial: http://sites.google.com/site/apachecxfnetbeans/loanproc
Just skip the first few paragraphs (Database integration, testing etc. etc. .. all of which you should already have knowledge about).
The CXF integration in Netbeans is useful for writing fast clients using the built-in netbeans functionalities.
cheers


What do these numbers mean in the tennis WTA calendar?

Question: Take a look at the rectangle in this picture.

I understand that M stands for the whole amount of participants (it is like "S" for Singles).
Q stands for qualifiers.
D for doubles tournaments.
X stands for mixed tournaments.
What do "32,16,16" (in the Shenzhen tournament) mean?
I have been told that for example in the Shenzhen tournament the qualification board can have 16 female players and only 4 may qualify. It means that each player must win two matches to enter in the competition. But, how do you know that only 4 can qualify? It is not written in the 2018 WTA calendar.
Moreover, how come in the Australian Open the 2018 prize money is not showed?
Comment: This older question seems to be related: [Meaning of shortcuts like "128S/96Q/64D/32X" for tennis tournaments](https://sports.stackexchange.com/q/4383)
Comment: It is possible that prize money for [Grand Slams](https://en.wikipedia.org/wiki/Grand_Slam_(tennis)) are omitted since they are sanctioned by [ITF](https://en.wikipedia.org/wiki/International_Tennis_Federation) and not [WTA](https://en.wikipedia.org/wiki/Women%27s_Tennis_Association).
Comment: I took a look at the related question but it is not enough.
I will edit the question, though.
Answer:
What do "32,16,16" (in the Shenzhen tournament) mean?
I have been told that for example in the Shenzhen tournament the qualification board can have 16 female players and only 4 may qualify. It means that each player must win two matches to enter in the competition. But, how do you know that only 4 can qualify? It is not written in the 2018 WTA calendar.

The first part of this question is explained in this question and answer.  In the 2018 Shenzhen Open, there were 32 women that competed in the main draw of the singles tournament.  Those 32 women were chosen in a number of ways: Some slots in the main draw are reserved for the tournament by their WTA ranking.  Some slots are for Wild Cards; the tournament organizers can put anyone they want in those slots.  And the remaining slots are for the winners of the qualifying tournament.  In this tournament, there were 16 women competing in the qualifying tournament for 4 slots.  You can see this in the 2018 Shenzhen Open Qualifying Draw bracket.  After two rounds, there are four players left that then qualify for the 2018 Shenzhen Open Main Draw bracket (Those who qualified by winning in the qualifying draw are denoted with a "Q.")

But, how do you know that only 4 can qualify? It is not written in the 2018 WTA calendar.

That information is not available in the "32S/16Q" shorthand notation.  It varies with each tournament.  For example, the 2018 Sydney International tournament (30S/32Q) had 32 competing in the qualifying tournament, but only for 4 slots, so the competitors had to win three matches in the qualifying tournament in order to get into the main draw.  However, in the 2018  Hobart International (32S/24Q), there were 6 slots reserved for qualifiers, so the 24 competitors in the qualifying tournament only needed two wins in order to make it to the main draw.
Comment: This answers the first part well (though it looks like we could've closed-as-duplicate?).  Confusing to me was the number 30; turns out in Australia, apparently, they like to give the 1/2 seeds byes in the first round.  Not sure why!
Answer: (Partial answer)
From WTA 2018 calender:

TFC: Total Financial Commitment is the Tournament's Investment in the event, including Tour Fees, Bonus Pool contributions and on-site prize money
: Unlisted amounts are TBD for each event based on the Prize Money Formula Rule (Premier 5 Minimum - $2,666,000; Premier 700 Minimum - $776,000)

That means prize money is not decided yet for Australian Open, which will be done through Prize Money Formula Rule (see: WTA 2018 rulebook page 167 for more information).


AWS MSK Default enable.auto.commit setting

Question: Does AWS' Managed Streaming for Apach Kafka (MSK) have enable.auto.commit set to true by default? I't not showing up in the docs, and I want to make sure that my consumers are properly committing offsets.
Or does MSK follow the Kafka process cited here where if a consumer sets a ConsumerGroup ID, then MSK automatically sets enable.auto.commit = true by default?
Comment: MSK is a hosted server. It doesn't modify client settings
Comment: @OneCricketeer Ah, this is a consumer setting. Thanks for pointing me in the right direction.
Answer: enable.auto.commit is a consumer setting, not a cluster setting. The consumer is responsible for directing Kafka to commit its offest to the __consumer_offsets topic.
Answer: The group.id and enable.auto.commit would be set in the same location, in the consumer client, and are not controlled by the server-side, so there is no such "default" in MSK or any other Kafka environment that is controlled outside your code.


JMS and JTA Transactions in Java EE

Question: I think I am not getting something right with JMS and JTA. I am running in a Java EE container with all CMTs. Here is what I am doing:

In an SLSB, write something to the database
From the same method of the SLSB, post a message to a JMS queue
An MDB in the same container listens to the JMS queue and picks up the message
The MDB reads the database

The problem is, the MDB does not see the changes made to the database in step 1.
I verified that steps 1 and 2 happen inside a single XA transaction, as expected. My expectation is that a second XA transaction would start at step 3, after the first XA has been committed. But it seems that the MDB receives the message before the XA transaction that posted the message has been committed.
Is my expectation wrong and what I am seeing is normal?
I am running under JBoss 6. The SLSB is local. Both the SLSB and the MDB are in the same application.
Comment: I would generally expect that the MDB would not fire until the transaction in steps (1+2) commits, as until that point the message should be 'locked' in the transaction and not generally visible until commit (there are sometimes provider-specific caveats here though). It's hard to say for sure with the information given, but if step 2 isn't being done within a transaction it would explain what you see - although I know that you say you have verified steps 1+2 are atomic, is there any chance this is not correct?
Comment: @Antonio That would make it overly complicated and closely tied with the DB vendor. I already use loads of JMS and it makes more sense in this project to leverage JMS more.
Comment: @strmqm That's my thought too. I will test more carefully to make sure that steps 1+2 are indeed being done inside an XA transaction.
Comment: Could you specify why you are doing this? Does your db support firing events when it changes a table, you could make it fire off a http request to your application, stating the table name, action (insert,update etc) and id, then your app listens to it, and does its thing.
Answer: I found the problem! My JMS connection factory was not XA aware. I had looked up /XAConnectionFactory for my JMS connection factory. In spite of the name, that's the wrong resource to lookup for a regular app in JBoss. There is a java:/XAConnectionFactory too, which does not work either. The correct resource name is java:/JmsXA. I used it and everything is working just as expected.
Thanks to @strmqm for nudging me to the right direction.
Comment: A pleasure, i've been through a very similar experience in the past!
Answer: I saw a conceptually similar problem in an app built w/ WebLogic 7.  The DB commit from tx1 wasn't complete by the time that tx2 (initiated by a JMS send in tx1) tried to read it.
The trouble there was that our configuration involved a WLS 7 XA emulation layer with a non-XA db connection (to Oracle DB).  This risk was part of that XA shortcut.  Apparently if we'd gone w/ the true XA all the way to the DB, that hole would have closed.  Never ended up testing that.
You say this is JBoss.  Any chance that they've got some similar shim that bypasses the XA and gives this same surprising result?

JMS and JTA Transactions in Java EE


Are my answers valid?(simple proof, convergence, sequences)

Question: I am doing questions from a textbook that doesn't provide me with answers so I would be very grateful if someone could let me know if I am on the right lines with these answers:
1) Let $ k,l $ be two non negative integers. Show $ min(2k,2l)\leq k+l$
I showed this with two cases.
Case 1: Suppose $k=l$ then trivially $k+l=2k=2l$ so $min(2k,2l)=k+l$
Case 2: Suppose $k\geq l$ without loss of generality, then $2k>2l$ so $min(2k,2l)=2l$ and $2l=l+l \leq l+k$. Hence $min(2k,2l) \leq k+l $
2) Let n bet natural numbers. Suppose $(a_n)$ is a convergent sequence with limit L. Suppose also that, for some N (Natural number) and real K, $a_n$>K whenever $n >N$. Show $L \geq K$.
I did this by contradiction.
Suppose $K>L$ then for n>N $|a_n-K| < |a_n-L|< \epsilon$ for $\epsilon >0$ (definition of convergence).
this implies that K is the limit of the sequence i.e K=L which is a contradiction so $K \leq L$
3) Suppose $(a_n)$ is a bounded sequence and that $(a_n)$ does not converge to 0. Show that there is a subsequence $(a_k)$ converging to a non-zero limit.
I said: $|(a_n)|<M$ because it is bounded.Let $\epsilon = M/2$ so there exists an N such that for n>N  $|a_n-0|$>M/2. If there is a $|a_n|>M/2$ then there is a subsequence $|a_k-0|>M/2$ for all k. so $(a_k)$ does not converge to 0. But Bolzano Weierstrass says every bounded sequence has a convergent subsequence so we can conclude that there is a non-zero limit to the subsequence.
Any pointers appreciated.
Answer: $(1)$ What you do is fine, but your second case can be modified slightly to include the first case.
$(2)$ You have the right idea, but more should be done.  What I mean is just because $a_n>K$ for $n\geq N$ doesn't mean $|a_n-L|<\varepsilon$ for $n\geq N$.
$(3)$ You didn't use the fact that $\{a_n\}$ doesn't converge to $0$ properly.  To do this, you should write "there is some $\varepsilon>0$ and a subsequence $\{a_{n_k}\}$ such that $|a_{n_k}-0|\geq\varepsilon$ for all $k$.  Other than that, it seems like you have the right idea.


Force div to accomidate image (min-height not working)?

Question: I've got a bunch of divs, one after the next, each with an image inside it. When I set min-height to a value higher than the height of the image, everything works fine:

But if I have it set to 50px while the image is 100+px, the images kind of "cascade"

What can I do to force the div to be at least as tall as the image inside it?
CSS
body {
    background: #cccccc;
    margin: 0px;
}
a {
    text-decoration: none;
    color: #333333;
}
a:hover {
    text-decoration: underline;
}
.reply {
    min-height: 50px;
    padding: 10px;
    background-color: #eeeeee;
    font-size: 14px;
    margin: 10px;
}
.post {
    padding-top: 10px;
    /*background-color: #ff0000;*/
}
.postimage {
    float: left;
    padding-right: 10px;
}
.postcomment {

}

HTML
<!DOCTYPE html>

        <link rel="stylesheet" href="main.css" />

            One

            Two

            Three

            Four

Answer: Add clear: left to your div.
See this?
.postimage {
    float: left;
    padding-right: 10px;
}

When you float the contents of the div, the div does not stretch vertically to accommodate.
So, adding this:
.reply {
    min-height: 50px;
    padding: 10px;
    background-color: #eeeeee;
    font-size: 14px;
    margin: 10px;
    clear: left;
}

Will resolve the issue.
Alternate solution
Another solution which I tend to prefer is to use the overflow hack, rather than clear:
.reply {
    min-height: 50px;
    padding: 10px;
    background-color: #eeeeee;
    font-size: 14px;
    margin: 10px;
    width: 100%;
    overflow: hidden;
}

You would expect that this would hide the part of the image below the div, but it has a different result: The overflow: hidden does not hide the contents, but rather causes the div to stretch down to contain the entire image.
Note: for this method to work on older browsers, you must specify a width (notice that I added that in the css above).
Comment: @See my "alternate solution", which solves your issue (my answer has been edited)
Comment: The `overflow` method does work. Any idea why the `clear` method doesn't?
Comment: Absolutely.  Clear is causing the div to clear any *previously floated elements*.  It does not cause the div to clear it's contents, but rather to clear any floats *before* it.  The overflow method causes the div to clear it's contents.


delete folder from s3 nodejs

Question: Hey guys I was trying to delete a folder from s3 with stuff in it but deleteObjects wasn't working so I found this script online and it works great my question is why does it work? Why do you have to listObjects when deleting a folder on s3 why cant I just pass it the objects name? Why doesn't It error when I attempt to delete the folder without listing the objects first.
first attempt (doesnt work)
  var filePath2 = "templates/" + key + "/test/";
    var toPush = { Key: filePath2 };
    deleteParams.Delete.Objects.push(toPush);
    console.log("deleteParams", deleteParams);
    console.log("deleteParams.Delete", deleteParams.Delete);

    const deleteResult = await s3.deleteObjects(deleteParams).promise();
    console.log("deleteResult", deleteResult);

keep in mind folderPath2 is a folder that has other stuff in it I get no error but yet the catch isn't triggered and it says deleted and than the folder name.
second attempt (works)
async function deleteFromS3(bucket, path) {
  const listParams = {
    Bucket: bucket,
    Prefix: path
  };

  const listedObjects = await s3.listObjectsV2(listParams).promise();
  console.log("listedObjects", listedObjects);
  if (listedObjects.Contents.length === 0) return;

  const deleteParams = {
    Bucket: bucket,
    Delete: { Objects: [] }
  };

  listedObjects.Contents.forEach(({ Key }) => {
    deleteParams.Delete.Objects.push({ Key });
  });
  console.log("deleteParams", deleteParams);

  const deleteResult = await s3.deleteObjects(deleteParams).promise();
  console.log("deleteResult", deleteResult);
  if (listedObjects.IsTruncated && deleteResult)
    await deleteFromS3(bucket, path);
}

than I call the function like so
const result = await deleteFromS3(myBucketName, folderPath);

Comment: Possible duplicate of [How can I delete folder on s3 with node.js?](https://stackoverflow.com/questions/20207063/how-can-i-delete-folder-on-s3-with-node-js)
Answer: Folders do not exist in Amazon S3. It is a flat object storage system, where the filename (Key) for each object contains the full path.
While Amazon S3 does support the concept of a Common Prefix, which can make things appear as though they are in folders/directories, folders do not actually exist.
For example, you could run a command like this:
aws s3 cp foo.txt s3://my-bucket/folder1/folder2/foo.txt

This would work even if the folders do not exist! It is merely storing an object with a Key of folder1/folder2/foo.txt.
If you were then to delete that object, the 'folder' would disappear because no object has it as a path. That is because the folder never actually existed.
Sometimes people want an empty folder to appear, so they create a zero-length object with the same name as the folder, eg folder1/folder2/.
So, your first program did not work because it deleted the 'folder', which has nothing to do with deleting the content of the folder (since there is no concept of 'content' of a folder).

delete folder from s3 nodejs


BeautifulSoup .previous_sibiling returns None

Question: Here's the sample HTML

Vegetable Basket

This vegetable basket is the perfect gift for your health conscious (or overweight) friends!
Now with super-colorful bell peppers!

$15.00

And I'm trying to parse the price of an object represented by its image url.
html = getHTML("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html, "html.parser")
print(bsObj.find("img", {"src":"../img/gifts/img1.jpg"}).parent.previous_sibiling)

bsObj.find("img", {"src":"../img/gifts/img1.jpg"}).parent returns:

But bsObj.find("img", {"src":"../img/gifts/img1.jpg"}).parent.previous_sibiling always returns None.
Shouldn't that be returning  tag for the price?
Answer: First of all, you have a typo - previous_sibiling vs previous_sibling:
>>> from bs4 import BeautifulSoup
>>>
>>> data = """

... Vegetable Basket
...
... This vegetable basket is the perfect gift for your health conscious (or overweight) friends!
... Now with super-colorful bell peppers!
...
... $15.00
...
...
...
"""
>>>
>>> soup = BeautifulSoup(data, "html.parser")
>>>
>>> image_url = "../img/gifts/img1.jpg"
>>>
>>> image = soup.find("img", src=image_url)
>>> price = image.parent.previous_sibling.get_text(strip=True)
>>> print(price)
$15.00

Another option would be to use find_previous() to find a text node that starts with $:
>>> price = image.find_previous(text=lambda text: text and text.strip().startswith("$")).strip()
>>> print(price)
$15.00

Comment: ohh it's the typo. it did return None. so I never thought about the typos. ty


Translation issues-How can we set admin in default English language in multilingual site

Question:
Possible Duplicate:
Do not translate the admin area / How can I set the language of the admin area to English?

I have a problem with a multilingual website.I used English and Arabic as two languages .Done all the laguage settings.But when i tried to translate a basic page content to arabic ,the whole admin turned to arabic and showed rtl mode.I need to fix it asap.Please guide me.
NB: i have all the modules related to multilingual site at local and transferred the whole files and same database to server.At local it was working fine.But at live it won't!.please
Answer: Try setting your language detection to be "user preference" first.  That way your account setting will override any other detection.


User logout when browser closes

Question: Is there a way to automatically log out users when they close a browser?
I've tried to set (settings.php)
<code>
ini_set('session.gc_maxlifetime', 0);
ini_set('session.cookie_lifetime', 0);
</code>
but this doesn't work. Seems to me like it has anything to do with the 'sid' stored in the 'sessions' table?
Comment: see my comment below, ini_set('session.cookie_lifetime', 0); should work. Where core sets a session cookie it uses `session_get_cookie_params` to read the parameters which should change by that ini_set.
Comment: This method work correctly if you compeletly close browser, if you just clost the drupal tab in firefox user seesion_cookie still alived but if you close firefox compeletly it works. do you find solution for this?
Comment: this [article](http://naveensnayak.wordpress.com/2010/12/02/drupal-end-session-on-closing-the-browser/) has info on D6, not sure if it will work in D7
Comment: This doesn't work in D7 because the session id is stored in 'sessions' table
Comment: The session id is also stored in the sessions table in D6. There's absolutely no reason why the suggested `ini_set('session.cookie_lifetime',  0);` wouldn't work in D7.
Comment: There's one reason why this wouldn't work. In a browser with tabs, the session only clears when the whole browser is closed, not the tab alone. Other than that, it should work as expected.
Comment: The solution @mototribe proposed works for me in IE, Firefox, Chrome. Did have to flush the cache to clear old settings. Here's another [more recent article](http://geroldm.com/2011/11/drupal-logout-user-when-browser-is-closed/) recommending the same solution.
Answer: There is the session_expire module, and this module's page has some information about garbage collector confs and stuff.

User logout when browser closes


hook_form_node_type_form_alter does not work

Question: The sort comments module has a  function in sort_comments.module as below:
  /* firstname.lastname@example.com - blackice78 */
  define('SORT_COMMENTS_OLDER_FIRST', 1); // default
  define('SORT_COMMENTS_NEWER_FIRST', 2);
   /* Alter node type form: allow user to decide comments sorting */
 function sort_comments_form_node_type_form_alter(&$form, $form_state) {
  $form['comment']['comment_default_sorting'] = array(
 '#title' => t('Sort'),
 '#type' => 'select',
 '#options' => array(1 => t('Older first'),
                     2 => t('Newer first')),
 '#default_value' => variable_get('comment_default_sorting_' . $form['#node_type']-  >type, SORT_COMMENTS_OLDER_FIRST),
  );
 }

so that if you go to structure>content types, and for example for Article choose edit, then in comment setting, it will give you a drop down menu, so that you can select the order for showing comments, older first or newer first.
I am trying to do something similar, so in order to see how does it work, I have this in my annotations.module file:
define('Annotations_OLDER_FIRST', 1); // default
define('Annotations_NEWER_FIRST', 2);
/* Alter node type form: allow user to decide comments sorting */
function Annotations_form_node_type_form_alter(&$form, $form_state) {
  $form['comment']['annotations'] = array(
    '#title' => t('Sort'),
     '#type' => 'select',
    '#options' => array(1 => t('Older first'),
                     2 => t('Paragraph number')),

  #default_value' => variable_get('annotations_' . $form['#node_type']-  >type, Annotatiios_OLDER_FIRST),
  );
  }

But I can not see the drop down menu, at the same place that I see the drop down menu for sort comments module. Does anybody know what is the reason?
Answer: You have a syntax error on the last line, it should start with an apostrophe, and your constant is mispelled.  So it probably isn't compiling properly.  If drupal was picking up the hook you would probably get a white screen of death.
So this means:
You need to make sure the beginning of the function name is exactly the same as your module name - did you use a capital A when naming the module?  PHP is case sensitive.
Lastly, make sure you clear the cache so that Drupal picks up the new hook.  Install drush if you haven't already, go to the /install_directory/sites/mysite directory and run
drush cc all

(assuming you're on linux with command line access)
Comment: Thank you for your answer. I fixed the mistakes that you mentioned, but still it did not work. I have to mention in my Annotations.module file, I also have some other functions like : Annotations_form_comment_form_alter, Annotations_form_comment_form_validate, Annotations_form_comment_form_submit. I created a new module with function comment_sort_form_node_type_form_alter, and it worked. I am really interested to know why it does not work when I have this function in my Annotations.module file. Thanks again for your answer.
Comment: This is just a hunch, but try making your module name all lower case. i.e. `annotations` rather than `Annotations` and make sure all of your functions are changed the same way, then flush cache and try again.


How to remove bullets from drupal menu?

Question: I have created a drupal menu and added a couple of links. Unfortunately, when displayed, these come with bullets. How can I remove these? I am using the Precise theme, but it does not seem to be added by this theme.
Answer: This could be default browser styles. It does't matter if they are added by the browser by default or by CSS, the solution is to remove them with CSS.
li {
  list-style: none;
}

You should create a sub_theme where you create and add your custom styles.
Comment: @JVerstry The most specific styling rule wins, most likely the reset has a more specific rule than I posted as example above, you could do something like `body ul li` or add a id on your page, maybe `#page` or similar.
Comment: It did not work. With FireBug, I noticed that Drupal explicitly creates li lists, and not links only. I may need to create a view of links...
Comment: Someone suggested .block-menu-menu-name ul.menu li {   list-style: none; list-style-image: none; } on another question and it worked.
Answer: It can be a tough job to adjust the styling of Drupal 7 menu's. Their nested styling and classnames sometimes make it hard to override, so I came to the conclusion to completely not load the default Drupal styling for menu's in my custom themes. The results are clean pure HTML menu lists which need some custom resetting/styling off-course (primary tabs become a clean list as well!).
function YOURTHEME_css_alter(&$css) {
  // remove Drupal menu styling!
  unset($css['modules/system/system.menus.css']);
}

Answer: I finally replaced my menu with a view where I set the display format to "Unformatted list."
Answer: Do as @googletorp said, but add !important at the end.
li {list-style: none !important;}

Comment: ^this.  In my experience if you have to use `!important` then either you or the author of the CSS you're trying to over-ride has gone wrong somewhere.
Comment: `!important` should be a last resort, specific styles are better.

How to remove bullets from drupal menu?


Linking to property values in a Semantic Form

Question: I have a Semantic Form, which has several input fields with tokens. These input fields allow the user to pick a range of values from a property. I would like to know how to convert these values from text to links, so that on the resulting MediaWiki page the user could click on the value of a property to navigate to the corresponding SearchByProperty page.
In the Wiki I have (http://idlab.tlu.ee/patterns/index.php/Cross-Device_Drag-and-Drop), for example the values in property Design Motivation would be links, which would take the user to the corresponding SearchByProperty pages, for example this one: http://idlab.tlu.ee/patterns/index.php/Special:SearchByProperty/Design-20motivation/Creating-20technological-20infrastructure
Answer: I think the normal way this is accomplished is by using the Template output format. Then in the Design Motivation field you can link to the Search by property page in the template.
The way I would normally have accomplished this is by having the type of the property Design motivation as Page not Text. Then in the Design motivation template I would have an #ask query listing pages using this property. You lose the ability to restrict inputs like that, but in my experience it's pretty easy to catch (often mistakenly) newly created Design motivations.
Comment: Changing the type of the property to Page indeed turns its values into links, however these point to empty pages. Is there a way to make them point to the corresponding search pages?
Comment: http://semantic-mediawiki.org/w/images/f/fc/What's_new_in_Semantic_Forms.pdf#14 shows that there are new mapping options that might help you


Serialize adding unexpected data

Question: $post = &$_POST;
$arr = $post['articles'];
var_dump($arr);
//array (size=3)  0 => string '145' (length=3)  1 => string '123' (length=3)  2 => string '128' (length=3)

$sArr = serialize($arr);
var_dump($sArr);
//string 'a:3:{i:0;s:3:"145";i:1;s:3:"123";i:2;s:3:"128";}' (length=48)

die();

I have an array that I wish to serialize to store in my DB.
But the output is not as expected, I need a string like:
{145, 123, 128}

But some other data has been added - why and how can I remove it?
Comment: That is how serialization works - the output it gives is correct. You can then unserialize that data later to turn it back into an array
Comment: Um, this is how the serialize function works. I'm not sure why you expect any different behavior, specifically your required format.
Comment: PHP serialise includes all the metadata about the variable being encoded (namely its type and variable name) so it can be unserialised into the exact same state later.  The output is correct.  By the way, serialising data to put it in a relational database is a REALLY BAD IDEA!  Everybody I know who has ever done it has come to regret it.  Make use of dependant tables instead, that's what relational DBs are designed to do, after all.
Comment: Is your database in Postgresql?
Answer: The reason for that can be found in the PHP documentation. it says

useful for storing or passing PHP values around without losing their
type and structure

So the serialize function must encode also the value types etc. I would guess that i is the index, and s is the type "string".
To get your result, use implode instead.
Comment: Actually the `i` stands for `integer`:
    `a = array, i = integer, s = string, b = boolean, etc.` as a key in an array can be any type.
Your suggestion to use implode using the `,` delimiter may work but the example given looks more like json which can be achieved by using [json_encode()](http://php.net/manual/en/function.json-encode.php) function.
Answer: you can use use json_encode for any complex data and it's standard.
<?php
$arr=[145, 123, 128];//considering your input is like this
echo json_encode($arr);
?>

this up will answer exactly
[145, 123, 128]

and if you need curly braces that much you can use this instead
echo '{'.substr(json_encode($arr),1,-1).'}';

Comment: For your second point, this is not how to do it. Use the `JSON_FORCE_OBJECT` option instead. Otherwise, this is the correct answer.
Comment: to  @miken32  : but  `SON_FORCE_OBJECT` whould include indices into json too.
 like : {"0":145,"1":123,"2":128}
Comment: Good point. I just cringe whenever I see attempts to "build" JSON from strings. Though looking at the question again it's not even asking for valid JSON!
Answer: join will do the magic:
$sArr = '{' . join(', ', $arr) . '}';

Answer: Have you tried:
$sArr = implode(",", $arr);

Serialize adding unexpected data


jmeter - asynchronous TCP sampler options?

Question: I'm hoping someone has some experience with asynchronous testing and how to accomplish it with Jmeter.  If someone does know, but not with jmeter, also open to other options, but more familiar with jmeter and the context is for load/stress testing.
Definition: For example, sending raw TCP textual datastreams where the "session" id is within the datastream itself.  Everything is asynchronous and could be 'out-of-order' as far as returns.
Example: So, given a sample of 10 datastreams with an end signal of \n over 5 threads, it is possible for all 10 to be sent over the same TCP port before the first one responds, and the response could be in any order.
session00001datasenthere\n
session00002datalsosenthere\n
session00003differentdata\n
...
session00010moredifferentdata\n
Using Jmeter, I do want to measure how long it takes for each given datastream based on the sessionid (say data bytes 8-12 of the streams in this example) to return.  The intent is to use Jmeter for what it is good at, load/stress testing across multiple machines, but smart enough to understand the asynch TCP data (opposed to your normal HTTP session request/response).
Constraint is during any given testing session the 'sessionid' is unique at least until a response stream is returned (for logistic reasons, otherwise couldn't pull this off ;-).
Thanks in advance, and just to ensure intent is understood, this is to take advantage of all the nice ready-to-go reports/listeners/plugins/analytics available to Jmeter.
EDIT: The implementation of the server under test is Netty, not dissimilar to the Telnet example.  If there is a Jmeter example of testing the Netty example Telnet server that may also help.
-D
Comment: could you show a full example Saying thread1 sends this, thread 2 this..., response for threadxxx... ? Not clear what you want to do
Comment: What is you challenge exactly? Is it related to setting unique session id in each request?
Comment: Jmeter does not know when a response comes back that it is tied to which request.  Setting a 'sessionid' on the request sent out is easy but is dependent on the TCP payload, how do you setup your tcp sampler test, or maybe custom java client sampler, to handle whatever the sessionId is for the TCP payload?  EXAMPLE:  session 00003 was sent with a bunch of other payloads, how can you tell Jmeter that when session00003 comes pack to compare the time request to the time response to measure the actual response time of session00003 rather than just the first response in an asynchronous environment?
Answer: Your option I think is to implement a Java Request Sampler.
You could define the following parameters for your Java Request Sampler implementation:

server host
server port
connection identifier(see later)
session identifier
data

Read carefully the documentation of JavaSamplerClient to understand the lifecycle. Each thread will have one instance of your sampler.
Then in your implementation you need to take care of the following things:

create a connection handler class, which opens up sockets for each connection identifier. Test cases using the same connection identifier will send data through the same socket. This connection handler should take care of sending the data synchronized way and to give back the response to the appropiate instance, which is waiting for it
in your sampler you have to create exactly one connection handler (or one per server, or one per port, as you wish)
when the sampler sends some text, you give it to the connection handler, and the sampler waits till the response comes.

This way you can simply convert your asynchronous problem to a synchronous one with implementing this conenction handler, which is shared between the sampler instances. But take care of the implementation to be sure that your thread programming does not fake the results with some testing tool side bottleneck.


oracle rman duplicate database

Question: I'm trying to duplicate from active database. I have configured everything according to oracle docs. still in the middle of the process I get the error
RMAN-06025: no backup of archived log for thread 1 with sequence 58 and starting SCN of 2001221 found to restore

Does anyone know how to solve this? Thanks in advance.
ps: this is my rman configuration on the source database:
RMAN configuration parameters for database with db_unique_name XE are:
CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
CONFIGURE BACKUP OPTIMIZATION OFF; # default
CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default
CONFIGURE CONTROLFILE AUTOBACKUP OFF;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '%F'; # default
CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT   '/backup/ora_df%t_s%s_s%p';
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
CONFIGURE COMPRESSION ALGORITHM 'BASIC' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE ; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/u01/app/oracle/product/11.2.0/xe/dbs/snapcf_XE.f'; # default

Comment: Provide the command that you have used to duplicate the database.
Comment: thank you for your comment. it's 'duplicate target database to xe - from active database - nofilenamecheck"
Answer: I solved the problem by switching to backup based duplication. at fist I got the same error, following instructions in here:
https://oracle-base.com/articles/11g/duplicate-database-using-rman-11gr2
I did a point in time duplicate and it worked fine.
Answer: I used Oracle 12c. For copying 1 db to another say from some test stage to own local machine and own local DB use the bundled app SQL Developer that comes with the installation. In the menu choose tools -> database copy.
The rest is quite self explanatory. You choose source and target DB and choose to copy only the objects or a whole schema. There might some permission involved here also depending on roles and permissions.

oracle rman duplicate database


Entity Reference View format

Question: Is there a way to change the Entity Reference view to a different format than an entity reference list?
I'm trying to list taxonomy terms and other custom taxonomy fields to the user when they use the edit form of the node. Ideally, I would list the taxonomy reference as a table with multiple columns. I haven't found a way to convert this list to a table. Does anyone have any idea?
Answer: You can use Entity Reference Views module

This module provides an advanced Entity Reference widget that uses a
  view embedded in a modal dialog for selecting items. The view can be
  paginated and have exposed filters.

You can also use tables in your views for referencing now.

Entity Reference View format


Erro para fazer requisição em Ajax

Question: Estou enviando um request por ajax para meu servidor REST e estou recebendo de volta:
Access to XMLHttpRequest at 'http://localhost:8081/datasnap/rest/TCadastros/Grupo/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Junto com:
OPTIONS http://localhost:8081/datasnap/rest/TCadastros/Grupo/ 500 (Internal Server Error)
Alguem pode me dar uma luz de como resolver? Eu entendo que o problema provavelmente é no header de origem (Access-Control-Allow-Origin) mas não sei como passa-lo ou se o problema esta no client side ou server side.
Meu ajax está assim:
$(document).on('click', "#modalgravar", function(){

        var Ecdgrupo = $("#Cdgrupoedit").val();
        var Egrupo = $("#grupoedit").val();
        var eData = {"Cdgrupo": Ecdgrupo, "Grupos": Egrupo};
        var eURL = "http://localhost:8081/datasnap/rest/TCadastros/Grupo/"

    alert(JSON.stringify(eData));

        $.ajax({
        type:"PUT",
        url: eURL,
        crossDomain : true,
        data: JSON.stringify(eData),
        contentType:"application/json",
         headers:{'Access-Control-Allow-Origin': '*'},

                success: function(){
                    alert("Editado!");
                },
                error: function(){
                    alert("ERRO:  O grupo não foi editado!");
                 },

              });
           });

Quando tento realizar a chamada no Internet Explorer ele funciona perfeitamente, assim como usando o Postman. Mas no chrome e firefox ele me da esses erros.
Comment: Qual a linguagem do backend cara ? php, c#, nodejs ??
Answer: O erro especificamente quando contêm null:

from origin 'null' has been blocked by CORS policy

Indica que você esta tentando acessar via protocolo file:// provavelmente (definitivamente?!), logo para isto ser permitido (se é que esta a intenção) o crossDomain:true não vai funcionar, isto tem que ser resolvido no back-end do seu "REST", até dá para resolver algumas situações no HTML mesmo, mas nem vou entrar nestes detalhes.
Já o erro 500 (Internal Server Error) indica erro no lado do servidor, não é no teu Ajax, isso porque quando o dominio de origem é diferente do dominio acessado no Ajax ele vai tentar acessar a URL via OPTIONS para verificar se existe as configurações para o CROSS-ORIGIN (CORS), se tiver configurado em seu back-end a rota com options e liberado com os headers (obviamente não precisa de todas, somente das que precisará enviar na requisição HTTP):
Access-Control-Allow-Credentials
Access-Control-Allow-Headers
Access-Control-Allow-Methods
Access-Control-Allow-Origin
Access-Control-Expose-Headers
Access-Control-Max-Age

Mas como no seu back-end/rest não deve nem existir isso, a tua aplicação BACK-END emite erro, pois a rota com OPTIONS não é configurada, ou esta mal configurada, ou tem algum erro no script, por ser qualquer coisa, claramente tudo isso é devido erro de uso seu
Comment: Caro @GabrielMidão então tem que entrar em contato com quem fez ele para modificar, me parece que funciona em localhost, signifca provavelmente que o outro desenvolvedor trabalha contigo, ou é parceria, se for o caso ele é quem poderá resolver, se ele entender de CORs é claro. Infelizmente é complicado resolver no front-end, já que `Access-Control-Allow-Origin` deve ser usado do lado do servidor não no Ajax. Creio que não podemos ajudar mais que isso, mas espero que as explicações ajudem a orientar sua equipe de trabalho. Até breve.
Comment: Me ajudou bastante, agora sei o caminho para corrigir. Obrigado novamente Guilherme!
Comment: Obrigado pela resposta Guilherme! Eu ainda sou iniciante então deixa eu ver se entendi algumas colocações: Quando vc diz protocolo file:// está se referindo ao caminho do HTML que eu estou usando no caso? Se for isso então de fato está assim mas não é definitivo, apenas para teste e desenvolvimento basico. O servidor REST não fui eu que criei, me foi cedido pronto para ser usado conforme o que estou desenvolvendo, porém vou verificar nele a questão dos Headers.

Erro para fazer requisição em Ajax


Golang mongoDB search document

Question: I started to learn mongoDB and I'm trying to search users by a few parameters, username, firstname, lastname. In the example below I can search users by username and I get data.
<code>// Search users
func (r *Mongo) Search(ctx context.Context, query string) ([]*User, error) {
    findOptions := options.Find()
    // Sort by `username` field descending
    findOptions.SetSort(bson.D{{"username", -1}})

    filter := bson.M{"username": bson.M{"$regex": query, "$options": "i"}}
    cursor, err := r.col.Find(ctx, filter, findOptions)
    if err != nil {
        return nil, err
    }

    var results []*User
    if err = cursor.All(ctx, &results); err != nil {
        return nil, err
    }

    return results, nil
}
</code>
The following example search multiple parameters, but the result is empty.
<code>// Search users
func (r *Mongo) Search(ctx context.Context, query string) ([]*User, error) {
    findOptions := options.Find()
    // Sort by `username` field descending
    findOptions.SetSort(bson.D{{"username", -1}})

    filter := bson.M{
        "username": bson.M{"$regex": query, "$options": "i"},
        "$or": []interface{}{
            bson.M{"firstname": bson.M{"$regex": query, "$options": "i"}},
            bson.M{"lastname": bson.M{"$regex": query, "$options": "i"}},
        },
    }

    // filter := bson.M{"username": bson.M{"$regex": query, "$options": "i"}}
    cursor, err := r.col.Find(ctx, filter, findOptions)
    if err != nil {
        return nil, err
    }

    var results []*User
    if err = cursor.All(ctx, &results); err != nil {
        return nil, err
    }

    return results, nil
}
</code>
Question, how can I search by multiple parameters(use $or)?
And Is this search option optimal and correct, or is there a more correct search option in MongoDB, analog of LIKE from SQL?
Thanks in advance for the answer.
Answer: If someone needs to search by several parameters, this might be useful:
I put the filter assembly in a separate method
<code>func (r *Mongo) queryBuilderFilter(query *Query) bson.M {
    var andFilters []bson.M

    if query.Query != "" {
        orFilters := []bson.M{
            {
                "username": bson.M{"$regex": primitive.Regex{Pattern: "^" + query.Query + "*", Options: "i"}},
            },
            {
                "firstname": bson.M{"$regex": primitive.Regex{Pattern: "^" + query.Query + "*", Options: "i"}},
            },
            {
                "lastname": bson.M{"$regex": primitive.Regex{Pattern: "^" + query.Query + "*", Options: "i"}},
            },
        }
        andFilters = append(andFilters, bson.M{"$or": orFilters})
    }

    if len(andFilters) == 0 {
        // Handle empty and, since there must be one item.
        return bson.M{}
    }
    return bson.M{"$and": andFilters}
}
</code>

Golang mongoDB search document


How can I use only the root layout from a live view template in Phoenix?

Question: Mainly I want to get rid of the

tag surrounding the rest of the page. That's defined in live.html.leex so I thought I could exclude it by putting this line into router.ex:
    live "/watch/:guest_id", WatchLive, layout: {MyAppWeb.LayoutView, :root}

It's still there though. How can I exclude live.html.leex?
Answer: Just to follow this up it's worth noting for the next person; :put_root_layout plug in the :browser pipeline in router.ex can end up causing two layouts (live view and a root layout).
I wanted these to be different so I've added a :browser pipeline without the :put_root_layout and another :layout pipeline with just that.
So I have :browser and :browser_with_layout which extends it.
Answer: As a first idea you can just change it if it's not affecting to other pages)
But seriously, you can use put_layout from Phoenix in your controller.
Try that:

https://hexdocs.pm/phoenix/Phoenix.Controller.html#put_layout/2


Using forms and templates and _submit callback

Question: I'm trying to wrap my head around the process of creating a form and handling the submitted data using x_submit().
I start by having a form callback:
function world_form(&$form_state) {

  // if ($form_state['post']) { drupal_set_message("Solved!"); }

  $forms['fieldset_options'] =
    array('#type' => 'fieldset',
          '#title' => t('Options'),
          '#collapsible' => FALSE,
          '#collapsed' => FALSE);

  $forms['fieldset_options']['tags'] =
    array('#type' => 'item', '#title' => 'Simple stuff');

  $forms['fieldset_options']['checkbox1'] =
    array('#type' => 'checkbox', '#title' => t('Solve world problems'));

  $forms['fieldset_options']['submit'] =
    array('#type' => 'button', '#button_type' => 'submit', '#value' => 'Go!');

  // $forms['submit'] = array('#type' => 'submit', '#value' => 'Go!');

  return $forms;
}

So I specify a theme callback, which takes me to a file world.tpl.php in which I do:
print drupal_get_form('world_form');

which invokes my form callback. So far so good. Now the problem I have is that I want to handle when this form is submitted (more specifically, I want the value of the checkbox when it is checked). I read a lot of documentation and most mention the world_form_submit function. So I create one like this:
function world_form_submit($form, &$form_state) {
  drupal_set_message("Posted!");
}

But after I've done that the function isn't called. However if I instead use the line which is commented out in my form function and comment out the '#type' => 'button' field it DOES get called and I can now access the checkbox state, however the problem I have now is that the form is not updated with the state of the checkbox (I.e. if I check the box and submit I get to the same page but the box is no longer checked).
So my questions are:

Why isn't the _submit callback called when I use a "regular" submit button? Do I have to use the $forms['submit'] way?
If I do get the _submit callback called, can I still update my form to reflect what it was before I submitted, and
How can I get the checkbox state in my world.tpl.php file? Say I want to print something if it is checked.

Thank you for your time.
Answer: Many questions here:

Your form function function should return the form array and doesn't need an argument unless you need it for something specific.
You should at least have an element of type 'submit' (not button) in your form.
Chances are good your submit function will get called if you implement it this way.
If the form fails validation, FAPI will restore it to the values submitted, keeping what was typed by the user.
You shoudn't try to embed business logic in your template, but rather in your module and/or a preprocess function.
Comment: Sorry I forgot to add the return statement in the example. I added it now. It is there. But the problem for me now is still that I want to do something with my checkbox values... assuming I do something in my `_submit` function, how would I return the result to the template file? E.g. I fetch data from a db in the `_submit` function, where do I store that data to have it printed out in the template?
Comment: Ideally, with a [theme](http://api.drupal.org/api/drupal/includes!theme.inc/function/theme/6) function. [This document](http://drupal.org/files/theme_flow_6_1.pdf) may be of help.


visual paradigm two databases in same project

Question: How can I have two databases in the same project in Visual Paradigm 10?
Right now I created two Entity Relationship Diagrams One for each database.
The problem is when I go to Tools > Database > Generate I can only select one specific database and both diagrams get applied to it.
I want each file to apply to it's own database.
Answer: Visual Paradigm can define multiple databases for the project (one for each DBMS), but any instance it will only pick one (the default one) for code/DDL generation. Within a project all models should be on the same database. I suggest you can send in your request to Visual Paradigm's support team (firstname.lastname@example.com) to discuss in details about your usage, and see how they can help.


How to extract a dynamic pattern from a command output after removing a couple of patterns using for loop

Question: Using the first "for" loop to extract a specific line from the output, while want that extracted output to be further removed with certain patterned number of text, can you please assist on this..
for /f "tokens=* delims= " %i in ('dir /r ^| findstr -li "zone.id"') do @echo %i >> C:\zone.txt

the output of the above loop is like:
 26 789A44F9D1497937126FF305C6CB89D0.ics:Zone.Identifier:$DATA
 29 active.csv:Zone.Identifier:$DATA
 26 file trans today.jpg:Zone.Identifier:$DATA
 26 BC of raji.pdf:Zone.Identifier:$DATA
 29 modern - Contest 2016 Submission_updated 2019 - july-10.pdf:Zone.Identifier:$DATA
 26 mesge_mon_results (1).csv:Zone.Identifier:$DATA
 26 [MS-DoCTS].pdf:Zone.Identifier:$DATA

i want to remove the space before and after 26 / 29 including the 2 digit number and :$DATA and get the output as below:
789A44F9D1497937126FF305C6CB89D0.ics:Zone.Identifier
active.csv:Zone.Identifier
file trans today.jpg:Zone.Identifier
BC of raji.pdf:Zone.Identifier
modern - Contest 2016 Submission_updated 2019 - july-10:Zone.Identifier
mesge_mon_results (1).csv:Zone.Identifier
[MS-DoCTS].pdf:Zone.Identifier

despite it can be easily done using the replace option in notepad, i like to automate this through batch script.
Comment: change `tokens=*` to `tokens=1*` and `echo %j`
Comment: Thank you Stephen for the comment, Tried this in between a series of attempts.. but still :$DATA stuck behind :)
Answer: You should use Regex in vbscript with a batch file like this code : You can see Regex Demo here
@echo off
Mode 85,20 & color 0A
Title Replace String using Regex with vbscript
Set "InputFile=%~dp0zone.txt"
Set "OutPutFile=%~dp0New_Zone_After_Replacing.txt"
echo(
:: To show Results on screen of console
Call :Search_Replace "%InputFile%" CON
:: To write Result in new file
Call :Search_Replace "%InputFile%" "%OutPutFile%"
echo(
echo Press any key to show the results in a new file :
echo "%OutPutFile%"
pause>nul
Start "" "%OutPutFile%"
echo(
echo Did you want to update and replace all in your original file "%InputFile%" ?
Pause>nul
Move /Y "%OutPutFile%" "%InputFile%">nul
Start "" "%InputFile%" & Exit
::-----------------------------------------------------------------------------------
:Search_Replace <InputFile> <OutPutFile>
(
    echo WScript.StdOut.WriteLine Search_Replace(Data^)
    echo Function Search_Replace(Data^)
    echo Dim strPattern, strReplace, strResult,oRegExp
    echo Data = "%~1"
    echo Data = WScript.StdIn.ReadAll
    echo strPattern = "\b(\d\d\s)(.*)(:\$DATA)"
    echo strReplace = "$2"
    echo Set oRegExp = New RegExp
    echo oRegExp.Global = True
    echo oRegExp.IgnoreCase = True
    echo oRegExp.Pattern = strPattern
    echo strResult = oRegExp.Replace(Data,strReplace^)
    echo Search_Replace = strResult
    echo End Function
)>"%tmp%\%~n0.vbs"
cscript //nologo "%tmp%\%~n0.vbs" < "%~1" > "%~2"
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
Exit /B
::----------------------------------------------------------------------------------

EDIT : Using Regex with Powershell in a batch file :
@echo off
Title Search and Replace with Powershell and batch
Set "InputFile=%~dp0zone.txt"
Set "OutPutFile=%~dp0New_zone.txt"
Call :Search_Replace "%InputFile%" "%OutPutFile%"
If Exist "%OutPutFile%" Start "" "%OutPutFile%"
Exit
REM -------------------------------------------------------------------------------------
:Search_Replace <InputFile> <OutPutFile>
Powershell ^
GC -path "%~1" ^| %% { $_ -Replace '\b(\d\d\s^)(.*^)(:\$DATA^)','$2' } ^| Out-File "%~2"
Exit /B
REM -------------------------------------------------------------------------------------

Comment: Thank you Hackoo for the swift advice. I will try this.
Comment: Thank you Hackoo, the powershell based script works fine.
Answer: Just do a replacement to get rid of :$DATA. You'll need delayedexpansion however.
@echo off & setlocal enabledelayedexpansion
(for /f "tokens=1*" %%i in ('dir /r ^| findstr /IRC:"zone\.id"') do (
    set "line=%%~j"
    echo !line::$DATA=!
 )
)>C:\zone.txt

You also do not need to use delims= " as whitespace is a default delimeter.
One more note, this would need to go into a batch file, not on cmd
If you require this to run from cmd and not from a batch file then from cmd activate delayedexpansion by running cmd /V:ON and use this line:
for /f "tokens=1*" %i in ('dir /r ^| findstr /IRC:"zone\.id"') do set "line=%~j" & (echo !line::$DATA=!)>>C:\zone.txt

Comment: Thank you Gerhard for the correction and explanation.


Meteor: How to detect device model & OS version?

Question: I want to get user's the device model, OS version and screen resolution from my Cordova clients.  Kadira does this beautifully.

How do I do this in my app? Is there an existing package?
Thanks
Answer: An almost trivial answer without any Cordova plugins or Meteor packages:
var device_info = window.navigator.userAgent;
var display_size = screen.width + 'x' + screen.height;

device_info looks something like "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 5 Build/LMY48M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/50.0.2661.86 Mobile Safari/537.36",
Quick and dirty, but all the information is in there and there are no Cordova native plugins to go wrong.
Comment: Probably it wont get you the device uuid though
Answer: I think you're looking for this plugin: https://www.npmjs.com/package/cordova-plugin-device
/////// EDIT //////////////
Well, I don't use meteor, but I can drop you a jquery sniplet:
jQuery(document).ready(function($) {

    $(document).on('deviceready', function() {

        $('#device-platform').html(device.platform);
        $('#device-version').html(device.version);
        $('#device-cordova').html(device.cordova);
        $('#device-model').html(device.model);
        $('#device-uuid').html(device.uuid);

    });

});

Comment: Nice, any Meteor package wrappers?
Comment: Well, I don't use meteor, but I can drop you a jquery sniplet
Comment: Take a look at [the guide](http://guide.meteor.com/mobile.html#installing-plugins)
Comment: Thanks for the help guys, I ended finding a more trivial solution which suited me. The plugins would have necessitated all my deployed users to upgrade from App Stores (quirk of Meteor).


$d(X_n, Y) \to 0$ implies convergence in probability

Question: Suppose we have the following metric:
$$d(X,Y) = E\left(\frac{|X-Y|}{1+ |X-Y|}\right)$$
I woud like to prove that
$$d(X_n , Y)\to 0 \implies X_n \xrightarrow{P} Y$$
I would like to use the theorem that says
$$ X_n \xrightarrow{L^p} Y \implies X_n \xrightarrow{P} Y$$
So, the problem is to prove that
$$\lim_{n\to \infty} E\left(\frac{|X_n-Y|}{1+ |X_n-Y|}\right)=0 \implies\lim_{n\to \infty} E\left(|X_n-Y|^p\right)=0 $$
but I can't figure it out.
Comment: Indeed $$d(X_n , Y)\to 0 \implies X_n \xrightarrow{P} Y$$ holds and $$ X_n \xrightarrow{L^p} Y \implies X_n \xrightarrow{P} Y$$ holds but there is no chance that $$d(X_n , Y)\to 0 \implies X_n \xrightarrow{L^p} Y$$ could hold. Did you check any simple examples?
Answer: As Did pointed out in a comment, your proposed strategy won't work. But you can get the result by more or less unpacking the definitions and using the fact that $P(A) = E(\mathbf{1}_A)$. Here's a sketch.
$$P(|X_n - Y| \geq \epsilon) = E(\mathbf{1}_{|X_n - Y| \geq \epsilon}),$$
so
$$\frac{\epsilon}{1 + \epsilon}P(|X_n - Y| \geq \epsilon) \leq E \Big( \frac{|X_n - Y|}{1 + |X_n - Y|} \mathbf{1}_{|X_n - Y| \geq \epsilon} \Big).$$
We can make the right-hand side as small as we want, so
$$\frac{\epsilon}{1 + \epsilon}P(|X_n - Y| \geq \epsilon) \leq \frac{\epsilon^2}{1 + \epsilon},$$
and then $P(|X_n - Y| \geq \epsilon) \leq \epsilon.$


Computing $\int_{|z|=\rho} {1 \over |z-a|^{4}}\ |dz|$ when $0 > \rho \ne |a|$

Question: Goal: In what follows we let $\gamma = \rho e^{it}$ on $0 \le t \le 2\pi$ serve as the paramaterization of the curve $|z| = \rho$.  We also assume that $\rho > 0$ (else the computation is trivially equal to zero).
We wish to compute
$$
\int_{|z|=\rho} {1 \over |z-a|^{4}}\ |dz|
$$
when $0 < \rho \ne |a|$.
Attempt, with questions in step (3) and (4):

We have that
\begin{align*}
= & \int_{|z|=\rho} {1 \over |z-a|^{4}}\ |dz| \\
= & \int_{|z| = \rho} {1 \over (z-a)^2 \overline{(z - a)^2}}\ |dz| \\
= & \int_{|z| = \rho} {1 \over (z-a)^2 (\overline{z} - \overline{a})^2}\ |dz| \\
= & \int_0^{2 \pi} {1 \over (\rho e^{i t} - a)^2 (\rho e^{-i t} - \overline{a})^2} |i\rho e^{i t}|\ dt\\
= & \rho \int_0^{2 \pi} {1 \over (\rho e^{i t} - a)^2 (\rho e^{-i t} - \overline{a})^2} \ dt\\
\end{align*}
As a consequence, we can say either of the following:
\begin{equation*}
\tag{*}
\int_{|z|=\rho} {1 \over |z-a|^{4}}\ |dz| = \rho \int_0^{2 \pi} {{1 \over (\rho e^{i t} - a)^2} \over (\rho e^{-i t} - \overline{a})^2} \ dt
\end{equation*}
or also
\begin{equation*}
\tag{**}
\int_{|z|=\rho} {1 \over |z-a|^{4}}\ |dz| = \rho \int_0^{2 \pi} {{1 \over (\rho e^{-i t} - \overline{a})^2} \over (\rho e^{i t} - a)^2} \ dt
\end{equation*}
Now if $\rho < |a|$, then doesn't the fact that ${1 \over (z-a)^4}$ is analytic on the disk of size $\rho$ imply that the integral is zero (via Cauchy's integral theorem on a disk)?
On the other hand, if $\rho > |a|$, can we apply Cauchy's Integral Formula to the numerator of, say, $(*)$  to yield the computation?

EDIT: Substituting $|dz| = {-i\rho \over z}\  dz$ and $\overline{z} = {\rho^2 \over z}$ yields:

\begin{align*}
= & \int_{|z|=\rho} {1 \over |z-a|^{4}}\ |dz| \\
= & \int_{|z| = \rho} {1 \over (z-a)^2 \overline{(z - a)^2}}\ |dz| \\
= & \int_{|z| = \rho} {1 \over (z-a)^2 (\overline{z} - \overline{a})^2}\ |dz| \\
= & \int_{|z| = \rho} {1 \over (z-a)^2 ({\rho^2 \over z} - \overline{a})^2}\ {-i\rho \over z}\  dz \\
= & \int_{|z| = \rho} {{-i\rho \over z({\rho^2 \over z} - \overline{a})^2} \over (z-a)^2 }\ \  dz \\
\end{align*}
But it seems like here Cauchy's Integral Formula doesn't apply since ${-i\rho \over z({\rho^2 \over z} - \overline{a})^2}$ is undefined at $0$ and hence not analytic inside $\gamma$.
Comment: on the circle you have $|dz|=-i\rho\,dz/z$ and $\bar z=\rho^2/z$. Just substitute these, and then apply Cauchy's formula, as you planned.
Comment: @user8268: Thanks for that suggestion.  I edited my post w.r.t. those comments and ran into another problem at the end.
Comment: I'm going to give 100 bounty to a clear answer to this post (can't offer it until tomorrow). :)
Comment: Actually ${-i\rho \over z({\rho^2 \over z} - \overline{a})^2}=-i\rho z/(\rho^2-\bar a z)^2$, so no singularity at $z=0$. There is only one thing you need to take care of: either $|a|<\rho$ or $|a|>\rho$ - take care where you see singularities inside the disc $|z|=\rho$. Use Cauchy's formula or residue formula, as you prefer. I'm sure you can finish the calculation without bounties :-)
Answer: I'm in the process of working through this exact problem, and had the exact same point of confusion as the OP. Since this is so far unanswered, I'll put my answer here for the future benefit of others like myself. Please check it thoroughly. I have posted it in good faith, but everyone makes mistakes!
Beginning from the last step in the OP's work:
$$\int_{|z|=\rho}\dfrac{\left(\frac{-i\rho}{z\left(\dfrac{\rho^2}{z}-\overline{a}\right)^2}\right)}{(z-a)^2}dz=-i\rho\int_{|z|=\rho}\dfrac{1}{z\left(\dfrac{\rho^2}{z}-\overline{a}\right)^2(z-a)^2}dz$$
$$=-i\rho\int_{|z|=\rho}\dfrac{z}{(\rho^2-\overline{a}z)^2(z-a)^2}dz,$$
and we can (finally) employ the Residue Theorem. If $\rho<|a|$, then there is no pole at $z=a$, and regardless, there is a pole of order $2$ at $z=\rho^2/\overline{a}$. Calculating the residues is basic (and exceedingly tedious to type out), so we leave that to the reader. The residue of the integrand at $z=\rho^2/\overline{a}$ is $-\dfrac{a\overline{a}^3+\rho^2\overline{a}^2}{(\rho^2-a\overline{a})^3}$ so:
For $\rho<|a|$:
Our result is $-2\pi\rho\dfrac{a\overline{a}^3+\rho^2\overline{a}^2}{(\rho^2-a\overline{a})^3}$.
For $\rho>|a|$: In this case there is also a pole of order $2$ at $z=a$ and the residue there is $\dfrac{\overline{a}a+\rho^2}{(\rho^2-a\overline{a})^3}$. So, our result in this case is the previous residue plus this one, and of course we must multiply by $-i\rho(2\pi i)$. After a little simplification, we arrive at $\dfrac{2\pi\rho}{(\rho^2-a\overline{a})^3}(a\overline{a}-a\overline{a}^3+\rho^2-\rho^2\overline{a}^2)$.


Is it possible to integrate Zoho CRM with Drupal Webforms?

Question: How would one integrate Zoho CRM with the Drupal Webform module? Salesforce has a webform module that woks well. As I understand the webform module API is different to the Drupal forms API, making it more challenging. I have found an sandbox ZOHO API drupal module that seems to have lost some steam. Any pointers would be appreciated.
Comment: Did you meanwhile find a solution?
Answer: Please checkout http://www.drupal.org/project/zohocrm. There isn't a submodule in there to specifically syncronize webforms, however, when you have zohocrm set up properly, it's pretty easy to use it with some custom code to send webform data to zoho. In the code below, we are inserting a Case into Zoho. You could easily modify to insert a Lead or Contact:
<code>/**
 * Implements hook_webform_submission_insert().
 */
function my_module_webform_submission_insert($node, $submission) {
  $components = $node->webform['components'];

  // Get all submission values.
  $form_values = array();
  foreach ($components as $key => $component) {
    $form_values[$component['form_key']] = $component['type'] == 'textfield' ? check_plain(trim($submission->data[$key]['value'][0])) : $submission->data[$key]['value'][0];
  }

  switch($node->nid) {
    case '234':
      $notes = 'Phone: ' . $form_values['phone_number'] . "\n";
      $notes .= 'Message: ' . $form_values['message'];

      // Build Zoho data for Case.
          $data['records'][] = array(
            'Request Type' => $form_values['topic'],
            'Subject' => $form_values['subject'],
            'Description' => $notes,
          );

          // Send case data to Zoho.
          my_module_send_record($data, 'Cases', NULL, TRUE);
    break;
  }
}

/**
 * Send record to Zoho to insert or update.
 */
function my_module_send_record($data, $module, $record_id = NULL, $workflow = NULL) {
  $zoho = zohocrm_get_client();
  if ($zoho === FALSE) {
    return;
  }

  zohocrm_log($data, 'ZOHO DATA');

  $zoho->setModule($module);

  // Trigger Zoho workflow rules
  if ($workflow) {
    $params = array('wfTrigger' => 'true');
  }

  try {
    if (!empty($record_id)) {
      zohocrm_log('UPDATE RECORD');
      $response = $zoho->updateRecords($record_id, $data, $params);
    }
    else {
      zohocrm_log('INSERT RECORD');
      $params['duplicate'] = 2;
      $response = $zoho->insertRecords($data, $params);
    }

    watchdog('zohocrm', t("Successfully sent data to Zoho CRM. Zoho module: @module"), array('@module' => $module), WATCHDOG_INFO);
    zohocrm_log($result = $response->getResponse(), 'ZOHO CRM RESPONSE');

    // Let other modules process their tasks.
    module_invoke_all('zoho_record_sent', $data, $module, $result['recordId']);
  }
  catch (Exception $e) {
    drupal_set_message(t('Sending data to Zoho CRM failed. Error message: @message', array('@message' => $e->getMessage())), 'error');
    watchdog('zohocrm', t("Sending data to Zoho CRM failed. Zoho module: @module. Error message: @message"), array('@module' => $module, '@message' => $e->getMessage()), WATCHDOG_ERROR);
  }
}
</code>
Answer: yes it is absolutely possible to integrate zoho crm (any module) with drupal webform, Just open your webform.module from Drupal Backend and add Zoho Api method to integrate your webform data with Zoho.
<code>
if (isset($form['#node']) && $form_id == 'webform_client_form_177') {
        $node = menu_get_object();
        $title = $node->title;
        $form['form_name'] = array(
        '#type' => 'hidden',
        '#value' => $node->title,
        );
        $form['#submit'][] = 'insert_into_zoho';
    }
</code>
insert_into_zoho is the simple function i created to post data into crm with api method insertRecord().
https://www.zoho.com/crm/help/api/insertrecords.html
Comment: if you want to capture leads from drupal webform, you can use zoho api method to get leads/contacts from drupal webform form.
Answer: We were able to accomplish this easily using Zapier, which has built-in Zoho integration. Zapier is a subscription service which allows you to map inputs from one source to values in another destination. Using Webform's built-in handler to POST the submission values to Zapier makes it possible to easily forward the results into a new Zoho lead.


Match from a key and return unique ID in R

Question: The task: I webscraped a large data set that includes a variable (data$author) I need to clean. It's partly organized by job title, partly organized by name. I need this naming convention standardized for analysis by the correct job title held by the associated person's name. So, in my below example, Jim is the Prez, Bob is the CEO, etc. A further complication is that people move around in jobs over time, so the name-job link is associated by year. In short, I want to create a new variable in the dataframe with a standardized job title.
Here's my thinking: create a matching function to check each entry against the master key, and return the correct job title (by associated name+date) to a new vector.
jobs <- c("Prez", "CEO", "VP", "VP", "Director", "Assistant", "Secretary", "Intern")
names <- c("Susan", "Bob", "Susan", "Jim", "Gail", "Emily", "Dan", "Anne")
year <- c("86", "85-86", "85", "85-86", "85-86", "85-86", "85-86", "85-86")

key <- cbind(jobs, names, year)

DocID <- c(1:20)
author <- sample(c(jobs,names), 20, replace=T)
data <- cbind(DocID, author, year_data)

data$cleaned <- Magic.Clean.Function(data$author)

Hoping to end up with a 'data$cleaned' vector listing just the corrected job titles.
EDIT: Sorry if this is a little messy, I'm trying to recreate a simplified version of my actual DF. Thanks for the help!
Comment: can you show your expected
Comment: Your `data` do not have `year` column. Since titles varies over years, you need to include `year` in your data. Am I missing something here?
Comment: What are the values of `year_data`. Please edit your question with it.
Comment: I haven't built the key yet. So I can format the year_data in whatever makes sense. My original data is DDMMYY and lubridated so I imagine I'll continue with that format.
Answer: library('data.table')
setDT(data)
setDT(key_df)
setnames(key_df, "names", "author")  # rename names to author column in key_df
data[key_df, on = c('author', 'year'), nomatch = 0]  # match on only author and year values between data and key_df datatables, and show the matched rows of data.
#    DocID author  year      jobs
# 1:    11  Susan    85        VP
# 2:     2    Jim 85-86        VP
# 3:    13   Gail 85-86  Director
# 4:     8  Emily 85-86 Assistant
# 5:    16  Emily 85-86 Assistant
# 6:     5   Anne 85-86    Intern
# 7:     6   Anne 85-86    Intern

OR
# if you want to add jobs column in your data
data[key_df, on = c('author', 'year'), jobs := jobs]
data

a vector of length(author) that returns the corrected job title
data[key_df, on = c('author', 'year'), nomatch = 0, author]
# [1] "Susan" "Jim"   "Gail"  "Emily" "Emily" "Anne"  "Anne"

# unique authors
data[key_df, on = c('author', 'year'), nomatch = 0, unique(author)]
# [1] "Susan" "Jim"   "Gail"  "Emily" "Anne"

Data:
jobs <- c("Prez", "CEO", "VP", "VP", "Director", "Assistant", "Secretary", "Intern")
names <- c("Susan", "Bob", "Susan", "Jim", "Gail", "Emily", "Dan", "Anne")
year <- c("86", "85-86", "85", "85-86", "85-86", "85-86", "85-86", "85-86")

key_df <- data.frame(jobs, names, year, stringsAsFactors = FALSE)

DocID <- c(1:20)
set.seed(2L)
author <- sample(c(jobs,names), 20, replace=T)
data <- data.frame(DocID, author, stringsAsFactors = FALSE)
data$year <- c( key_df$year, key_df$year, key_df$year[1:4])

Comment: use the data posted in the answer. I changed names.
Comment: I think I see what you did (but I'll have to familiarize myself quickly with data.table).  But the result I need is a vector of length(author) that returns the corrected job title.
Comment: Still tinkering with it -- thanks for the help. I'll update when I know more!


move_uploaded_file falhando

Question: Olá, pessoal, tudo bem? Eu estou com um problema para salvar imagens dentro do servidor. Esse código eu encontrei na internet, mas não funciona. Me retorna alguns erros. Podem me ajudar?
Este é o código:
if ( isset( $_FILES[ 'lutadorUm' ][ 'name' ] ) && $_FILES[ 'lutadorUm' ][ 'error' ] == 0 ) {
    echo 'Você enviou o arquivo: ' . $_FILES[ 'lutadorUm' ][ 'name' ] . '
';
    echo 'Este arquivo é do tipo:  ' . $_FILES[ 'lutadorUm' ][ 'type' ] . '
';
    echo 'Temporáriamente foi salvo em: ' . $_FILES[ 'lutadorUm' ][ 'tmp_name' ] . '
';
    echo 'Seu tamanho é: ' . $_FILES[ 'lutadorUm' ][ 'size' ] . ' Bytes

';

    $arquivo_tmp = $_FILES[ 'lutadorUm' ][ 'tmp_name' ];
    $nome = $_FILES[ 'lutadorUm' ][ 'name' ];

    $extensao = pathinfo ( $nome, PATHINFO_EXTENSION );

    $extensao = strtolower ( $extensao );

    if ( strstr ( '.jpg;.jpeg;.gif;.png', $extensao ) ) {

        $novoNome = uniqid ( time () ) . ".".$extensao;

        $destino = 'imagens/' . $novoNome;

        if (move_uploaded_file ( $arquivo_tmp, $destino ) ) {
            echo 'Arquivo salvo com sucesso em : ' . $destino . '
';
            echo ' ';
        }
        else {
            echo 'Erro ao salvar o arquivo. Aparentemente você não tem permissão de escrita.
';
            echo $destino;
        }
    }
    else {
        echo 'Você poderá enviar apenas arquivos "*.jpg;*.jpeg;*.gif;*.png"
';
        echo $destino;
    }
}
else {
    echo 'Você não enviou nenhum arquivo!';
}

Este são os erros:

Warning: move_uploaded_file(imagens/149149930358e679279a144.jpg):
  failed to open stream: No such file or directory in
  C:\xampp\htdocs\back_classes\envioUfc.php on line 34
Warning: move_uploaded_file(): Unable to move
  'C:\xampp\tmp\php6E3B.tmp' to 'imagens/149149930358e679279a144.jpg' in
  C:\xampp\htdocs\back_classes\envioUfc.php on line 34

Obs: Eu tenho a pasta dentro da pasta do projeto. E mesmo quando apontei diretamente para o servidor, não funcionou. Por exemplo: "localhost/back/imagens/".
Comment: Como assim? "C://users/usuario/back/imagens", é isso?
Comment: Obrigado! Era isso mesmo!
Answer: O caminho do teu .php não deve estar relativo a pasta imagens, só vendo a estrutura de pastas do projeto especifico para ter certeza, pelo caminho back_classes\envioUfc.php creio que a pasta imagens esteja fora de de back_classes então deve usar assim:
$destino = '../imagens/' . $novoNome;

Se não funcionar é porque o caminho esta errado, para ajustar também pode tentar o caminho absoluto (supondo que a pas imagens esteja dentro de htdocs):
 $destino = 'C:/xampp/htdocs/imagens/' . $novoNome;

Se estiver dentro de back_classes e a falha ocorre é porque você esta incluindo o envioUfc.php em outro ficheiro .php (com include ou require) que esteja em um nivel diferente, então pode experimentar isto:
 $destino = 'C:/xampp/htdocs/back_classes/imagens/' . $novoNome;

Quando for enviar a um servidor de produção terá que ajustar este caminho absoluto.
Um exemplo para facilitar e evitar manutenção ou ajustes seria criar um arquivo global que deve ser incluido em todos arquivos com require_once, neste arquivo global.php deve conter isto:
<?php
//Define a constante
define('ROOT_PATH', dirname(__FILE__) . '/');

E nos arquivos como index.php e outros adicione isto acima de tudo:
<?php
require_once 'global.php';

Se estiver em uma pasta diferente da pasta aonde esta o index.php, use assim:
<?php
require_once '../global.php';

E o $destino deve ficar assim:
$destino = ROOT_PATH . 'imagens/' . $novoNome;

Comment: Okay, vou fazer isso, obrigado!!
Comment: Desculpa, mas aparentemente ele não ta salvando no servidor. No localhost eu encontro o arquivo dentro da pasta imagens, mas no servidor ela não ta lá. Eu falei que funcionou, porque eu vi que tinha salvo o link no banco
Comment: Okay, mas eu usei o global.php como você sugeriu.
Comment: Ocorre o mesmo erro
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/56679/discussion-between-krint-and-guilherme-nascimento).

move_uploaded_file falhando