Owl Carousel + Vue.js com item dinamicos

Question: Olá,
Tenho um componente que me inicializa um slider com items dinâmicos vindos da base de dados.
No entanto, tenho uma caixa de pesquisa que faz uma nova requisição à base de dados e retorna novos items para substituir os existentes no slider. Mas não está a substituir, estando a ficar por cima do slider.
Segue o código do template do componente: (Existe sempre um item padrão (banner_default) que deve ser sempre o primeiro slide do slider)
<template>

{{ week }} / {{ year }}

            {{ slide.title }}

                    #{{ tag.tag }}

Segue o script:

owl-carousel.vue.js
import './assets/owl.carousel.css'
import './assets/owl.theme.css'
import './assets/owl.carousel.js'

export default {
  name: 'OwlCarousel',
  props: {
    items: Number,
    itemsDesktopSmall: Array,
    itemsTablet: Array,
    itemsTabletSmall: Array,
    itemsMobile: Array,
    value: Array
  },
  data () {
    return {
      widget: null
    }
  },
  computed: {
    options () {
      return {
        items: this.items,
        itemsDesktopSmall: this.itemsDesktopSmall,
        itemsTablet: this.itemsTablet,
        itemsTabletSmall: this.itemsTabletSmall,
        itemsMobile: this.itemsMobile,
        navigation: false,
        slideSpeed: 300,
        pagination: true,
        paginationSpeed: 400,
        singleItem: (this.items || 1) === 1,
        navigationText: ['', ''],
        autoPlay: false
      }
    }
  },
  watch: {
    value: {
      immediate: true,
      handler: function () {
        if (this.widget) {
          this.widget.trigger('destroy.owl.carousel')
          this.widget = null;
        }
        if (this.value && this.value.length > 0) {
          this.$nextTick(() => {
            this.widget = $(this.$el).owlCarousel(this.options)
          })
        }
      }
    }
  }
}

aqui está um exemplo de utilização do componente.:
<owl-carousel :items="3" :items-desktop-small="[1280,3]" :items-tablet="[900,2]" :items-tablet-small="[750,2]" :items-mobile="[600,1]" v-model="items">

        ...

</owl-carousel>

Caso o carousel não tenha itens dinâmicos (que não foi o nosso caso), é interessante que adicione a diretiva v-once a ele. A razão para tal é bem explicada no seguinte artigo.: How To (Safely) Use A jQuery Plugin With Vue.js
<owl-carousel :items="3" :items-desktop-small="[1280,3]" :items-tablet="[900,2]" :items-tablet-small="[750,2]" :items-mobile="[600,1]" v-model="items" v-once>

        ...

</owl-carousel>

No meu caso estava utilizando um template de terceiros, e o tema do mesmo estava bem customizado, então o owl-carousel se tornou um dependência um tanto quanto acoplada.
mas de forma geral, deve-se evitar utilizar componentes baseados em jQuery, afinal o Vue é bastante possessivo quanto à DOM e o jQuery é um terrorista que não respeita isto.
Neste ponto o Vue Awesome é seu amigo.: Carousel


How to change default content type machine name in commerce kickstart?

Question: I am using Drupal commerce kickstart 7 . I have installed perfecly . I am using demo store also. It have content types like hats, storage devices , etc,... I am using hats content type. So products show url like that hats/lloyd-l40s-40-full-hd-smart-led-television. But i want to show like products/lloyd-l40s-40-full-hd-smart-led-television.How to rename???
Thanks in advance
Answer: You can only set the machine name when you create the content-type. After that, it is not editable anymore. That's why you have to think twice when you create a new content-type. Your only solution is to delete this content-type and recreate one with the right machine name.
If it is only the appearance of the URL that doesn't suit you, you can also use URL aliases modules like https://www.drupal.org/project/pathauto and replace the word 'hats' by the word 'products' for example (in the module configuration).


Is a chi square test appropriate?

Question: I have a dataset which consists of fish density/biomass from two sampling periods (1 and 2) in two locations (A and B). In sampling period 1 locations A and B are both clear, while in sampling period 2 A is clear but B is experiencing very high turbidity. I want to assess whether the increased turbidity has caused a change in how the fish are using the habitat-- i.e. if they are preferentially choosing the clear "A" location at sampling period 2, compared to sampling period 1.
I was thinking I could assess this with a chi-square test, but my measures of biomass and density are continuous, not discrete-- would rounding up to the nearest whole number be valid?/Any other suggestions on how to analyze this? I don't think an ANOVA will work because I really only have one measure of density/biomass per group/time.
*** EDIT ***
I actually have 100's of measures of density and biomass in each sampling of the 4 sampling areas/periods-- density and biomass were obtained using a sonar-like device that pings the fish every minute or so. But these measures obviously won't be independent of each other, so I was planning on just averaging across the sampling period.
Comment: No.  Your measurements are not counts and rounding to integers won't make them counts. After all, you could change your units of measurement and get quite different integers after rounding.  It sounds as if you have no information about variability in any case.
Comment: It's not clear you can make these independent. They sound like pseudoreplications to me.  I think you have 4 data points. You can simply report the four numbers as descriptive.
Comment: S. Thompson describes how to analyze such samples in his book *Sampling.* The later chapters focus on methods to sample ecological systems, such as transect sampling. The idea is that you need to estimate the chances of detecting any individual and any pair of individuals in the population (based, perhaps, on the properties of your sonar); and then you can use those chances in a Hansen-Hurwitz like estimator.
Comment: @MisterMak Imagine there is a camera on the bottom of the boat. The camera takes a picture of all of the fish which are directly under the boat every minute. The boat weaves back and forth over the sampling area and takes 100 pictures in total. There is variation in the number of fish in each picture, but no way to say with any confidence how many of those fish are unique individuals. This is why I was planning on averaging across all of the fish "photos" because the measurements won't be independent from each other.
Comment: whuber's reference is probably better, but one thing that could be done is you could run an exemplary chi squared test on some fish numbers that make some sense at some point in time. If this gives you a p-value of about zero (really far lower than any reasonable cutoff for significance) you could state that the evidence looks very clear and strong for a change despite the specific test just giving an example calculation rather than being precise for your problem. (Of course still assuming that individual fish are independent.)
Comment: It sounds as if you have 4 data points, A1, A2, B1 and B2, and you want to see if there is a change between B1 and B2 using A1 and A2 as controls.  Without knowing more about the fluctuations (eg the points follow a gaussian distribution), I think it is hard to say much.  Otherwise, you could build a model and do a likelihood ratio test.
Comment: Can you make an assumption as to the typical fish mass in order to obtain the number of fish, and from there use Poisson statistics, or Gaussian if the numbers are high enough?
Comment: You can't somehow "back-engineer" your measurements to estimate a count of fish, can you? The theory behind the chi squared test is valid for counts, not for continuous measurments, as was already stated. That said, even if you had counts, it'd be dubious to assume that the fish are independent of each other, which would also be required by the chi-squared test.
Comment: @NickCox Actually, I have a little bit of variability information-- the fish data was collected via a sonar-like device which pinged the fish and calculated the number and biomass of them at that instance in time. It did this every second or so in each sampling area for about 100 seconds (so 400 measurements total). Because these samples weren't going to be independent of each other I was planning on just averaging across each sampling area/period, but maybe there's a way to use those data? Could I use that data to estimate the number of fish in each area and then do a Chi square test on that?
Comment: Can you take measurements that are more time apart from each other, so that independence looks more realistic?
Comment: @Lewian To clarify I do actually have measures of the number of fish per acre (density), and biomass. The reason that the result comes out as continuous is because I have 100 measures of density and biomass per sampling period/time which I average to obtain an overall density measure (because the 100 density measurements within the same sampling period/time won't be independent of each other).
Comment: But you wouldn't think it is reasonable to assume the individual fish independent of each other, would you?
Comment: @Lewian The sampling was in response to a once in 100-year rainfall event which led to increased turbidity. It would be impossible to recreate the unique site conditions for the"treatment" sampling period.
Comment: @Lewian I assume the individual fish to be independent of each other-- but I can't say with any confidence that the 19th ping taken within a given sampling period/area is going to have completely different individuals than the 20th ping.
Comment: @Dugan, within each of the 4 categories, what causes the fluctuations?  If it is not the number of fish, can it be the instrument used to make measurements?
Comment: For each of the measurements A1, A2, B1 and B2, if you take the mean and standard deviation, would that overestimate the fluctuations?  If so, and you do a likelihood ratio test, could you still put a constraint on the p-value?
Comment: @MisterMak I think it'd be more likely underestimate the fluctuations since the individuals in ping #20 could be recounted in ping #21.
Comment: Is there maybe some way to develop a measure of how independent the samples are from each other? like if I assume that fish follow a random walk type movement pattern then samples that are collected farther away from one another both temporally and spatially should be more independent? Could this then be used to do some sort of likelihood ratio test?
Comment: @whuber maybe I'm misunderstanding it but I just read up on  Hansen-Hurwitz like estimators-- my understanding is that this is a way to estimate total population size when you have samples collected from clusters of different sizes. Like estimating the total number of trees on a set of islands when you assess the number of trees on a subset of the islands and then correct for island size. So I'm not sure how it would apply here.
Comment: If you are not trying to estimate the size of some kind of fish population, then what are you trying to do?
Comment: @whuber I'm trying to determine whether the fish are preferentially choosing the clear sampling area versus the non-turbid sampling area. I can see how estimating population size would get me that (I could enter the population size estimate in the chi-square analysis), but I don't see how a Hansen-Hurwitz like estimator would work in this situation. The issue is not that my samples are from different sized clusters, it's that they're not spatially/temporally independent of each other.
Comment: I would think coefficient estimates from a linear model would be sufficient if you use the individual samples?

Roughly $y = \beta_0 + \beta_{loc} x_{loc} + \beta_{turbid} x_{turbid} + \epsilon$. $\epsilon \sim N(0, \sigma)$ or similar with centered/standardized $y_i$. (Maybe with interaction?)

If you dummy-coded $x_{turbid}$, then $\beta_{turbid}$ would reflect the expected deviation from baseline associated with turbid conditions.

You can then compute related p-values / confidence intervals if you want, or use the model for ANOVA, etc.
Comment: @Gianni Thanks for the suggestion! I've just been reading up on spatial regression models. I don't know much about them so I'm a little unsure on the formula you've provided. Is this a spatial error model, a spatial lag model a SLX spatially lagged X model or a global spatial model? Which do you suggest and why? Do you have a recommended program for running this? I have been reading about GeoDa and the R package spdep.
Comment: I had something simpler in mind. I understand your locations as categorical: you're either in location A or B. Likewise for observation periods. Likewise for turbidity. So you can treat these as binary indicator variables in a regression model.

Even though your samples within a group are not IID, they are IID wrt samples within other groups. The coefficient for turbidity is an expected deflection between groups, not samples. So I think you shouldn't need a structured noise model, unless there are other within-group differences you're interested in.
Comment: For software: I'm not that familiar with the R ecosystem. I would approach this with `statsmodels` in Python as the simplest choice. (Usually I'd put a prior on it and actually work in `PyMC3` or `numpyro`, but that might be overkill for your purposes, unless there's a lot of additional complexity that's of practical interest to you.)
Answer: Would this work (posting as an answer because it's not really a comment)?
I have 100 samples in each of the four sampling groups (A1, A2, B1, and B2). The samples collected within A1 are not independent from each other, but they are independent from the samples collected in A2, B1 and B2.
Therefore, could I take a random sample in sampling group A1, another random sample in sampling group A2, B1 and B2 and perform a Chi-square test on these 4 numbers. Obtain the Chi-square test statistic and then repeat this procedure 10,000 times to obtain an average Chi-square value with a standard error, and then get a p Value from that?
Comment: I think it depends on what statistical rigour you want.  You could probably obtain a result that convinces people (and even referees) if the effect exists (or doesn't), though you should explain clearly what you are doing.  Also, it is often useful to run simulations (ie generate mock data sets A1, A2, B1 and B2 and push them through your analysis pipeline) ahead of time to see if things behave as expected.
Comment: If observations in A1 are not independent of each other, randomly sampled elements from A1 are not independent either. So no, random sampling from your data doesn't help.
Comment: @Lewian even if I'm only using one "photo" per group? i.e. one photo of fish numbers from each of groups A1, A2, B1, B2, is hen calculate the chi square, then repeat?
Comment: Can you show the distribution of counts in A1 for instance, to confirm whether or not if follows a Poisson distribution?
Comment: @Dugan: As I wrote before as a comment to the original question, if you use one number per group a chi squared test can be, let's say, "well motivated", and if that gives you an "about zero" p-value, I'd be fine with the conclusion that something's going on there. However if you repeat this with different photos, you don't add independent information, so I don't see this getting you much further.

Is a chi square test appropriate?


How to theme simplenews newsletters in D7?

Question: I'm looking for something like a walk-through.  (The guide here, http://drupal.org/node/268404, was apparently written before the D6 rewrite).
The reason I'm after this is that when I use the default simplenews newsletter format, and enter for the subject "test" and for the body "test content" my resulting emails look like this:
<code>-------- TES
-----------------------------------------------------------------
Test content**myReport taxonomy**
**myURL**

-- Unsubscribe from this newsletter:
**myUnsubscribeURL**
</code>
(The contents between the ** are correct, I've left them out for privacy).  But you can see the issues are things like:

The "t" at the end of "test," the last letter of the header, is left off for some reason.
I'm not sure where the hyphens are coming from, or how to modify that formatting decision. I'd like to eliminate the hyphens both before the heading, and between the heading and the body.
The body of the email abuts the name of the report taxonomy without space or break.
The body of the email comes before the name of the report taxonomy, I'd rather reverse the order.

Can anyone point me to a simple guide to alleviate at least these four problems?  Greater customizability would be helpful, but I need to address these for a minimum viable newsletter before getting fancy.
Answer: This happens because this is the default HTML to Plaintext conversion that Drupal is applying to all mails.
If you don't want this, either adjust the templates (you can find them in the theme folder, just copy to your theme and start adjusting it) to avoid HTML or enable a module like Mime Mail that allows to send HTML formatted mails.
No idea why the title is cut off.
Answer: Berdir is right, but I like to use the HTML Mail module instead of Mime Mail. (I show how to do this in a video series, but it's a paid series. If you want, you can check it out at http://modulesunraveled.com/simplenews. But basically you want to use the HTML Mail module.)


Como fazer para a  com a tag  só aparecer depois da foto ser carregada?

Question: boa tarde amigos. Estou utilizando JQuery para assim que receber a imagem pelo input "file", mandá-la para a tag img colocada próxima à ele, porém, quero que apareça a imagem somente depois de carregada... Se eu coloco as proporções em que a imagem deve aparecer após carregada, as bordas da tag ficam aparecendo mesmo sem imagem alguma

/*Parte JQuery que envia a imagem para a tag*/

 /*  css  */
.imagem_prepost img{
  width: 90px;
  height: 100px;
  border-radius: 0;
}

<form  method="post" class="form-group">

      <input name="arquivo" id="input_preview" type="file" />
      <button type="submit">Postar</button>

</form>
Answer: Você pode usar .show() do jQuery para exibir a tag img. Primeiro você precisa adicionar display: none; à imagem para ela ficar escondida por padrão. Depois, no seu evento de onloadend basta exibir a tag img usando .show().
Veja o exemplo a seguir:

/*Parte JQuery que envia a imagem para a tag*/
$(function(){
    $('#input_preview').change(function(){
        const file = $(this)[0].files[0]
        const fileReader = new FileReader()
        fileReader.onloadend = function(){
            // adicionando .show() ao preview da imagem
            $('#img_preview').attr('src',fileReader.result).show();
        }
        fileReader.readAsDataURL(file);
    })
})
/*  css  */
.imagem_prepost img{
  width: 90px;
  height: 100px;
  border-radius: 0;
  /* deixando a imagem escondida */
  display: none;
}

<form  method="post" class="form-group">

      <input name="arquivo" id="input_preview" type="file" />
      <button type="submit">Postar</button>

</form>

Adicionalmente, você pode fazer a verificação se o arquivo existe ou não e usar .hide() caso não exista. Veja o exemplo a seguir:

$(function(){
  $('#input_preview').change(function(){
      const file = $(this)[0].files[0]

      const fileReader = new FileReader()

      // Se algum arquivo foi passado
      if (file) {
         $('#img_preview').show();
         fileReader.readAsDataURL(file);
      }
      // Se não foi passado nenhum arquivo
      else $('#img_preview').hide();

      fileReader.onloadend = function(){
          $('#img_preview').attr('src',fileReader.result);
      }
  })
})
/*  css  */
.imagem_prepost img{
  width: 90px;
  height: 100px;
  border-radius: 0;
  /* deixando a imagem escondida */
  display: none;
}

<form  method="post" class="form-group">

      <input name="arquivo" id="input_preview" type="file" />
      <button type="submit">Postar</button>

</form>
Comment: Se vocẽ for colocar um botão de `x`, basta adicionar um evento de `.click()` no botão e dentro do evento aplicar o `.hide()`. Dessa forma: `$("#botao").click(function(){ $('#img_preview').hide(); });`. E você pode colocar para esse botão aparecer somente quando a imagem for selecionada, igual fez com a `div` de _preview_.
Comment: Isso depende de como você faz para indicar que o post possui uma foto. Pode dizer como está fazendo isso?
Comment: Tanto o php quanto o código que manda a requisição pro servidor
Comment: valeu mano, quebrou o maior galho... só mais uma pergunta... qual evento eu poderia adicionar caso a foto que ele escolhesse fosse a errada ou se ele desistisse de colocar a foto? tipo um botãozinho de "x" pra retirar a imagem... como eu o faria?
Comment: valeu mano! acabei de usar aqui...
Comment: mano... surgiu um novo problema kkkkkk, está funcionando corretamente a parte de desaparecer e etc.. mas como meu site já está fazendo postagens, quando eu retiro a foto com o hide() no botão com evento onclick(), pelo fato de somente esconder a imagem, quando eu vou postar depois de "excluí-la" na preview, ainda assim posta com a foto... gostaria de saber como retirá-la totalmente da postagem...
Comment: se refere ao código php?
Comment: coloquei o código aí mano, espero que dê pra entender...
Answer: Você pode adicionar uma classe pra esconder a div, e remover ou adicionar caso seja selecionado uma imagem. Caso não selecionar nenhuma imagem, a div irá desaparecer novamente.
/** javascript */
$(function(){
    $('#input_preview').change(function(){
        const container = $('.imagem_prepost');
        const image = $('#img_preview');

        const file = $(this)[0].files[0]

        if (file) {
            const fileReader = new FileReader()
            fileReader.onloadend = function(){
                image.attr('src',fileReader.result)
            }
            fileReader.readAsDataURL(file);
        }

        file ? container.removeClass('hide') : container.addClass('hide');
    })
})

/** css */
.imagem_prepost img{
  width: 90px;
  height: 100px;
  border-radius: 0;
}

.hide {
    display: none;
}

Comment: opa, valeu pela dica tb mano!!! assim como o mauro, quebrou um "galhão"!!


Como eu faço pra verificar se existe um arquivo?

Question: Usei a função file_exists e ela até encontra o arquivo.
O problema é que quando não encontra, não é exibida a mensagem que não existe (não entra no else).
<?php
    $email = $v->email;
    $email = strstr($email, '@', true);
    $url = base_url();
    foreach (array('png', 'jpg', 'gif') as $ext) {
        if (!file_exists("./uploads/{$email}." . $ext)) {
            continue;
        }
        $email = "$email.$ext";

        $filename = "./uploads/{$email}";

        if (file_exists($filename)) {
            echo "O arquivo $filename existe";
        } else {
            echo "O arquivo $filename não existe";
        }

        echo "";
        break;
    }
?>

Answer: Isso porquê você verifica a existência do arquivo duas vezes e na primeira você executa continue caso o arquivo não exista. O continue faz com que a iteração atual seja finalizada e, assim, o segundo if não é executado.
O que pode fazer é remover o primeiro if:
foreach (array('png', 'jpg', 'gif') as $ext)
{
    $email = "$email.$ext";
    $filename = "./uploads/{$email}";

    if (file_exists($filename)) {
        echo "O arquivo $filename existe";
        echo "";
        break;
    } else {
        echo "O arquivo $filename não existe";
    }
}

Desta forma, iria funcionar, mas apareceria várias mensagens na página. Uma forma interessante de fazer é manter uma imagem de avatar genérica e, se o sistema encontrar o arquivo, substituir a imagem. Algo como:
$avatar = "./uploads/avatar.png";

foreach(array("png", "jpg", "gif") as $ext)
{
    $filename = "./uploads/{$email}.{$ext}";

    if (file_exists($filename))
    {
        $avatar = $filename;
        break;
    }
}

echo ""

Desta forma, se o sistema não encontrar nenhum dos arquivos, é exibido o avatar genério uploads/avatar.png, mas se encontrar, exibe a imagem encontrada.
Comment: Obrigado Anderson, sua resposta me ajudou!


Read and write a file in groovy

Question: I'm new to groovy and SOAP UI free. I'm using a groovy script to drive my test for SOAP UI.
I want to write a script that reads a file of person IDs, removes the first one, sets a property, writes the file back out without the one I just read.
Here's my first cut at it:
List pids = new ArrayList()

new File("c:/dev/pids.csv").eachLine { line -> pids.add(line) }

String pid = pids.get(0);
testRunner.testCase.setPropertyValue( "personId", pid )
pids.remove(0)

new File("c:/dev/pids.csv").withWriter { out ->
    pids.each() { aPid ->
        out.writeLine(aPid)
    }
}

The output gets displayed on SOAP UI and the file doesn't get touched. I'm lost.
Answer: ArrayList pids = null
PrintWriter writer = null

File f = new File("c:/temp/pids.txt")

if (f.length() > 0){
   pids = new ArrayList()

   f.eachLine { line -> pids.add(line) }

   println("Item to be removed: " + pids.get(0))
   //testRunner.testCase.setPropertyValue( "personId", pid )
   pids.remove(0)

   println pids

   writer = new PrintWriter(f)
   pids.each { id -> writer.println(id) }

   writer.close()
}
else{
   println "File is empty!"
}

Comment: Yeah, that's what I ended up doing, only I used BufferedWriter. When all else fails, use Java. :)  Thanks for the response.
Answer: def myFile = new File("newfile.txt")

def newFile = new File("newfile2.txt")

//testRunner.testCase.setPropertyValue( "personId", pid )

PrintWriter printWriter = new PrintWriter(newFile)

myFile.eachLine { currentLine, lineNumber ->

    if(lineNumber > 1 )

       printWriter.println(currentLine)
  }

printWriter.close()

Read and write a file in groovy


Print out objects stored in a list

Question: I am new to Python, busy creating a blackjack game. I have almost got printing out my deck of cards right, but I can't seem to iterate through all the cards stored in the list.
suits = ['Hearts','Diamonds','Spades','Clubs']
ranks = ['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace']
values = {'Two':2, 'Three':3,'Four':4,'Five':5,'Six':6,'Seven':7,'Eight':8,'Nine':9,'Ten':10,'Jack':10,'Queen':10,'King':10,'Ace':(1,11)}

playing = True

class Card:
    def __init__(self, suit, rank):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        print(f"{self.rank} of {self.suit}")

class Deck:

    def __init__(self):
        self.deck = []
        for suit in suits:
            for rank in ranks:
                self.deck.append(Card(suit, rank))

    def __str__(self):
        for card in self.deck:
            return f"{card.rank} of {card.suit}"

deck = Deck()

print(deck)

Output with return:
Two of hearts

Output with print:
Two of Hearts
Three of Hearts
Four of Hearts
Five of Hearts
Six of Hearts
Seven of Hearts
Eight of Hearts
Nine of Hearts
Ten of Hearts
Jack of Hearts
Queen of Hearts
King of Hearts
Ace of Hearts etc...plus error

So I know the correct syntax for str is to use return and not print. But if I use print then I get exactly what I want, all my cards in the deck, except with this error: str returned non-string (type NoneType). If I use return, which is the correct syntax, then when I print my deck all that prints out is the first card, the two of hearts. Why is that?
Comment: Its probably due to returning in a for loop, you might want to try using `yield` instead of return but really this isn't what the str method is for, make a separate function
Answer: Within a method, return can only be executed once, then control returns to the calling code, so you can't have a return inside a loop. One solution is to build the entire string to be printed, then return that.
If you change your code in class Deck to:
def __str__(self):
    return "\n".join(f"{card.rank} of {card.suit}" for card in self.deck)

It will return a string containing the entire deck of cards so that your print functions correctly.
Comment: Thanks! This works great and I really appreciate the explanation as well :)
Answer: You could use a list comprehension to achieve the desired print of your deck of cards.
[f"{card.rank} of {card.suit}" for card in deck]

This statement would create a python list that contains string representations of the cards in your deck. Now we can turn this list of strings into one single string by using the string.join() method, which concatenates the strings in the list and delimits them with the preceding string to join.
"\n".join([f"{card.rank} of {card.suit}" for card in deck])

If you print this you would get:
Two of Hearts
Three of Hearts
Four of Hearts
Five of Hearts
Six of Hearts
Seven of Hearts
Eight of Hearts
Nine of Hearts
Ten of Hearts
Jack of Hearts
Queen of Hearts
King of Hearts
Ace of Hearts
Two of Diamonds
Three of Diamonds
Four of Diamonds
Five of Diamonds
Six of Diamonds
Seven of Diamonds
Eight of Diamonds
Nine of Diamonds
Ten of Diamonds
Jack of Diamonds
Queen of Diamonds
King of Diamonds
Ace of Diamonds
Two of Spades
Three of Spades
Four of Spades
Five of Spades
Six of Spades
Seven of Spades
Eight of Spades
Nine of Spades
Ten of Spades
Jack of Spades
Queen of Spades
King of Spades
Ace of Spades
Two of Clubs
Three of Clubs
Four of Clubs
Five of Clubs
Six of Clubs
Seven of Clubs
Eight of Clubs
Nine of Clubs
Ten of Clubs
Jack of Clubs
Queen of Clubs
King of Clubs
Ace of Clubs

And your complete code is now:
suits = ['Hearts','Diamonds','Spades','Clubs']
ranks = ['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace']
values = {'Two':2, 'Three':3,'Four':4,'Five':5,'Six':6,'Seven':7,'Eight':8,'Nine':9,'Ten':10,'Jack':10,'Queen':10,'King':10,'Ace':(1,11)}

playing = True

class Card:
    def __init__(self, suit, rank):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        print(f"{self.rank} of {self.suit}")

class Deck:
    def __init__(self):
        self.deck = []
        for suit in suits:
            for rank in ranks:
                self.deck.append(Card(suit, rank))

    def __str__(self):
        return "\n".join([f"{card.rank} of {card.suit}" for card in self.deck])

deck = Deck()

print(deck)

Print out objects stored in a list


Empty field message is showing for a few seconds

Question: I am new to jQuery and I'm trying to understand it using a tutorial. I started with registration form validation. I made a script and it's working fine, but message shows for a few seconds. I want message to show until user fills the field again.
<!DOCTYPE html>

<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">

 <form id="form1">
  Name<input type="text" name="fname" id="fname">
  <input type="submit" value="submit" id="submit">
</form>

Comment: you should to use `$('#form1').submit(function() {});` instead of `$("#submit").click(function(){});`
Comment: if tutorial use `click` event, search for other one, this will teach you bad practice.
Comment: Why not use window.confirm popup box rather than changing a p element?  That way you don't have to add extra buttons and can easily add functionality for the yes no
Comment: @ eicto :-you are right i made certain change and i paste it change code now it is fine.please solve the issue....
Comment: @user1817669 now can you please tell me whats your issue?
Answer: Hi do one thing replace below code with your  code

Comment: Hi if you use return true it will submit your form weather you leave the field blank but if you have checked the validation and its true mean you left the field blank in such case you use return false it wont submit your form till you fill up all the field and submit again.
Comment: both are right but what the concept behind that.i want to know
Answer: Better to use <form>'s event, rather than onclick for submit.
Change your script to:

Comment: The reason is, you should not submit the form in the HTML Way. You need to submit using JavaScript. :)
Answer: use return false at the end of your function
$("#form1").submit(function(){
    if ($('#fname').val()=="") {
        //$("#ms").show("slow");
        $("p").html("Are you sure?");
        //$(this).show("Are you sure?");
    }
    return false;
});

and for  your second question use keyup
$('#fname').keyup(function(){
  if(empty($(this).val()))
      $("p").show();
  else
     $("p").hide();
});

however.. i recommend you to use some jquery validation plugins rather than writing your own...


Doesn't the $p$ depend on $m$

Question: Consider the following text:

where $p \in \mathbb Z$. Can you tell me please: doesn't $p$ depend on the $m$? So it is preferable maybe to write $p_m$? Or does $p$ not depend on $m$?
Comment: It does depend upon $m$.
Comment: Quite generally, the phrase "For a fixed ..." usually indicates constants introduced later on depend on that fixed value, unless they're specifically said not to.
Answer: Indeed $p$ does depend on $m$, but adding the extra subscript as you request would be unnecessary notation.  The $p$ is not important, what's important is that $x$ is in an interval of width $\displaystyle\frac{1}{2^m}$.

Doesn't the $p$ depend on $m$


Setting first slide to display using PowerPoint-Api

Question: I use NetOffice.PowerPointApi to play some Powerpoint-Slides of an existing PPTX. This is how this is done:
PowerPoint.Application powerApplication = new PowerPoint.Application();
PowerPoint.Presentation presentation = powerApplication.Presentations.Open("C:\\dev\\test.pptx", MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoTrue);
// presentation.SlideShowSettings.StartingSlide = 2;
presentation.SlideShowSettings.Run();
while (powerApplication.ActivePresentation.SlideShowWindow.View.CurrentShowPosition < 4)
{
   System.Threading.Thread.Sleep(2000);
   powerApplication.ActivePresentation.SlideShowWindow.View.Next();
}

Now my plan was to display slide 3 to 4.
But when I set the startingSlide (commented out in my example) I receive an error on powerApplication.ActivePresentation.SlideShowWindow.View.CurrentShowPosition :

{"SlideShowView.CurrentShowPosition : Invalid request.  There is
  currently no slide show view for this presentation."}

This only happens when I set the property StartingSlide. If I don't, the presentation runs from the first until the 4th slide.
Answer: You need to set more properties of the SlideShowSettings object:
using NetOffice.OfficeApi.Enums;
using NetOffice.PowerPointApi.Enums;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using PowerPoint = NetOffice.PowerPointApi;

namespace PlayPowerPoint
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var app = new PowerPoint.Application())
            {
                var presentation = app.Presentations.Open(Path.GetFullPath("Test.pptx"), MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);

                var slideShowSettings = presentation.SlideShowSettings;

                slideShowSettings.StartingSlide = 2;
                slideShowSettings.EndingSlide = 4;
                slideShowSettings.RangeType = PpSlideShowRangeType.ppShowSlideRange;
                slideShowSettings.AdvanceMode = PpSlideShowAdvanceMode.ppSlideShowManualAdvance;

                slideShowSettings.Run();

                var slideShowView = presentation.SlideShowWindow.View;

                while (slideShowView.CurrentShowPosition < slideShowSettings.EndingSlide)
                {
                    Thread.Sleep(2000);
                    slideShowView.Next();
                }

                presentation.Saved = MsoTriState.msoTrue;
                presentation.Close();

                app.Quit();
            }
        }
    }
}

Comment: Surprisingly after over 2 years I had the same requirement again and you just answered that question correctly :) \o/
Comment: Haha, what a lucky coincidence that I should be randomly browsing all the NetOffice questions yesterday then :-) Good luck with your project!


A tough problem on linear algebra

Question: Suppose $V$ is a finite dimensional vector space over the field $\mathbb C$, and $T \in \mathcal{L}(V)$ is an arbitrary operator operating on $V$. Then $T$ is diagonalizable iff $V=\operatorname{null} (T-\lambda I)\oplus \operatorname{range} (T-\lambda I)$ for all $\lambda \in \mathbb C$.
The first implication is obvious. It is well known that for any operator $T$, $V=\operatorname{null} T \oplus \operatorname{range} T$, so one implication immedaitely follows.
For the secodn implication, i dont know where to start any help is appreciated
Answer: Let $\lambda_1,\ldots,\lambda_n$ be the eigenvalues of $T$. For each $k\in\{1,\ldots,n\}$, let $V_k$ be the generalized eigenspace corresponding to $\lambda_k$. Then $T(V_k)\subset V_k$ and there is some basis $B_k=\{v_1,\ldots,v_m\}$ of $V_k$ such that the matrix of $T|_{V_k}$ is$$\begin{bmatrix}\lambda_k&\eta_1&0&0&\ldots&0\\0&\lambda_k&\eta_2&0&\ldots&0\\\vdots&\vdots&\vdots&\vdots&\ddots&\vdots\\0&0&0&0&\ldots&\lambda_k\end{bmatrix},$$where each $\eta_l$ is either $0$ or $1$. If $T$ is not diagonalizable, there is at least one $k$ such that some $\eta_l$ is $1$. Suppose, for intance, that $\eta_1=1$. Then $v_1\in\operatorname{null}(T-\lambda_k\operatorname{Id})\cap\operatorname{range}(T-\lambda_k\operatorname{Id})$.
Comment: Can you olease explain the proof more simply. I am not getting it fully
Comment: Can you please tell me where are you having problems?
Comment: Like, what are the $v_k$'s mentioned in $T(v_k) \subset V_k$?
Comment: Also why is the matrix like that?
Comment: The expression $T(v_k)\subset V_k$ was due to a typo. What I meant was $T(V_k)\subset V_k$. And to see why there is such a matrix, just take a Jordan normal form of $T$.
Comment: thank you a lot, but any other way except jordan form? We havent been taught that et
Answer: Use Jordan canonical form of the $T$.
Start with letting $T$ is not diagonalisable. Then $T$ has eigenvalue $\lambda$ which has a jordan block of size atleast $2$. Show that for that eigenvalue $\lambda$, $V=\operatorname{Null}(T-\lambda I)\oplus\operatorname{Range}(T-\lambda I)$ doesn't hold.

A tough problem on linear algebra


Ubuntu server dhcp - duplicate leases

Question: So we have an ubuntu server running DHCP & DNS managed through webmin (because it's less effort )
Nothing is BROKEN, but I noticed duplicate leases showing.  Anyone know why and how I can prevent that from happenning?
e.g. this android phone shows twice
10.56.9.120 90:21:55:c9:4b:75   android_200142972d3b1451    2012/01/19 06:17:25 2012/01/19 07:17:25
10.56.9.120 90:21:55:c9:4b:75   android_200142972d3b1451    2012/01/19 06:47:23 2012/01/19 07:47:23

this iMac shows twice :
10.56.9.70  c4:2c:03:06:87:87   host3   2012/01/19 05:58:55 2012/01/19 06:58:55
10.56.9.70  c4:2c:03:06:87:87   host3   2012/01/19 06:28:55 2012/01/19 07:28:55

this laptop shows 4 times, twice for LAN and twice for Wireless
10.56.9.87  ac:81:12:13:a5:ff   host4   2012/01/19 06:14:34 2012/01/19 07:14:34
10.56.9.47  1c:75:08:56:72:ba   host4   2012/01/19 06:14:35 2012/01/19 07:14:35
10.56.9.87  ac:81:12:13:a5:ff   host4   2012/01/19 06:44:34 2012/01/19 07:44:34
10.56.9.47  1c:75:08:56:72:ba   host4   2012/01/19 06:44:35 2012/01/19 07:44:35

Answer: Its normal behavior, and in your case you see different lease times too. Instead of constantly rewriting the entire leases file the dhcp daemon just appends to the end. When it restarts it reads the last records for each entry to build its active database.
Check the second paragraph under the Format topic at dhcpd.leases(5) manpage:
http://linux.die.net/man/5/dhcpd.leases

Ubuntu server dhcp - duplicate leases


What's the musical term for a repeated phrase with shifting emphasis?

Question: For example, a riff/pattern that's three beats long played over 4/4 so that a different part of the phrase is emphasized on each repetition.
This happens briefly in The Killers "Somebody told me", with the phrase "bring it back down" in the prechorus, where the first time "bring" falls on beat 2 but the second time it falls on 1.
I seem to remember there being a specific name for this, but I can't find it anywhere. Anyone know?
Comment: It's the *hemi-* component that makes it specific to x+x/2:x, so we could generalize it with a new term "*n*-ola". :) Or, perhaps they could be described with more words, like *rational polyrhythm*.
Comment: look what you made me do
Comment: I usually hear these phrases referred to as hemiolas, although I don't think that's the correct usage of the term.
Comment: Polyrhythm perhaps?
Comment: @Peter does *hemiola* refer to a 3:2 relationship specifically? Maybe we're looking for a more general term that refers to a similar concept but for any X:Y relationship...
Comment: @topomorto Well, I have heard many musicians refer to repeating rhythms that go across the bar as "hemiola," but my web searching seems to indicate that it refers specifically to 3:2 relationships.
Answer: This is an example of beat displacement. If it occurs repeatedly, it is a form of cross-rhythm (or cross-beat).
Answer: The usual term (from European Medieval and some Indian music) is "isorhythm."
Comment: An isorhythm is a repeated rhythm, but it doesn't have the connotation of going across the bar line, so it doesn't fully answer the OPs question.


What's the relation between real and quaternionic symplectic group

Question: I have read John Baez on symplectic but not understood the relation between the real symplectic group $Sp(2n,\mathbb R)$ and the quaternion group $Sp(n)$. They seem to both have real dimension $n(2n+1)$  which I understand in the real case but not in the quaternion case. I know that there is a matrix representation of a quaternion as a $4 \times 4$ real orthogonal matrix or a $2 \times 2$ complex matrix so that the quaternion case would be isomorph to $Sp(4n,\mathbb R)$ and $Sp(2n,\mathbb C)$ respectively.
Another confusion is how a quaternion inner product decomposes into an orthogonal and symplectic case. This is clear to me in the complex case where the orthogonal structure is the real part and the imaginary part is the symplectic one. The unitary group keeps these two parts invariant seperatly. But in the quaternion case there are three symplectic forms for each of $i$, $j$ and $k$ imaginary parts. What is the equivalent to the unitary group?
Comment: There is a group called the complex symplectic group, of complex dimension $n(2n+1)$, and these are two of its "real forms": the real symplectic group is its so-called split form, which is in some sense as noncompact as possible, and the quaternion group is its compact form, which is as compact as possible.
Comment: Meanwhile I have found [this](http://www-math.mit.edu/~dav/classicalgroups.pdf) where in section 4 titled "Natural Inclusions" the doubling of dimension is described in (4.2). But I'm still confused what exactly Sp(n) is.
Comment: I have found [this](https://www.math.u-psud.fr/~boalch/cours09/hk.pdf) paper which describes the three symplectic forms that confused me on page 33. In section "Quaternionic vector spaces, some group theory 2" it gives an explicit construction of $Sp(n)$.
Answer: As Qiaochu says, there is a complex symplectic group $G = Sp(2n,\mathbb{C})$ and these are both real forms of it. To see this we could consider $\mathbb{C}^{2n}$ equipped with a symplectic form $\omega$. Then a real structure on $\mathbb{C}^{2n}$ is some antilinear endomorphism $\sigma$ with $\sigma^2 =1$, and a quaternionic structure is also an antilinear endomorphism $j$ but with $j^2=-1$. Then we either look at $\mathrm{Fix}(\sigma)\subset\mathbb{C}^{2n}$ which is a real subspace or we view $\mathbb{C}^{2n}$ as $\mathbb{H}^{n}$ using the original complex $i$, our new $j$ and $k:=ij$.
Now for these to give us real forms of $G$ we need these structures to play nicely with $\omega$. The two cases you mention are the real case where $\omega$ descends to a symplectic form on $\mathrm{Fix}(\sigma) \cong \mathbb{R}^{2n}$, and the case that $\omega$ forms a Hermitian inner product on $\mathbb{H}^n \cong \mathbb{C}^{2n}$ (note that there is no non-degenerate symplectic form on $\mathbb{H}^n$). There are a few other real forms ($Sp(p,q)$) where $\omega$ forms "inner products" of various signatures on $\mathbb{H}^n$. The dimension of all these real forms must be the same.
In general we can understand the majority of the real forms of Lie groups by applying some real quaternionic or Hermitian structure in the defining representation of the complex group.
Comment: @Craig Note the basis doesn't fully anti commute but yes that is a problem. $\omega(ia,jb) = ij \omega(a,b)$ but skew symmetry says this is also $-\omega(jb,ia)= - ji\omega(b,a) = ji\omega(a,b)$
Comment: Can you expand or offer references as to your note "there is no non-degenerate symplectic form on $\mathbb{H}^n$"? Is this because of the anti-commuting nature of the basis?
Comment: Wow! Fun, this works for orthogonal structures too! Not only are they degenerate they are identically zero. Thanks :)


How to grant permissions to Network Service to write in a remote location

Question: I need to grant permissions to the Network Service account to write on a different machine on the same network. Can you tell me which permissions I should add?
Thanks!
EDIT
From http://technet.microsoft.com/en-us/library/ms143504.aspx

Services that run as the Network Service account access network resources by using the credentials of the computer account
Answer: Grant rights to the remote resources to the computer account; this will allow for NETWORK SERVICE to access the resources.
Note that for this to work, the systems must be in a domain.
When granting permissions, Computer accounts aren't searched by default.  You'll need to change your search scope in the permission granting dialog:

Then select the computer that the NETWORK SERVICE is running as.
Comment: The "Computers" options is not there. How can I add it? Thanks!
Comment: @Timmy It's not under the object types button?  What is showing there?
Comment: I've added a sentence from msdn that I might be misunderstanding. Doesn't it say that network resource access is possible?
Comment: @Timmy You're absolutely right - I was thinking that was just `SYSTEM`, I was mistaken.  Answer edited.


Could a predictor with a zero correlation to a response be significant in a multiple regression?

Question: Suppose we have a multiple regression with $n$ predictors.  All of them have significant correlations with the response except for one.  Could the predictor with the zero correlation to the response be significant?
Comment: With "zero correlation", do you mean this is true theoretical in the underlying distribution, or do you mean this is true in the actual sample?
Comment: Actually, both cases would be interesting.   I guess if it's only true in the sample, the predictor could still be significant due to some sampling error.
Answer: The prototypical situation in which a variable has a zero marginal correlation with the response, but a significantly non-zero association conditional on the inclusion of the other covariates is called suppression.  There are a number of threads on this topic on CV:

Suppression effect in regression: definition and visual explanation/depiction
X and Y are not correlated, but X is significant predictor of Y in multiple regression. What does it mean?
How can including an IV uncorrelated with the DV improve a multiple regression model?

It is also possible that the variable is not a suppressor, but is relevant and is just 'cancelled out' by another variable with the opposite effect that it is correlated with.  Here are some things to read to help understand that:

Does causation imply correlation?
Is there a difference between 'controlling for' and 'ignoring' other variables in multiple regression?
Comment: very interesting, now I understand that a suppressor could have no explanatory power on response, but  it can strengthen the effect of another predictor.  is it possible to pair up or group predictors so that it would be easy to see what predictors are getting amplified by the suppressor?
Comment: That's a good question, @mss. I'll have to think about it. Generally, you have a specific hypothesis a-priori that you are assessing (or in a predictive model, you just don't care); you don't usually throw in a bunch of variables & try to figure out which is which. Among other things, there are multiplicity issues that way. You could ask a new question about this.
Comment: here is a follow up [question](http://stats.stackexchange.com/questions/245142/is-it-possible-to-identify-an-iv-whose-effect-on-dv-is-being-strengthen-by-a-sup)
Comment: in my particular case it's more of an exploratory analysis and a lot of IVs were thrown into regression. there is an intuitive reason behind each IV.  However, it feels like some of them are not necessary or redundant. I'm trying to see if there is a sound method to drop some IVs.
Comment: @mss, that's a question of feature selection, not primarily about understanding suppression. Feature selection is a very tough issue. Although written in a different context, you might be interested in reading my answer [here](http://stats.stackexchange.com/a/20856/7290). Your best bet for feature selection is to replicate your study or have hold out data in some form.
Answer: Yes, it can happen and even more extreme scenarios might happen.
Think that you have 2 features, the beginning of a period $s$ and its end $e$.
Assume the the concept is the period length $l = (e-s)$ and we will build the data set so both $s$ and $e$ are independent of $l$.
Correlation consider only a single feature and the concept and it will be $0$ (by construction). However, given the start and the end of the period, you have all the information on its length.
Returning to your question, you can build a scenario in which the zero correlation predictor and on of the others predictor sum is the concept. Multiple regression is very suitable to these problems so you can get perfect prediction. That will be even easier if you'll remove all the rest of the predictors.
Comment: You are trying to solve a feature selection problem https://en.wikipedia.org/wiki/Feature_selection There are plenty of methods to cope with the problem (e.g., see here in the tag and at Wikipedia). However, please not that this is an NP-complete problem and we don't have  a fast algorithm to the problem.
Comment: I was trying to see if somehow using the correlation matrix I can do variable selection.  Your simple example clearly shows  that won't work.  I have a regression with a large number of predictors and I'm very surprised to see that almost all of them are significant.  I know that the t-stats could be biased upward for many reasons.  However, assuming there no biases,  what are the ways to determine if all the predictors are truly needed in the regression?


Quando clicar no botão do form 2 atualizar label do form 1

Question: Como posso puxar a label do form1 para o form2 para dar label.Refresh?
Comment: Qual tipo de aplicação?
Comment: WinForms, esqueci de colocar
Comment: https://pt.stackoverflow.com/q/102839/18246
Answer: Quando você instanciar o form 2 ao construir ele (Abrir o form), você precisa passar uma referencia ao objeto do form 1 (Form Anterior), ou seja ter uma propriedade do tipo Form1. Para que no form 2 você chame um método publico que atualize, ou acesse diretamente a propriedade do objeto se ele for publico.
Estudar orientação a objeto ajuda a entender melhor.
Exemplo de como ficaria a classe dos dois Forms:
Form 1
public partial class Form1 : Form
{
    public label labelNome;

    public void AbrirForm2()
    {
        Form2 segundoForm = new Form2();
        segundoForm.form1Reference = this;
    }
}

Form 2
public partial class Form2 : Form
{
    public Form1 form1Reference = null;

    public void EventoQueAlteraLabelDoForm1()
    {
        if(form1Reference != null)
            form1Reference.labelNome.text = "Hello World";
    }
}

Comment: Não entendi muito bem, sou iniciante em c#
Comment: Tentei deixar mais fácil de entender. Você conseguiu ?
Comment: Eu queria editar uma label já existente no Form 1
Comment: Eu obtive este erro: Referência de objeto não definida para uma instância de um objeto.'


How to get upload/download speed with Java

Question: I want to get the current donload/upload speed in Java.
I need some information how I can use the data from /proc/net/dev
[root@laptop ~]# cat /proc/net/dev
Inter-|   Receive                                                |  Transmit
 face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
    lo: 2522296   27390    0    0    0     0          0         0  2522296   27390    0    0    0     0       0          0
  eth0: 206888698752 159544908    0    0    0     0          0      6415 24408080083 127074897    0    0    0     0       0          0
 wlan0: 3008127954 2403692    0    0    0     0          0         0 247504697 2097580    0    0    0     0       0          0
[root@laptop ~]#

I suspect that I have to do do something like this:
CURRENT_Receive - PREV_Receive = current_speed

Can you give me some hint or code example?
Answer: Seems that your problem can be easily solved with bash script (wget -O /dev/null some_url_of_big_file for example). Then, if you want to get the result in your java code, you should create environment variable for it and call System.getenv() in your java code.
Comment: About what? All steps seem to be easily googled. First, you use bash script to define your network speed and store it in environment variable. Second, you use `System.getenv()` to get access to env. variables in your java code.


Showing total of amount in view

Question: I am listing the fee of students in a view developed using views 3. How can I show the total of fee for all records displayed at bottom as Total Fee:
Thanks for your help.
Answer: Sounds like a job for Views Calc.

This module adds simple calculations to a views table. Requires the
  Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug
  in theme makes the view look more spreadsheet-like (right justifies
  numeric fields, shades calculated columns and rows, and underlines
  calculated rows).
Comment: I have used this module it works fine for showing the total but ends up with errors. Some other functionality of my views stops working. Please suggest me something else.
Comment: You're probably better off opening another question and actually listing your errors.

Showing total of amount in view


Get Dynamic Index of Rows

Question: I've created an SQL Query that orders all the rows of a table by a specific way.
Q: How can I get the row number (index?) of a certain row in such a dynamically created list?
Thanks in advance.
Comment: What do you want to do with xth row number?  If you just want a row index, use `row_number() over (order by field1, field2, ...)`.
Answer: SELECT Row_NUMBER() OVER (ORDER BY <your criteria>) as RowIndex, other fields
FROM MyTable

Update:
To add this as a field, you can do:
UPDATE T
SET T.Indexfield = X.RowIndex
FROM MyTable T
INNER JOIN (SELECT Row_NUMBER() OVER (ORDER BY <your criteria>) as RowIndex, other fields
            FROM MyTable) as X
    ON X.<field> = T.<Field>

Comment: This didn't seem to work until I've added parentheses to ROW_NUMBER (-> ROW_NUMBER()). Thanks. How would I go about looping through the rows of the list and, for example, give this new index as a value to a column of that row?
Comment: @Acidic - see edit.  I think update syntax is valid but you may need to change the order
Comment: What does `FROM MyTable T` supposed to mean? I cannot seem to understand it or make it work. Is it an attempt to pass reference to the table to a variable T?
Comment: It's pseudocode.  you need to, you know, put in real table and field names.

Get Dynamic Index of Rows


Opening SQLite .db from assets

Question: Somehow I've got an error of copying a .db file in Log (as you see log in the code)
The napoleon.db file is in the assets folder, so as I assume everything should work, but it doesn't
Why doesn't it find it?
I'm doing it by example, but it doesn't work.
Any thoughts?
public class MySqLiteOpenHelper extends SQLiteOpenHelper{
    private static String DATABASE_NAME = "napoleon.db";
    public final static String DATABASE_PATH = "/data/data/com.example.task/databases/";
    private static final int DATABASE_VERSION = 1;

    private SQLiteDatabase dataBase;
    private final Context dbContext;

    public MySqLiteOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.dbContext = context;
        // checking database and open it if exists
        if (checkDataBase()) {
            openDataBase();
        } else
        {
            try {
                this.getReadableDatabase();
                copyDataBase();
                this.close();
                openDataBase();

            } catch (IOException e) {
                throw new Error("Error copying database");
            }
            Toast.makeText(context, "Initial database is created", Toast.LENGTH_LONG).show();
        }
    }

    private void copyDataBase() throws IOException{
        InputStream myInput = dbContext.getAssets().open(DATABASE_NAME);
        String outFileName = DATABASE_PATH + DATABASE_NAME;
        OutputStream myOutput = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    public void openDataBase() throws SQLException {
        String dbPath = DATABASE_PATH + DATABASE_NAME;
        dataBase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        boolean exist = false;
        try {
            String dbPath = DATABASE_PATH + DATABASE_NAME;
            checkDB = SQLiteDatabase.openDatabase(dbPath, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            Log.v("MyLog", "database does't exist");
        }

        if (checkDB != null) {
            exist = true;
            checkDB.close();
        }
        return exist;
    }

    @Override
    public void onCreate(SQLiteDatabase arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub

    }
}

Comment: whats the error in logcat?
Comment: Error copying database
Comment: do some research first ... and use https://github.com/jgilfelt/android-sqlite-asset-helper
Answer: You should use this DB Path:
if(android.os.Build.VERSION.SDK_INT >= 17){
   DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
else
{
   DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}

For Jellybean 4.2 multi users change:
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
to:
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
Comment: well, the problem is different - instead of list of tables it returns only android_metadata. I'll accept yours because the paths are correct
Comment: It seems like the db is not returning tables. Instead of it says that table name is android_metadata .
Comment: well, it's strange, I just uninstalled app and reinstalled it and the problem is gone. The whole problem, half of day to research, the downvoted question solved only with uninstalling app.. brilliant :(
Comment: would you please give me a little help because I'm not familiar with quiery? I got this : Cursor c = db.query("Org", null, null, null, null, null, null); but also need to add to selecting table named "Org" following: Cursor c = db.rawQuery(" SELECT "+ id + " AS _id") because SimpleAdapter need to have an _id field nesessarily for some reason. How do I combine this 2 into one quiery?
Answer: Use below post learn line by line step to copy db from asset to app memory
http://iamvijayakumar.blogspot.in/2013/11/copy-sqlite-database-file-from-assets.html
Comment: You mean, my question? or you meant answer by this person?  Because I didn't upvote
Comment: @user2976267 . that guys deleted his comment now

Opening SQLite .db from assets


Catia V5 macro to access axis-system inside a geometric set

Question:
Using a Catia V5 macro I want to save axis system and other geometric elements  inside a geometic set to a txt file. I'm able to access the geometric elements like points and lines but not the axis system(Shown in image) .
'Procedure to access the geometic elements inside a geometric set
Dim prtDoc  As Part
Dim hbds As HybridBodies
Dim hbs As HybridShapes
Set hbs = hbds.GetItem(objSel.Item2(1).Value.Name).HybridShapes

To access a geometric element and get its type
MsgBox TypeName(hbs.Item(i))

But how to access the axis system?
Comment: I really don't think you are suposed to have an Axis System inside a geometrical set. Also, what is the selected element you have in your selection?
Comment: Selected element is a Geometrical Set. I want to export all the required data to a text file. Geometric set(CSYS) contains all the data I want as shown in figure.
Comment: My actual geometric set contains lines,  circles, arcs. I'm able to import all except local axis system.
Comment: Check out the answer I posted, see if it helps you.
Answer: Axis Systems can't be found inside a Geometrical Set by looping through child items via the CATIA API.
A hybridBody (Geometrical Set) only contains HybridShapes, HybridBodies and Sketches.
You can see Lines, Points, and such other items because they are all HybridShapes.
As far as I know, the only way of getting the Axis System object inside a Geometrical Set is through the Selection.Search method.
Assuming you have the CSYS Geometrical Set in your selection, you can do the following:
Dim Selection as INFITF.Selection
Dim AxisSystem as INFITF.AxisSystem
'Initialize Selection and other code here
Selection.Search("'Part Design'.'Axis System';sel")
for i = 1 to Selection.Count2
    set AxisSystem = Selection.Item2(i).Value
    '...
Next

Comment: Thank you AugustoQ. Now, I'm able to export the axis system data using search and selection.


Qual e a diferenca entre Kotlin data class e Scala case class?

Question: Em Scala temos case classes, por exemplo:
case class Pessoa(nome: String, sobrenome: String)

e em Kotlin temos data classes:
data class Pessoa( val nome: String, val sobrenome: String )

Qual a diferença entre as duas?
Comment: A resposta resolveu o que procurava saber? Acha que é possível aceitá-la agora? Se não, precisa que algo mais seja melhorado?
Answer: Essencialmente elas são usadas para o mesmo objetivo, ou seja, elas definem um record. Portando elas ganham automaticamente os principais métodos necessários, entre eles os métodos "acessores" para os campos, os de equalidade, hash code, representação textual (toString) e cópia.
Em Scala também são providos métodos de apply() e unapply() para as case classes.
Em Kotlin, nas data classes, são providos métodos que ajudam a seleção de padrões de forma semelhante ao unapply(), ainda que menos poderosos, a linguagem não exige a existência do apply(). Ela também tem métodos "acessores" Java Beans, além dos normais que estão disponíveis para qualquer classe em Kotlin. Não é possível usar herança em registros. Ela exige o uso de var ou val para os parâmetros para indicar que são campos.
Java em versões mais novas tem um mecanismo semelhante chamado record.
Coloquei no GitHub para referência futura.
Comment: Uma coisa interessando do Scala é o método `copy` também.
Comment: https://en.wikipedia.org/wiki/Algebraic_data_type, outro tópico que Scala `case class` se baseiam (não sei à respeito Kotlin).


Atualizar função penas uma vez ao carregar

Question: Tenho o seguinte script:
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function update() {
  for($i=0;$i<300;$i++){ // a cada 300x (5min) faz um refresh
      atualizaLeilao();
      await sleep(1000);
  }
 location.reload();
}

$(document).ready(function () {
    update();
});

A função atualizaLeilao() retorna um status que é definido como: leilao_status
Existem os status 1, 2 e 3. Sabendo os status fiz o seguinte:
if (leilao_status == 3) {

**AQUI A FUNÇÃO NOVA.**

}else{

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function update() {
  for($i=0;$i<300;$i++){ // a cada 300x (5min) faz um refresh
      atualizaLeilao();
      await sleep(1000);
  }
 location.reload();
}

$(document).ready(function () {
    update();
});

}

No caso para o status = 3, eu preciso que ele execute a função atualizaLeilao() apenas uma vez, ou seja, quando a página é carregada ou quando ela é atualizada.
O problema é que para pegar o status é preciso executar a função atualizaLeilao()  antes, sem executar a função antes não tem como saber o status.
Como posso fazer ele buscar o status antes em seguida executar as funções de acordo com as regras?

Tentei dessa forma:
function atualizaLeilao(){
    var leiloes = '';
    $.ajaxSetup({ cache: false });
    $('.itemLeiao').each(function () {
        var auctionId = $(this).attr('title');
        if (leiloes != '') leiloes = leiloes + ',';
        leiloes = leiloes + auctionId;
    });
    if(leiloes){
        $.ajax({
            url: 'get.php',
            dataType: 'json',
            type: 'POST',
            data: 'leiloes=' + leiloes,
            global: false,
            success: function (data) {
                $.each(data, function (j, item) {
                    var leilao_id = item.leilao.id_leilao;
                    var leilao_status = item.leilao.status;

            });
            },
        });
  }
 }
    document.addEventListener("DOMContentLoaded", function() {
    atualizaLeilao();
    });

    if (leilao_status == 3) {

    $(document).ready(function () {
    setInterval('atualizaLeilao()', 300);
    atualizaLeilao();
    });

    } else {

    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
    async function update() {
      for($i=0;$i<300;$i++){ // a cada 300x (5min) faz um refresh
          atualizaLeilao();
          await sleep(1000);
      }
     location.reload();
    }

    $(document).ready(function () {
        update();
    });

    }

Answer: Faz um return leilao_status; na função atualizaLeilao(), algo assim:
function atualizaLeilao(){
   leilao_status = 3;
   return leilao_status;
}

E no if, você compara se o retorno da função é 3:
if (atualizaLeilao() == 3) {

**AQUI A FUNÇÃO NOVA.**

}else{

...

}

Edit
Mas para que o valor retornado da função seja repetidas vezes comparado, você pode incluir o código numa função. Esse if "solto" só irá fazer a comparação 1 vez no carregamento da página. Então o código ficaria assim:
function atualizaLeilao(){
    var leilao_status = item.leilao.status;
    return leilao_status;
}

function checa(){
   if (atualizaLeilao() == 3) {

      var tempo = setInterval('checa()', 300);

   }else{

      clearInterval(tempo);

      function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
      }
      async function update() {
        for($i=0;$i<300;$i++){ // a cada 300x (5min) faz um refresh
            atualizaLeilao();
            await sleep(1000);
        }
       location.reload();
      }

       update();

   }
}

$(document).ready(function(){
   checa();
});

Comment: Não funcionou, eu atualizei a pergunta com a forma que eu tentei fazer.
Comment: Ele até funcionou, carregou a função, mas não obedeceu as regras, não ficou atualizando de acordo com o status.
Comment: Se tiver com status 2 ou 1 ele pode alterar a qualquer momento, mas se já carregar com o status 3 ele não vai alterar.
Comment: Coloquei tudo numa função, veja: https://jsfiddle.net/48owsy99/4/
Comment: Ixi, não ta funcionando não. :/ Atualizei a pergunta com uma parte mais completa da função atualizaLeilao()
Comment: Vc tá querendo ver o status de vários items com o Ajax ou espera receber apenas um?
Comment: Quando acessa um item em uma página, ele carrega esse JS com os dados daquele item. Cada item pode ter um status diferente. Além do status ele pega outras informações também, que não coloquei ali.
Comment: Atualizei o Fiddle. Porque é o seguinte: ao chamar a função que retorna o Ajax, o retorno não é imediato, aí tem que usar um callback .then... Veja o código: https://jsfiddle.net/48owsy99/8/
Answer: tente executar a função atualizaLeilao logo quando o programa carregar, para isso faça algo como:
(function()){
    atualizaLeilao();
}());

Com isso o programa executará a função sem que ela precise ser chamada, assim deverá retornar um status.
Comment: Nao funcionou. Eu atualizei a pergunta com uma forma que eu tentei, quase deu certo.
Comment: Carregou a função, mas não obedeceu as regras, não ficou atualizando de acordo com o status
Comment: oh, vc nao pode definir uma variável fixa dentro da função, ao criar um var leilao_status vc faz com que a variável exista somente enquanto a função é executada, crie-a por fora (sem valor) e dentro da função remova o var, de modo a somente atualizar seu valor
Comment: Hum, tentei tirar o var mas não funcionou também, criei ela dentro da função, sem sucesso.


Same size for multiple plots on different pages

Question: Here is a MWE:
---
output:
    pdf_document
title: Multiple plots on multiple pages
---

\newpage

```{r}
library(ggplot2)
library(cowplot)

p1 <- qplot(1:10,1:10)
p2 <- qplot(1:10,11:20)

myplots  = list(p1,p2)

plot_grid(plotlist = myplots,ncol = 2)
```
\newpage

```{r}
p1 <- qplot(1:10,1:10)
p2 <- qplot(1:10,11:20)

p3 <- qplot(1:10,21:30)
p4 <- qplot(1:10,31:40)
p5 <- qplot(1:10,41:50)
p6 <- qplot(1:10,51:60)

myplots  = list(p1,p2,p3,p4,p5,p6)

plot_grid(plotlist = myplots,ncol = 2)

```

I have 2 plots on the second page and 6 plots on the third page. Because there are 2 plots on page 2,they are bigger in size and there 6 plots on page 3,they are smaller in size.
How can I have that EACH individual plot is the same size on both the pages ?
Answer: You need to manually specify the figure height in R-chunk to fit your needs. In your case, the first chunk for 1-row grid can be set as {r, fig.height = 3} while the second chunk for the 3-rows grid can be set as {r, fig.height = 9}. The number is optional but you must maintain the proportion (in this case 1:3).
Comment: It was the simplest solution that I can think of as long as you don't have to much figure to adjust. You can consider this blog post: http://michaeljw.com/blog/post/subchunkify/ to set a function that can help you do in-line re-chunk with other preferred sizes.
Comment: Many thanks. Is there a way of automating this ?


Translated Nodes Redirect To Homepage

Question: I'm using Drupal 8.6.9 and have four languages setup:

English (Default)
Spanish
German
French

When I create a node of any content type and publish it as each one of these languages, everything seems fine when logged in. When I log out and view these pages they're fine again, but only for the default language. If I try to view a translated version of a node I just get redirected to the site's root back on the default translation.
I'm using URL detection which works when logged in fine.
There are no custom permissions setup and everything is properly published.
I can see that the redirect is a 308 Permanent Redirect from looking at the dev tools.
I've tried rebuilding permissions, clearing the cache etc with no success, any help would be much appreciated!
Thanks
Comment: Are you sure you're just using URL detection?
Comment: @Clive Yes as well as the default 'Selected language' option you cannot disable. I tested disabling 'URL' detection and changing the 'Selected language' to French which worked when logged out.
Answer: Solved. The issue was arising from a change I'd made to the KernelRequestSubscriber where I was redirecting users that hit the homepage that wasn't on the actual root of the site (to stop the homepage from being accessible from multiple routes - duh).

Translated Nodes Redirect To Homepage


Regaining piano skills

Question: I used to play the piano for 6 years between ages 7 and 13. I practised 3 hours a week and had a weekly one hour lesson with a teacher. I played pieces like Beethoven's Fur Elise, Bach's Inventions no.1 and 8, as well as Paul Desmond's Take Five. This put me at about RCM level 7, which is equal to ABRSM grade 5. I had classical training so obviously I also practised scales, arpeggios, etc.
I never really liked classical music though, so after those six years I moved to another teacher mainly focusing on playing pop songs by ear, but after a year I finally quit.
It's been 4 years since I quit playing the piano and haven't touched it since. Lately I started to appreciate classical music, and I really want to get back to playing the piano.
Assuming I get a good teacher, how long will it take me to regain the skills and technique I lost? Thanks
Edit: just a few more questions i:
1) does this previous experience give me an edge over other pianists at the same level as the leveli reached but who gained it later than me?, will this experience help progress faster or is it meaningless?
2)assuming i have regained the technique and level i was before i quit, and suppose we mark begginer as 0% and being able to play liszt's transcription of danse macabre as 100%, where does it put me on that scale?
3)the same as number 2 ut this time we mark being able to accompany opera singers in operas like macbeth, or nabucco using the piano accompaniment from the vocal score as 100%
Comment: Try and see: pick up one of a level 7 practical piece and try to play. You will then see how long you can regain your skills.
Answer: You played piano for a fairly extensive length of time, and reached a fairly high level of playing (Inventions aren't the easiest thing to play), so you would probably jump back into it fairly quickly. The muscle memory from playing never completely disappears, so with consistent (and productive) practice, you could easily reach the skill level you were at, especially considering you worked scales and arpeggios which helps even more.
I would say that with consistent practice you could almost get back to the level you were at within a few months, just don't start with anything too hard that will discourage you. Try starting with something like a beginner or intermediate level sonata.
Answer: It's hard to say for your specific case, but it only took me about six months to get back to where I was when I went back to classical piano, and I didn't have a teacher when I came back to it, and I had a longer break.
I think you'll find the skills come back very fast, but not the stamina. So you have to hold back and slowly build up how long you play every day, even though you will quickly remember the old techniques and songs, you just won't be able to play for three hours at once on your first day without injury.
Answer: Considering your prior level (Inventions, Fur Elise, etc.), prior amount of practice per week (3 hours), amount of time off (4 years), and current age (17?), you should not have any difficulty picking right back up almost within the first month, maybe even 1-2 weeks. Find a good teacher, listen to that teacher, and enjoy. I promise you that what you're doing will pay dividends for the rest of your life in ways you will never predict. Good luck, and keep us posted!
Answer: From my own experience (I've been separated from the piano for 5 years), you'll need one or two months to fully recover. That is something which has stayed in your brain and muscles. As Czerny said : "One should never have to relearn (technique, especially, EdN) what he already had".
Now, I'd say it's even better to step away, from times to times, and you'll see your playing has matured. I assume this is what going to happen here; my guess being you should feel more confident, even if technically less good.

Regaining piano skills


What does the floating point "f" designator signify?

Question: I wonder if someone can clarify what the "f" behind a floating point number is used to signify?
float myFloat = 12.0f;

as apposed to:
float myFloat = 12.0;

I have seen this used many times but its pretty hard to find an explanation either online or in books. I am assuming its either something carried over from another language thats supported for consistency by C or maybe its there as a directive for the compiler when it comes to evaluate the maths.
I am just curious if there is any practical difference between the "f" and using the "." to signify a floating point number?
Comment: The two questions do cover the same ground, if I had to give a difference I might be so bold as to suggest that this question is clearer and better worded, the answer and comments by @paxdiablo are likewise clear and succinct.
Comment: Potential dupe.  Could you clarify how your question might be different than this one: http://stackoverflow.com/questions/3696902/difference-between-2-0-and-2-0f
Answer: It means it's a single-precision float rather than a double precision double.
From the C99 standard:

An unsuffixed floating constant has type double. If suffixed by the letter f or F, it has type float.

Objective-C is based on C, maybe not C99, but this convention has been around in C for a long time.
Comment: ok, I already thought it was, I thought "double myFloat = 12.0;" was double precision.
Comment: No, the `12.0` itself is double. You may _assign_ it to a float (as you do in your question) but it may well lose precision in the process.
Comment: I understand, the actually floating point constant 12.0 is taken to be of type double, which in turn is assigned to a float and may be truncated. Just curious as I have never used "f".
Answer: There are sometimes performance concerns when converting from float to double, and you can avoid them by using the 'f'. Also when doing say a square root, sin,cos, etc, a wild guess would say that
float answer = sqrt(12.0f)
is about 10x slower than
float answer = sqrtf(12.0f)
It really makes a difference on the phone and iPad, if you are doing millions of these kinds of operations. Stay in float if you need speed and can deal with the lower resolution. If you are not good at math, or not using much math in your program use double everywhere, as there are more gotchas when using the lower precision 32 bit float.


Finding text in word both in headings and pages

Question: I am trying to find out if any cutomvariables are used in a document, however I have problems finding out if this is the case if it is defined in header or footer.
Here is my sub that loops through all customVariables:
Sub deleteCustomVarNotInUse()
Dim doc As Document
Set doc = ActiveDocument
 For i = 1 To Documents(doc).CustomDocumentProperties.Count

        If CustomProperties.findProperty(doc, Documents(doc).CustomDocumentProperties(i).name) Then

             'Delete variable...
        End If
Next i
End Sub

Here is the function that I tried to modify from here
Public Function findProperty(doc As Document, findText As String) As Boolean
    On Error Resume Next

    findProperty = False
    Dim rng As Range
    Dim intSecCount As Integer
    Dim intHFType As Integer

    Set rng = Documents(doc).Content
    rng.Find.Execute findText:="DOCPROPERTY*" & findText, Forward:=True
    If rng.Find.found = True Then
        findProperty = True
        Exit Function
    End If

    intSecCount = Documents(doc).Sections.Count
    For intSection = 1 To intSecCount
        With Documents(doc).Sections(intSection)
            For intHFType = 1 To 3
                Set rng = Documents(doc).Sections(intSection).Headers(intHFType).Range
                rng.Find.Execute findText:="DOCPROPERTY*" & findText, Forward:=True
                If rng.Find.found = True Then
                    findProperty = True
                    Exit Function
                End If
            Next intHFType
        End With
    Next intSection

End Function

Answer: This seems to work:
   Public Function findProperty(doc As Document, findText As String) As Boolean
    Dim rngStory As word.Range
    Dim oFld As word.Field

    findProperty = False
    For Each rngStory In doc.StoryRanges
      Do
        For Each oFld In rngStory.Fields
          If oFld.Type = wdFieldDocProperty Then
              'Dig a little deeper and see what the field code contains.
              If InStr(UCase(oFld.Code.Text), UCase(findText)) Then
                findProperty = True
                Exit Function
              End If
          End If
        Next oFld
        Set rngStory = rngStory.NextStoryRange
      Loop Until rngStory Is Nothing
    Next rngStory

End Function


Triangle centers Orthocenter

Question:
An acute $\triangle ABC$, inscribed in a circle $k$ with radii $R$, is
  given. Point $H$ is the orthocenter of $\triangle ABC$ and $AH = R$.
  Find $\angle BAC$. (Answer: $60^\circ$)

$AD$ $-$ diameter, thus $\angle ACD = \angle ABD = 90^\circ$. Also $HBDC$ is parallelogram because ($HC || BD$, $HB || CD$). It seems useless and I don't know how to continue.
Answer: Hint: Let $P$ be the intersection of ray $HE$ with the circumcircle of $\triangle ABC$. Then, $\angle PAC = \angle PBC = \angle FAC = 90^\circ - C$.
It follows that $\triangle PAH$ is isosceles at $A$, and that $AP = AH = R$. Consequently $\triangle APO$ is an equilateral triangle.
Finally, $$\angle PAO = (90^\circ - C) + \angle CAO = \angle OAB + \angle CAO = A,$$
and we are done.
Comment: Why are the angles $OAB=PAC=90-C$
Comment: $\angle OAB = 90 - \angle ADB = 90 - \angle C$.

Triangle centers Orthocenter


php recursive folder readdir vs find performance

Question: i came across few articles about performance and readdir
here is the php script:
function getDirectory( $path = '.', $level = 0 ) {
    $ignore = array( 'cgi-bin', '.', '..' );
    $dh = @opendir( $path );
    while( false !== ( $file = readdir( $dh ) ) ){
        if( !in_array( $file, $ignore ) ){
            $spaces = str_repeat( ' ', ( $level * 4 ) );
            if( is_dir( "$path/$file" ) ){
                echo "$spaces $file\n";
                getDirectory( "$path/$file", ($level+1) );
            } else {
                echo "$spaces $file\n";
            }
        }
    }
    closedir( $dh );
}
getDirectory( "." );

this echo the files/ folders correctly.
now i found this:
$t = system('find');
print_r($t);

which also find all the folders and files then i can create an array like the first code.
i think the system('find'); is faster than the readdir but i want to know if it'S a good practice?
thank you very much
Comment: A system call certainly isn't portable. Your example code is dependent upon a *nix OS.
Comment: It's also a bad idea to get used to using `system()` calls. They should be fine without parameters, but if you construct them dynamically based on user input, you're likely to create bad security holes.
Comment: i have centos 5 with apache and php+mysql that is ok?
Comment: @Inerdial oh i didn't think about that thanks
Answer: Here's my benchmark using a simple for loop with 10 iteration on my server:
$path = '/home/clad/benchmark/';
// this folder has 10 main directories and each folder as 220 files in each from 1kn to 1mb

// glob no_sort = 0.004 seconds but NO recursion
$files = glob($path . '/*', GLOB_NOSORT);

// 1.8 seconds - not recommended
exec('find ' . $path, $t);
unset($t);

// 0.003 seconds
if ($handle = opendir('.')) {
 while (false !== ($file = readdir($handle))) {
  if ($file != "." && $file != "..") {
   // action
  }
 }
 closedir($handle);
}

// 1.1 seconds to execute
$path = realpath($path);
$objects = new RecursiveIteratorIterator(
 new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
  foreach($objects as $name => $object) {
   // action
  }
}

Clearly the readdir is faster to use specially if you have lots of traffic on your site.
Comment: Good answer, but am I missing something... the `readdir()` solution on its own is not recursive. Will this not skew the results?
Comment: How to benchmark individual functions like you, aki?
Answer: 'find' is not portable, it's a unix/linux command. readdir() is portable and will work on Windows or any other OS. Moreover, 'find' without any parameters is recursive, so if you're in a dir with lots of subdirs and files, you will get to see all of them, rather than only the contents of that $path.
Comment: Well, let's put it this way. Speed-wise it won't matter much, but to control behavior of function using find - you'll need to tweak 'find' commandline parameters, rather than using code-way of controlling your function behavior. I, for one, wouldn't go with find, unless there would be a very specific reason to do it.
Comment: Although I see that your function is recursive as well, so ignore the rant about recursiveness. Note though, that output of 'find' is also formatted in a peculiar way.
Comment: i never used windows so it's unix or linux only, for the formating i can deal with
Comment: you saying if i look for files only i can use: `-type f` instead of in the php `is_file` or is_dir?
Comment: Yep, you can do that if you want to look for files only.


How to learn Windows Server Management

Question: I am new to Windows Server Management and have a little experience with linux server management before. Right now, I manage a small network composed of 4 servers shipped with Windows server 2008 r2. We run our property software on those servers and want to monitor the server performance in order to make sure servers hardware are good enough to run those applications. And my questions are:

Do I need to add an active directory role in one of the servers?
PS: Actually, I have skimmed the book windows server 2008 inside out(WSIO), but it seems that it is prepared for large company network and it is such a thick book.
How can I set the MMC to enable monitoring all the servers in one console instead of remote  desktop.
Any easy and good book for Windows Server Management. The WSIO seems a good reference but not a good tutorial.
Comment: Windows administration is not a light topic; hence the very thick books about it. I'd highly recommend bringing in a  consultant or investing the (significant) time to learn how to do it right.
Answer: 1 you can choose to use active directory or not.
active directory extend the security boundry from one server to all servers in active directroy.
but, active directory useful in the large enterprise network.
other hands, you can set the same password for local administrators account of 4 servers.
when user name and password is same in two servers, you can access the logon user in console to other servers as credential of users as the same name.
2 you can use the customized mmc console.
<code>start > run > mmc.exe
</code>
you can show the mmc console. and add the snap-in using .
and, save the mmc console.
actually, you need to install the administration pack. for using that services management snap-in that is not installed on local server.
Please refer the follow link:
Remote Server Administration Tools for Windows 7
http://technet.microsoft.com/en-us/library/ee449475(WS.10).aspx
3 -

How to learn Windows Server Management


Finite State - Understand state transition function

Question: Context: Finite State, State transition system -> state transition function
I'm trying to understand what is being meant by this formula:
$γ:S \times A \times E \to 2^S$
The text above (translated from German into english) says:

How a state can be changed is described by a (yet still unknown)
  function which calculates a possible next state which is triggered by
  an action or an exogenous event.

I understand that $S$ is a set of states, $A$ a set of Actions and $E$ a set of exogenous events but what does $2^S$ say?
Comment: My first impression is that `2^S` means the power set of $S$, the family of subsets of $S$.  It would improve your Question to cite your source.
Answer: $2^S$ is the power set of $S$. $\gamma : S \times A \times E \to 2^S $ means that from a state $s$ the transition system goes to a set of states depending on what action $a \in A$ and event $e \in E$ are chosen. This means that the transition system is nondeterministic because from one state we can go to many different states with the same action and event.
Comment: Here's the Wikipedia page on [nondeterministic finite automata](https://en.wikipedia.org/wiki/Nondeterministic_finite_automaton), which explains the relationship to deterministic finite automata in some detail, i.e. what happens "before 'turning the crank' again".
Comment: I wonder what you do after the 'transition'. I guess you have to pinpoint what it is before 'turning the crank' again. (+1)


Incoherence using Euler's formula

Question: Using the relation $\ e^{ix} = \cos(x) + i\sin(x)$ and substituting for $\ x = \pi$, we have the well-known Euler identity, $ e^{i\pi} = -1$. Substitute also for $ x = -\pi $, we have $ e^{-i\pi} = -1$. So we can say $ e^{i\pi} = e^{-i\pi}$ and taking $\ln$ on both sides, $i\pi=-i\pi$. There is clearly something wrong here. Can some help me to figure out what's wrong?
EDIT :
I actually had a confusing output from my calculator while trying to solve the problem :
Comment: The logarithm _is not_ a function for complex numbers (as you discovered ;-) If you look at the values for $e^{i x}$, you see that it is periodic with period $2 \pi$, so the inverse isn't well defined.
Comment: What do you mean saying _The logarithm is not a function for complex numbers_? My calculator gives me $ln(e^{x*i}) = x*i$
Comment: Then your calculator is doing it wrong. What calculator is this?
Comment: It's TI NSpire CX Cas, the best one as I know.
Answer: $e^{ix}=e^{iy}\implies e^{i(x-y)}=1=e^{2n\pi i}$ as $e^{2n\pi i}=\cos2n\pi+i\sin2n\pi=1$
$\implies x-y=2n\pi$ where $n$ is any integer
Comment: Your calculation can be true if and only if $ln$ be a one-to-one function and $ln$ is not.
Comment: Got your logic but still, can't see why mine is wrong...
Answer: The logarithm is multi-valued.  So we define a branch cut of the logarithm as a principal branch along an axis (or any line) so that we only use one cycle of phase of period $2 \pi$; this keeps that principal branch as a single-valued function.
Answer: In definition of $ln(z)$ for $z\in \mathbb{C}$ we have:
$$ln(x+iy)=ln(|x|)+iArg(y)$$
Since $Arg$ can achive multi values by difference $2k\pi$ so $ln(x+iy)=ln(x+i(y+2k\pi))$.
Answer: Make sure you have the latest software, I am using OS 3.6. Also set calculator  Document Settings Page (Home -> 5: Settings -> 2: Document Settings) on the Real or Complex line - Select Rectangular instead of real. Good Luck Benny

Incoherence using Euler's formula


What are these two file permissions for?

Question: What does UID root and GID root mean?
Difference?
Please give me some examples...
Thanks
Comment: Are you refering to "setuid root" and "setgid root" ?
Answer: UID stands for user ID, and GID stands for group ID. They are numeric identifiers associated by a UNIX or Linux system with an user or group account, respectively (e.g. 0 or 5160). Systems also use human-readable users and groups for convenience (e.g. root or adm).
Users represent an individual person or role, whereas groups represent a collection of people or roles. Each is used by the system to manage who gets access to resources like files, processes, etc.
On many systems, you'll find that users and groups (confusingly) might be named the same thing, even though they have different functions. Also, some people (confusingly) use UID or GID to mean the same as user or group instead of the numeric IDs. You can find all the names and IDs, and how they are mapped to each other in files like /etc/passwd and /etc/group which you can read about in the appropriate man pages.
So, "UID root" (mistakenly) means the root user, and "GID root" (mistakenly) means the root group.
Answer: UID root says the file is owned and fully controlled by the user root.
GID root says that members of the group root can control the file as per the group permissions.
Comment: It could also be the user httpd is impersonating, just going on the question's tags.