Outlook refuses to connect to Exchange

Question: Outlook 2007 under Windows XP connecting to Exchange 2003 SP2: when started, it flips back and forth between "Connecting to Exchange Server" and "Disconnected" three or four times, then gives up and stays disconnected.
I tried deleting the ost file (which was nearly 2GB), turning Cached mode on and off, recreating the account inside the Mail control panel, changing the account to use HTTP, and probably some other things.  None of it seemed to make any difference, until …
After fiddling with it for a while, I got this absurd error message dialog at startup, and it exits after I click OK:

Cannot start Microsoft Office Outlook. Cannot open the Outlook window. The set of folders cannot be opened. Microsoft Exchange is not available. Either there are network problems or the Exchange server is down for maintenance.

(I'm not sure if I can even trust that message.  It's so long, it just feels like a random offset into Outlook's stack of error messages.)
Either way, the Exchange server is available to everyone else, and is available via OWA from that computer.  I ran Process Explorer against Outlook and it showed 5 or so ESTABLISHED connections to our Exchange server, plus listening on two UDP ports, and two CLOSE_WAIT connections to localhost.  If I managed to look at Outlook's IP connections while it was doing its Connecting/Disconnected dance, it had a huge number of connections open to the Exchange server.  It more than filled ProcExp's dialog box; I'm guessing at least 20, probably more.
The only other odd thing is that our network admin at some point added a wildcard DNS record to the domain name that we use for email, and now Outlook will sometimes (always?) start by complaining about autodiscover.example.com's SSL certificate.  There is a web server there, but it doesn't have any sort of email autodiscover anything on it.  It doesn't make any difference if I click "OK" or "Cancel" (or whatever the buttons are).  I also added a bogus entry for the hostname to Windows' hosts file, pointing it at 127.0.0.2, and it stopped complaining about the certificate.  (The CLOSE_WAIT sockets above were from before I made this change, and went away after.)  I don't think this is related, as the same problem should exist for everyone, but it might be.
This is the second time this user has had this problem.  The first time, I never found a solution other than reinstalling Outlook.  Now that it's a pattern, I'd like to find a permanent solution, rather than assume it's a random glitch.
Edit:
The user's Outlook started working again, partially, last night while at home connected to the office via VPN.  It's unclear how much of the "partially" is due to me screwing around with his account settings.  Probably a large portion.  That said, once I recreated his account settings properly this morning, he says that a large number of folders were moved around.  Honestly, this feels to me like user error, but it might also be a symptom of the problem.
I'll have to come back to this if and when the problem crops up again.
Comment: Have you tried creating a new Outlook profile?
Comment: No, I didn't try a whole new profile.  That's something to check.
Answer: Sounds like you may have hit the 32 connections limit with Exchange 2003.  We've been battling that for years without a fix for some users.  A reboot of the Exchange server will clean up the connections, but I've got no clue what causes it for some users.
Comment: Do you have a link for this "32 connections limit"?
Comment: Check the server logs for this:

http://support.microsoft.com/kb/842022
Answer: Simple..Just open  outlook from the 'run' command using the command line 'Outlook.exe /profiles'. The profile screen will come up...go through the advanced options and create new profile ,name it and make it the default option(very imp or u will have the same problem again!) and your outlook will open up. Once there, you can then see your corrupt profile and delete or view it and create new connection settings for your new profile. Had to try lots of stuff before i found this solution. I know how frustrating this can be so good luck guys!Post back if it works for you!
Answer: Had this problem before and I really had a hard time getting answers for this. I found some simple trick on the net to make it work. Try disable then re-enable your NIC or flushing your dns then registering it again. But this problem will occur again if your restart your pc. I almost lost hope til I had this crazy idea. On your TCP/IP settings, i put the IP of my mailserver to WINS server settings then the problem just went away. I still dont know how did that resolved the problem so I'm still researching to get a clearer answer.
Answer: I've seen the same things happen when DNS isn't working quite correctly.
Check DNS settings on the client, it should only have internal AD/DNS servers listed. Check on the Exchange server, should be the same (internal DNS servers only). Check the DNS records to be sure that whatever the exchange server's name is (the A record/s) correct, and there are no "extra" entries or anything strange there.
Do you have a WINS server, if so check records in there, make sure they match DNS. Again if you have a WINS server, is WINS-to-DNS configured? And is DNS-to-WINS configured?
Comment: If and when the problem recurs, I'll definitely check this.
Comment: Definitely sounds like a DNS problem, especially if it mysteriously started working when the user opened a VPN connection (which would have changed/reset DNS settings).  If the problem recurs: can the user nslookup exchange-hostname?  What about exchange-hostname.yourdomain?
Answer: I'd run a repair on Office. You are getting errors relating to general functionality as well as connection errors.

Outlook refuses to connect to Exchange


How to get time labels of silence periods in a file

Question: Can someone advise a way how to automatically (with a script) get a list of time labels for periods of silence in an audio file?
Such a list can be obtained with the help of Audacity, but it seems there is no way to easily automate this task.
The list can be in any format. Moreover, it can even be a list with averaged (RMS?) for some time window sample values for the whole file, from which silence periods can be detected.
Comment: This sounds like it would be a better fit for [Signal Processing](https://dsp.stackexchange.com)
Comment: Before posting here I checked that site and thought that this site is more appropriate: every music program has features related to silence (generating, removing...) so there are probably users of such programs who know how to do that. But if moderators decide to move this question, that's OK.
Comment: If you have any programming experience, and the audio is in an uncompressed format, it shouldn't be too difficult to programme a simple command-line tool yourself.
Comment: @Bob Seems like a good idea. I work with mp3 files, but I can convert them to raw audio with SoX.
Comment: "it seems there is no way to easily automate this task" Have you looked into Audacity's Macros?
Answer: There are a few tools to do this but you might need to do a bit of work to install them.

Aubio is a useful library https://aubio.org/manual/latest/cli.html#aubioquiet
Sox can't but ffmpeg can - see this answer
Essentia is a heavy duty library but has some command line tools available https://essentia.upf.edu/extractors_out_of_box.html The extractor you would need is https://essentia.upf.edu/reference/std_StartStopSilence.html
Answer: Try java sound api.
Check the following url for examples.
Java Sound Resources: Examples: A - Z
Comment: The most appropriate section seems to be [this](http://jsresources.sourceforge.net/faq_audio.html#silence_supression), but it is of limited use besides introducing the term *noise gate*.


Views Grouping field:Add Ordered class to Grouping row

Question: I use Views and Grouping field to integrate my data.
But i need each grouping row ordered.
I want to override the views-view-grouping.tpl.php, and change the "view-grouping" class to "view-grouping-1","view-grouping-2","view-grouping-3"...
The original code is belowed:
    <?php

/**
 * @file
 * This template is used to print a single grouping in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $grouping: The grouping instruction.
 * - $grouping_level: Integer indicating the hierarchical level of the grouping.
 * - $rows: The rows contained in this grouping.
 * - $title: The title of this grouping.
 * - $content: The processed content output that will normally be used.
 */

?>

<?php print $title; ?>

    <?php print $content; ?>

The File is located at all/module/views/theme/
Does someone meet the same problem before?
Thx for help.
Answer: Javascript?

$('.view-grouping').each(function(i){
  $(this).addClass('view-grouping-' + (i+1));
});


Sin Cos equation help

Question: Can you please help me prove that this equation is true?
$$\left(1- \frac{2\tan(x)}{\sin(2x)}\right)^2 = \left(1- \frac{2\tan(x)}{\tan(2x)}\right)^2$$
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognize and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: Please edit your question to include your attempts and ask a specific question where you get stuck. There is an obvious first step you should be taking without asking us.
Comment: @user2661923 It's correct. Without squaring both sides, it is not.
Comment: Sin Cos equation but there is no Cos?
Answer: I am assuming you are familiar with half and double angle formulae(especially manipulation in terms of $\tan(\theta/2)$,
we shall be using the following formulae for the proof :-
$\sin2x = \frac{2\tan x}{1+\tan^2(x)} $
$\tan2x = \frac{2\tan x}{1-\tan^2(x)}$
Now to prove the following relation,

Substitute $\sin2x$ and $\tan2x$ on the LHS and RHS of the equation

We notice that the $2\tan x$ terms get cancelled leaving us with:
$(1-(1+\tan^2(x))^2 = (1-(1-\tan^2(x))^2$

Opening the parentheses, this simplifies to:
$(-\tan^2(x))^2 = (\tan^2(x))^2$

We may absorb the negative sign on the LHS, leaving us with:
$\tan^4(x) = \tan^4(x)$
Hence proving that the relation is true.
Hope this helps!
Comment: You are also requested to learn the formatting method of [mathjax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Comment: Hello and Welcome to Mathematics StackExchange. You are requested not to answer low quality questions which show no effort on the asker's part, as outlined by the recent [Enforcement of Quality Standards](https://math.meta.stackexchange.com/questions/33508/enforcement-of-quality-standards).
Comment: Thanks @MrKaushik, seems like this is a good way to prove. :)

Sin Cos equation help


How to display the created_at in words in an article on Rails

Question: I'm new into coding and even more new with Rails.
I'm trying to create a simple blog application, I've the articles list on the index with their title, content and created at (I used time_ago_in_words for this) however, when I try to use it inside the show view of an article it returns me an error.
With <%= @article.created_at(time_ago_in_words) %> it returns

wrong number of arguments (0 for 1..2) on the line

Posted by Author <%= @article.created_at(time_ago_in_words) %>

With <%= @article.time_ago_in_words(article.created_at) %> it returns

undefined local variable or method `article' for #<#:0xb4ba430c> on the line

Posted by Author <%= @article.time_ago_in_words(article.created_at) %>

My articles controller
class ArticlesController < ApplicationController

    def index
        @articles = Article.all.order("created_at DESC")
    end

    def show
        @article = Article.find(params[:id])
    end

    def new
        @article = Article.new
    end
end

So I would like to know what is the properly way to display the created_at date but in words, because if I use <%= @article.created_at %> it works fine but the date it returns something like 2015-08-17 15:49:11 UTC which doesn't seems good.
Any help is highly appreciated.
Comment: It is more effective to read [documentation](http://apidock.com/rails/ActionView/Helpers/DateHelper/time_ago_in_words) than to shuffle code until it works (which you didn't manage to pull off here, anyway)
Answer: The correct syntax is <%= time_ago_in_words(@article.created_at) %>


(Co)homology of HNN extensions

Question: Let $G$ be a group with a subgroup $A$, and let $\varphi:A\rightarrow G$ be any injection. The HNN extension with base $G$ and associated subgroups $A$ and $\varphi(A)$ is defined as $$G^{\ast}=\langle\; S_{G},\; t\;|\;R_{G},\;t^{-1}at=\varphi(a),\;a\in A\;\rangle,$$
where $\langle\; S_{G}\;|\;R_{G}\;\rangle$ is a presentation for $G$.
Is there any method or theorem that one could use to compute the (co)homology of $G^{\ast}$?
Comment: I don't know...but have you looked in Ken Brown's book?
Comment: If you have a $K(G,1)$ and a $K(A,1)$, Hatcher's Algebraic Topology (Section 1.B) gives a construction of a $K(G^*,1)$ using mapping cylinders.  You may be able to use that to compute the cohomology.
Answer: Let $\varphi,\psi: A\to G$ be two embeddings of a group $A$ to a group $G$ and denote by $G^*$ the corresponding HNN-extension. Robert Bieri in his article proved that  for any $G^*$-module $M$ there are long exact sequences for homology
$$
 \to H_n(A,M) \to H_n(G,M) \to H_n(G^*,M) \to H_{n-1}(A,M) \to
$$
and cohomology
$$
\to H^n(G^*,M) \to H^n(G,M) \to H^n(A,M) \to H^{n+1}(G^*,M) \to
$$

(Co)homology of HNN extensions


Flags: flagging unflagging rules, how to check if an user has already flagged a node?

Question: I'm using Drupal 7 and I created 3 flags for article content type; these flags are global flags: bad, nice and cool. Now, I want create a rule in order to check if an user has already flagged an article.
For example: a user flags article as bad.
Now the user wants to flag the same article as nice.
Theoretically, the user must unflag bad and flag nice.
I want a rule that check if the user has already flagged a node; if yes, the previous flag must unflagged.
In Rules there are Rules Conditions that can execute php code, but flag api, has a $flag-is_flagged function that checks if an user flagged a node only if the flag is non-global flag.
Any idea?
Answer: What you're trying to achieve (= allow users to flag nodes by one out of 3 flags), is by design NOT something you can implement by using a global flag. Because global flags cannot be used by individual users. So I suggest you rethink/rework the design of those flags, so that they are NOT defined as global anymore. After you do so, you should be able to implement what you're trying to do, by using the Rules module, and with no need for PHP code. Read on for more details on how to do so.
Have a look at this rule (in Rules export format):
{ "rules_unflag_related_flags" : {
    "LABEL" : "Unflag related flags",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag" ],
    "ON" : { "flag_flagged_this_is_nice" : [] },
    "IF" : [
      { "flag_flagged_node" : {
          "flag" : "this_is_bad",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ]
        }
      }
    ],
    "DO" : [
      { "flag_unflagnode" : {
          "flag" : "this_is_bad",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

Some details about the above rule:

Rules Event: A node has been flagged, under "Nice".
Rules Condition: The flagged node is flagged with flag "Bad", by the flagging user.
Rules Action: Unflag the flagged node, for flag "Bad", by the flagging user.

You should be able to import the above rule in your own site, provided you first adapt the machine names of both flags (this_is_nice and this_is_bad) to fit your own machine names.
If nice is not sufficient (and it should be cool also ...)
If you want to implement similar logic for the "cool" flag, you can rework the Rules Condition and Rules Action in the sample rule above towards a Rules Component (say you name it "Disallow BAD flag"), and remove them from the rule shown above. Then clone this Rules Component towards a similar one for the "Cool" flag  (say you name it "Disallow COOL flag"), in which you change all "bad" to "cool". And finally invoke both Rules Components via an extra Rules Action (1 for each) in the sample rule above.
Or you can use the Conditional Rules module to consolidate both rules in a single rule. Here is a variation of the above rule (using flags with machine names this_is_nice, this_is_bad and this_is_cool), to illustrate how such rule would look like:
{ "rules_unflag_related_flags" : {
    "LABEL" : "Unflag related flags",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "flag" ],
    "ON" : { "flag_flagged_this_is_nice" : [] },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "flag_flagged_node" : {
                "flag" : "this_is_bad",
                "node" : [ "flagged-node" ],
                "flagging_user" : [ "flagging_user" ]
              }
            },
            "DO" : [
              { "flag_unflagnode" : {
                  "flag" : "this_is_bad",
                  "node" : [ "flagged-node" ],
                  "flagging_user" : [ "flagging_user" ],
                  "permission_check" : "1"
                }
              }
            ]
          },
          {
            "ELSE IF" : { "flag_flagged_node" : {
                "flag" : "this_is_cool",
                "node" : [ "flagged-node" ],
                "flagging_user" : [ "flagging_user" ]
              }
            },
            "DO" : [
              { "flag_unflagnode" : {
                  "flag" : "this_is_cool",
                  "node" : [ "flagged-node" ],
                  "flagging_user" : [ "flagging_user" ],
                  "permission_check" : "1"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

Easy, no?


AUC for more than two groups?

Question: Standard ROC curves look at how setting various thresholds on a continuous measure can be used to predict a two-level ordinal outcome (example: antibody level -> (not sick, sick) ). This can then be integrated over the whole range of thresholds yielding the classical Area Under the Curve (AUC).
The AUC has an interesting alternative definition: it is also the probability that, for a given pair of subjects, the continuous measure will rank them correctly with respect to the ordinal outcome.
In the case where this ordinal outcome has more than two levels (example: not sick, a little sick, very sick) , this alternative definition can be used to get a natural generalization of the concept of AUC.
My question is: does this generalization have a name? Is it a standard or at least known measure? Are there any more widely used alternatives?
Comment: This paper : http://link.springer.com/article/10.1023/A%3A1010920819831#page-1 has a very similar approach, but considers the case where the output classes are not ordered and thus gives a different expression.
Answer: I'm no expert, but I have recently read a paper exploring some of the AUC extensions to multiclass.  They called their extension Volume Under the ROC Surface and they also explored some other extension options.  Here's a direct link to the work of Ferri et al:
Volume Under the ROC Surface for Multi-class Problems
Comment: If I understand correctly, the problem they tackle is a bit different (and more complicated), since they seem to assume any classifiers working on any inputs, whereas I use the original ROC curve with a single scalar input and the trivial threshold classifiers. Good finding anyways, thanks!

AUC for more than two groups?


Best rigorous book on probability theory for ESL

Question: I know this is similar to many questions asked here before, but I couldn't find question that addressed what I need.
I started ESL but I'm having a lot of trouble with the probability theory part of it. I have taken a statistics which covered all the basic concepts but it wasn't very rigorous so I'm having trouble getting through the book.
So, can someone recommend a good comprehensive book on probability theory to go through before tackling ESL?
Comment: I'm assuming "ESL" stands for "Elements of Statistical Learning". A free and online book that I've personally used is https://probabilitycourse.com/
Answer: I found "A First Course in Probability" by Ross the most interesting intro to, well, a first course in stats.
Comment: How would this compare to 'Probability and Measure by Billingsley'? I was considering that one too.
Comment: I think that Ross's is more friendly, with real-life examples, while Billingsley's seems to be more mathematically profound. I think that it is up to you, your enthusiasm and background. Reading each of them cover to cover will give you a lot.


Lowering the key of the song Drive by Incubus

Question: I don't have a lot of knowledge of music theory and I am trying to learn all by myself online. I am trying to play and sing the song Drive by Incubus on my guitar. The original song seems to be in the key of G. The chords for verse and chorus of the song in this key are: [ Em - Em9 | Cmaj7 - Em/A (slash chord) ]. In the pre-chorus, the chords are: [ Cmaj7 | A ].
This key is too high for my voice and I want to lower it by two keys to the key of E. I am trying to use the following chart to find the chords in the key of E.

If we can simply transform the chords using this chord chart, I think the chords in the key of E should be, for the verse and the chorus: [ C#m - C#m9 | Amaj7 - ? ] (I am not sure how to transform the slash chord!). In the pre-chorus, I think the chords should be: [ Amaj7 | F#7 ].
Is this the correct way to change keys for a song? What am I doing wrong? What should the correct chords be for this song, if I want to go down two keys?
Thanks!
Comment: You are doing things correctly. Every chord, including the lower part of slash chords, should be lowered by the same amount.
Comment: So the slash chord in the key of E should be C#m/F#?
Comment: Yes, C#m/F# is correct.
Comment: Lowering from G to E would be lowering it "three keys" (though I'm not sure that's standard terminology)- G down to F# down to F down to E.
Comment: Hmmm...perhaps its better to speak in terms of lowering by steps or tones? So G to F# is lowering by a half-step and so on.
Answer: When transposing a chord chart, each letter name must be changed by the same interval, which is to say, the same number of half steps. This includes both sides of a slash chord.
Lowering from G to E -- a minor third, or three half-steps -- is indicated correctly in the question: Em becomes C#m, and Em/A becomes C#m/F#.
Answer: If you make a grid of the chromatic scale, i.e. A A# B C C# D D# E F F# G G#
Repeat the grid downwards, forming a complete square, A# B C C# D D# E F F# G G# A and so on.
So if for instance we change the key from A to A#, and say the chord sequence is A /G /D
Then we track down the grid and the chords would be A# / G# / D#. Now if by chance the chords are Am or A7, you just transfer that as well. So say the A chord is an A7, then in the new key it would be an A#7. And if say it was an Am, then in the new key it would be an A#m.  Scan the grid downwards until you find the key you want to change your song to.  Then track along the top to find the chords in the song.  Hope this helps.  It's simple when you grasp it.  Cheers.
Comment: Can you post a picture of the grid you suggest using?


While dentro de outro While (PHP - SQL)

Question: Dei uma buscada no forum e na internet, porem não consegui resolver o problema ainda! Eu estou fazendo uma consulta no banco pelo PHP e buscando usuarios. Depois que busco os usuarios eu busco as formações academicas dele dentro dessa outra busca (pois pode haver mais de uma) com isso o segundo while funciona apenas no primeiro usuario, no segundo em diante ele parece que "para".
Seguem meus codigos:
Busca usuarios

$query_busca_prof = "SELECT * FROM tags, user WHERE tag_tag LIKE '%$busca%' AND tag_user = user_id";
$Busca_busca_prof = mysql_query($query_busca_prof, $bd) or die(mysql_error());
$row_busca_prof = mysql_fetch_assoc($Busca_busca_prof);
$totalRows_busca_prof = mysql_num_rows($Busca_busca_prof);

Imprimir Usuarios e formação

do {

    $query_busca_forma = "SELECT * FROM user_prof_forma WHERE user_prof_forma_user = '".$row_busca_prof['user_id']."'";
    $Busca_busca_forma = mysql_query($query_busca_forma, $bd) or die(mysql_error());
    $row_busca_forma = mysql_fetch_assoc($Busca_busca_forma);
    $totalRows_busca_forma = mysql_num_rows($Busca_busca_forma);

    echo $row_busca_prof['user_nome'];

    do {

        echo $row_busca_forma['user_formacao'];

      } while ($row_busca_forma = mysql_fetch_assoc($Busca_busca_forma)); // este que não funciona

} while($row_busca_prof = mysql_fetch_assoc($Busca_busca_prof));

Obrigado pela atenção!
Comment: Um join ou mais não mata esses whiles encadeados? Não use funções obsoletas ou vai ter o trabalho de atulizar o código depois.
Comment: parece que o erro esta no `while`, voce fala para realizar a ação quando for `=` ou seja, só 1x e ele vai ficar igual, tente substituir por `<` ou até mesmo fazer o while com uma contagem usando o `mysql_num_rows`
Comment: vou colocar a resposta e voce confirma ok @LeonardoCarmo ?
Comment: @DiegodeSouzaSilva É que eu simplifiquei o html, então join nao iria resolver, porque a estrutura eu preciso que faça a impressão separadamente! Mas já entendi agora rs
Comment: @rray não entendi muito bem o que você quis dizer!
Comment: Faça como o rray falou, se vc usar join vc pode evitar esses whiles desnecessários
Comment: Na sua variável "$query_busca_prof" está a consulta sql. Use join nela para vc evitar esses while, é lógico que vai ter que mudar o código acima...
Comment: @Leonardo, o rray quis dizer que um jeito mais apropriado é uma query SQL com JOIN (LEFT JOIN, RIGHT JOIN, etc.. ) . Assim eliminaria esses laços de repetição.
Comment: @DanielOmine entendi! E se eu colocar meus selects você acha que conseguiria me ajudar? Porque não sei como poderia fazer um unico select e trabalhar com html diferenciado para cada resultado depois, sendo que podem ser mais do que um
Comment: poste os selects aí.
Comment: @DanielOmine editei lá!
Comment: não entendi o trecho `'%$busca%' AND tag_user = user_id`. O campo `user_id` vem de onde? Não seria uma variável PHP?
Answer: o comando mysql_fetch_assoc() é o comando que adquire um registro a partir de uma query executada. Ele precisa ser executado iterativamente:
while($row_busca_forma = mysql_fetch_assoc($Busca_busca_forma)){
    // Faça suas atividades aqui dentro
}

Seu código só funciona para o primeiro registro exatamente porque você só está executando o mysql_fetch_assoc apenas uma vez.
Leitura recomendada: Por que não devo usar mysql_*
Comment: Obrigado pela recomendação, vou ler!
Answer: Na realidade o Jeito correto de colocar várias linhas de uma busca dentro de um array, é com um while, dessamaneira:
$query_busca_prof = "SELECT ...";
$result= mysql_query($query_busca_prof, $bd) or die(mysql_error());

$array_content = array();

while ($row = mysqli_fetch_array($result, MYSQL_ARRAY))
{
    $array_content[] = $row;
}

Do jeito que você está fazendo, você apenas pega a primeira linha e coloca no array, você pode checkar isso imprimindo o array em questão.
Comment: Utilizei desta forma mas não esta imprimindo nada!
Comment: @LeonardoCarmo no teu caso, você teria que fazer isso para os dois while que fez... É que agora estou no trabalho, mas vou reescrever o código para comportar melhor a tua situação.
Answer: Quando você declara no seu while($row_busca_forma = mysql_fetch_assoc($Busca_busca_forma) ele só ira executar uma vez para que o resultado seja igual =, logo...ira parar a execução.
Tente colocar um sinal de menor ou igual <=, por exemplo;
while($row_busca_forma <= mysql_fetch_assoc($Busca_busca_forma)
Comment: Resolveu exatamente como eu precisava! Obrigado!
Comment: @LeonardoCarmo, marque como resposta correta por favor.
Comment: Preciso esperar 5m!
Comment: Agora que testei mais vi, na verdade não resolveu 100%! Se possui 2 registros ele não coloca os corretos, ele repete o mesmo duas vezes!

While dentro de outro While (PHP - SQL)


Fragment erro "Unable to start activity"

Question: Minha aplicação da erro ao abrir em um tablet e não consigo identificar o erro ele informa que tenho que habilitar:

Unable to start activity
  ComponentInfo{com.example.everton.horoscopo/com.example.everton.horoscopo.MainActivity}:
  android.view.InflateException: Binary XML file line #15: Binary XML
  file line #15: Error inflating class fragment.

Não entendi o erro segue os código se alguém pode me ajudar agradeço.
Minha main activity
package com.example.everton.horoscopo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.example.everton.horoscopo.fragments.HoroscopoDetailFragment;

public class MainActivity extends AppCompatActivity implements OnHoroscopoClickLlistener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private boolean istablet() {
        return getResources().getBoolean(R.bool.tablet);

    }

    private boolean isSmartphone() {
        return getResources().getBoolean(R.bool.smartphone);
    }

    @Override
    public void onMovieClick (long id){
        if (isSmartphone()) {
            Toast.makeText(this, "bbb " + id, Toast.LENGTH_SHORT).show();
            Intent it = new Intent(MainActivity.this, HoroscopoDetailActivity.class);
            it.putExtra("Horosc", String.valueOf(id));
            startActivity(it);

        } else {
            HoroscopoDetailFragment horoscopoDetailFragment = new HoroscopoDetailFragment();
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.frag_detalhe, horoscopoDetailFragment)
                    .commit();
        }
    }
}

o xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.everton.horoscopo.MainActivity">

    <fragment
        android:layout_width="390dp"
        android:layout_height="match_parent"
        android:name="com.example.everton.horoscopo.fragments.HoroscopoListFragment"
        android:id="@+id/fragmentLista"/>

    <fragment
        android:layout_width="409dp"
        android:layout_height="match_parent"
        android:name="com.example.everton.horoscopo.fragments.HoroscopoDetailFragment"
        android:id="@+id/fragmentDetail"/>

</FrameLayout>

e o erro
10-09 16:50:34.702 23809-23815/? E/art: Failed sending reply to debugger: Broken pipe
10-09 16:50:35.111 23809-23809/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.everton.horoscopo, PID: 23809 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.everton.horoscopo/com.example.everton.horoscopo.MainActivity}: android.view.InflateException: Binary XML file line #15: Binary XML file line #15: Error inflating class fragment
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
   at android.app.ActivityThread.-wrap11(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:148)
   at android.app.ActivityThread.main(ActivityThread.java:5417)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #15: Binary XML file line #15: Error inflating class fragment
   at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
   at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
   at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
   at com.example.everton.horoscopo.MainActivity.onCreate(MainActivity.java:17)
   at android.app.Activity.performCreate(Activity.java:6237)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
   at android.app.ActivityThread.-wrap11(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:148)
   at android.app.ActivityThread.main(ActivityThread.java:5417)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #15: Error inflating class fragment
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
   at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
   at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
   at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
   at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
   at com.example.everton.horoscopo.MainActivity.onCreate(MainActivity.java:17)
   at android.app.Activity.performCreate(Activity.java:6237)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
   at android.app.ActivityThread.-wrap11(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:148)
   at android.app.ActivityThread.main(ActivityThread.java:5417)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
   at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
   at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
   at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
   at android.database.CursorWrapper.getString(CursorWrapper.java:137)
   at com.example.everton.horoscopo.fragments.HoroscopoDetailFragment.onCreateView(HoroscopoDetailFragment.java:50)
   at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)
   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1230)
   at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1332)
   at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2288)
   at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
   at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:356)
   at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
   at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:754)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
   at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
   at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
   at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
   at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
   at com.example.everton.horoscopo.MainActivity.onCreate(MainActivity.java:17)
   at android.app.Activity.performCreate(Activity.java:6237)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
   at android.app.ActivityThread.-wrap11(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:148)
   at android.app.ActivityThread.main(ActivityThread.java:5417)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Answer: Pessoal desculpa a demora pra responder é que estava sem tempo para ve. Resolvi o problema. O problema era que no main activity não estava passando o Bundle para a classe do detail fragment segue a solução:
Main activity
 frag = findViewById(R.id.fragmentDetail);
           HoroscopoDetailFragment horoscopoDetailFragment= HoroscopoDetailFragment.newInstance(id);
            horoscopoDetailFragment.teste(true);
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragmentDetail, horoscopoDetailFragment)
                    .show(horoscopoDetailFragment)
                    .commit();

inicialmente passei o Bundle pela main mas depois criei um metodo e passei por la.
DetailFragment
 public static HoroscopoDetailFragment newInstance(long id) {
    Bundle args = new Bundle();
    args.putString("Horosc", String.valueOf(id));
    HoroscopoDetailFragment horoscopoDetailFragment= new HoroscopoDetailFragment();
    horoscopoDetailFragment.setArguments(args);
    return horoscopoDetailFragment;
}

Obrigado a todos pela ajuda.
Answer: No seu .xml consta desta forma R.id.fragmentDetail e na sua classe você chama R.id.frag_detalhe. Tente conferir e colocar corretamente os identificadores pois estão com ids diferentes.
Outro possível erro está no .xml no qual você define o nome do seu fragment.
android:name="com.example.everton.horoscopo.fragments.HoroscopoListFragment"

Tente alterar para class.
class="com.example.everton.horoscopo.fragments.HoroscopoListFragment"

Answer: Olá, Everton
Vamos observar o trecho abaixo onde você infla o fragment em sua activity:
HoroscopoDetailFragment horoscopoDetailFragment = new HoroscopoDetailFragment();
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.frag_detalhe, horoscopoDetailFragment)
                    .commit();

Esse treco indica que você está relacionando uma instância de HoroscopoDetailFragment no componente visual que tenha o id frag_detalhe, certo? Vamos agora observa o seu layout para vermos onde se encontrar esse componente visual com esse id:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.everton.horoscopo.MainActivity">

    <fragment
        android:layout_width="390dp"
        android:layout_height="match_parent"
        android:name="com.example.everton.horoscopo.fragments.HoroscopoListFragment"
        android:id="@+id/fragmentLista"/>

    <fragment
        android:layout_width="409dp"
        android:layout_height="match_parent"
        android:name="com.example.everton.horoscopo.fragments.HoroscopoDetailFragment"
        android:id="@+id/fragmentDetail"/>

</FrameLayout>

Consigo ver dois componentes fragment, um com o id fragmentLista e outro com o id fragmentDetail, mas não consigo ver alguém com o id frag_detalhe. O que está acontecendo é que o código está tentando inflar um componente visual com um id que não existe.
O que você precisa fazer é apenas ajustar os ids, ou modificando no layout ou modificando na Activity, para que os dois referenciem o mesmo componente com os mesmo id.
Abraço


Redesigning a site with fixed sizes

Question: This turns out to be really interesting, I have got my question and replies in this site
media queries and to adapt the ready made site
Now it seems that they only target "width", what about the height of the screen, the one that is long in width and short in height ?
I would like to fit my topmenu+body+footer into a height of 800px, and also tried out
<code>@media all and (min-height: 768px) and (max-height: 959px) {
div#container{
  position:relative;
  margin:0 auto;
  height:70%;
  min-height:70%;}

div#content {
  min-height: 350px;
}
}
</code>
but it is useless.
Answer: You can detect portrait or landscape using:
<code>/* Portrait */
@media screen and (orientation:portrait) {

}
</code>
or
<code>/* Landscape */
@media screen and (orientation:landscape) {

}
</code>
Or, if you want to be more precise:
<code>@media screen and (device-aspect-ratio: 16/9) {

}
</code>
or, more commonly used:
<code>@media all and (max-height: 1000px) and (min-height: 700px) {

}
</code>
Comment: Ok, thank you so very much, your numbers mess my mind, should I quit again ? :-D
Comment: Oh, my numbers are just to show you what you can do if needed. You said "what about targeting the height of the screen, the one that is long in width and short in height" - this is how you do that.

Redesigning a site with fixed sizes


Mathematics for Pleasure of a Beginner

Question: I've just read "The Music of the Primes" by Marcus du Sautoy, it is worth a read. I'm not from a maths background, but I'd like to develop a deeper understanding of the concepts. The poetry of math is something I'd like  to experience and I feel like I didn't find as much joy in math as there is in the world of numbers.
Elliptical curve crypto-systems sounds like a direction I might want to head towards. I have no concept of where to start, or how in depth I would need to go to understand elliptical curves. Geometry was the most interesting math to me, but I am willing to move in different directions based on advice and materials.
In sum, I want to sit down with math again to give myself the chance at something I haven't experienced, the music of mathematics. There is no timeline or test on the horizon. What captivates you about math? What are the most interesting questions? Where would you recommend I start?
Thank you for any thoughts ahead of time.
Comment: Elliptical curve cryptography definitely isn't for the faint of heart...
Comment: You should make your question more precise. State your mathematical background and aim more precisely. If you only want fiction math, request for such list. If you actually want to do math at research level in future, state so.
Comment: Nothing to do with elliptic curves, but you might be interested in Poetry of the Universe by Robert Osserman, http://www.goodreads.com/book/show/282508.Poetry_of_the_Universe
Comment: The prerequisites for understanding and appreciating the beauty of the theory of elliptic curves encompass pretty much an entire undergraduate degree. Just to expose yourself to some beautiful mathematics, you could have a look at "Proofs from THE BOOK" by Aigner and Ziegler. If you are serious about elliptic curve cryptography and want to start learning mathematics in depth, pick up an undergraduate Calculus book and see how you get on.
Comment: You are completely correct, sorry for the delay. I took Statistics, Pre-Cal, Algebra, and Geometry in high school and almost nothing in college.
And thank you for the suggested reading. I was afraid that elliptical curves might be beyond my reach. Do you think the best thing to do is to just pick up any Calc book and start working the problems?
Answer: A very nice book is Paul Nahim's "An imaginary tale: The story of $\sqrt{-1}$". The books by William Dunham ("When Euler  met l'Hôpital", "Journey through Genius", and others) give a historical perspective.
Free for personal use are several nice textbooks by The Trillia Group.
Answer: That book is really inspiring. I have a background in physical chemistry but this book made me studying mathematics just because I found it pleasurable. I've started from basic undergraduate mathematics books and currently I'm studying G.C.Smith's "Introductory mathematics algebra and analysis" book.

Mathematics for Pleasure of a Beginner


How best can I programmatically apply `__attribute__ ((unused))` to these auto-generated objects?

Question: In my makefile I have the following target, which "compiles" text/HTML resources into unsigned char arrays using xxd -i.
I wrap the result in an anonymous namespace and header guards for multiple-inclusion safety both inside and between translation units.
templates.h:
    @echo "#ifndef TEMPLATES_H" > templates.h
    @echo "#define TEMPLATES_H" >> templates.h
    @echo "// Auto-generated file! Do not modify!" >> templates.h
    @echo "// NB: arrays are not null-terminated" >> templates.h
    @echo "// (anonymous namespace used to force internal linkage)" >> templates.h
    @echo "namespace {" >> templates.h
    @echo "namespace templates {" >> templates.h
    @cd templates;\
    for i in * ;\
    do \
        echo "Compiling $$i...";\
        xxd -i $$i >> ../templates.h;\
    done;\
    cd ..
    @echo "}" >> templates.h
    @echo "}" >> templates.h
    @echo "#endif" >> templates.h

The output, if I had just one such resource, looks like this (actual content redacted):
#ifndef TEMPLATES_H
#define TEMPLATES_H
// Auto-generated file! Do not modify!
// NB: arrays are not null-terminated
// (anonymous namespace used to force internal linkage)
namespace {
namespace templates {
unsigned char alert_email_finished_events_html[] = {
  0x3c, 0x74, 0x61, 0x62, 0x6c, 0x0d, 0x0a
};
unsigned int alert_email_finished_events_html_len = 7;
}
}
#endif

What would be the best way to programmaticaly apply GCC's __attribute__ ((unused)) to these character arrays? I don't want GCC warning about any resources that I end up not using in any given TU, but I also don't want to turn "unused variable" warnings off altogether.
Comment: Any reason why you don't compile using `-fvisibility=hidden` and only export those symbols you do want to have external linkage ? This way you could avoid including the templates everywhere.
Comment: @MatthieuM. Seems cumbersome since I want external linkage by default everywhere else. I want an approach that affects just the templates, and nothing else. I'm not too worried about duplicating the templates everywhere for the time being as I'm only using them in one TU; this approach simply provides error mitigation for when someone comes and `#include`s `template.h` in another TU for the first time. If it eventually ends up in lots of TUs then, sure, something cleverer may be worth devising.
Comment: @MatthieuM. (The other answer is that I don't yet completely "get" `-fvisibility="hidden"`. :P)
Comment: Another solution would be to selectively apply `__attribute__ ((visibility ("hidden"))` to those symbols then, instead of marking them as `unused`. The issue I have with unused is that a symbol used *but* marked as unused may cause warnings (if not immediately, perhaps in the future).
Comment: @MatthieuM.: Really? The [doc](http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#Function-Attributes) says "This attribute, attached to a function, means that the function is meant to be **possibly** unused. GCC will not produce a warning for this function."
Comment: @MatthieuM.: So I'd use "hidden" visibility and get rid of the anonymous namespace, and I gain sharing of identical objects across modules?
Comment: I think it was suggested on Clang, may have been abandonned though if GCC never warns. It is still misleading, of course, but then for generated code it does not matter as much.
Comment: @MatthieuM.: Indeed, it's more like `maybe-unused` :D
Answer: I think a quick sed should work, given that the output of xxd -i is very regular:
xxd -i $$i | sed -e 's/ =/ __attribute__((unused)) =/' >> ../templates.h


Customizar Asp.net Identity - Várias classes como User no Identity

Question: Sabemos que nosso usuário no asp.net identity é a classe com nome de ApplicationUser
Gostaria de criar outras classes que herdem dela
Por que?
Por que, digamos que eu tenha a classe Cliente, Vendedor, Usuário.
Quero que todos eles sejam usuários do meu sistema
Então tenho a minha classe padrão que vem ao criar o projeto:
public class ApplicationUser : IdentityUser
{
}

E tenho minha classe cliente por exemplo.
public class Cliente: ApplicationUser
{
    public string CNPJ { get; set; }
}

Ao ir para a action Register, passei o Cliente para registrar como usuário, já que o mesmo herda de ApplicationUser:
public async Task<ActionResult> Register(Cliente model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() {
            UserName = model.UserName,
        };
        var result = await UserManager.CreateAsync(user, model.PasswordHash);
        if (result.Succeeded)
        {
            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }
    return View(model);
}

Ao ir para essa Action, me deparo com o seguinte erro:
Invalid column name 'CNPJ'.

Ao tentar chamar o método CreateAsync(user,model.PasswordHash)
O que estou fazendo errado? Posso fazer isso que estou fazendo? Herdar e ter várias classes como "user" no identity?
PS: Já fiz migrations e dei update-database
Answer: Duas maneiras de resolver:
1. Faça Cliente herdar direto de IdentityUser
public class Cliente : IdentityUser
{
     [CNPJ]
     public string CNPJ { get; set; }
}

2. Coloque CNPJ direto em ApplicationUser
public class ApplicationUser : IdentityUser
{
     [CNPJ]
     public string CNPJ { get; set; }
}

Aproveitando, vou te passar meu CNPJAttribute para validação:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
sealed public class CNPJ : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null) return null;

        int[] multiplicador1 = new int[12] { 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };
        int[] multiplicador2 = new int[13] { 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };

        int soma, resto;

        string digito, tempCnpj, CNPJ;

        CNPJ = value.ToString().Trim();
        CNPJ = CNPJ.Replace(".", "").Replace("-", "").Replace("/", "");

        if (CNPJ.Length != 14)
            return new ValidationResult("CNPJ Inválido.");

        tempCnpj = CNPJ.Substring(0, 12);
        soma = 0;

        for (int i = 0; i < 12; i++)
            soma += int.Parse(tempCnpj[i].ToString()) * multiplicador1[i];
        resto = (soma % 11);

        if (resto < 2)
            resto = 0;
        else
            resto = 11 - resto;

        digito = resto.ToString();
        tempCnpj = tempCnpj + digito;
        soma = 0;

        for (int i = 0; i < 13; i++)
            soma += int.Parse(tempCnpj[i].ToString()) * multiplicador2[i];
        resto = (soma % 11);

        if (resto < 2)
            resto = 0;
        else
            resto = 11 - resto;

        digito = digito + resto.ToString();

        if (CNPJ.EndsWith(digito))
            return null;
        else
            return new ValidationResult("CNPJ Inválido.");
    }

    public override string FormatErrorMessage(string name)
    {
        return name;
    }
}

Comment: Nunca tentei algo assim com tantas camadas de herança. Normalmente deixo minhas aplicações a níveis de estratificação simplificados. De repente posso tentar alguma coisa.


Find the maximum value of $a-b$ where $4a+5b=61$ and where $a$ and $b$ are positive whole numbers.

Question: I am at a beginners level at maths. I have tried to work out the question myself, but I have seen a more simpler way of getting to the answer in which I haven't understood.
Here's the simpler approach to this question:
$4a+5b=61$
When $b=1$,  $a=14$
When $b=5$,  $a=9$
When $b=9$,  $a=4$
From the pattern we add $4$ to the value given to b each time and we subtract $5$ from the value given to a each time. That is the shortcut to get all the possible values.
Why is this so?
The solution goes on to say
when $a=14$ and $b=1$ ; $a-b=13$ which is the maximum value of $a-b$.
Comment: because adding  4 to b and subtracting 5 creates a difference of  4(5)-5(4)=0
Comment: http://mathworld.wolfram.com/DiophantineEquation.html
Answer: HINT: $$b =\frac{61}{5}-\frac{4a}{5}$$ then $$a-b=\frac{9}{5}a-\frac{61}{5}$$
Answer: We have the diophantine equation
$$4a+5b=61$$
To see that every integer solution can be produced by taking a particular solution and then adding some multiple of $5$ to $a$ and subtracting the same multiple of $4$ from $b$, consider the following:

$$4a=61-5b$$
$$5b=61-4a$$
We see (where '$|$' means 'divides)
$$4\,|\,61-5b$$
$$5\,|\,61-4a$$
$\implies$
$$4\,|\,1-b$$
$$5\,|\,1+a$$
$\implies$
$$4\,|\,b-1$$
$$5\,|\,a+1$$
Hence if $(a_0, b_0)$ is a solution, any other solution must be of the form $(a_0+5i, b_0+4j)$ for some integers $i, j$.

Next, we need to show if $(a_0, b_0)$ is a solution, then $(a_0+5k, b_0-4k)$ is also a solution for all integers $k$.
$$4a_0+5b_0=61$$
$\implies$
$$4a_0+5b_0+20k-20k=61$$
$\implies$
$$4a_0+5b_0+4(5k)-5(4k)=61$$
$$4(a_0+5k)+5(b_0-4k)=61$$

Therefore, all solutions must be of the form $(a, b)=(a_0+5k, b_0-5k)$ once a particular solution $(a,b)=(a_0,b_0)$ is found and for all integers $k$.

However, the question is after positive integer solutions, hence the largest value of $a-b$ is when $(a,b)=(14,1)$
Answer: Since $61(-4+5)=61$, we can extend this to the full solution set with
$$
4\ \overbrace{(5k-61)}^a+5\ \overbrace{(61-4k)}^b=61
$$
For $a,b\ge0$, we need $13\le k\le15$. Since $a-b=9k-122$, we want to use $k=15$ where $a-b=13$.
Answer: $$\max_{\begin{array}{c} 4a+5b=61 \\ a,b\in \mathbb Z^+ \end{array}}a-b$$
A solution to $4a+5b=61$ is $a=9$ and $b=5$. So the general solution is
$a=9-5t$ and $b=5+4t$, where $t$ is an integer.
We note that $b> 0 \implies t \ge -1$ and $a > 0 \implies t \le 1$. So we need $-1 \le t \le 1$.
Since $a-b = 4-9t$ is a decreasing function of $t$, its maximum value will occur when $t=-1$. That is when
$(a,b) = (14, 1)$


Reply packets of application layer

Question: my task is as follows: collect some information about application-level network requests (for example, in .pcap file) and repeat these requests on another computer running python 3.6. For example, I have a pcap file with an http request to some site, I want to repeat it on another computer using some python lib, is there a way to do this? I am interested in HTTP, HTTPS, FTP, DNS, IMAP, SSH protocols. Thanks in advance.
Comment: Welcome to [Stack Overflow.](https://stackoverflow.com/ "Stack Overflow") Please be aware this is not a code-writing or tutoring service. We can help solve specific, technical problems, not open-ended requests for code or advice. Please edit your question to show what you have tried so far, and what specific problem you need help with. See the [How To Ask a Good Question](https://stackoverflow.com/help/how-to-ask "How To Ask a Good Question") page for details on how to best help us help you.
Answer: You can use TCPReply for replying a .pcap file.
Just sniff your data with wireshark on one computer, save it to .pcap file., and you can play it later using the TCPReply tool.
Comment: the problem is that TCPReply does not take into account session specifics, so various errors may occur at the connection confirmation stage, so most of the traffic will look like a single request with a subsequent error in the response. I may be wrong, but I think it works like this. I see a possible solution to sending application le.vel requests so that the OS itself can deal with all the problems at the lower levels.

Reply packets of application layer


Using a for loop in Microsoft cmd.exe, how can I process only the files with a certain extension?

Question: I have a the folder c:\test\ and two files in it a.txt and b.txtv.
I would like to process just the files with extension equal to .txt.
If I write this commands
cd c:\test
for %f in (*.txt) do echo %f

I will get the result where both a.txt and b.txtv are listed.
The same happens with
cd c:\test
dir *.txt

It seems .txt is the same of .txtv.
I have Windows XP SP3 in Italian and the result of
ver

is Microsoft Windows XP [Versione 5.1.2600].
The same result is from Windows 7 in English Microsoft Windows XP [Version 6.1.7601].
Comment: Just a side note but Windows Ver. 6.1 is the official version number for Windows 7.
Answer: Try using forfiles instead.  It seems to be more restrictive on what it returns for the extension, plus it has the added benefit of a built in for loop.  Should already be on the Win7 box, but you might have to install a 2003 Server Resource kit on the XP box to get it on there.
Answer: for %%I in (*.*) do if "%%~xI"==".txt" (echo %%I)

That should do it.
Edit: that's the "scripting" syntax. If you want to type this at the command line, you must remove one of the % sign each time they are doubled, linke this:
for %I in (*.*) do if "%~xI"==".txt" (echo %I)

Answer: It's really simple in PowerShell and works fine with the following:
PS C:\Users\bpabst\Desktop> ls *.txt

Directory: C:\Users\bpabst\Desktop

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---          7/2/2012  11:19 AM         11 test.txt

Comment: So how does this explain the behavior OP is seeing with `cmd` and `FOR`?
Comment: How about in this pre-existing question: http://stackoverflow.com/questions/1523043/how-to-loop-through-files-and-rename-using-powershell
Comment: I'm still not seeing "powershell" listed anywhere in the OP's question. They even tagged it [batch] and [cmd].
Comment: "Better technology" -- Sorry, I think you're missing the point of the OP's question.


Popup do JComboBox ficar visível até clicar na seta

Question: Tenho um JComboBox populado com JCheckBox's funcionando normalmente, mas quando eu clico em um item, o popup do JComboBox fecha. Para ver se o JCheckBox realmente foi marcado, é necessário abrir de novo.
Queria saber se é possível fazer com que o popup só feche quando clicar naquela setinha que fica do lado novamente.
Frame com o JComboBox:
package NewClass;

import javax.swing.JCheckBox;

public class NewJFrame1 extends javax.swing.JFrame {

    JCheckBox[] jcb1 = new JCheckBox[3];

    public NewJFrame1() {
        jcb1[0] = new JCheckBox("Inclusão");
        jcb1[1] = new JCheckBox("Alteração");
        jcb1[2] = new JCheckBox("Exclusão");
        initComponents();
        jComboBox1.insertItemAt("Opções", 0);
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jComboBox1 = new JComboCheckBox(jcb1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(84, 84, 84)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(202, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(62, 62, 62)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(218, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame1().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JComboBox<String> jComboBox1;
    // End of variables declaration
    }

Classe que insere os JCheckBox's no JComboBox:
package NewClass;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class JComboCheckBox extends JComboBox {

public JComboCheckBox() {
    addStuff();
}

public JComboCheckBox(JCheckBox[] items) {
    super(items);
    addStuff();
}

private void addStuff() {
    setRenderer(new ComboBoxRenderer());
    addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            itemSelected();
        }
    });
}

private void itemSelected() {
    if (getSelectedItem() instanceof JCheckBox) {
        JCheckBox jcb = (JCheckBox) getSelectedItem();
        jcb.setSelected(!jcb.isSelected());
        setSelectedIndex(0);
    }

}

class ComboBoxRenderer implements ListCellRenderer {

    private JLabel defaultLabel;

    public ComboBoxRenderer() {
        setOpaque(true);
    }

    public Component getListCellRendererComponent(JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus) {
        if (value instanceof Component) {
            Component c = (Component) value;
            if (isSelected) {
                c.setBackground(Color.WHITE);
                c.setForeground(Color.BLACK);
            } else {
                c.setBackground(Color.WHITE);
                c.setForeground(Color.BLACK);
            }
            return c;
        } else {
            if (defaultLabel == null) {
                defaultLabel = new JLabel(value.toString());
            } else {
                defaultLabel.setText(value.toString());
            }
            return defaultLabel;
        }
    }
}
}

Answer: Seguindo a dica desta resposta do SOEn, uma das formas de se fazer isso é alterando o método setPopupVisible() da própria classe JComboBox, adicionando uma condição para que este popup permaneça aberto.
Como o objetivo é manter aberto somente quando houver alteração de alguma seleção, você pode utilizar uma flag. Crie uma variável como selectedHasChangedna sua classe de combobox e defina seu valor inicial como false, pois não é desejável que o popup fique visível quando abrir a tela, e o setPopupVisible() será chamado durante a construção do componente na tela:
private boolean selectedHasChanged = false;

No método InteSelected(), você altera a flag para true:
private void itemSelected() {
    if (getSelectedItem() instanceof JCheckBox) {
        JCheckBox jcb = (JCheckBox) getSelectedItem();
        jcb.setSelected(!jcb.isSelected());
        setSelectedIndex(0);
    }
    selectedHasChanged = true;
}

E no setPopupVisible() defina a flag para que ela defina a visibilidade:
@Override
public void setPopupVisible(boolean v) {

    super.setPopupVisible(selectedHasChanged);
}

Veja o resultado:
Comment: Obrigado, funcionou, muito interessante.


How do I submit call handler on radio button selection?

Question: I use the advanced polls module in Drupal 7. I am trying to alter the behaviour so that the vote is submitted as soon as the radio button is selected (without having to hit Vote).
The module is using an ajax callback:
$form['submit'] = array(
'#type' => 'submit',
'#ajax' => array(
  'callback' => 'advpoll_form_submit',
  'wrapper' => 'advpoll-form-' . $values->nid,
  'name' => 'submit1',
),
'#id' => 'edit-submit-advpoll-' . $values->nid,
'#value' => t('Vote'),

);
How can I invoke this callback with radio buttons?
I am happy for a quick and dirty javascript/jQuery solution as time is a real factor.
I have tried a jQuery solution:
$('input[type="radio"]').change(function() {
  $('#advpoll-form-296').trigger('click');
});

However this is not invoking the action as expected.
I cannot call submit() as I don't want to cause a page reload.
I have managed to get my original code to fire by adding a click event to the ajax array in the .module file.
advpoll.module:
function advpoll_choice_form($form, &$form_state, $values) {

$form['submit'] = array(
'#type' => 'submit',
'#ajax' => array(
  'callback' => 'advpoll_form_submit',
  'wrapper' => 'advpoll-form-' . $values->nid,
  'name' => 'submit1',
  'event' => 'click', //Added click event
),
'#id' => 'edit-submit-advpoll-' . $values->nid,
'#value' => t('Vote'),

);
I am aware I should not override code within the module. How would I go about getting this into a theme hook?
Comment: have you tried using the jquery submit() function? https://api.jquery.com/submit/
Comment: Quick and dirty: `$('#advpoll-form-296').submit();`. The Drupal way is more complicated
Comment: Cannot use submit() without reloading. Edited question to include more detail.
Answer: This should do it:
$(function() {
  $('input[type="radio"]').on('change', function() {
    $(this).parents('form').submit();
  });
});

You might want to qualify the selector for $('input[type="radio"]') to the scope of the form you're working with, else if you include this in a JavaScript file that's accessed on many different pages, you'll definitely run into problems!
Demo:  http://plnkr.co/edit/8448bjiywnVtbT3CV6s6?p=info
Comment: can't use submit() without causing a reload. Good suggestion on selector. Updated question with more detail. I just need to work out how to add the click event as a theme hook.
Answer: It's been a while since this was posted but I hope this answer can help anyway
The simple way I found to do it (I'm using the advpoll module as well) is to add the same AJAX handler to the options dropdown using hook_form_alter
So, in my custom module:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // The submit form has ID advpoll_choice_form
  if ($form_id == 'advpoll_choice_form') {
    foreach ($form as $key => &$value) {
      // It seems that the radio buttons are under an array labelled 'choice_X'
      // where X is the number of options you have, so this just checks
      // it's doing it to the correct one
      if (substr($key, 0, 7) == 'choice_') {
        // Apply the same AJAX handler the submit button has to the radio buttons
        $value['#ajax'] = $form['submit']['#ajax'];
      }
    }
  }
}

Hope this helps someone in the future


Parsing JSON in c# (.NET2.0 / JSON.NET35)

Question: I have to customize a software which uses .net 2.0.
My task is to integrate a JSON REST API. For these purposes I am trying to use json.net which works fine for the calls.
Trying to parse the results I came up with this:
using (StreamReader responseReader = new StreamReader(webStream))
{
    try
    {
          JsonTextReader jsonreader = new JsonTextReader(responseReader);
          while (jsonreader.Read())
          {
          if (jsonreader.Path == "data.key" && jsonreader.TokenType == JsonToken.String) return jsonreader.Value.ToString();
          }
          throw new Exception("no token found in answer");
     }
     catch (Exception)
     {
          // error handling
          throw;
     }
}

This works fine on newer versions of Json.NET. Unfortunately, JsonTextReader.Path is not available in this version (3.5) and there is no chance to upgrade.
How can I parse the result to receive the given token under the attributes data->key?
The response looks like this

{   "status": {
      "code": 0,
      "httpStatus": 200,
      "text": "Request successful submitted",
      "success": true   },   "data": {
      "key": "dIwbU9ZjQDH6P95aMqs%2Bh%AKLA22%2ByeY2R7PC6IknkWC%2BlrmcN%2Blm5F3WNBa027gTm%0D%0A2zp5NGC1X2NON72A7N%2BZjB2fxJizUg0paiVdWlv4K1ZSKLlIGprTVoaMHqA1%0D%0AcfCHnV6E%0D%0A"
  },   "success": true }
Answer: Json.Net v3.5 is rather old now, but something like this should work.
Replace this:
while (jsonreader.Read())
{
    if (jsonreader.Path == "data.key" && jsonreader.TokenType == JsonToken.String)
        return jsonreader.Value.ToString();
}

with this:
JObject obj = JObject.Parse(json);
return obj["data"]["key"].ToString();

Comment: Thank you, this is very useful! For addition: The tokenstring in this example can be retrieved by responseReader.ReadToEnd()


Windows 7 iSCSI initiator disconnect issues

Question: I have Windows 7 workstation installed on 2 LUNS connected via 2-port Intel Pro/1000 PT, one LUN per port, first LUN is a system drive. LUNS are on the different targets.
There are absolutely no problems with a system LUN, but according to the system event log, the second LUN keeps disconnecting and reconnecting: "Connection to the target was lost. The initiator will attempt to retry the connection.", it happens every 1-2 minutes. There is no any system freezes etc., just a messages in the logs. But of course I would like to have this fixed. Is it possible?
Some additional info:
all power management features for the adapters are disabled.
MSC for the target is set to "Failover only".
The target is Solaris Express (ex. OpenSolaris) COMSTAR, but I guess it's not important - other machines don't have any issues as well as the first LUN on this Windows 7 machine.
p.s. I've tried to copy some large files to the second LUN to see any freezes, but for some reason disconnects are disappeared until the copy process is completed. Looks like Windows iSCSI initiator "plays" with a LUN only when it's idle. But for what?
Answer: Looks like I've already answered this one on ru_root, but for the record:

disable tcp offloading. and generally
go over ProSet's options, might be
something worthwhile in there
check the initiator for a persistent
connection option, I remember
something of the sort in there
If MPIO is used, it is possible that
you're losing a path and not the
connection
If everything else fails, I'd get a
tcpdump and analyse it for iSCSI
related traffic issues.

BTW, if you're using a team, it will not work with MPIO apparently: http://technet.microsoft.com/en-us/library/ee338480(WS.10).aspx
Comment: tcpdump helped :D http://opensolaris.org/jive/message.jspa?messageID=422020#422020


prime divisibility:v what is the formula?

Question: I know how to divide certain numbers, like $$\frac{x}{2}$$ whereas $x$ ends in 2, 4, 6, 8, or 0. and my idea to represent $x$ is $$a+10b+100c+1000d...$$ and it is divisible by 3 if $$\frac{a+b+c+d...}{3}$$ is a whole number.
$\frac{x}{5}$ is possible if the number ends in 0 or 5.
$\frac{x}{6}$ is possible if $\frac {x}{3}$ and $\frac{x}{2}$ are both possible. this is the same for all composite numbers.
my big question is: what about larger $$\frac{x}{p}$$ where p is any prime number and x is any number you are trying to test? is there any formula that can be directly applied to any prime-regular number combination to find the divisibility?
Answer: You have asked about two different kinds of divisibility tests.
The tests for divisibility by $2$ and $5$ work so nicely because we write our numbers in base $10$ and those are the prime factors of $10$. If we wrote using a different base $b$ we could test for divisibility by a prime factor of $b$ by checking just the last (units) digit.
In base $10$ there are digit tests for other numbers too. You show that you know that to test for divisibility by $3$ or $9$ you use the sum of the digits. For $11$ you look at the alternating sum and difference of the digits. For $4$ you look at the last two digits. There's a test for $7$ too, but it's really ugly.
The second kind of test you're thinking about is the one you quote for $6$. If a number is divisible by each of two primes $p$ and $q$ then it will be divisible by their product $pq$. That's a fact about numbers and doesn't depend on the base you use to write them. (It can also be generalized a bit.)
See https://en.wikipedia.org/wiki/Divisibility_rule (and other web links for "divisibility test").
Comment: As a generalization, in any base $b$ and for any prime $p | b$, you can test divisibility by $p^k$ by checking the last $k$ digits. That is why the test for 4 works.
Answer: I know the following about the general case for base $b$;
If $p|b$, then you can check divisibility by $p^k$ by checking the last $k$ digits of the number in question.
If $b \equiv 1 \pmod{p}$, then the sum of digits test applies.
If $p-1=b$, then the alternating sum of digits test works.
I am under the impression (possibly mistaken) that is is always possible to construct a digit test, however in the majority of cases it is rather absurd and not worth doing.
Comment: As a comment on the last thing I said, a digit test can always be constructed when we know the residues of $b^n \pmod{p}$. More times than not creating such a test would yield something very ugly, but sometimes it works well - for the case $b,p = 10,3$, we have that $10^n \equiv 1 \pmod{3} \forall n$, which is why the sum of digits test works.
Comment: For prime $p$ and base $b$ there's always a test that works on digit blocks of size $n$ for some $n$ dividing $p-1$. When $p=7$ and $b=10$ you need blocks of length $6$, so not very useful.


Custom filtering and grouping in Django Rest Framework

Question: I'm working on functionality which allows users to create custom filters on specific models and store those results as a group. As a working example (imports omitted for brevity):
class Client(models.Model):
    email = CIEmailField()

class Activity(models.Model):
    client = BaseForeignKey("client.Client", null=True, related_name="logged_activities")
    employee = BaseForeignKey("business.Employee", null=True, related_name="logged_activities")
    created = models.DateTimeField(auto_now_add=True)

We want to create filters which will group Clients on Activitys based on the creation time and associated Employee and store those results in a group to be used later. This is pretty straightforward task, except a user is allowed to modify the filter configuration and update fields on a Client, both of which may change whether or not a Client matches the filter criteria. (Note: in this example it's not possible updating a Client could change the result set, but future filters will.)
I'd like a many-to-many so we can easily get the groups a client is in, and conversely get the clients in a group, but it's not clear to me the best way to handle the filter configurations. This is currently supported in our system but the filters don't work correctly and the filter queries are run whenever information about a group needs to be used. Given that, as well as some other factors, we've decided to rebuild this functionality instead of attempting to refactor the current implementation.
Answer: One crude way of handling it would be the following. You create a mapping or a hook that's key would match a field on the intermediate model on the many to many field. Then you register (add a key/value) for each of the various filters in the mapping/hook. You create your instances of the intermediate model with the appropriate keys. Then when you need to utilize a particular group's functionality, you pull the model instance out of the database, and use the key to find the particular filter functionality out the mapping/hook.
config_groups = {}

class BaseConfig:
    key = None # Must be overridden by subclasses
    # I assume each of your filters has some common interface.
    # Put that here and raise NotImplemented exceptions for each function.

class AFilterConfig(BaseConfig):
    key = 'a_filter'
    # Implement AFilter's specific filtering logic.

config_groups[AFilterConfig.key] = AFilterConfig

class ConfigGroup(models.Model):
    # Relationship fields to Client and/or Activity
    key = models.CharField(max_length=16, unique=True, choices=list(config_groups.keys()))

def view_function(request):
    config_group = ConfigGroup.objects.get()
    filter_config = config_groups[config_group.key]

If you want to take it a step further you can look into making this mapping/hook an actual Django model field. Such that you would be able to do the following without having to deal with importing and indexing into the mapping/hook.
def view_function(request):
    config_group = ConfigGroup.objects.get()
    filter_config = config_groups.filter_config


Mixing macro-DO-loops with data step DO-loops

Question: Some context:
I have a string of digits (not ordered, but with known range 1 - 78) and I want to extract the digits to create specific variables with it, so I have
"64,2,3" => var_64 = 1; var_02 = 2; var_03 = 1; (the rest, like var_01 are all set to missing)

I basically came up with two solutions, one is using a macro DO loop and the other one a data step DO loop. The non-macro solution was to fist initialize all variables var_01 - var_78 (via a macro), then to put them into an array and then to gradually set the values of this array while looping through the string, word-by-word.
I then realized that it would be way easier to use the loop iterator as a macro variable and I came up with this MWE:
%macro fast(w,l);
do p = 1 to &l.;
    %do j = 1 %to 9;
        if &j. =  scan(&w.,p,",") then var_0&j. = 1 ;
    %end;
    %do j = 10 %to 78;
        if &j. =  scan(&w.,p,",") then var_&j. = 1 ;
    %end;
end;
%mend;

data want;
string = "2,4,64,54,1,4,7";
l = countw(string,",");
%fast(string,l);
run;

It works (no errors, no warnings, expected result) but I am unsure about mixing macro-DO-loops and non-macro-DO-loops. Could this lead to any inconsistencies or should I just stay with the non-macro solution?
Answer: Your current code is comparing numbers like 1 to strings like "1".
&j. =  scan(&w.,p,",")

It will work as long as the strings can be converted into numbers, but it is not a good practice.  It would be better to explicitly convert the strings into numbers.
input(scan(&w.,p,","),32.)

You can do what you want with an array. Use the number generated from the next item in the list as the index into the array.
data want;
  string = "2,4,64,54,1,4,7";
  array var_ var_01-var_78 ;
  do index=1 to countw(string,",");
     var_[input(scan(string,index,","),32.)]=1;
  end;
  drop index;
run;

Comment: You do not need to tell SAS the number of elements in the array when you have listed them in the statement. It can count.  As to mixing %DO and DO it is fine, just be clear what is happening.  Use the MPRINT option to help as you can then see the actual SAS code the %DO loop generated.
Comment: Thanks Tom! Your array solution is pretty close to mine, except why can we define arrays without specifying their length? About the mixing of data step and macro DO-loop, any advice? Actually I was wondering that this was working at all...
Comment: Excellent tip to use the mprint option! Got it now. About the length, I've never seen any mention of not stating it...I usually used the {*} but apparently this is default, thx again.


Is there a way to know X is really causing Y?

Question: The real question here is if there is a way to know X is causing Y rather than simply being associated with it. In my example Y seems to be telling more of X(if not causing it) than X says about Y.
This is not about causality per se, I know that correlational studies can not show that. But we will never be able to do random assignment, it would not even be legal. So correlation is what we have. My problem is that I am having growing doubts about the use of regression to show that X causes a change in Y. For example in our survey of satisfaction we measure a wide range of predictors of satisfaction, like satisfaction with pay, and then use it to predict overall satisfaction. Satisfaction with pay (a dummy predictor variable) has the highest odds ratio in the survey (the DV is a two level variable satisfied/not - I am running logistic regression). If you are satisfied with pay you are 19 times more likely to be overall satisfied than if you are not satisfied with pay. The odds ratio suggests that this is a key factor in overall satisfaction therefore at least compared to 30 other predictors.
The problem is that there is little indication this really matters. 90 plus percent of our staff are satisfied (that the number is so high might be part of the problem because there are only 47 usable cases that are dissatisfied out of 448 total cases - also we have 31 predictors). And dissatisfaction with pay is  extremely high. So pay looks like a key driver of overall satisfaction based on the odds ratios, but satisfaction with pay is very low and overall satisfaction is quite high. It seems that while overall satisfaction reflects real differences between those who are satisfied with pay and not, those differences don't change whether customers are satisfied or not. Which confuses me given my understanding of regression.
It is interesting that two variables with much lower odds ratios have higher levels of statistical significance. Pay is significant at the ,1 level they are at the .05 level.
Comment: Hi @user54285. I'm studying a course which deals with similar issues to your question. I would like to note the difference between an *observational study* and an *experimental study*. The former can only provide you with suggestions of associations, while the latter can give you information about causation. You can see texts on Experimental design that make this clear. From what I understand in your example, your predictors (satisfaction with pay) are observational, and not in your control, so you can only infer association with your response. There may or may not be a confounding variable.
Comment: From what I know, I don't believe you can use a special technique to extract causal conclusions from your data. I'm only an undergrad, so hopefully someone more experienced can confirm this. But your doubts about regression seem reasonable to me. A statistically significant relationship between X and Y does not necessarily mean X _causes_ Y, it just suggests they move together. However, it also means we are unsure if setting X to a particular value will cause the same change in Y, as opposed to letting nature set X and Y and just "observing" it.
Comment: It's possible that your target causes one of your predictors. I don't think there's a magic bullet to tell if this is true. A (maybe) relevant example: I used to work in bars and restaurants. The pay isn't great. Few would answer yes to the direct question "Is your pay satisfactory", and everyone knows this. BUT, employees generally only actively grouse about the pay when they're unsatisfied with the job more generally. Target - > predictor.
Comment: If dissatisfaction with pay is extremely high, and you live in a free country (or at least a relatively free country), then your dissatisfied employees will vote with their feet: out the door. I personally think dissatisfaction with supervisors is more common than with pay. People tend to leave bad bosses at least as much if not more than bad pay.
Answer: I'm a little confused when you say both that "The real question here is if there is a way to know X is causing Y rather than simply being associated with it." as well as "This is not about causality per se, I know that correlational studies can not show that." This is definitely about causality.
Theorem 1.2.8 (Observational Equivalence) in Pearl's book Causality: Models, Reasoning, and Inference, p. 19, runs like this:

Two DAGs are observationally equivalent if and only if they have the same skeletons and the same sets of $v$-structures, that is, two converging arrows whose tails are not connected by an arrow.

This implies, among other things, that the DAG $X\to Y$ is observationally equivalent to $Y\to X:$ these two DAGs have the same skeleton and the same $v$-structures. Therefore, there is nothing at all you can do to distinguish between the two.
In general, the only thing you can really rely on in a situation like this is human intuition or expert opinion.
Comment: Hi @user54285, I made a comment above. To share my understanding here, I think a factor X can still have a high odds ratio with Y without actually causing it. There might just be a confounding variable that raises X and Y together. There may be various other factors, such as number of close relationships, which may raise overall satisfaction and satisfaction with pay together (the person may just be more content with less). Hopefully these comments may be helpful, again just a disclaimer I'm only an undergrad!
Comment: Glad to see someone other than me given disclaimers. :) There could be some variable driving both not in the model, always a problem. I am more interested in finding something to test causality in this case, but I think now this can only be done with theory which sadly does not really exist in this case. Experimental design, that is not an observational study, would be the ideal but as with most government issues random assignment is not even legal with my question. So correlation is all you have.
Comment: What I meant is that causality in the classic sense can't be proven because I did not do random assignment and can not. I wondered if there were any ways you could be more sure (I know some theoretical ways like regression discontinuity designs, but I have not done them from graduate work - they are rarely used).  I don't know what DAG means or  skeleton or v structure. I assume you are saying that whether X is driven by Y or Y  by X (or either) really can only be known based on theory or inference. But I think that is where I am having to use intuition. I just hoped there was another method.
Comment: I am a practitioner rather than a statistician.  So I look at regression fairly simply. I assume if the mean difference on Y between two levels of a dummy X are large this suggest that something about X pushes Y in a specific direction. I always have. But looking at this data makes me honestly wonder. It is very unlikely logically for satisfaction with pay to drive overall satisfaction significantly because then satisfaction would be much lower. But it has a very high odds ratio. I was hoping for some trick to get around this. Thanks. what I need maybe is multivariate descriptives. :)


deletion of records using dates

Question: i have a table as CostData in that i have a column as Month_year which is in mm/dd/yyyy format
and now i want to delete data based on date. suppose i give start date as 01/31/2012
and end Date as 01/31/2013 it should delete whole one years record. and i have to text box's to take input of start and endDate
("Delete from CostData where Month_year between {0} and {1}'", TextBox2.Text, TextBox1.Text)
this is the query that I'm using, but its not working. Month_year is of date type.
Comment: What data type is Month_Year and in which RDBMS?
Comment: 'm using sql server 2008 and month_year is of date type
Comment: Nothing wrong with your query -- unless textbox values are off.  See here: http://sqlfiddle.com/#!3/9717d/1 -- What does your SQL String evaluate to after it gets populated?
Comment: what error do you get? and correct me if I am wrong, does `{0}` work for parameterized queries I think that would be `@Month`
Comment: "m getting a error for the string so 'm not sure as what to use {0}0r ?? @spandy
Comment: @sgeddes after it gets populated i have to delete tat whole durations data
Comment: @sgeddes and thanks for the link you have provided it will be usefull
Answer: Actually, I think you're issue is with your SQL String.  If you posted more of your code, I could tell for sure, but I suspect your using String.Format in the above?  If so, just wrap {0} and {1} around apostrophes:
<code>("Delete from CostData where Month_year between '{0}' and '{1}'", TextBox2.Text, TextBox1.Text)
</code>
Please look into using parameterized queries -- this method is vulnerable to SQL Injection.
Good luck.
Comment: Not sure I'm following you -- did you see my edits above with the exact string?
Comment: yes exactly :-) your rite that was the error with string. thank you very much. its working now. @sgeddes
Comment: @user1986144 -- no problem, glad we could help.  With that said, please do look into  parameterized queries as the above method is highly vulnerable to SQL Injection.  Do a quick search to see examples.  Best of luck.
Answer: I'm a little rusty, but I think it's something like this:
<code>...where month(Month_year) => {0} and month(Month_year) <{1}
</code>
Comment: actually i have taken it as strings so it had to be '{0}' and '{1}'

deletion of records using dates


Exec JS after flag ajax result

Question: In my portal I need to use "flags" module to create a simil twitter "follow/unfollow". I have installed and configurated this module. All works, via AJAX too.
Now I need to exec some other JS function after that the flag module has completed his call. I think that I need to add (on the backend) some "commands" before flags return "commands" to execute in the frontend.
How I can I do this ?
Thanks, M.
Comment: https://www.drupal.org/project/subscriptions check out this module also, may be what you are trying to implement.
Comment: Beebee: thanks but in my project I use flags for other things.
Answer: here is API https://www.drupal.org/node/336122
The two events
The flagGlobalAfterLinkUpdate event
This event is triggered immediately after a flag link has been updated. (Flag links appear in two flavors: "Bookmark this!" and "Unbookmark this!", and when we speak of "update" we mean this change in appearance).
The flagGlobalBeforeLinkUpdate event
This event is triggered just before a flag link is updated. As will be explained later, the existence of this event is for cosmetic reasons only: it allows us to carry out actions while the throbber () is still visible.
<code>$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
  alert('Object #' + data.contentId + ' (of type ' +
    data.contentType + ') has been ' + data.flagStatus +
    ' using flag "' + data.flagName + '"');
});
</code>

Exec JS after flag ajax result


How to bulk delete translation strings

Question: I imported some translations using the locale update module but the translations are horrible and it would be better to revert to English.
How do I bulk delete all the imported translations in Drupal 8?
I found an issue on adding back the D7 translation string deletion option to the UI, but I want to mass delete all strings, not individual strings.
Drupal 7 version of this question
EDIT: Deleting the language is one approach, but I can't do that because I already have a lot of content translated into the language.  I want to keep the content that I have translated into the language, but delete all the user interface strings that were imported through localization update.
Answer: If you intend to remove ALL strings imported through interface translation, you could execute something like this:
// Replace the empty string with your target language code.
$langcode = '';
\Drupal::database()
  ->delete('locales_target')
  ->condition('language', $langcode)
  ->condition('customized', 0)
  ->execute();

You may also want to reset the source file history information, so - if you change your mind afterwards - you can re-import the very same translations:
\Drupal::database()
  ->delete('locale_file')
  ->condition('language', $langcode)
  ->execute();

or
locale_translation_file_history_delete([], [$langcode]);

As the locale module makes heavy use of static caches, you may run above commands in a dedicated process as, e.g. Drush PHP CLI (drush php:cli).
Answer:
Suggestion 1

if you want to get rid of all translations of a language, just delete the langauge in /admin/config/regional/language

Suggestion 2
if there are some specific string you want to be not translated, Go to locales_source to identify those strings lids, then execute the following code (devel/php or custom hook_update_N or drush ev...)

$lids = [4, 5];
db_delete('locales_target')->condition('lid', $lids, 'IN')->execute();

hope this helps
Comment: Thanks! I don't want to delete the language because I have *content* translated into the language that I need to keep.  I want to delete the *interface* translations for the language, but keep the content in the language.
Answer: I found http://web.archive.org/web/20230609014802/http://vaerenbergh.com/blog/drupal-8-reimport-all-translation-files the only solution that worked:
DELETE FROM key_value WHERE collection='locale.translation_status';
UPDATE locale_file SET timestamp = 0;
UPDATE locale_file SET last_checked = 0;

then
drush ev "\Drupal::state()->set('locale.translation_last_checked', 0);"
drush cr
drush locale-check && drush locale-update && drush cr

How to bulk delete translation strings


set columns in table to invisible

Question:
The two tables are inside one div (please see code below for an cut out of the code from  bottom table), I would like to make the first column of the bottom div invisible....any ideas? thanks for replies

                Summary

                Labour
                <%: this.FormatMoney(LabourTotal)%>

Comment: @John....can you be more specific?  You wan to hide the  in the bottom row?
Comment: Just set the border to none?
Answer: if you want to make it look like its 'merged' with the cell that contains the total value, use CSS 'border-right-style' on the desired cell, for example:

Answer: Don't create the unwanted column, and instead position the second (now two column wide) table using the style. I would probably have removed the width from the second table and replaced it with float:right to make it align to the right...

set columns in table to invisible


Python command line arg with getopt does not work

Question: I modified the sample code given here:
sample code for getopt
as follows, but it does not work. I am not sure what I am missing. I added a "-j" option to this existing code. Eventually, I want to add as many as required command option to meet my needs.
When I give input as below, it does not print anything.
./pyopts.py -i dfdf -j qwqwqw -o ddfdf
Input file is "
J file is "
Output file is "

Can you please let me know whats wrong here?
#!/usr/bin/python

import sys, getopt

def usage():
    print 'test.py -i <inputfile> -j <jfile> -o <outputfile>'

def main(argv):
   inputfile = ''
   jfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hij:o:",["ifile=","jfile=","ofile="])
   except getopt.GetoptError:
      usage()
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         usage()
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-j", "--jfile"):
         jfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg

   print 'Input file is "', inputfile
   print 'J file is "', jfile
   print 'Output file is "', outputfile

if __name__ == "__main__":
   main(sys.argv[1:])

Comment: Don't use getopt. Use argparse.
Comment: I'm surprised `getopt` isn't deprecated yet.
Comment: Probably because it was never intended to be the primary method for parsing options; it's only there as a stepping stone for users coming from C. It's nearly self-deprecated :)
Answer: Your error is omitting a colon following the i option. As stated by the link you supplied:

options that require an argument should be followed by a colon (:).

Therefore, the corrected version of your program should contain the following:
   try:
      opts, args = getopt.getopt(argv,"hi:j:o:",["ifile=","jfile=","ofile="])
   except getopt.GetoptError:
      usage()
      sys.exit(2)

Executing it with the specified arguments derives the expected output:
~/tmp/so$ ./pyopts.py -i dfdf -j qwqwqw -o ddfdf
Input file is " dfdf
J file is " qwqwqw
Output file is " ddfdf

However, as a comment to your question specifies, you should use argparse rather than getopt:

Note: The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. Users who are unfamiliar with the C getopt() function or who would like to write less code and get better help and error messages should consider using the argparse module instead.