Azure AD B2C custom policy not returning account lockout error (50053)

Question: I was testing AD B2C smart lockout feature following this link.
My current smart lockout settings:

The sign-ins log showed that the account I used for testing is successfully locked:

However, in my sign-in page that is using custom policy, the error is not showing my account being temporarily locked despite having Localized String in my TrustFrameworkExtensions.xml:
<LocalizedString ElementType="ErrorMessage" StringId="UserMessageIfUserAccountLocked">#Your account is temporarily locked to prevent unauthorized use. Try again later.</LocalizedString>

The error message in sign-in page is always The username or password provided in the request are invalid:

May I know what could be the direction for me to troubleshoot this/ common causes to this?
EDIT: From Chrome developer tools, the call is always returning the same The username or password provided in the request are invalid. response even if the lockout threshold is exceeded.
Comment: We know what the cause is, but we have not fixed it just yet. If you really need a quick fix, remove the metadata item "grant_type" from login-noninteractive technical profile. This might have untoward side effects that are not yet known.
Comment: Can you do a successful login at all?
Comment: @JasSuri-MSFT yes, I can successfully login and issue JWT with the correct password.
Comment: Ok thanks for confirming, we are aware of the issue and are working on it.
Comment: Hi @JasSuri-MSFT, thanks for your confirmation and help! To supplement, the issue is reproducible on different tenants in different subscriptions. The only thing being shared is the custom policies.(which the tenant name and IEF ids... are replaced). I hope it can give more clues, but unfortunately I cannot share the custom policy here due to some non-disclosure agreement. Kindly let me know what other information could be useful to you and I will check if I can supply. Many thanks again.
Comment: @JasSuri-MSFT Thanks for your help! We can confirm that the temp fix proposed is working. Looking forward to your perm fix. :)
Comment: Hi, @ray. Try to use unique passwords, see the similar [issue](https://social.msdn.microsoft.com/Forums/en-US/ea917a58-cdba-412d-a24d-1e4d1b90f17a/b2c-account-locking-is-not-working-properly?forum=AzureSecurityCenter).
Comment: Thanks @JasSuri-MSFT, what (if any) are the repercussion of making that change? Are there any side-effects to be aware of?
Comment: No known bad side effects at this time.
Comment: Any update on this Jas? Is it possible to check account lock status during sign in journey and control messaging and behavior? Our requirement is to not accept correct password during lock out and always display "Your account is currently locked. Wait X minutes before trying" - I tried using AAD read user by email address but not sure which claim to check and how to stop the journey from executing following steps...
Answer: I had a similar issue with this exact message not appearing when a user is locked out. Except that I am not using any custom user policies, so the quick fix suggested by Jas was not relevant for me.
I found that I was able to get it working by enabling custom languages for the user flow, and overriding the default value for that error message:
{
  "ElementType": "ErrorMessage",
  "ElementId": null,
  "StringId": "UserMessageIfUserAccountLocked",
  "Override": true,
  "Value": "Your account is temporarily locked to prevent unauthorized use. Try again later."
}

Comment: Thanks for your effort first. Although I do not work on the ADB2C project anymore, I doubt that the team will switch from custom policy to user flow. AFAIK, the quick fix provided from @JasSuri-MSFT is still valid and in-force, though a perm fix will be even better :)


How can policy parameterization be simpler than action-value parameterization in function approximation?

Question: In the second edition of the book "Reinforcement Learning: an introduction" by Sutton and Bato page 323 (Policy gradient chapter) it says that:
"Perhaps the simplest advantage that policy parameterization may have over action-value parameterization is that the policy may be a simpler function to approximate."
Can anyone please explain the reason?
Thank you
Answer: Consider a game on the positive half of the number line, where you start at some integer $k$, and can move down by 1 or up by 1 each turn. The reward function is $f(x)$ for some monotonically decreasing function $f$ which is very hard to model -- for example, $f$ could be the negative cost of the optimal solution to a TSP problem on the first $x$ points in some set.
Then clearly, computing all these rewards and the action-value function is quite difficult. However, the optimal policy is simple: move down by 1 always.
Comment: Can you explain more everything after "-- for example", please?
Comment: If you're unfamiliar with the traveling salesman problem, then that probably wasn't a helpful example. Just imagine that $f$ is a very hard function to model -- the world is filled with such functions.
Comment: Ok, thanks. But how about moving down by 1 in the game. What was the goal of the game
Comment: @AliGh the MDP formulation does not require a goal -- usually the problem is considered solved when the reward is maximized. In this case, reward is maximized when you reach $0$, since $f$ is maximized there.
Comment: Actually, it is true when we have the reward function. Otherwise, we need to know the object.
Comment: not sure what point you're trying to make
Comment: Nothing related to the question. Just about your last claim. Thanks
Comment: @AliGh The reward is maximized at 0 because $f$ is monotonically decreasing.
Answer: Simple rule, action-value would be a mapping to the discrete function while policy network would be mapping to the continuous field. A continuous function is simpler to approximate.
Comment: I'm pretty sure this is not right. What do you even mean by " action-value would be a mapping to the discrete function "


Does the LIV Golf League recognize finishes in major championships?

Question: LIV Golfers Brooks Koepka and Phil Mickelson finished tied for second in the Masters tournament. Does LIV Golf recognize results in major championships?
Phil Mickelson 2023 LIV Golf results do not include the Masters.

For comparison, the PGA Tour includes Jon Rahm's Masters win in their results.
Comment: My hunch is no, they dont. But I think finding proof might be hard, it seems like access to the LIV rules and regulations/players handbook is via a court order, where as you can read the PGA equivalent [here](https://qualifying.pgatourhq.com/static-assets/uploads/2022-2023-PGA-TOUR-HBandRegs-DEC%202022.pdf). Page 84 details how performances in majors contribute towards the fedex cup.
Answer: Per the information available on the LIV Format page, the 14 LIV events are the only ones that are included in their format.  The first 13 count for the individual title, and the 14th determines the team winner.  Non LIV events do not count for their rankings, so for example the Masters would not be included.
Their format is pretty different from the PGA format, with only 48 players at each tournament and no cut, 54 hole (3 day) tournaments, and a team overall result being determined at the end (which means all players need to play all three rounds).


What does the '°' notation signify?

Question: I just saw this comment by Tim, in another question:

D° can't have a C. It's spelt D, F, Ab, Cb.Or as a triad, just the 1st 3 notes. Ao/F is F b9, and Ao/F# will just be F#o. Or D b9/F#. If this helps - hope so.

What exactly are D°, A°/F, A°/F# and F#°? This is the first time I have seen something like this.
Comment: I assumed that was just a diminished sign in an easier to type form. Technically it should be a superscript degree sign, but that's not easy to input in Stack Exchange.
Comment: I've edited your Do by `D°`, that means `D°` isn't Do. `D°` = D dim and  `D°7 = D dim 7. Also Ao and F#o are written wrong.
Answer: The 'o' bit designates dim, or diminished. Slightly different from the ø which is half-diminished.(Which was pointed out by someone as wrong - it should be a third diminished!) Wish my keyboard could print it properly - it probably can, but I'm not clever enough to make it work! Half-dim.,(that could even be me...) incidentally is aka m7b5.
Comment: @Tim- yes, do listen to it.  But the way the piece is constructed, basically alternate I and ii chords in Ionian, makes the V9 a modern interpolation.
Comment: @Tim- I guess everything is off subject, if you just look at it hard enough.  Yes, with modern ears, it sounds like a g-b-d-f-a ninth chord, minus the root.  But the g never happens in the whole piece as root of a chord: this is a good example of an ionian piece that is decidedly not major.
Comment: I'd just like to point out that perhaps the oldest known half diminished seventh chord, in this case b d f a, comes in the English medieval canon _Sumer is icomen in_.
Comment: @ScottWallace - I'm betting it's actually V9 without the root. Can't say I know it. Must listen...
Comment: @ScottWallace - can't find the run mentioned in any of the dots I've trawled through.
Comment: @Tim- You have to look at the six part version, the four part canon plus the two "pedes" or feet.  I'll see if I can find it for you.
Comment: @Tim- here's one transcription: look at the last eighth note of bar 23: http://hz.imslp.info/files/imglnks/usimg/8/8c/IMSLP124264-WIMA.6bb3-Anonymous_Sumer_is_icumen.pdf

cheers from sunny Vienna, Scott
Comment: @ScottWallace - yes, seems like a perfect cadence, almost, going domiant (no root)9 to root (sus4) to I. thanks. We're just about to get moaned at now! Specially as it's off subject.
Comment: @Tim- hmmm.  Depends on what you mean by "synonymous", doesn't it?  _Sumer is icumen in_ doesn't have one single V chord: it's just alternating I and ii chords, with some passing notes.  To me at least, it sounds quite different than major harmony.  But if you want to call it major, I can't really fault you.
Answer:
`What does the '°' notation signify?

° means diminished, which means that you play a minor chord with a flattened five.

`What does the 'X/Y' notation signify?

This is called slash chords.
This means that you play an inversion of the X chord where the lowest note is Y.
Example: C/G is played as G, C, E.
In some cases, like the ones that you present, an extra note might be added that is not necessarily a part of the original chord.
Example: C/Bb is played as Bb, C, E, G, which is just an inversion of C7 with the seventh note in the bass.

What is D°?

D, F, Ab

What is A°/F?

F, A, C, Eb

What is A°/F#?

F#, A, C, Eb

What is F#°?

F#, A, C

I found this site to useful: https://www.pianochord.org/
To find out what D° means, then you

select D in the top bar
check through the D chord categories; since it's not there, you
go down to the Explanations below
find Ddim - D diminished (D°)
select Ddim in the listing above

This gives https://www.pianochord.org/d-dim.html

On the website, you also get help to fingering.
Comment: I wonder why in this collection of chords there is no D dim7? D°7?
Comment: I don't know whether it has been added in the meantime. But it's there now.
Comment: "which means that you play a minor chord with a flattened five" While that's true, to me,a dim is different from a m7b5.  Both are a minor chord with a flat 5, but the 7th of the former is 1/2 step lower than the latter.
Comment: @Duston, I completely agree that `dim` and `m7b5` are different, but notice that I'm talking about `dim` and not `dim7`. I also agree with you that `dim7` and `m7b5` are different by the 7th being shifted a semitone.

What does the '°' notation signify?


Can you receive an email as an actual text file?

Question: Is it possible to setup a mailbox (using MS Exchange) to receive emails and store them as a text file on the server?
A developer has asked if this is possible so he can then build it into his application.
Any help is always appreciated
---EDIT---
Speaking to the developer who's requested this, he's explained in more detail what he needs.
He basically wants users to be able to email firstname.lastname@example.com and to some how get those emails in text format into an SQL database.
Has anyone had any experience with this before or know of any application that can do this?
 .
Thanks
Elliott
Answer: Although it could probably be done it's not a straightforward or standard thing for Exchange. I would suggest the developer use POP3 or IMAP to fetch the messages from Exchange and then do whatever he needs to do with them. It's much easier and more portable than trying to make Exchange do something it wasn't meant to do. As POP3 is particularly easy to program this should be quite trivial for an experienced programmer.
Answer: Short answer: Sorta.
Long Answer: Exchange allows you to export messages and mailboxes with the Export-Mail command, but, of course, it only lets you export it to Microsoft's crappy PST format. From there you have a number of utilities that can break down the pst to text. It's guaranteed to be extremely tedious.
John is absolutely correct. You'd be much better off downloading the mail programmatically using POP or IMAP.
Answer: I'm not familiar with MS Exchange, but for me it would be more natural connect to server via IMAP and walk thru inbox directly. Because I don't think that running developed application on the same email server is good idea (which is mandatory for accessing files). And sharing folder with text emails to be accessible from network? Not a good idea either..
Regards, Martin.
Answer: To add to the other excellent answers:
We had to do just this on a project I worked on.
We just let the admin enable IMAP access on the Exchange server, then used the JavaMail library to download the mails via IMAP (it was a Java project).
Worked like a charm, so I'd definitely recommend it. There's tons of IMAP libraries around for just about any language.
Using IMAP instead of text files also allows for other nifty tricks. You could for example move emails to other folders on the server after processing them (such as "processed", "wrong format", ...). All these folders can be viewed as regular folders using any email program (including, but not limited to Outlook), and users can directly see all the mails before and after processing, maybe even queue a mail for reprocessing simply by moving it back into the inbox.
We used that to give users a simple way to control the mail processing.


Recursive Calls in Euclidean Algorithm

Question: <code>algorithm gcd(x,y)
     if y = 0
        then return(x)
else return(gcd(y,x mod y))
</code>
we're given this as the euclidean algorithm.

I get everything up to "so in both cases the first argument decreases by..." But Im really confused about how we get the 2n.
Answer: If $x$ has $n$ bits, $\left\lfloor\frac{x}2\right\rfloor$ has $n-1$ bits, so decreasing $x$ by a factor of at least $2$ reduces the number of bits by at least $1$. After at most $n$ such reductions you reach $0$ bits, meaning that the first argument is $0$, and the algorithm terminates. It takes $2$ calls to ensure a reduction by a factor of at least $2$, so at worst it takes $2n$ calls to get $n$ reductions by a factor of at least $2$ and hence a $0$ first argument.
Answer: Let us look at the minimal numbers $a,b\in\mathbb{N}$, $a>b$ for which Euclid algorithm will have $n$ steps. It can be shown that $a\geq F_{n+2}$, and $b \geq F_{n+1}$, where $F$ defines Fibonacci sequence.
By induction on $n$.
Base: $n = 1$.
There are numbers $a=2$ and $b=1$.
Let the claim holds for $n-1$.
Let us look minimal numbers that are requires for $n$ steps.
There are numbers for which $a_1 = b$ and $b_1 = a\mod b$ require $n-1$ steps.
By the inductive assumption that numbers are $a_1 =F_{n+1}$ and $b_1=F_n$.
So, minimal numbers for $n$ steps are those which gives $b = F_{n+1}$ and $a = a_1 + b_1$. Therefore
$a = a_1 + b_1 = F_{n+1} + F_n = F_{n+2}.$
That concludes the proof.
Now, for the numbers $a, b\in\mathbb{N}$, $a>b$, $a\leq F_{n+2}$ we'll need not more than $n$ steps.

Recursive Calls in Euclidean Algorithm


Recebendo valor de um método para outro - Objective C

Question: Eu preciso receber o valor que vem das configurações do aparelho (Que eu já consegui, como está no código abaixo) e preciso passar esse retorno para uma string que vai permitir o login ao meu aplicativo, dê uma olhada no código:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString* txt = [defaults objectForKey:@"txtEmail"];

O código acima está no AppDelegate.m (Dentro da pasta chamada Baker), e é por esse trecho que eu estou pegando as informações que foram configuradas no aparelho, até aqui tudo bem, está funcionando certo. O problema é que eu preciso passar essa variável 'txt' para outra classe (se é que posso chamar assim) chamada Constants.h (Está na pasta chamada BakerShelf) e colocar nesse trecho de código:
#define NEWSSTAND_MANIFEST_URL @"[link_do_site]?digitha_userid=[txt]

Substituindo o [txt] pelo valor recebido do primeiro trecho.
Obrigado.
Comment: Pelo que entendi da semântica do arquivo `Constants.h` é que outros arquivos usem ele, e não o contrário. Logo você teria que dar um include nele (`Contants.h`) de dentro do `AppDelegate.m` (de uma olhada em http://stackoverflow.com/questions/439662/what-is-the-difference-between-import-and-include-in-objective-c) e ai poderá usar tudo que foi declarado no `header`.
Comment: Na verdade como é uma constante, você não pode mudar o valor dela, porque no momento da definição você não possui o valor do "txt", você teria que ao utilizar o valor, criar uma nova NSString dando replace no placeholder. De uma olhada em http://stackoverflow.com/questions/668228/string-replacement-in-objective-c.
Comment: Obrigado pelo ajuda, isso vai ser útil, mas minha dificuldade está em trazer a variável de um arquivo para outro. Uma variável está declarada no AppDelegate.m, e eu preciso usar ela no Constants.h. Sabe como posso fazer isso?
Comment: Ótimo! Consegui obter os valores e colocar na string. Mas pelo que vc falou então eu não vou conseguir colocar essa string de volta nesse trecho de código `#define NEWSSTAND_MANIFEST_URL @"[link_do_site]?digitha_userid=[txt]` ? Pq eu preciso que a minha string alterada volte para o Constants.h para ser usada nesse #define, não tem nhm meio de eu fazer isso?
Comment: Já que eu já tenho a string organizada, não tem como eu fazer algo assim: `#define NEWSSTAND_MANIFEST_URL = variavel`?
Comment: Conheço duas formas: Em vez usar define, declare ela como `static` (tendo um template usando define). Ou coloque ela nas preferencias do usuário depois de fazer o replace.
Comment: Criei como `static` e o código ficou assim `static NSString *NEWSSTAND_MANIFEST_URL = urlTxt`. Porém ele da um erro "Initializer element is not a compile-time constant"." Pelo que eu entendi, esse `Constants.h`é um arquivo que vai ser lido antes da execução do programa, então tudo deve ser estático, e não da para usar variáveis. Teria alguma sugestão de como resolver esse problema?
Comment: Obrigado pela ajuda, consegui resolver o problema criando uma variável global com a string, e dando replace nas partes que eu precisava editar, funcionou sem problemas.
Answer: Amigo, estive com um problema parecido com o seu, estava tentando armazenar dados gerados em uma classe e passar para outra. A solução que encontrei foi a seguinte:
Vá na classe que irá receber os dados, e crie uma variável que irá guardar os dados e sua propriedade. Depois crie também um método que receba como argumento os dados que você quer guardar, e dentro do método faça ele ser armazenado na variável que você criou.
No arquivo ClasseOrigemDados.m, coloque o #import "ClasseQueArmazena.h" e instancie um objeto da classe que irá receber os dados, e passe o valor que vc quer no argumento do método.
Como no código de exemplo que vou fazer abaixo para ficar melhor ilustrado.
*** ClasseQueRecebeDados.h ***

import<UIKit/UIKit.h>

@interface ClasseQueRecebeDados : NSObject{

 NSString* receptor;

}

@property(nonatomic, retain) NSString* receptor;

-(void)metodoTransfereDados:(NSString*)dadosRecebido;

@end

No arquivo ClasseQueRecebeDados.m você implementa esse método da seguinte maneira:
#import "ClasseQueRecebeDados.h"

@implementation ClasseQueRecebeDados

@syntesize receptor;

-(void)metodoTransfereDados:(NSString*)dadosRecebido{

 self.receptor = dadosRecebido;
}

@end

Agora em ClasseQueForneceDados.m você faz assim:
// Importe a classe para instanciar um objeto dela e ter acesso ao seu método.
    #import "ClasseQueRecebeDados.h"

      @implementation ClasseQueForneceDados

    -(void)DentroDeAlgumMetodoDaClasseQueForneceDados{

     ClasseQueRecebeDados* armazenador = [[ClasseQueRecebeDados alloc]init];

      // Aqui você instancia a classe ClasseQueRecebeDados e usa o método.
     [armazenador metodoTransfereDados: self.dadoQueSeráEnviadoHaOutraClasse];

    }
    (DEMAIS CODIGO DA IMPLEMENTAÇÂO ...)

    @end

Ao usar o método, você enviará os dados para às variáveis do objeto que você instanciou.  Dentro do método, acredito que será mais útil guardar os dados em uma plist, do que ter ele somente na memória do app, deste modo os dados ficarão visíveis de vários pontos do app.
Espero que tenha ajudado, qualquer dúvida basta comentar abaixo!
Comment: Existe também o uso de singleton. Pode ser interessante para você. Dê uma olhada nesse link: http://pt.stackoverflow.com/questions/25447/manter-objeto-vivo-na-memoria-para-outra-classe/25466#25466
Answer: #import <UIKit/UIKit.h>

@interface UIView ()

@end

NSString *Global_PESS_CODIGO;

#import <UIKit/UIKit.h>
#import "Constants.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

e no Appdelegate.m
NSString* txt = [defaults objectForKey:@"txtEmail"];

Global_PESS_CODIGO = txt;

depois é só importar #import "Constants.h" quando vc quiser usar a string
Answer: Por que você precisa definir uma constante? Por que não criar uma classe com um método que retorna o valor?
Asim:
@interface Constants
+ (NSString *)newsstandManifestURLString;
@end

@implementation Constants
+ (NSString *)newsstandManifestURLString {
    NSString *txt = [[NSUserDefaults standardUserDefaults] objectForKey:@"txtEmail"];
    return [NSString stringWithFormat:@"[link_do_site]?digitha_userid=%@", txt];
}
@end


Dont want to uninstall my module in openerp

Question: My requirement is that if anyone install my module in openerp gtk-client after that he/she can't uninstall that module in current database.Consider database name as 'XYZ'.
Answer: I found a solution by inheriting the ir.module.module class and overriding the button_uninstall method.
Answer: To uninstall a module, you can go to Administration / Modules / Modules... search and open your module.
Then, there is a "uninstall" button to uninstall your module. However, it's a Beta version of the functionnality. I've never had a problem yet.
EDIT:
According to your comment, the only way to do that is to specify a security file to prevent a user can go into the administration menu.
Comment: Bt I dont want to uninstall my module.Take in mind that anyone can install my module but cant uninstall it even if he/she wants.
Answer: As I recall, the use control module could not be uninstalled. There was a big discussion about it in this bug, and it's since been removed from the extra addons branch. You could poke around in the source code to figure out what it was doing to be so nasty.
Answer: Not quite what you asked, but you could maybe configure __openerp__.py to:

set you module in the Hidden category
set auto_install to True

In this way, you are guaranteed that your module will be installed, and not uninstallable.


Difference between cURL and SOAP in PHP?

Question: I am curious to know about different ways of implementing web services in PHP? Is there other ways except cURL and SOAP? How SOAP is different than cURL? Is there any similarities also between them?
Thanks,
ursitesion
Answer: You can implement a web service in PHP with SoapServer or with PHP - return JSON creating a REST interface. There are other ways, such as XML-RPC, but I usually end using either SOAP or REST, I prefer REST whenever possible.
Curl is a tool that you can use to consume a web service, it's not used to create a web service.
Answer: REST or SOAP reading that might help.
Probably best to think of cURL as just a way to send a request (eg GET,POST) to another server.
There are alternatives to cURL, including just straight file_get_contents()
Edit : replaced a rotted link.  Also, having used SOAP quite a lot since this first reply, I'd add that another main reason you'd prefer SOAP to REST would be if you have to absolutely, positively double check that every transaction was received, else have the opportunity to resend it. No doubt you can do this with a suitably designed REST webservice, but that would need careful design and testing.
Comment: Can we send an AJAX to a cURL service?
Comment: Typically Ajax communicates from the client, say the browser, back to Server A (the mother ship) which can then cURL out to Server B and get data.
Comment: That means... AJAX can not make any request to the cURL right.?? cURL service is only open to servers.?
Comment: @Cups The above link is expired.
Comment: Cheers, updated it with another similar link, added more of my own thoughts too.


I can't figure out the bug on cs50 pset4 serpia filter. The expected figures and the actual looks the same but still giving a error

Question: I am doing cs50 pset4 sepia filter. The tests results from check50 show that the last two tests fail, but all the other tests are okay. I can't figure out what is the problem, because the expected output and my actual output are the same.
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            float orginalRed = image[i][j].rgbtRed;
            float originalGreen = image[i][j].rgbtGreen;
            float originalBlue = image[i][j].rgbtBlue;

            float spRed = round(.393 * orginalRed + .769 *  originalGreen + .189 *  originalBlue);
            float spGreen = round(.349 *  orginalRed + .686 * originalGreen + .168 *  originalBlue);
            float spBlue = round(.272 *  orginalRed + .534 *  originalGreen + .131 *  originalBlue);

            if (spRed > 255.0)
            {
                spRed = 225;
            }

            if (spBlue > 255.0)
            {
               spBlue = 255;
            }
            if (spGreen > 255.0)
            {
               spGreen = 255;
            }
            image[i][j].rgbtRed = spRed;
            image[i][j].rgbtGreen = spGreen;
            image[i][j].rgbtBlue = spBlue;

        }
     }
}

Answer: The one thing sticking out is that you set red to 225 if it exceeds 255. That looks wrong.
Anyway, simplify:
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            RGBTRIPLE x = image[i][j];

#define X(r, g, b) fmin(255, round(r * x.rgbtRed + g * x.rgbtGreen + b * x.rgbtBlue))
            image[i][j].rgbtRed = X(.393, .769, .189);
            image[i][j].rgbtGreen = X(.349, .686, .168);
            image[i][j].rgbtBlue = X(.272, .534, .131);
#undef X
        }
    }
}

Answer: If you look closely at the results from the 2 check50 tests that were wrong, line 7-9 of the expected output is:
255 251 195
255 255 214
255 255 232
Then lines 7-9 of the actual output are:
225 251 195
225 255 214
225 255 232
The red values of the actual output should have been rounded to 255 instead of 225. The bug is at line 17, where you say:
spRed = 225; instead of spRed = 255;
I also replaced the if statements with a ternary operator and replaced the use of variables orginalRed, orginalBlue, and orginalGreen with the actual pixel values, for better run time and simplicity.
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
    for (int i = 0; i < height; i++)
    {
        for (int x = 0; x < width; x++)
        {
            float spRed   = round(.393 * image[i][x].rgbtRed + .769 * image[i][x].rgbtGreen + .189 *  image[i][x].rgbtBlue);
            float spGreen = round(.349 * image[i][x].rgbtRed + .686 * image[i][x].rgbtGreen + .168 *  image[i][x].rgbtBlue);
            float spBlue  = round(.272 * image[i][x].rgbtRed + .534 * image[i][x].rgbtGreen + .131 *  image[i][x].rgbtBlue);

            image[i][x].rgbtRed   = (spRed   < 255) ? spRed   : 255;
            image[i][x].rgbtBlue  = (spBlue  < 255) ? spBlue  : 255;
            image[i][x].rgbtGreen = (spGreen < 255) ? spGreen : 255;
        }
    }
    return;
}

Answer: The arrays could be the problem also you just return maybe it waits you to return 0 extra. But usually main problem in c I think arrays.
Have you use allocate memorty for this array : image[i][j]


Adding distances/weights to absorbing markov chain

Question: in presence of an absorbing state, I want to calculate mean/expected 'distance' from any state to that absorbing state. What I mean by distance is that I want to give different lengths from one particular state to another.
For example, below i wrote a simple coin toss, 2 levels deep. One player is in Start S, with a coin toss he goes A or B. If he reaches A, with %100 probability he reaches End after. But if he reaches B, he either reaches End or he turns back to Start with equal probability.
\begin{align*}
\begin{pmatrix}
 & S & A & B & E \\
 S & 0 & \frac{1}{2} & \frac{1}{2} & 0\\
 A & 0 & 0 & 0 & 1  \\
 B & \frac{1}{2} & 0 & 0 & \frac{1}{2} \\
 E & 0 & 0 & 0 & 1
\end{pmatrix}
\end{align*}
Later I found total transition matrix between transient states
\begin{align*}
    (I-Q)^{-1} = \left(\begin{array}{rr}
\frac{4}{3} & \frac{2}{3} & \frac{2}{3} \\
0 & 1 & 0 \\
\frac{2}{3} & \frac{1}{3} & \frac{4}{3}
\end{array}\right)
  \end{align*}
So if I sum first row, I find 8/3 , that is expected number of steps from Start to End
Now where I am stuck is, probabilities stay same but if going from one state to another  differs, I dont know how to manipulate these matrices to take distances.
For example, distance from A-> E may be 1 km, but B -> E may be 5 kms. S-> A may be 20 kms, rest can be 1 km. How can I manipulate these matrices to get this information. Thanks in advance
Answer: One way to approach this is to create another Markov chain where the states are the transitions that have positive probability in the original Markov chain, plus one state for the initial state. We only need to include transitions from transient states since that's all we're interested in. So we exclude the transition $E$ to $E$. In your example we would have states: $S,SA,SB,AE,BS,BE$. Our transition matrix, $F$, for this new Markov chain is:
\begin{align*} F =
\begin{pmatrix}
   & S & SA & SB & AE & BS & BE \\
 S  & 0 & \frac{1}{2} & \frac{1}{2} & 0 & 0 & 0 \\
 SA & 0 & 0 & 0 & 1 & 0 & 0 \\
 SB & 0 & 0 & 0 & 0 & \frac{1}{2} & \frac{1}{2} \\
 AE & 0 & 0 & 0 & 0 & 0 & 0 \\
 BS & 0 & \frac{1}{2} & \frac{1}{2} & 0 & 0 & 0 \\
 BE & 0 & 0 & 0 & 0 & 0 & 0 \\
\end{pmatrix}
\end{align*}
Entry $F_{i,j}$ in matrix $(I-F)^{-1}$ represents the expected total number of visits to state $j$ beginning in state $i$ (states $i,j$ being states in the new Markov chain), using the same reasoning as for the $Q$ matrix in the original Markov chain. Here, we have,
\begin{align*} (I-F)^{-1} =
\begin{pmatrix}
   & S & SA & SB & AE & BS & BE \\
 S  & 1 & 2/3 & 2/3 & 2/3 & 1/3 & 1/3 \\
 SA & 0 & 1 & 0 & 1 & 0 & 0 \\
 SB & 0 & 1/3 & 4/3 & 1/3 & 2/3 & 2/3 \\
 AE & 0 & 0 & 0 & 1 & 0 & 0 \\
 BS & 0 & 2/3 & 2/3 & 2/3 & 4/3 & 1/3 \\
 BE & 0 & 0 & 0 & 0 & 0 & 1 \\
\end{pmatrix}
\end{align*}
For example, $F_{0,5} = 1/3$ is the expected number of times we move in one step from state $B$ to state $E$ (in the original Markov chain) given that we start from state $S$.
We also need a distance vector for the distances between states: $S\; (=0),SA,SB,AE,BS,BE$:
\begin{align*} D =
\begin{pmatrix}
 0 \\
 20 \\
 1 \\
 1 \\
 1 \\
 5 \\
\end{pmatrix}
\end{align*}
The expected total distances covered is then given by,
\begin{align*} (I-F)^{-1} \times D =
\begin{pmatrix}
 50/3 \\
 21 \\
 37/3 \\
 1 \\
 53/3 \\
 5 \\
\end{pmatrix}
\end{align*}
Since we start at state $S$, the value required is $\dfrac{50}{3}$.
Comment: I appreciate it. Thank you very much
Comment: @xcvbnm No problem. Glad I could help.


Using Random Forest Regression vs Classification for Confidence Metrics

Question: I have a fairly large dataset with each sample corresponding to one of two target values. I'm using a random forest to assign confidences to new samples for what class they may belong to.
My question is: Does the output of a random forest regressor (mapping each new sample to [0.0, 1.0], where 0 and 1 are the labels for the training samples) differ as a metric for "confidence" from the probabilities given by a random forest classifier on the same data? In other words, would it be valid to train a random forest regressor on the data and interpret the model's outputs on various new samples as the probability that it belongs to class 1?
Any explanation/intuition behind answers would be much appreciated!
Answer: Random forest algorithms for regression in classification are nearly the same. The important difference is the loss function used for the training. For classification, they typically use entropy, or Gini impurity, for regression squared or absolute error. You can use squared error for classification tasks, it even has a special name: Brier score. Recently there was an interesting paper by paper by Hui and Belkin (2020) showing that using squared error as a loss function for a neural network may give as good if not better results as compared to the "default" log loss. However, keep in mind that using different loss functions may lead to different results.
But why would you do that? Random forest classifier does predict the probabilities, scikit-learn has the predict_proba function for that purpose.
Moreover, if you care more about the probabilities than the hard classification, you should validate and calibrate the probabilities. For more details check questions tagged as calibration.
Answer: yes, that should be the objective. train on one dataset and test on other datasets. Confidence and accuracy should be same. if not your model might be over fit or under fit.


Number of distinct permutations given a character set.

Question: How many distinct three-letter sequences with at least one $T$ can be formed by using three of the six letters of $TARGET$? One such sequence is $T-R-T$. [MathCounts 2005 National Countdown]
The problem given is easy, because the word given is small enough for casework. (One $T$ implies there are $3*4*3=36$ words. Two implies there are $3*4=12$).
However, how does this generalize to $n$ given characters and $m<n$ letter long distinct words? If $n=m$, there is the standard technique of dividing by the number of repeated letters factorial, but for a long word such as $AAABCCDEEEFFG$, I don't know how to effectively compute all possible $7$ letters words.
(All I need is this, as generalizing the "at least one $T$'s" part is just subtracting the words that can be made with zero $T$'s)
Answer: There is a generating function approach for this.
Classify letters in AAABCCDEEEFFG according to frequency of occurrence.
Three occur once [B, D, G], two occur twice [C, F], and two occur thrice [A, E].
Find the coefficent of $x^7$ in $7!\cdot(1+x)^3\cdot(1+x + x^2/2!)^2\cdot
 (1+x+x^2/2!+x^3/3!)^2$
PS
Re your query, look here
Comment: The coefficient from Wolfram is 727/18
Comment: Sorry. 7! multiplier got omitted, has been inserted. Answer will be 203,560.
Comment: Can you provide a proof of this? I do not understand why this works.
Comment: See link given in PS


Python capture group from string, with regex

Question: I'm new to python, coming from a basic knowledge of perl.
I'm trying to capture a substring with regex.
>>> a='Question 73 of 2943'
>>> import re
>>> re.match("Question.*(\d+)\s+of", a).group(0)
'Question 73 of'
>>> re.match("Question.*(\d+)\s+of", a).group(1)
'3'

What I wanted to do was to catch 73 in the group. I assumed that the parenthesis would do that.
Comment: Operator `*` is _greedy_. Use `*?` instead. Or, better yet, insert a `\s` in the regex before the number.
Answer: .* is greedy. What this means is it will continue to match any character (except for line terminators) 0 or more times. That means the (\d+) capture group you have set up will never happen. What you can do is make the .* part lazy by adding a ? so your regex would look like...
re.match(r"Question.*?(\d+)\s+of", a)

The difference between lazy and greedy regex is well explained here
Answer: If you would like to capture 73 only, you can do
re.search(r'\d+', a).group() which stops searching for a match after finding the first match.
Answer: Your .* part will capture any character included a digit. Better to use except.
Question[^\d]*(\d+)\s+of

that should give you 73


Describing all plane curves with constant curvature

Question: I know that by Frenet-Serret, we have (I know this is only for curves parametrized by arclength, but since every plane curve can be reparametrized by arclength, there's no loss of generality):
$t'(s) = k(s)n(s) \Rightarrow t''(s) = k(s)n'(s)$ (since $k(s)$ is constant)
$n'(s) = -k(s)t(s)$
Since the curvature is constant, I can call $k(s) = c$ and get:
$t''(s) = -c^2 t(s)$
$t''(s) + c^2t(s) = 0$
which has solutions:
$t(s) = A_1 \cos(cs) + A_2 \sin(cs)$ (where I also assume $||t|| = ||n|| = 1$)
so
$a(s) = \frac{1}{c} (A_1 \sin(cs) - A_2 \cos(cs)) + A_3$ is the form all regular curve planes are (I forgot to add regular in the beginning, but it's in the exercise)
"Squaring" both sides, we get:
$||a(s) - A_3||^2 = \frac{1}{c^2} ||A_1||^2 \Rightarrow ||a(s) - A_3||^2 = \frac{1}{c^2} \Rightarrow ||a(s) - A_3|| = \frac{1}{c}$, which is clearly the equation of a circle (I used Gribouillis' answer in the middle of these steps)
Comment: No, you can write $t''=k n'$ only after saying that $k$ is constant, because this is obtained by derivating $t' = k n$. Also note that $t$ is a vector, which means that $K_1$ and $K_2$ are vectors. You need to compute $\|t\|$ at the end, in order to obtain a condition of $K_1$ and $K_2$.
Comment: I don't understand how you replace $t(s)$ with $a(s)$ in the second line. Why not write directly $t'' = -c^2 t$ ? After solving this, you need to add the condition that $\|t\| = 1$, because $t$ and $n$ need to be orthogonal.
Comment: @Gribouillis:  The title idicates that $k$ is constant.
Comment: You're quite right, I've edited my post to reflect that. Thanks! Am I correct now?
Comment: @Gribouillis Forgive my naivety, but how do I compute $||t||$? I can imagine setting $A_1 = (a_1, b_1)$ and $A_2 = (a_2, b_2)$ and proceeding from that, but is there a better way?
Answer: You have
$$
1 = \|t\|^2 = (A_1 \cos(cs) + A_2\sin(cs))^2 = A_1^2 \cos^2(cs) + A_2^2 \sin^2(cs) + 2 \cos(cs)\sin(cs)(A_1\cdot A_2)
$$
Differentiating gives (we assume $c\not=0$)
$$
(A_2^2 - A_1^2)2\cos(cs)\sin(cs)+ A_1\cdot A_2 2(\cos^2(cs) - \sin^2(cs)) = 0
$$
which you can rewrite as
$$
(A_2^2 - A_1^2)\sin(2cs)+ 2 A_1\cdot A_2 \cos(2cs) = 0
$$
derivating again gives
$$
(A_2^2 - A_1^2)\cos(2cs)- 2 A_1\cdot A_2 \sin(2cs) = 0
$$
It follows that $A_1^2 = A_2^2$ and $A_1\cdot A_2 = 0$. Inserting this
in the first equation above shows that $A_1$ and $A_2$ are two orthogonal vectors with norm $1$.
With very little work, you can now conclude that the curve is a circular arc.
Comment: No, $\|a(s) - A_3\|^2 = \frac{1}{c^2}\|A_1\|^2 = \frac{1}{c^2}$. One gets a circular arc centered at $A_3$ with radius $r = \frac{1}{c}$.
Comment: No, it is either $\|a(t) - v\|=r$ or $\|a(t)-v\|^2 = r^2$. Remember that $\|a(t) - v\| = \text{dist}(a(t), v)$
Comment: After some time thinking I got to my edited answer, which shows it is indeed a circle. Does it check out?
Comment: I see my mistake. But shouldn't the radius be $\frac{1}{\sqrt{c}}$? My understanding is that if we have

$||a(t) - v|| = r^2$, that is a circle centered at v with radius r
Comment: I understand now. I appreciate your patience and thoroughness in the explanations. Thank you!
Answer: The OP's solution appears essentially correct to Yours Truly, though as suggested by Gribouillis in his comment it might be wise to say a bit more about $A_1, A_2$ and $K_1$, $K_2$, $K_3$.
Having typed these words, I present a more geometrically-flavored solution which does not rely so much on differential equations or their exact solutions.  To wit:
Suppose $\gamma(s)$ is our curve, parametrized by arc-length, and that
$\kappa(s) = 0; \tag 1$
then
$T'(s) = \kappa(s)N(s) = 0, \tag 2$
so
$T(s) = T_0, \tag 3$
a constant.  Then
$\dot \gamma(s) = T(s) = T_0, \tag 4$
whence
$\gamma(s) - \gamma(s_0) = \displaystyle \int_{s_0}^s \dot \gamma(u) \; du = \int_{s_0}^s T_0 du = T_0(s - s_0), \tag 5$
so
$\gamma(s) = T_0 (s - s_0) + \gamma(s_0), \tag 6$
which is the equation of a straight line.
If, on the other hand, we have constant
$\kappa(s) = \kappa > 0, \tag 7$
we consider the curve $c(s)$ defined by
$c(s) = \gamma(s) + \kappa^{-1} N(s); \tag 8$
we have
$\dot c(s) = \dot \gamma(s) + \kappa^{-1} \dot N(s) = T(s) + \kappa^{-1} (-\kappa T(s)) = T(s) - T(s) = 0; \tag 9$
it thus follows that the "curve" $c(s)$ is constant:
$c(s) = c_0; \tag{10}$
then (8) becomes
$c_0 = \gamma(s) + \kappa^{-1}N(s), \tag{11}$
or
$\gamma(s) - c_0 = -\kappa^{-1}N(s), \tag{12}$
and thus
$\Vert \gamma(s) - c_0 \Vert = \Vert -\kappa^{-1} N(s) \Vert = \kappa^{-1} \Vert N(s) \Vert = \kappa^{-1}, \tag{13}$
since $\Vert N(s) \Vert = 1$.  (13) indicates that every point or $\gamma(s)$ is the same distance $\kappa^{-1}$ from $c_0$; thus it is the equation of a circle, which in fact $\gamma(s)$ is.
We see that every constant curvature planar curve is either a straight line or a circle.
Comment: I very much dislike working with differential equations, so I appreciate your answer. Thanks!
Comment: I understand where you are coming from!
Comment: what if there is a negative constant?


Page manager, Panels and theme suggestions

Question: Page manager and theme suggestions
I have two types of layout
custom_2col_brick
custom_1col_landing

and I need to render the page according to the selected layout.
basically, I needed two page template for each layout. something like the following:
page__custom_2col_brick.html.twig
page__custom_1col_landing.html.twig

Is there a way to do this?
In Drupal 7 I could do it as follows, but panels_get_current_page_display is not working in Drupal 8
/**
 * Implements hook_preprocess_page().
 *
 * @see page.tpl.php
 */

function THEME_preprocess_page(&$variables) {

    if (module_exists('ctools') && module_exists('page_manager')) {
        $display = panels_get_current_page_display();
        $layout = (isset($display->layout)) ? $display->layout : false;

        /* layout e.g column_one_fluid, column_three_fluid etc. */
        $fluid   =  $layout ? preg_match("/\s*.+_fluid$/", $layout) : false;

        /* layout e.g column_one_landing, column_three_landing_fluid etc. */
        $landing =  $layout ? preg_match("/\s*.+_landing$|\s*.+_landing_fluid$/", $layout) : false;

        $variables['page_fluid'] = ($fluid) ? true : false;
        $variables['page_landing'] = ($landing) ? true : false;

        if($fluid) {
             $variables['theme_hook_suggestions'][] = 'page__fluid';
        }
        if($landing) {
            $variables['theme_hook_suggestions'][] = 'page__landing';
        }

    }

Answer: If you don't already have one create a yourtheme.layouts.yml file in your theme folder. There you will define the regions, preview icons, and labels.
custom_2col_brick:
  label: Two Column Brick
  category: My Custom Layouts
  template: layouts/custom_2col_brick
  icon: layouts/custom_2col_brick.png
  regions:
    left:
      label: Left
    right:
      label: Right
    footer:
      label: Footer
custom_1col_landing:
  label: One Column Landing
  category: My Custom Layouts
  template: layouts/custom_1col_landing
  icon: layouts/custom_1col_landing.png
  regions:
    main:
      label: Main Region
    footer:
      label: Footer

Now you can create your page__custom_2col_brick.html.twig and page__custom_1col_landing.html.twig files in your layouts folder. Inside there you can define your template. For example custom_1col_landing.html.twig could contain

        {{ content.main }}

        {{ content.footer }}

Once finished you should have the following files. (The preview icons are optional)
/yourtheme/yourtheme.layouts.yml
/yourtheme/layouts/custom_2col_brick.html.twig
/yourtheme/layouts/custom_1col_landing.twig

Comment:
All pages and layouts works just fine but there is no such a page template suggestion! There should be something like page--custom_2col_brick.html.twig
Comment: this screenshot can be more meaningful. [screenshot](https://dl.dropboxusercontent.com/u/37848856/screenshot_355.png)
Comment: I'm not sure I understand. Every page that is set to use the custom_2col_brick.html.twig will be using that template. Why would you need a page--custom_2col_brick.html.twig? If you need multiple pages to use different versions of the template you should be using panels to do so.
Comment: custom_2col_brick.html.twig render only Content region in the page template. but I want to change other parts of the page template.
Panels is an API in Drupal 8 So, I already use Page Manager and Panelizer.
I need to change some things on the default page template. It will be an alternative page template for custom_2col_brick layout.
Comment: You could try to keep page.html.twig as blank as possible, and fill everything with panels and blocks.
Comment: Thanks Matt, I guess there's nothing else I can do.
panel layout data not accessible through THEME_preprocess_page function.
Thanks again.
Answer: Use hook_theme_suggestions_HOOK_alter() and \Drupal::routeMatch()->getRouteObject().
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mytheme_theme_suggestions_page_alter(&$suggestions, &$vars) {
  $request = \Drupal::routeMatch()->getRouteObject();
  if ($request->getDefault('_entity_view') === 'page_manager_page_variant') {
    $page_name = $request->getDefault('page_manager_page');
    $page_variant = $request->getDefault('page_manager_page_variant');
    $suggestions[] = 'page__page_manager';
    $suggestions[] = 'page__page_manager__' . $page_name;
    $suggestions[] = 'page__page_manager__' . $page_name . '__' . $page_variant;
  }
}

Comment: Please explain the code you included in your answer, to avoid it gets deleted via moderation as a low quality answer ...
Comment: Hey gambry, Thanks for help.
This method seems to work but page_manager_page_variant does not mean anything. ( custom_page-panels_variant-0
, home_page-panels_variant-1 etc.)
This will change on every page and I can not define a constant value.
It makes more sense to use a value that I can define with page_manager ui. Would it make sense to use context for this purpose? and  How do I access to variants contexts ? Thank you.
Answer: Expanding upon gambry's answer:
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mytheme_theme_suggestions_page_alter(&$suggestions, &$vars) {
    $request = \Drupal::routeMatch()->getRouteObject();
    if ($request->getDefault('_entity_view') === 'page_manager_page_variant') {
        $page_variant = $request->getDefault('page_manager_page_variant');
        $name = 'page_manager.page_variant.' . $page_variant;
        $config = \Drupal::configFactory()->getEditable($name);
        if ($config->get('variant') === 'panels_variant') {
            $layout_id = $config->get('variant_settings.layout');
            $suggestions[] = 'page__page-manager';
            $suggestions[] = 'page__page-manager__' . $layout_id;
        }
    }
}

This should give you the layout id. In my case, i have a panel using the default 1 column layout, and I can use the following twig templates:

page--page-manager--layout-onecol.html.twig
page--page-manager.html.twig
page.html.twig

I agree with Matt that for the meat of the page you should use the panel layout's twig files (the yourtheme.layouts.yml method). Only use the above if you're trying to override the overall page template based on the panel layout.


Vector subspaces are the same as the parent vector space.

Question: I came across this question in Halmos's book which i was not sure how to answer
"If M and N are subspaces of a vector space V, and if every vector V belongs either to M or to N(or both), then either M = V or N = V or both."
As i was told inorder to show two finite vector spaces are the same it is enough to show basis of the first is also the basis of the second.
Proof Attempt
Assuming m is basis of M and n is a basis of N and based on the information in the question that every vector of V belongs to M or to N (or both), then either the dim V = dim M or dimV = dim N or both must hold otherwise the it would not be possible for every vector of V to belongs to M or to N (or both). If the dimensions of the basis are the same then to span the whole vector space all we need to do is find the appropriate scalars to represent any vector in V.
Hence we conclude M = V or N = V or both.
Was my reasoning and proof correct ? If not how to improve it.
Any guidance or help would be much appreciated.
Comment: What you've written isn't a proof. In the end of your second sentence you're basically appealing to the statement you're trying to prove. I would suggest that you try to prove the contrapositive.
Comment: @Hardy Related problem. Suppose that $U$ is a subspace of $V$ and $\operatorname{dim} U = \operatorname{dim} V$. Prove that $U = V$.
Comment: Cool thanks very much i would try that.
Comment: I suppose i'd try to form an argument based on the contradiction let's assume U is not equal to V, so that implies there are vectors in V which are not present in U. Since they both have the same dimensions and and U is a subspace of V they must have some common vectors and that would require them to have the same basis, which would imply that the only way there could be vectors in V which are not in U if there is a restrictions on the scalar values allowed for U, as in a different field is used which woudl violate the definition of the vector space. what do u think ?
Answer: If both $M\ne V$ and $N\ne V$ then you can find $v\notin M$ and $w\notin N$. The vector $v+w$ can not belong to $M$ or $N$.


How do you construct a probability tree for overlapping events?

Question: I'm new to probability so apologies if this question is very basic.
I was preparing a tree for an experiment involving drawing two cards from a deck of 52, one after the other.
The events of interest were the probability of drawing an ace followed by a black card.
The first part of the tree was simple - 4/52 for an ace, 48/52 for a non-ace.
The second part though, got me puzzled. The probability of drawing a black card on the second draw depends on whether the initial card was black. But the way the tree was formulated, the color of the 1st card is not revealed.
What exactly is going on here? Is the tree impossible to complete because it was not properly formulated?
Thanks for any tips / insights!
Answer: We work through this using conditional probabilities.
The probability of drawing an ace as the first card is, as you've calculated, $1/13$.  Given that the first card is an ace, the probability that it is black, denoted by $p(\text{card 1 is black} | \text{card 1 is ace}) = 1/2$, and similarly for the probability that card 1 is not black; evidently, the probability that the first card is both an ace and black is equal to $2/52$, and similarly for the probability that the first card is both an ace and red.
Given that card 1 is black, the probability that card 2 is black is $12/51$.  If it isn't black, the probability that card 2 is black is $13/51$.
Combining all this using the rules of conditional probability gives us:
$\begin{eqnarray}
p(\text{ace followed by black}) &=& p(\text{2 is black | 1 is ace}) p(\text{1 is ace}) \\&=& p(\text{2 is black | 1 is ace and black}) p(\text{1 is ace and black)}) \\&&+ p(\text{2 is black | 1 is ace and red}) p(\text{1 is ace and red)})
\\ &=& (12/51)(2/52) + (13/51)(2/52)
\\ &=& {50 \over 51*52} = 0.01886
\end{eqnarray}$
Answer: You need a slightly more sophisticated tree


Help with the last chord in progression

Question: I have following progression:
G-Em-Bm-C
G-Em-Bm-C
G-Bm-F#m-A
D-Bm-F#m-???
G-Em-Bm-C...
I am happy with the progression and it works well, but struggling with the last chord.
Any suggestions?
Thanks!
Comment: @SebastianHoffmann No pun intended? :-)
Comment: Your progression is okay, it's not offensive to the ear, but it seems like you've set out on a journey with no destination in mind. You found some roads that are interesting to travel, but don't know where they're taking you. Perhaps a better approach would be to determine where your ear wants to go, then figure out how to get there. What chord feels best to you leading back into the G? And what might lead best to that chord? Try working back from there.
Comment: G feels natural
Comment: No pun intended ^^ I would also replace F#m with F#7 in the 15th bar
Answer: A great deal depends on how you're voicing the chords. Here are a few options.

My personal favorite: F#7 (or just F#, if you're trying to stick to triads).1

X:0
T:Chord progression idea
K:none
M:none
L:1/1
"^G"[GBd] "^Bm/F#"[^FBd] "^F#m"[^FA^c] "^A"[EA^c] |
"^D"[^FAd] "^Bm/F#"[^FBd] "^F#m"[^FA^c] "^F#7"[^F^A^ce] | "^G"[GBd]

The obvious choice: A

You start with G-Bm-F#m-A. Then effectively substitute D for G, but then continue the same way. So a listener is prepped to hear an A chord, especially since the first part of the song also has two repetitions of its own chord sequence.

The dark horse candidate: E

If you voice G-Bm-F#m-A such that the top pitches are D-D-C#-C#, then you can begin the next group the same way (D-Bm-F#m with top pitches again D-D-C#), but this time let the top pitch progress down to B.
Also provides a nice contrast to the Em earlier in the song.
X:0
T:Another chord progression idea
K:none
M:none
L:1/1
"^G"[GBd] "^Bm/F#"[^FBd] "^F#m"[^FA^c] "^A"[EA^c] |
"^D"[^FAd] "^Bm/F#"[^FBd] "^F#m"[^FA^c] "^E"[E^GB] | "^G"[GBd]

1 A beautiful example of this F#7 G progression can be heard in John Lennon's "Imagine". In the transition from "You may say I'm a dreamer" into "but I'm not the only one" the chords E7 F are used. You can hear them below at 2:15 (link is set to 2:10).
Comment: @wabisabied Your comment jogged my memory. That F#7 -> G progression (E7 -> F) shows up in John Lennon's "Imagine". I've added that to the post.
Comment: Thanks! Really appreciate, doesn't feel like any of these options nicely transit back to G..
Comment: I like the sound of your first choice, the F#7. Not expected but gets there in an interesting and pleasing way.
Answer: Since it looks like you're on your way back to G I think the way to go is to play a D7, a good ol' V7 chord. What do you think? I think it works well because you modulated to D for a bit then the I chord becomes the V chord back to your original key.
Answer: Expanding on my comment to your question, suggesting you work back from where you want to go, that last F#m isn't playing nice to my ear. I suggest you change it to a C chord, and end with D7.
G-Em-Bm-C G-Em-Bm-C
G-Bm-F#m-A D-Bm-C-D7
G-Em-Bm-C…
I think there are also cases to be made for:

changing the third G to an Em. I think it helps prepare the ear for that eventual F#m-A (or F#7-A,) but it's your song and I may be missing your intent.
as others have suggested, changing that F#m to F#7.

G-Em-Bm-C G-Em-Bm-C
Em-Bm-F#7-A D-Bm-C-D7
G-Em-Bm-C...

Help with the last chord in progression


Find the Cartestian form of $6 - 7i$ rotated anticlockwise through $\frac{3\pi}{4}$ about the origin

Question: Find the cartestian form of $6 - 7i$ rotated anticlockwise through $\frac{3\pi}{4}$ about the origin
I realize that I am going to be doing something like:
$\sqrt{85}e^{i\alpha}.e^{i\frac{3\pi}{4}}$ where $\alpha = \arctan{(\frac{7}{6})}$
and then converting to Cartesian form. I guess I am having trouble dealing with the $\alpha$ term since the answer I am trying to arrive at is $\frac{1 + 13i}{\sqrt{2}}$ , i.e, an exact representation not involving any $\arctan$ terms.
How do I arrive at the given answer?
Answer: You do not need to convert 6-7i to polar form at all. Geometry suffices to show us $e^{i\pi/4}=\frac{-1+i}{\sqrt2}$; simply multiply your original complex number by this in standard $a+bi$ form.
Comment: A fiendish plan in its simplicity!
Comment: An elegant solution!
Answer: You should have
$$ r(cos(\theta) + isin(\theta))$$
Your problem seems to be that $\theta = arctan(7/6) + \frac{3\pi}{4}$
You might try using the compound angle formulae:
$$sin( arctan(\frac{7}{6}) + \frac{3\pi}{4}))$$
$$= sin(arctan(\frac{7}{6}))cos(\frac{3\pi}{4})) + sin(\frac{3\pi}{4}))cos(arctan(\frac{7}{6}))$$
We can use a right-angled triangle idea (we can find the sign by noting that we're in the 1st quadrant) to find $sin(arctan(\frac{7}{6}))$.
If we create a right-triangle with opposite 7 and adjacent 6, it's hypotenuse will be $\sqrt(85)$, so:

$sin(arctan(\frac{7}{6}))$ = $\frac{7}{\sqrt{85}}$
$cos(arctan(\frac{7}{6}))$ = $\frac{6}{\sqrt{85}}$

This should get you to the answer quickly.
Comment: I'm not sure if the ambiguity of negative signs is dealt with well enough? But @robjohn's answer is a better solution anyway.


DetailsView does not appear despite visible = true, and how to bind to an empty hashtable?

Question: I am trying to bind a hashtable to a detailsview in my ASP.NET web app. When I do this, the detailsview does not appear on the webpage when I do a debug. I have checked ALL the properties for the control and ensured that the visible and autogeneratecolumns (there is no autogeneraterows property) is set to true, and it is.
Also, I want to bind this detailsview to a hashtable, but when I do, I keep getting object reference not set to an instance of an object errors due to the datasource property or when I say datasource = strings.keys (where strings is the Id of the hashtable). I can understand why this happens, as the strings.keys property is null (hasn't been specified, even when I specify it from using an external example of how this property is used, same error). I was expecting the detailsview to just render  an empty table with Key and Object rows. How could I achieve that? Eventually, I want to bind a label to a value I get back from the hashtable (using a function returning a string).
Thanks
Answer: Could you initialize the hashtable with one element containing Key and Value of empty string? Then, you'll have an instantiated hashtable object, which can be repopulated with the selected data when the user clicks. Also, heed the event you use in the page lifecycle to instantiate the hashtable.
Answer: Ok so I've done this now:
I have a BLL class which is responsible for retrieving and adding items to the hashtable collection. One of the functions is AddToCollection(), which takes parameters for key and value. I select this method via the objectdatasource control, and make up parameter values. I still don't see the detailsview on my page though?
ASPX code:
<asp:DetailsView ID="CopyDetails" runat="server" AllowPaging="True"
                 Height="161px" Width="140px" BackColor="White"
                 AutoGenerateRows="true" BorderColor="Gray"
                 BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"
                 Font-Size="10px">
    <PagerStyle BackColor="#00CCFF" />
</asp:DetailsView>

<asp:ObjectDataSource ID="ObjectDataSource2" runat="server"
                      SelectMethod="ReturnString" TypeName="Strings">
    <SelectParameters>
        <asp:Parameter DefaultValue="Test" Name="SendFrom" Type="String" />
        <asp:Parameter DefaultValue="1" Name="StepOfSite" Type="Int32" />
    </SelectParameters>
</asp:ObjectDataSource>


Access node only from manual URL

Question: Looking for a module or hint to allow a node only be accessed from the manually set URL.
Ex. having node 42 with  URL path setting = myStory can only be accesed with http://host/myStory, while http://host/node/42 will return a NOT FOUND.
Comment: I'd strongly recommend that you have a rethink about your strategy here - "security through obscurity", which I'm certain is what you're attempting to accomplish, is a waste of time. Besides, your users will always be forwarded to the alias anyway. And whether or not the alias is the same you'll still find canonical and shortlink meta tags with the old node/ path, unless you alter all that as well. It's not worth the effort
Comment: @Clive It is not for security. I want to e-mail to users a link so they can (temporary) read the node without to login or be a authent user. Simple avoid that someone can loop thru all node numbers to get the content.
Comment: Yep I understand that, that's called security through obscurity - you're trying to stop people finding other content based on a URL, not based on proper authentication. Suffice to say this is not a simple job (as well as being very bad practice, but that's your call obviously). There are a few hypothetical solutions but they all involve multiple steps and probably some patches to core. I would genuinely consider changing your approach, this will take a long time, cause you a lot of headaches, and won't actually solve the problem you're looking to solve
Comment: @Clive propably you are right for the trouble to get when trying to get this working with Drupal. But I cannot follow your concerns about security. What is the diference to transfer a *secret key* in a request URL from transfering a *session cookie* in the request header or coded in the URL. Common *HTTP session* handling **is** security by obscurity. My *secret* nodes won't be listed in any public view.
Comment: Let's just agree to disagree, this isn't the right place for a debate...
Answer: With respect to all of the commentary given to the question, if you really want to do this, you can look at $_SERVER['REQUEST_URI'] in any number of places and based upon its content, do things differently.
For example, if you go to:
www.example.com/path/to/hidden/content

$_SERVER['REQUEST_URI'] will be /path/to/hidden/content

yet if you go to
www.example.com/node/###

$_SERVER['REQUEST_URI'] will be /node/###

but the same content will be displayed while the url in the browser will be different.
So, if you want to obfuscate your nodes based up that, you could delete their content in a preprocess hook, or cobble together something in hook_init to do a 404 but just also be very wary of the caching of pages for anonymous users as well, so hook_boot would be needed instead, and do you want to do this for logged in users and any of numerous other what ifs.........
Plus, if you have global redirect or another similar module installed, the above won't work as it will have already redirected you to the alias.
Answer: I believe your looking for the Rabbit Hole module.

Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx

And from options:

Deliver a page not found page.
Comment: That will give a 404 for the alias as well

Access node only from manual URL


What is format of this file?

Question: I have a file like this:
+----[ Stream 0 ]
|
| Type: Video
| Codec: H264 - MPEG-4 AVC (part 10) (h264)
| Original ID: 1030
|
+----[ IRIB TV3 [Program 103] ]
|
| Status: Running
| Type: Digital television service
| Now Playing: میان برنامه
| Publisher: IRIB
|
+----[ EPG IRIB TV3 [Program 103] ]
|
| 2014-08-03 14:42:00:Hello
|
+----[ Stream 1 ]
|
| Type: Audio
| Codec: MPEG AAC Audio (mp4a)
| Original ID: 1031
|
+----[ end of stream info ]

What is format of this file , Is there any simple way to convert it to XML?
Comment: Sure, just wrap the whole thing in a `CDATA`. Or did you have some particular XML format you wanted? If so, what's the schema? Do you have something in particular you want to be able to search or xls or whatever, or do you just want some "store any generic hierarchy of strings" schema like plist?
Comment: No, I want particular XML format,Like plist.
Comment: It would be helpful if you actually told us what that format is.
Comment: Where did you get this file? It seems like some EPG or PSI but its not in a format I recognize.
Comment: It's EPG info from IRIB TV3.
Answer: The language you use for parsing this file is up to you, and depends what you are familiar with. Many people would use Perl, but I would use XSLT 2.0.
I would start by doing it line-by-line: there's a small number of different patterns to the lines, and I would translate
+----[ Stream 0 ]

to
<Stream>0</Stream>

and
Status: Running

to
<Status>Running</Status>

That would give you something that's XML, and phase 2 is to convert it into useful XML, which you can do using the grouping facilites in XSLT 2.0 to create something like
<Report>
  <Stream nr="0">
    <Type>Video</Type>
    ...
    <Program nr="103">
      <Status>Running</Status>
      ...
    </Program>
  </Stream>
  <Stream>...
</Report>

But there's no magic bullet here; unless someone has already produced code you can re-use, you're going to have to write a parser for this stuff.

What is format of this file?


não consigo fazer com que aparece quantos alunos foram aprovados

Question: Algoritmo para ler 2 notas de um aluno, calcular e imprimir a média final. Logo após escrever a mensagem "Calcular a média de outro aluno 1.Sim 2.Não?" e solicitar uma resposta. Se a resposta for 1, o algoritmo deve ser executado novamente, caso contrário deve ser encerrado imprimindo a quantidade de alunos aprovados. Para ser aprovado o aluno tem que ter média maior ou igual a sete
Segue meu código:
<code>#include<stdio.h>
int main(void)
{
  float nota1,nota2,media1,media2,nota3,nota4,mediaf=1;
  int resp;
  char aluno1[10],aluno2[10];
    while(resp==1)
    {
        printf("Informe o nome do aluno:");
        gets(aluno1);
            fflush(stdin);
        printf("\nDigite a primeira nota do aluno: ");
        scanf("%f",&nota1);
        printf("\nDigite a segunda nota: ");
        scanf("%f",&nota2);
            fflush(stdin);
        media1 = (nota1 + nota2)/2;
            fflush(stdin);
        printf("\na media de %ce : %0.0f\n",aluno1, media1);
        printf("\nDigite 1 para continuar ou 2 para sair: ");
        scanf("%d", &resp);

    }
  do
    {
            fflush(stdin);
        printf("Informe o nome do aluno:");
        gets(aluno2);
            fflush(stdin);
        printf("\nDigite a primeira nota: ");
        scanf("%f",&nota3);
        printf("\nDigite a segunda nota: ");
        scanf("%f",&nota4);
             fflush(stdin);
        media2 = (nota3 + nota4)/2;
        printf("\nMedia de %s e: %0.0f\n",aluno2,media2);
            fflush(stdin);
        printf("\nDigite 1 para continuar ou 2 para sair\n");
        scanf("%d", &resp);
    }
  while (resp==1);

  return 0;
}

#include<stdio.h>

int main(void)

{
  float nota1,nota2,media1,media2,nota3,nota4,mediaf=1;
  int resp;

char aluno1[10],aluno2[10];

    while(resp==1)
    {

        printf("Informe o nome do aluno:");

        gets(aluno1);

            fflush(stdin);

        printf("\nDigite a primeira nota do aluno: ");

        scanf("%f",&nota1);

        printf("\nDigite a segunda nota: ");

        scanf("%f",&nota2);

            fflush(stdin);

        media1 = (nota1 + nota2)/2;

            fflush(stdin);

        printf("\na media de %ce : %0.0f\n",aluno1, media1);

        printf("\nDigite 1 para continuar ou 2 para sair: ");

        scanf("%d", &resp);

    }
  do
    {

            fflush(stdin);

        printf("Informe o nome do aluno:");

        gets(aluno2);

            fflush(stdin);

        printf("\nDigite a primeira nota: ");

        scanf("%f",&nota3);

        printf("\nDigite a segunda nota: ");

        scanf("%f",&nota4);

             fflush(stdin);

        media2 = (nota3 + nota4)/2;

        printf("\nMedia de %s e: %0.0f\n",aluno2,media2);

            fflush(stdin);

        printf("\nDigite 1 para continuar ou 2 para sair\n");

        scanf("%d", &resp);

    }

  while (resp==1);

  return 0;
}
</code>
Comment: Já tentou adicionar um contador para cada inserção de aluno? exemplo some as quantidades das variaveis aluno1 e aluno2, claro o melhor seria você unificar essas variaveis. Tente trabalhar com case  em vez do do .... while, coloque um case 1 (EXECUTA O CÓDIGO) break case 2 exit break. Acredito que dará certo
Answer: Olá, tudo bem?!
Vou lhe sugerir algumas alterações no seu código para que ele fique melhor:

Tem de ter mais cuidado com a forma como escreve o seu código e tentar mantê-lo o mais limpo e simples possível evitando repetições de linhas de código, por exemplo.
Em segundo lugar, não necessita de declarar tantas variáveis para resolver este problema. A gestão de memória utilizada é algo bastante importante e deve ter uma atenção especial com ela.
Além disso, lembre-se da estrutura de repetição do..while que lhe vai ajudar bastante a não cometer tantas repetições.
Por fim, tenha atenção à forma como são tratadas as variáveis do tipo char que armazenam mais caracteres. Para as exibir corretamente tem de utilizar o formato de leitura '%s' ao invés de '%c'.

Agora vou lhe mostrar a minha proposta de resolução do algoritmo. É bastante simples mas lembre-se: poderão existir resoluções ainda mais eficazes.
<code>#include<stdio.h>
int main(void)
{
  float nota1,nota2,media;
  int resp, aprovados;
  char aluno[10];
  aprovados = 0;
  do {
      printf("\nInforme o nome do aluno: ");
      scanf("%s", aluno);
  printf("\nDigite a primeira nota do aluno: ");
  scanf(" %f",&nota1);
  printf("\nDigite a segunda nota: ");
  scanf(" %f",&nota2);
  media = (nota1 + nota2)/2;
  printf("\nA media de %s e : %0.0f\n",aluno, media);
  if(media>=7){
    aprovados++;
  }
  printf("\nDigite 1 para continuar ou 2 para sair: ");
  scanf(" %d",&resp);
   }while( resp == 1 );
  printf("\nForam aprovados %d alunos.\n",aprovados);
 return 0;
}
</code>
Espero ter sido útil!
nota: cada um tem o seu estilo de código e de indentação, por isso, escreva o código como lhe for mais confortável.
Answer: Olá. Refiz seu código de uma forma mais simples. Se tiver dúvidas, só perguntar.
<code>insira o código aqui

#include <stdio.h>

int mediaParcial(){
float notaUm,notaDois,media;
int x,cont=0,escolha;

do{
printf("Calcular a média de um aluno\n");
printf("1.Sim 2.Não?\n");
scanf("%d",&escolha);
if(escolha==1){
fflush(stdin);
printf("Nota 1:");
scanf("%f",&notaUm);
printf("Nota 2:");
scanf("%f",&notaDois);
media=(notaUm+notaDois)/2;
if(media >= 7){
cont+=1;
}
}else{
break;
}
}while(escolha !=2);

 return cont;

 }

 int main(void) {
 int aprovados;
 aprovados=mediaParcial();
 printf("Foram Aprovados %d",aprovados);
 }
</code>


Toggle with check with jQuery

Question: I have a main element and 2 secondary. When main element is clicked it toggles both secondary ones.
$(".main").click(function() {
    $(this).toggleClass("classA").toggleClass("classB");
    $(".secondary").toggleClass("classC").toggleClass("classD");
));

However, each secondary can be clicked individually, and the class toggle will only affect that element.
$(".secondary").click(function() {
   $(".secondary").toggleClass("classC").toggleClass("classD");
));

I need to add a check/functionality to make sure that if all secondary elements are toggled, the main is toggled too.
Answer: try this:
$(".secondary").click(function() {
   $(".secondary").toggleClass("classC").toggleClass("classD");
   $('.main').click();
));

check out fiddle here:
http://jsfiddle.net/maniator/bx9QQ/
code:
$("#main").click(function() {
    $(this).toggleClass("classA").toggleClass("classB");
    $(".secondary").toggleClass("classC").toggleClass("classD");
});

$(".secondary").click(function() {
   $(this).toggleClass("classC").toggleClass("classD");
   $("#main").click;
});

html:

css:
#main {
    background: grey;
    height: 100px;
    width: 150px;
}

.secondary {
    background: blue;
    height: 50px;
    width: 90px;
    margin: 0 auto;
}

.classA {background: green !important;}
.classB {background: orange !important;}
.classC {background: yellow;}
.classD {background: purple;}

Toggle with check with jQuery


When is it appropriate to run a drupal_bootstrap?

Question: I have a static site with a drupal blog in a subfolder and I want to bring the latest posts into the homepage. I can run a drupal_bootstrap and then load the nodes I want. Is this an ok strategy? When is it appropriate to use drupal_bootstrap?
Answer: In order to bootstrap Drupal from another PHP script, you can use below code:
 define('DRUPAL_ROOT', '/path/to/drupal');
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

When ever you would like to call Drupal Functions or features outside of Drupal root you can use above code..
Answer: Yes, when using Drupal functionality make sure you run the bootstrap. It's more risky to create/alter/query the database native as dependencies might get corrupt/lost.
Answer: Check the doc of drupal bootrstrap: In order to bootstrap Drupal from another PHP script, you can use the following code:
define('DRUPAL_ROOT', '/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

drupal_bootstrap($phase = NULL, $new_phase = TRUE)

Parameters
$phase: A constant telling which phase to bootstrap to. When you bootstrap to a particular phase, all earlier phases are run automatically. Possible values:
DRUPAL_BOOTSTRAP_CONFIGURATION: Initializes configuration.
DRUPAL_BOOTSTRAP_PAGE_CACHE: Tries to serve a cached page.
DRUPAL_BOOTSTRAP_DATABASE: Initializes the database layer.
DRUPAL_BOOTSTRAP_VARIABLES: Initializes the variable system.
DRUPAL_BOOTSTRAP_SESSION: Initializes session handling.
DRUPAL_BOOTSTRAP_PAGE_HEADER: Sets up the page header.
DRUPAL_BOOTSTRAP_LANGUAGE: Finds out the language of the page.
DRUPAL_BOOTSTRAP_FULL: Fully loads Drupal. Validates and fixes input data.

$new_phase: A boolean, set to FALSE if calling drupal_bootstrap from inside a function called from drupal_bootstrap (recursion).
Return value
The most recently completed phase.
Also check this: How to call drupal_bootstrap from custom file in subfolder?
Comment: I was asking when is it appropriate, so I guess that it is always ok?
Comment: @AndrewWelch I guess its appropriate whenever you want to load drupal bootstrap from PHP script, there shouldn't be any problem of doing so, infact this the purpose of providing the option.


About $n$ consective integers such that each of them is a multiple of the element of a given set

Question: Let $S(a)$ be a set of the multiples of an integer $a$.
Then, here is my question.

Question : Is the following true for any $n\ge 2\in\mathbb N$ ?
Supposing that any two of $n$ integers $a_1, a_2,\cdots,a_n$ are coprime, then there exists a set of $n$ consective integers $k,k+1,\cdots,k+n-1$ such that
$$k+i\in S(a_j)\ \ \text{($i=0,1,\cdots,n-1$)}.$$
Suppose that if $k+p\in S(a_r), k+q\in S(a_s)$ and $p\not=q$ , then $r\not=s$.

Example : Suppose that $a_b$ represents that $a$ is a multiple of $b$.
The $(n,a_1,a_2,a_3)=(3,3,5,7)$ case has an example $[48_3, 49_7, 50_5]$.
The $(n,a_1,a_2,a_3,a_4)=(4,2,3,5,11)$ case has an example $[8_2,9_3,10_5,11_{11}]$.
The $(n,a_1,a_2,a_3,a_4,a_5)=(5,2,3,5,7,11)$ case has an example $[119_7,120_5,121_{11},122_2,123_3]$.
Motivation : We know the $n=2$ case is true. I've been able to prove that the $n=3,4$ cases are true. The above proposition seems true for $n$ in general, but I'm facing difficulty for proving that. Can anyone help?
Answer: We will prove a slightly stronger statement.

Let $n \geq 2$ be an integer, and $a_1,\ldots,a_n$ pairwise coprime integers. Then there exists an integer $k$ such that $k + i \in S(a_{i+1})$ for all $0 \leq i \leq n-1$.

The $n=2$ case is obvious. We will use induction on $n$. Let $n > 2$, and let $a_1,\ldots,a_n$ be pairwise coprime integers. By induction hypothesis, there exist integers $k,l$ such that  $k + i \in S(a_{i+1})$ for all $0 \leq i \leq n-2$ and $l + i \in S(a_{i+2})$ for all $0 \leq i \leq n-2$. Write $A = a_1 a_2 \cdots a_{n-1}$, $B = a_2 a_3 \cdots a_n$ and $C = a_2 a_3 \cdots a_{n-1}$. For any $0 \leq i \leq n-3$ we have $l + i \in S(a_{i+2})$ and $k + 1 + i \in S(a_{i+2})$, and thus $l - (k+1)$ is divisible by every $a_j$ for $2 \leq j \leq n-1$. So $l - (k-1)$ is also divisible by $C$. So we can write $l - (k-1) = xC$ for some integer $x$.
Now note that gcd$(A,B) = C$, and thus there exist integers $s,t$ such that $sA + tB = C$. We see that $l-(k+1) = xC = xsA + xtB$, which we can write as $l - xtB = (k+1) + xsA$. Now consider the consecutive integers $k + xsA, k + xsA + 1, \ldots, k + xsA + (n-1)$. For $0 \leq i \leq n-2$, $A \in S(a_{i+1})$, and thus $k + xsA + i \in S(a_{i+1})$. Finally, we note that $k + xsA + (n-1) = l - xtB + (n-2)$. As $B \in S(a_n)$, we get $k + xsA + (n-1) \in S(a_n)$. So the integers $k + xsA, k + xsA + 1, \ldots, k + xsA + (n-1)$ satisfy the conditions, which completes the proof.
Comment: A nice and simple answer! Thank you very much.


Problem with my domain

Question: I have a domain (.se) that I have "own" for years, I've been pointing
out a dyndns domain as the nameserver for my .se domain to be able to use my top domain
with a dynamic ip internet connection. This has been working for over 5 years, but now It has stopped working
The DNSCheck v1.0.1 response is this:
No name servers found at child.
Superfluous name server listed at parent:
A name server listed at the parent, but not at the child, was found. This is most likely an administrative error. You should update the parent to match the name servers at the child as soon as possible.
How do I resolve this?
Edit:
This is how it's setup:
domain.se NS domain.mine.nu

There is NO dns-server running on domain.mine.nu and have never been.
And thats it, it has worked flawlessly for over 5 years, but now it has stoped, can anyone figure out why?
Comment: I realize you're concerned about privacy, but you'll get a definitive answer rather than wild guessing if you just let us know what the domain is.
Comment: the domain is kuseman.se if that would help
Answer: This means that your nameservers (NS records) are not in the zone configured on your DNS server.
You should be able to do:
$ dig yourdomain.se NS @yourdnsmaster

and get NS records as a result.
Comment: I don't host a DNS-server and have never had, my .se domain have worked anyway "some how".
Comment: One other wierd thing is that I cannot access my domain.se but running a whois on it, that service can access my system, it tells me what server-os im running etc.
Answer: Try this:
dig se NS

Take one of those results, say a.ns.se, and do this:
dig @a.ns.se domain.se ns

This will give you the "parent" list of nameservers.  Now, take one of those results (let's say foons), and do this:
dig @foons.domain.se domain.se ns

This will give you the "child" list of nameservers.  You need to make these two lists equal by finding who is hosting your DNS (probably the site where you registered the domain) and fixing the problem there.
Comment: Hi, the first one gives my my dyndns nameserver, works!
The second one time outs.
I'm suspecting that I need to host my own nameserver (and thats why it's time out), but the thing is that I have never ran my own nameserver, it has worked anyway.
Answer: You need to look at the settings from your domain vendor (like Network Solutions or GoDaddy) that you purchased your domain from. There should be settings for DNS as part of your domain. Make sure that the DNS settings are pointing to dyndns DNS servers.
Follow the instructions here:
Custom DNS
HTH
Mike
Comment: The Custom DNS service would probably solve my issue, but the thing is that it have worked without it, why has it stoped working now?

the nameserver for my .se-domain points at my dyndns-domain (NOT dyndns nameserver), and I don't host my own nameserver.
Answer: Usually this kind of error is the result of an NS record mismatch.  For example, you have ns1/ns2.somedomain.com listed as the DNS servers with the registrar, but the actual DNS zone file lists ns1/ns2/ns3.otherdomain.net in the NS records.  Updating the NS records in the DNS zone file at the DNS service provider to match what you're using at the registrar (or the other way around) will generally correct these kinds of problems.

Problem with my domain


Alter Commerce Line Item Order Edit Form

Question: I would like to add a column on the line item table on the orders edit page. I've tried to use theme_registry_alter($theme_registry) to override the commerce line item theme_commerce_line_item_manager, but it seems like it's not working. Below is my code:-
function MODULE_theme_registry_alter($theme_registry) {
  if (isset($theme_registry['commerce_line_item_manager'])) {
    $theme_registry['commerce_line_item_manager']['theme path'] = drupal_get_path('module', 'MODULE');
    $theme_registry['commerce_line_item_manager']['function'] = 'MODULE_commerce_line_item_manager';
  }
}

function MODULE_commerce_line_item_manager(&$variables) {
  return 'Print something';
}

Am I missing something? Or is there any other way to alter the display or add a new column on the table?
I've also created a patch, but I don't feel it's the solution to alter the display. Please help. Thank you in advance.
Answer: If you want to add an editable column, you cannot do that just through the theme layer (though I think the same would hold true even for a non-editable column). Instead you need to alter the form element that gets created, even if it's just through an order edit form level alteration. First you need to create the elements you need in the form array and then you can override the theme function to ensure they get rendered into the table in the right column.
You should also look up documentation on how to override theme functions in general. You shouldn't need to alter the theme registry, just place the theme function in your theme's template.php, copy the functionality of the default theme function, and alter it to your need.
Comment: Hi Ryan, Thank you so much for responding. I just need to display the stock available on each line item. I'll try to alter it using my theme and will get back if I succeed.
Comment: Sounds good; you'll basically need to copy the normal theme function and then put your stock value code in the area where we drupal_render() different form elements into the line item table. I do still think you'll need a form alter, though, to stuff the appropriate stock value in the form array rather than trying to load it in the theme layer.


Overriding Minecraft Respawn Behavior

Question: I want to create a mod that overrides the default respawn mechanics. I want each player to start 100,000 blocks from spawn in a different direction and have that be their default respawn position. I tried overriding the ServerPlayerEntity with this behavior and it seemed like it might have worked but I couldn't find a way to have the server replace the default ServerPlayerEntity with my subclass.
This is what I was trying to do:
public class Server100KMPlayerEntity extends ServerPlayerEntity {
    public Server100KMPlayerEntity(MinecraftServer server, ServerWorld world, GameProfile profile) {
        super(server, world, profile);
    }

    @Override
    public void setSpawnPoint(RegistryKey<World> dimension, @Nullable BlockPos pos, float angle, boolean forced, boolean sendMessage) {
        if (pos != null) {
            super.setSpawnPoint(dimension, pos, angle, forced, sendMessage);
        } else {
            BlockPos newPos = PlayerPositions.valueOf(getEntityName()).getPosition(getServer().getWorld(World.OVERWORLD));
            super.setSpawnPoint(World.OVERWORLD, newPos, 0f, false, sendMessage);
        }
    }

    enum PlayerPositions {
        Player1(-70711, -70711),
        Player2(70711, -70711),
        Player3(-70711, 70711),
        Player4(70711, 70711);

        private final int x, z;

        PlayerPositions(int x, int z) {
            this.x = x;
            this.z = z;
        }

        public BlockPos getPosition(World world) {
            for (int d = world.getTopY(); d > world.getBottomY(); --d) {
                if (!world.isSpaceEmpty(new Box(new BlockPos(x, d, z)))) {
                    return new BlockPos(x, d - 1, z);
                }
            }
            return null;
        }
    }
}

I also looked into S2C and C2S events but didn't see anything there that looked helpful. Any advice would be greatly appreciated.
Comment: It's not managed by the server? Like it's spigot that determine your respawn point
Answer: You can inject a Mixin into the respawnPlayer method within the PlayerManager class, where you set the player's spawn point every time before they spawn.
Here's an example:
@Mixin(PlayerManager.class)
public class ServerPlayerEntityMixin {
    @Inject(method = "respawnPlayer", at = @At("HEAD"))
    public void respawnPlayer(ServerPlayerEntity player, boolean alive, CallbackInfoReturnable<ServerPlayerEntity> cir) {
        BlockPos yourPos = new BlockPos(0, 200, 0); // Whatever position you'd like (you can match the player's display name to a value or something)
        RegistryKey<World> dimension = World.OVERWORLD; // I'm assuming you'd like this to be in the overworld
        player.setSpawnPoint(dimension, yourPos, 0, true, false);
    }
}

One thing to note:
The Y axis matters when you're passing it to setSpawnPoint, if there are blocks present where the player would spawn, it will just default back to the world spawn point. Positions above ground and even in the air should work just fine however.
Comment: This was really close! It was missing a couple of things but it was certainly the right approach! Thank you!
Answer: example implementation
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

import java.util.Random;

public class CustomRespawnHandler extends ServerPlayerEntity {
    public CustomRespawnHandler(MinecraftServer server, ServerWorld world, GameProfile profile) {
        super(server, world, profile);
    }

    @Override
    public void setSpawnPoint(RegistryKey<World> dimension, @Nullable BlockPos pos, float angle, boolean forced, boolean sendMessage) {
        if (pos == null) {
            // Calculate the new respawn position based on player-specific logic
            BlockPos newPos = calculateRespawnPosition(getServerWorld());
            super.setSpawnPoint(World.OVERWORLD, newPos, 0f, false, sendMessage);
        } else {
            super.setSpawnPoint(dimension, pos, angle, forced, sendMessage);
        }
    }

    private BlockPos calculateRespawnPosition(ServerWorld world) {
        // Generate random coordinates
        Random random = new Random(getEntityName().hashCode());
        int x = random.nextInt(200000) - 100000;
        int z = random.nextInt(200000) - 100000;

        // Find a suitable respawn position
        for (int d = world.getTopY(); d > world.getBottomY(); d--) {
            if (!world.isAir(new BlockPos(x, d, z))) {
                return new BlockPos(x, d, z);
            }
        }

        // Return a fallback position if no suitable position is found
        return new BlockPos(x, world.getTopY(), z);
    }
}

Comment: This is pretty close to what I was doing that didn't work because I couldn't register this class as the ServerPlayerEntity that gets created.

Overriding Minecraft Respawn Behavior


Pegar dados de outro site, através da ClassName

Question: Como posso buscar dados presentes no HTML de outro site?
A parte do html do outro site é essa:

  COTAÇÕES
  <o:p></o:p>

No código do meu site tentei fazer assim:
 $html = new DOMDocument();
 $html->loadHTMLFile('http://www.agropan.coop.br/cotac.htm');

 echo $html->getElementByClassName('MsoNormal').getAttribute("p");

Na verdade, eu gostaria de buscar apenas o conteudo "COTAÇÕES" desde
 que ele seja buscado pela ClassName, como devo fazer?
Comment: Opa, boa noite, pode por favor me explicar o que pretende fazer? Você tem um site que você precisa obter somente o que tem dentro de uma div que possui uma classe "x" é isso?
Comment: exatamente amigo, preciso buscar o conteudo de outro site de uma determinada tag, através da ClassName, coloquei esse codigo acima para exemplificar
Comment: Entendi, eu já fiz isto, você irá utilizar cURL, não estou na frente de um computador agora, mais tarde caso não tenha solucionado, me comprimento em colocar um exemplo aqui!
Comment: Editei para evitar erros. veja se funciona dessa forma.
Comment: A DOM é mais completa e mais complicada que, para o seu caso, acaba matando uma formiga com uma bala de canhão. Experimenta com a [SimpleXMLElement](http://php.net/SimpleXMLElement)
Answer:     <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <?php
    error_reporting(E_ALL & ~ E_NOTICE);
    $html = file_get_contents("http://www.agropan.coop.br/cotac.htm");

    $DOM = new DOMDocument();
    libxml_use_internal_errors(true);
    $DOM->loadHTML($html);
    libxml_clear_errors();
    $finder = new DomXPath($DOM);
    $classname = 'MsoNormal';
    $nodes = $finder->query("//*[contains(@class, '$classname')]");
    foreach ($nodes as $node) {
      $result=$result.$node->nodeValue."***";
    }

    $result = preg_replace(array("/\t/", "/\s{2,}/", "/\n/"), array("", " ", " "), $result);
    $partes = explode('***',$result);
    $cotacoes=$partes[0];
    $cotacoes = trim(preg_replace('/[\r\n]+/', '', $cotacoes));
    $cotacoes = str_replace("COTAÇÕES", "", $cotacoes);

    echo $cotacoes;

    ?>

Outras formas de se evitar erros devidos a entidades inválidas "Tag o:p invalid in Entity".

1: Fazendo replace dessas entidades inválidas:
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <?php
    error_reporting(E_ALL & ~ E_NOTICE);
    $html = file_get_contents("http://www.agropan.coop.br/cotac.htm");

    $search = array("<o:p>", "</o:p>");
    $replace = array("", "","
");
    $html = str_replace($search, $replace, $html);

    $DOM = new DOMDocument();
    $DOM->loadHTML($html);
    $finder = new DomXPath($DOM);
    $classname = 'MsoNormal';
    $nodes = $finder->query("//*[contains(@class, '$classname')]");
    foreach ($nodes as $node) {
      $result=$result.$node->nodeValue."***";
    }

    $result = preg_replace(array("/\t/", "/\s{2,}/", "/\n/"), array("", " ", " "), $result);
    $partes = explode('***',$result);
    $cotacoes=$partes[0];
    $cotacoes = trim(preg_replace('/[\r\n]+/', '', $cotacoes));
    $cotacoes = str_replace("COTAÇÕES", "", $cotacoes);

    echo $cotacoes;

    ?>

2: Usando um @ em $DOM->loadHTML($html); `@$DOM->loadHTML($html);
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <?php
    error_reporting(E_ALL & ~ E_NOTICE);
    $html = file_get_contents("http://www.agropan.coop.br/cotac.htm");

    $DOM = new DOMDocument();
    @$DOM->loadHTML($html);
    $finder = new DomXPath($DOM);
    $classname = 'MsoNormal';
    $nodes = $finder->query("//*[contains(@class, '$classname')]");
    foreach ($nodes as $node) {
      $result=$result.$node->nodeValue."***";
    }

    $result = preg_replace(array("/\t/", "/\s{2,}/", "/\n/"), array("", " ", " "), $result);
    $partes = explode('***',$result);
    $cotacoes=$partes[0];
    $cotacoes = trim(preg_replace('/[\r\n]+/', '', $cotacoes));
    $cotacoes = str_replace("COTAÇÕES", "", $cotacoes);

    echo $cotacoes;

    ?>

Por id basta substituir

$classname = 'MsoNormal';
$nodes = $finder->query("//*[contains(@class, '$classname')]");

por
$id = 'MsoNormal';
$nodes = $finder->query("//*[contains(@id, '$id')]");

Comment: obrigado por ajudar, tentei assim, mas aqui pareceu varios erros, como "Notice: DOMDocument::loadHTML(): Namespace prefix o is not defined in Entity, line: 462" e "Warning: DOMDocument::loadHTML(): Tag o:p invalid in Entity" e "Warning: DOMXPath::query(): Invalid expression"
Comment: Se você olhar o código fonte da página www.agropan.coop.br/cotac.htm vai entender esses erros. Tem tag p class=MsoNormal cujo conteúdo é . Então o erro é que a Tag o: p é uma entidade inválida. Para evitar isso adicionei no código libxml_clear_errors();
Comment: No mais, só pedindo ao dono da página para evitar de usar entidades inválidas.
Comment: sensacional amigo, muito obrigado por sua ajuda, agora vou estudar esse codigo e me aprofundar, grande abraço
Comment: Leo, o que mudaria se ao invés de Class ser por ID?
Comment: @WladerMuriloAlexandro `$nodes = $finder->query("//*[contains(@id, '$classname')]");` Ai pra ficar bonito vc muda `$classname`  para `$id`
Comment: $id = 'MsoNormal';
    $nodes = $finder->query("//*[contains(@id, '$id')]");
Answer: No php você precisa fazer algumas alterações no php.ini para ele permitir que o file_get_contents consiga ler urls, file_get_contents tem a finalidade de ler arquivos, e por acaso ele também acessar Urls, por este motivo eu acredito ser melhor o uso do cUrl uma vez que este tem está finalidade e também mais suporte para! Mas sinta-se a vontade para utilizá-lo.
function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

Obtenha o código do endereço que você quer, e com expressão regular, capture o nó da classe que você precisa, acredito ser o melhor jeito de se fazer isto!
Veja abaixo um exemplo de expressão para isto...
^<[a-z]\s[a-z]+\=[MsoNormal]+\salign=center\sstyle=\'text-align\:center\'\>\s+(.*)\s

Talvez isto resolva!
Comment: @AndersonCarlosWoss pois bem, no php você precisa fazer algumas alterações no php.ini para ele permitir que o file_get_contents consiga ler urls, file_get_contents tem a finalidade de ler arquivos, e por acaso ele também acessar Urls, por este motivo eu acredito ser melhor o uso do cUrl uma vez que este tem está finalidade e também mais suporte para! Mas sinta-se a vontade para utilizá-lo.
Comment: @AndersonCarlosWoss feito!
Comment: Obrigado Marcus, deu certo aqui amigo


integration of fractions

Question: i am trying to integrate following equation
$$ \int\frac 1{(x^2-1)\cdot (x+2)}\,dx$$
i can represent $(x^2-1)=(x-1)(x+1)$  so,it would be converted in the following form
$$\int\frac1{(x^2-1)(x+2)}\,dx=\int \frac1{(x-1)(x+1)(x+2)}\,dx$$
or it is equal  $$\int \frac1{(x-1)(x^2+3x+2)}\,dx$$  last one  we can decompose  into form
$$ \frac1{(x-1)(x^2+3x+2)}=\frac A{x-1}+\frac{Cx+D}{x^2+3x+2}$$  am i right?or did i miss some term?
Comment: Why don't you use $\frac 1{(x-1)(x+1)(x+2)}$ and decompose as $\frac \alpha{x-1} + \frac\beta{x+1} + \frac\gamma{x+2}$?
Comment: i was thinking  that,because we have quadratic term,i would lose some fraction
Comment: In partial fractions, you typically don't use quadratics in the denominator unless they can't be further reduced.
Comment: The common name for this type of integration is Integration using Partial Fractions. This is a special case of integrating fractions of the general form of $f(x)/g(x)$
Answer: I think you can decompose it like this:
$$
\frac{1}{(x^2-1)\cdot(x+2)}=\frac{a}{x-1}+\frac{b}{x+1}+\frac{c}{x+2}
$$
Thus we can solve the following equations:
$$
a+b+c=0\\3a+b=0\\2a-2b-c=1
$$
getting $a=1/6,b=-1/2,c=1/3$.
Therefore,
$$
\int\frac{dx}{(x^2-1)\cdot(x+2)}\\=\int\frac{1}{6}\cdot\frac{dx}{x-1}-\int\frac{1}{2}\cdot\frac{dx}{x+1}+\int\frac{1}{3}\cdot\frac{dx}{x+2}\\=\frac{1}{6}\cdot \log(x-1)-\frac{1}{2}\cdot \log(x+1)+\frac{1}{3}\cdot \log(x+2).
$$
Comment: so it means that,my multiplication of (x+1) by (x+2) was  not necessary,thanks a lot of @rhenskyyy

integration of fractions


Python ORM for MS-Access

Question: I need to use a Python ORM with a MS-Access database (in Windows).
My first searches are not really succesfull :

SQLAlchemy : no MS Access support in the two last versions.
DAL from Web2Py : no Access (??)
Storm : no MS Access
sqlobject: no MS Access
dejavu : seems OK for MS Access but
is the project alive ?

Any ideas or informations are welcome ...
Answer: Web2py recently updated their DAL making it much easier to add support for new db engines.  I don't believe there is currently native Jet (MS Access) support, but the existing SQL Server support could probably be modified without much effort to provide MS Access support.  The latest version of the web2py DAL is a single stand-alone .py file, so it's not a "heavy" package.
For what it's worth, I've successfully used the web2py DAL as a stand-alone module with SQL Server after initially trying and giving up on SQLAlchemy.  In fairness to SQLAlchemy, I had used the web2py DAL as part of the framework and was already comfortable with it.
Comment: @philnext I probably would choose DAL and ask on Web2py discussion group, in the past something similar (though for DB2) has already been asked and Massimo Di Pierro [was in favour](http://groups.google.com/group/web2py/tree/browse_frm/thread/473e320d1c728a82/c52609a95f48a901?rnum=1&_done=%2Fgroup%2Fweb2py%2Fbrowse_frm%2Fthread%2F473e320d1c728a82%2Fa03c9e0fe2b31ee3%3F#doc_e02a1489115756b4) of providing an implementation for the missing feature. Maybe you could try too, who knows.
Comment: Yes Web2py seems to be a good concurent for my choice but as I am  very newbie in Python I would found a 'ready to go' solution.
Answer: Since Sep 2019 there is a Microsoft Access dialect for SQLAlchemy, called sqlalchemy-access. It uses the package pyodbc.
Installation:
pip install pyodbc sqlalchemy sqlalchemy-access

Python ORM for MS-Access