Is the Mean Absolute Percentage Error calculated correctly?

Question: I made a model based on raw data and I wanted to check how accurate the model was using the Mean Absolute Percentage Error. I'm pretty sure I calculated it correctly but my teacher said the percentage error seemed too large. This is what the model function with the raw/original data looks like:

And for my MAPE I got 32%.
Answer: Well if you look at the graph, you have differences on the order of 0.01, which are divided by values on the order of 0.1. This means you are finding the mean of values on the order of 0.1 (or 10%), so yes, I'd say your result looks too high. It looks to me like your MAPE should be around 10% or less. Are you dividing by the number of samples you've used to get your MAPE, or are you simply summing them?
It's hard to answer your question because you haven't said how you calculated MAPE.
Comment: Thanks for the input. 1) I calculated the absolute error by doing (actual value-model value)/actual value 2) I found the sum of all of the values 3) Multiplied the number by 100 4) Divided the value by the number of data points (in this case, 281).
Comment: Hmmm...it sounds like you're doing it correctly. Perhaps the data values near 0 are skewing the result? Have you tried removing the data values very close to 0 as a sanity check?
Comment: I just looked at the values near 0 on my table and I think you're right! The absolute error value suddenly goes up to 7. Should I therefore calculate the MAPE without the values? Or is there another solution?
Comment: Well gee that's a hard one! Is it for an assignment? MAPE is known to give skewed results for data that is very close to 0. Have you zero meaned the data yourself? Presumably sea level doesn't go below 0? Or does it?! If the data doesn't need to be zero meaned I would shift it back to where it was originally, & find MAPE for those values. If it needs to be shifted down to sit around 0 then I would be tempted to report 2 results, one including values near 0 & one excluding those values.
Comment: one last question, why do the results get skewed near 0?
Comment: Because you're dividing by values very close to 0, which causes very large changes in the sum. This should be avoided where possible. See http://www.forecastpro.com/Trends/forecasting101August2011.html for a summary of weaknesses of MAPE.


Panels not showing default image set in Field settings of content type

Question: The image you upload to be as a default image for all pages where you didn't upload custom images for each page, so it would show same one image from the content type settings.
It works in Preview when editing the node and it shows in non-panel pages.
In Panels it doesn't render entire field. But if you upload the custom image then it does show it. But not the default one.
I don't get it why
Comment: I am having the same exact issue. I'm on Pantheon, but it's also happening on my local install too.
Answer: This is an issue with CTools. Apply the patch from Default value of image field is not shown
Answer: For me the solution proposed by Stephen Martin did not work. I had to apply this patch (Comment #22) instead: https://www.drupal.org/node/2437773. This fixed the problem.


Shibboleth Transcoding Rules not picking up data / passthrough attributes from azureAD integration

Question: I followed the documentation to integrate Shibboleth 4.3 to use AzureAD as its proxy / IdP and everything redirects / responds as it should, but in the attribute resolver / claims rules, it is not picking up the attributes in the response back from Azure.  I can see in the logs it is going through the individual attributes / claims, which are mapped in the azureClaims.xml / resolver, but is not picking things to do the passthrough down to my servicer provider.
Below are the log entries in shibboleth:
<code>2023-01-30 23:12:10,735 - 10.254.252.105 - INFO [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:511] - Profile Action ValidateSAMLAuthentication: No transcoding rule for Attribute (Name 'http://schemas.microsoft.com/identity/claims/tenantid', NameFormat: 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified')
2023-01-30 23:12:10,735 - 10.254.252.105 - INFO [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:511] - Profile Action ValidateSAMLAuthentication: No transcoding rule for Attribute (Name 'http://schemas.microsoft.com/identity/claims/objectidentifier', NameFormat: 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified')
2023-01-30 23:12:10,735 - 10.254.252.105 - INFO [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:511] - Profile Action ValidateSAMLAuthentication: No transcoding rule for Attribute (Name 'http://schemas.microsoft.com/identity/claims/displayname', NameFormat: 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified')
2023-01-30 23:12:10,735 - 10.254.252.105 - INFO [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:511] - Profile Action ValidateSAMLAuthentication: No transcoding rule for Attribute (Name 'http://schemas.microsoft.com/identity/claims/identityprovider', NameFormat: 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified')
2023-01-30 23:12:10,735 - 10.254.252.105 - INFO [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:511] - Profile Action ValidateSAMLAuthentication: No transcoding rule for Attribute (Name 'http://schemas.microsoft.com/claims/authnmethodsreferences', NameFormat: 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified')
2023-01-30 23:12:10,735 - 10.254.252.105 - INFO [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:511] - Profile Action ValidateSAMLAuthentication: No transcoding rule for Attribute (Name 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname', NameFormat: 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified')
2023-01-30 23:12:10,735 - 10.254.252.105 - INFO [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:511] - Profile Action ValidateSAMLAuthentication: No transcoding rule for Attribute (Name 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname', NameFormat: 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified')
2023-01-30 23:12:10,735 - 10.254.252.105 - INFO [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:511] - Profile Action ValidateSAMLAuthentication: No transcoding rule for Attribute (Name 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress', NameFormat: 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified')
2023-01-30 23:12:10,735 - 10.254.252.105 - INFO [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:511] - Profile Action ValidateSAMLAuthentication: No transcoding rule for Attribute (Name 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name', NameFormat: 'urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified')
2023-01-30 23:12:10,735 - 10.254.252.105 - DEBUG [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:482] - Profile Action ValidateSAMLAuthentication: Incoming SAML Attributes mapped to attribute IDs: []
2023-01-30 23:12:10,735 - 10.254.252.105 - INFO [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:326] - Profile Action ValidateSAMLAuthentication: SAML authentication succeeded for '<my_azure_email>'
2023-01-30 23:12:10,735 - 10.254.252.105 - DEBUG [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:361] - Profile Action ValidateSAMLAuthentication: Added translated AuthnContext Principals: [urn:oasis:names:tc:SAML:2.0:ac:classes:Password]
2023-01-30 23:12:10,735 - 10.254.252.105 - DEBUG [net.shibboleth.idp.saml.saml2.profile.impl.ValidateSAMLAuthentication:300] - Profile Action ValidateSAMLAuthentication: Resetting authentication time to proxied value: 2023-01-31T00:58:45.582Z
2023-01-30 23:12:10,782 - 10.254.252.105 - DEBUG [net.shibboleth.idp.authn.impl.PopulateSubjectCanonicalizationContext:75] - Profile Action PopulateSubjectCanonicalizationContext: Installing 3 canonicalization flows into SubjectCanonicalizationContext
2023-01-30 23:12:10,782 - 10.254.252.105 - INFO [Shibboleth-Audit.SSO:338] - 2023-01-31T04:12:10.782744400Z|urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect|_2a73955fd5a49d06c9567eb52a05cd99|https://sts.windows.net/f42c8e55-f934-4f2c-b0ce-a1e403fd1b9d/|http://shibboleth.net/ns/profiles/saml2/sso/browser|https://<idp_url>/idp|urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST|_60d95c36-51de-45d7-bbcd-25539e822daf||urn:oasis:names:tc:SAML:2.0:ac:classes:Password||<my_azure_email>|_75101b2a-a777-485e-ab76-c816ff9f4301|
2023-01-30 23:12:10,813 - 10.254.252.105 - DEBUG [net.shibboleth.idp.authn.impl.SelectSubjectCanonicalizationFlow:100] - Profile Action SelectSubjectCanonicalizationFlow: Checking canonicalization flow c14n/attribute for applicability...
2023-01-30 23:12:10,813 - 10.254.252.105 - DEBUG [net.shibboleth.idp.authn.impl.SelectSubjectCanonicalizationFlow:83] - Profile Action SelectSubjectCanonicalizationFlow: Selecting canonicalization flow c14n/attribute
2023-01-30 23:12:10,860 - 10.254.252.105 - DEBUG [net.shibboleth.idp.attribute.resolver.impl.AttributeResolverImpl:251] - Attribute Resolver 'ShibbolethAttributeResolver': Initiating attribute resolution with label: c14n/attribute
2023-01-30 23:12:10,860 - 10.254.252.105 - DEBUG [net.shibboleth.idp.attribute.resolver.impl.AttributeResolverImpl:469] - Attribute Resolver 'ShibbolethAttributeResolver': Resolving dependencies for 'passthroughAttributes'
2023-01-30 23:12:10,860 - 10.254.252.105 - DEBUG [net.shibboleth.idp.attribute.resolver.impl.AttributeResolverImpl:478] - Attribute Resolver 'ShibbolethAttributeResolver': Finished resolving dependencies for 'passthroughAttributes'
2023-01-30 23:12:10,860 - 10.254.252.105 - DEBUG [net.shibboleth.idp.attribute.resolver.impl.AttributeResolverImpl:424] - Attribute Resolver 'ShibbolethAttributeResolver': Resolving data connector passthroughAttributes
</code>
Eventually, this errors saying nothing can be mapped when building this out.  Anything anyone has seen in terms of mapping this out that could have been missed?  Have gone through all the mappings a number of times and not seeing where this could have been missed.
Thanks
Nick
Answer: Have you included the azureClaims.xml file in conf/attributes/default-rules.xml? (and restarted Tomcat/Jetty)
Its saying it can't find a transcoder for http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name (among others) - is this defined in azureClaims.xml? It should look something like:
<code>        <bean parent="shibboleth.TranscodingProperties">
            <property name="properties">
                <props merge="true">
                    <prop key="id">azureName</prop>
                    <prop key="transcoder">SAML2ScopedStringTranscoder</prop>
                    <prop key="saml2.name">http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name</prop>
                    <prop key="saml2.nameFormat">urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified</prop>
                    <prop key="displayName.en">Name</prop>
                    <prop key="description.en">Azure UPN of an account expecting to be scoped thus transcoded that way</prop>
                </props>
            </property>
        </bean>
</code>
Specifically, the saml2.name needs to match than name of the attribute released by AzureAD - this should be shown in the assertion received from AzureAD a bit earlier in the process log.


element.scrollTo Not working on mobile

Question: So i am making a vertical scrolling carousel, and everything seems to be working great. I am able to scroll horizontally using both buttons and swipe gestures. ON SIMULATOR. When i put the website up on an actual mobile device, i get this error:
TypeError: e.scrollTo is not a function. (In 'e.scrollTo(i,0)', 'e.scrollTo' is undefined)
Like i said, this works on multiple browsers and on the mobile simulator, but isnt working on actual device. Here is the code:
Math.easeInOutQuad = function (t, b, c, d) {
  t /= d/2;
  if (t < 1) {
    return c/2*t*t + b
  }
  t--;
  return -c/2 * (t*(t-2) - 1) + b;
};

export default function ScrollTo(element, to, duration) {
  var start = element.scrollLeft,
    change = to - start,
    currentTime = 0,
    increment = 20;

  var animateScroll = function(){
      currentTime += increment;
      var val = Math.easeInOutQuad(currentTime, start, change, duration);
      element.scrollTo(val, 0);
      if(currentTime < duration) {
          setTimeout(animateScroll, increment);
      }
  };
  animateScroll();
}

called via
ScrollTo(document.getElementById("sidewaysScroller"), scrollerWidth, 800);

Note: I am using ReactJS, and I am reluctant to use a JQuery based solution.
Comment: Maybe it's trivial to say, but log `element` as a starting point.
Comment: ^ that or `JSON.stringify(element)` and append it to body if you don't have access to a console on the mobile device.
Comment: @Kootoopas its definitely finding the element, good idea though didn't even check it.
Answer: I solved this by using element.scrollLeft = val; , seems to work pretty well.

element.scrollTo Not working on mobile


How to enable user to click the View to hide the kb on iPhone?

Question: I find that the View do not have a touch inside or similar event. So, I make a button on top on the view, and set it Alpha to 0, but after I set to Alpha 0, it cannot touch anymore. Any ideas on this?
Answer: You can use UIView subclass and handle touch event there. Methods to look at (defined in UIResponder):
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event

If you want to use "invisible" UIButton you should set its type to UIButtonTypeCustom - by default it will appear with no image and title and with transparent background. So technically it will be invisible to user but still be able to respond to all events.


Pegar informações do objeto sender

Question: Como funciona a busca de informações atraves do objeto sender e em quais situações posso usa-lo, com quais tipos de eventos?
Isso para evitar redundância de eventos.  Onde posso explorar essas possibilidades?
Por exemplo :
vários botões de 0 a 9. E gerar um evento único para todo.
Answer:
O sender é do tipo Object, e tem a funcionalidade de quando o evento for executado, receber as informações de tal controle, por exemplo, se você clicar em um Button ele traz as informações desse Button.
Exemplo:

Em um formulário possui dois Button, um tem no seu Text com Mensagem 1 e Mensagem 2 respecitvamente o ButMensagem1 foi colocado na sua propriedade Tag o número 1 e no ButMensagem2 foi colocado o número 2. Como recuperar essas informações:
Código:
Obs: Lembrando que o evento Click vai ser o mesmo para os dois Button
private void ButMensagem_Click(object sender, EventArgs e)
{
    //Button butMensagem = (Button)sender;
    //ou
    Button butMensagem = sender as Button;
    switch (((string)butMensagem.Tag))
    {
        case "1": // mensagem 1
            {
                MessageBox.Show("Botão Clicado: Mensagem 1", "Clicado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
            }
        case "2": // mensagem 2
            {
                MessageBox.Show("Botão Clicado: Mensagem 2", "Clicado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                break;
            }
    }

}

Ou seja, usando um Cast você recupera qual Button foi clicado e com isso recupera as  configurações, eventos e propriedades. No caso foi recuperado a propriedade Tag e com isso a rotina toma a decisão de mostrar a Mensagem 1 ou Mensagem 2, dependendo do Button que foi acionado.
Answer: O sender deve ser entendido como um objeto coringa: a ideia de ele não ser tipado é justamente para que ele possa ser manipulado por eventos em que os tipos do objeto sejam diferentes, e que um único evento possa estar ligado a vários objetos.
Nesta resposta, digo como se pode escrever um único evento que manipule várias PictureBoxes. Repare que a solução sugere converter o sender para um tipo para realizar a manipulação de alguma propriedade ou implementar alguma regra de negócio (para o caso da pergunta, manipular a visibilidade quando o objeto é assinalado).
Seu exemplo já responde bem uma das vantagens de usar o sender, como trabalhar os valores de vários botões. O limite das possibilidades está justamente na quantidade de propriedades que o objeto possui. Após o casting, você pode ler e manipular a propriedade que desejar (deste que a propriedade não seja somente-leitura).

Pegar informações do objeto sender


nginx client_header_buffer_size Not effective

Question: An API service I built is runnig over HTTPS, which has a user get request parameter too long, and then the browser is directly inaccessible, and the parameters in the URL can be shortened.
The server uses the nodejs local test to see how long the parameters can be processed. Finally, it is possible to be a nginx problem, 'cause setting up client_header_buffer_size and large_client_header_buffers, restarting then nginx, I got the same result.
server {
   listen 443 ssl http2;
   listen [::]:443 ssl http2;
   ...
   client_body_buffer_size 600k;
   client_max_body_size 600k;
   client_header_buffer_size 600k;
   large_client_header_buffers 4 600k;
   ...
}

Is there anybody in my situation that can provide solutions?
In another case, I used Safari browser to access the URL with a long parameter. Page prompt 303 error? (shortening the web site normal)
Answer: From the description of client_max_body_size, you can set allowed size of the client request body. Try to set it to a max value say
client_max_body_size 100M;

or setting it to 0 will remove the check, which is not recommended.
client_max_body_size 0;


When to use statistical tests to compare two machine learning models

Question: I saw a paper comparing two ML models based on a statistical test. They tested these two models using different datasets and then they compared their accuracy results using a statistical test to see if their is any statistical significant. I was thinking if i were the author, I would just calculate the mean of the accuracy results and compare the two models based on their means. So, when to use statistical test and when to use simpler approaches like comparing the two means?
Answer: Quoting Francis X. Diebold "Comparing predictive accuracy, twenty years later: A personal perspective on the use and abuse of Diebold–Mariano tests" (2015),

We've all seen hundreds of predictive horse races, with one or the other declared the "winner" (usually the new horse in the stable), but with no consideration given to the statistical significance of the victory. Such predictive comparisons are incomplete and hence unsatisfying. That is, in any particular realization, one or the other horse must emerge victorious, but one wants to know whether the victory is statistically significant. That is, one want to know whether a victory "in sample" was merely good luck, or truly indicative of a difference "in population.""

(Emphasis is mine.)
So if you just calculated the mean of the accuracy results and compared the two models based on their means, you would not know how likely the apparent superiority of one model is due to sampling variation versus the genuine difference between the forecasting ability of the models. Statistical tests provide tools for assessing this.

So, when to use statistical test and when to use simpler approaches like comparing the two means?

If you want an answer with some certainty bounds (which I guess is always the case), you need a test. If you skip the test, you have no way of telling how trustworthy the result is, making it rather useless.
Comment: @nbro, The null hypothesis postulates equally good predictive performance in population, or in this case, for a given data generating process. The setup: we have a process that is generating the data; we compare two models on a sample generated by the process; we make inference about forecasts on an infinitely large sample from the same process.
Comment: @nbro, OK. Does that mean you have answered your question yourself, or is there anything left unanswered?


Runge-Kutta Method [ Butcher Tableau ] Show $A$-Stability.

Question: We consider the following Butcher Tableau:
\begin{array}{c|cc}
\frac{1}{3} &  \frac{5}{12}& -\frac{1}{12} \\
1 & \frac{3}{4} & \frac{1}{4}\\
\hline
  & \frac{3}{4} & \frac{1}{4} \\
\end{array}
What do I have to do?:
First I wrote down, everything I need:
For the $A$-stability I need:

the stability function $g(z)$

an explanation why $g$ has no pole in {$ z\in \mathbb{C}: \Re(z) \leq 0  $}

$\lim_{|z| \rightarrow \infty } |g(z)| \leq 1$

$ g(it) \leq 1  $ $ \forall t \in \mathbb{R} $

equation for the stability function $g(z)$ :
$ g(z) = 1 + zb^T(I_2 -zA)^{-1}e $
In general we shouldn't invert that matrix, but in this special case we have the formula for the inverse:
$\frac{1}{ad-bc}\begin{bmatrix}d&-b\\-c&a\end{bmatrix}$
So we get : $(I_2 -zA)^{-1} = \frac{1}{(1-\frac{5}{12}z)(1-\frac{1}{4}z)-(-\frac{1}{12}z)\frac{3}{4}z}\begin{bmatrix}1-\frac{1}{4}z&-\frac{1}{12}z\\\frac{3}{4}z&1-\frac{5}{12}z\end{bmatrix}$
simplify it a bit:
$ (I_2 -zA)^{-1} = \frac{6}{z^2-4z+6}\begin{bmatrix}1-\frac{1}{4}z&-\frac{1}{12}z\\\frac{3}{4}z&1-\frac{5}{12}z\end{bmatrix} $
Then:
$(I_2 -zA)^{-1}e = \begin{bmatrix}
\frac{2(3-z)}{z^2-4z+6}\\ \frac{2(3+z)}{z^2-4z+6}
\end{bmatrix} $
Then:
$ 1+ z (\frac{3}{4} , \frac{1}{4} )^T (I_2 -zA)^{-1}e = 1 + \frac{z(6-z)}{z^2-4z+6}$
Theres is a chance that I miscalculated somewhere ( if I find a mistake, I will edit this post ). But to be honest, the remaining steps for $ A $ Stability are my greater concern. I tried something for 3. and 4., but this wasnt effective.
Comment: Sorry! I finally found some time to check my calculation again and yes, you are right!
Answer: Now examine the absolute value for $z=iy$
$$
|g(iy)|^2=\left|\frac{iy+6}{-y^2-4iy+6}\right|^2=\frac{y^2+36}{(6-y^2)+16y^2}=\frac{(y^2+1)+35}{(y^2+1)^2+35}\le 1.
$$
By the maximum modulus principle the maximum absolute value for the holomorphic domain $Re(z)\le 0$ has to be on the boundary (including here the infinite point), thus  $|g(z)|\le 1$.
As the value at infinity is $0$, the method is, unlike the implicit trapezoidal method, A-stable and L-stable


Determining the root key and note of this riff

Question: I am just starting to produce music and, for music, I learn better by doing and then learning about what I've done.
Let's say that I have two measures in 4/4 time with each of the following eighth notes.
A4 B4 A4 G4 A4 G4 E4 A4 | A4 B4 A4 G4 E4 F4 G4 A4
How can I determine the key (as shown on web sites as such as beatport) and root note (unless that is what is shown on sites like beatport).
Edited for the full 4 measures:
A4 B4 A4 G4 A4 G4 E4 A4 | A4 B4 A4 G4 E4 F4 G4 A4 | A4 B4 F4 G4 A4 B4 A4 G4 | G4 A4 G4 A4 B4 C5 B4 A4
Answer: I'm pretty sure the key is the same thing as the root note. Anyway, I think that the key of that riff is A. A is the first note of the riff, it occurs a lot in the riff, and the notes are all on the A Minor scale. I'm going a little bit based on intuition, but that's my thought process.
Comment: The key is the root note _plus_ a quality like major, minor, dorian, etc. I'd definitely call this A minor or A aeolian, since we don't actually hear the 3rd of the scale.
Comment: @Spechal - Because I went to music school and studied aural skills for four years. :-) Long answer: because it starts and ends on A, and because the notes in between move in a pattern that tonicizes A. Note that if you are missing accidentals (like if the notes are actually A4, G#4, F#4, E4) this answer will change significantly.
Comment: @NReilingh I've added the final 2 measures (for this loop).  Also, how could you tell this in A minor?
Comment: Well all of the notes seem to be heading towards an A. Notice how prevelant the A is in the phrases. Basically I just played the riff in my head, and it sounded like A. Theoretically this could also be C major, but that seems less likely.


is there any good library for printing preview in MFC?

Question: I need to print records in a grid view, and need to preview it before
printing.
I want to know whether or not there is a strong library for printing
preview?
And with the library I can change the position, layout of the data to
print.
More important: I need to change the data's layout, how can I do that?
Comment: note that whatever print preview code you'll find, you'll have to write extra code to adjust it to your needs. Personally I don't like MFC print preview, anyway check this question:
http://stackoverflow.com/questions/1031036/implementing-my-own-print-preview and also search http://www.codeproject.com for print preview code.
Answer: MFC itself supports Print Preview, there shouldn't be a need for an additional library.
Comment: is this library can change it's layout ?
Comment: sorry but MFC print preview sucks.
Comment: any better solution ? let's say i want to print a bill according the records in database, how can i do it ?


@mailer and @twig in argument of a service error ServiceCircularReferenceException

Question: I'm trying to put twig like argument of my service but i have always the same error :
ServiceCircularReferenceException in bootstrap.php.cache line 2129
Circular reference detected for service "doctrine.orm.default_entity_manager",path: "doctrine.orm.default_entity_manager -> doctrine.dbal.default_connection -> wh.participant_listener -> wh.participant_notification -> twig -> security.authorization_checker -> security.authentication.manager -> fos_user.user_provider.username -> fos_user.user_manager".`
This is my service.yml file
wh.participant_notification:
    class: WH\TrainingBundle\Notification\Notification
    arguments: [@mailer, @twig]

wh.participant_listener:
    class: WH\TrainingBundle\EventListener\ParticipantListener
    arguments: [@wh.participant_notification]
    tags:
        - { name: doctrine.event_listener, event: postUpdate }
        - { name: doctrine.event_listener, event: postPersist }

My PartcicipantListenerFile
namespace WH\TrainingBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use WH\TrainingBundle\Notification\Notification;

class ParticipantListener
{

    protected $notification;

    public function __construct(Notification $notification)
    {
        $this->notification = $notification;

    }

}

This probleme exist only when i pass @wh.participant_notificationin arguments of my second service
Any body has an idea ?
Thank's a lot
Answer: I've find a solution, not pretty, but it works :
First i pass the service container in argument of my service
services:

wh.participant_notification:
    class: WH\TrainingBundle\Notification\Notification
    arguments: ['@service_container']

wh.participant_listener:
    class: WH\TrainingBundle\EventListener\ParticipantListener
    arguments: ['@wh.participant_notification']
    tags:
        - { name: doctrine.event_listener, event: postPersist }

then in my Notification.php class :
use Symfony\Component\DependencyInjection\ContainerInterface as Container;

private $container;

public function __construct(Container $container) {

    $this->container = $container;

}

public function subscribValidation ($participant) {

    $templating = $this->container->get('templating');
    $mailer = $this->container->get('mailer');

    ...

I can't create protected var $twig because the probleme persiste.
I repeat, its only with twig service (or template).
Maybe another one find a better solution ...
Comment: Indeed, the very cause is the declaration of both $mailer and $templating as protected properties of the listener.
Answer: The circular message, while unclear, should guide you.
Doctrine entity manager loads its listeners,wh.participant_notification among them. Your service requires twig which in turns requires a chain of other things, doctrine entity manager among them. This causes the exception above.
One solution to this issue could be to use setter injection
So you can just define your service as:
wh.participant_notification:
  class: WH\TrainingBundle\Notification\Notification
  calls:
    - [setMailer, ["@mailer"]]
    - [setTemplating, ["@templating"]]

and add to your Notification class the setter methods
class Notification
{
  private $mailer;
  private $templating;

  public function setMailer(\Mailer $mailer)
  {
    $this->mailer = $mailer;
  }

  public function setTemplating(\Symfony\Bundle\TwigBundle\TwigEngine $templating)
  {
    $this->templating= $templating;
  }

  ...your code...

Comment: - [setTemplating, ["@twig"]]

    public function setTemplating(\Twig_Environment $twig)
    {
        $this->template = $twig;

    }
Comment: (v 2.8.4-DEV) even the setter injection (as described here) keep on raising circular reference
Comment: Yes, you should add both setters ;)
Comment: Hey @Jerome I just expanded my answer. You should probably inject `templating` as service, not `twig`. And `TwigEngine` is probably the right choice, not `Twig_Environment`.


Prove: Let  ∈ ℤ and ,  be distinct primes. Then p|x and q|x if and only if pq|x

Question: Given this theorem: For every prime  and all integers a, b, if p|ab, then p|a or p|b
Prove: Let  ∈ ℤ and ,  be distinct primes. Then p|x and q|x if and only if pq|x
I have already proven if p|x and q|x then pq|x.
Now I need to prove it the other way around, if pq|x then p|x and q|x
I have this:
We have pq|x which means x = pqn, where n is some integer
Where do I go from here?
Comment: $x=pqn$ then $x=pn_1$ and $p|x$, $x=qn_2$ and $q|x$
Comment: If $x=pqn$, then it follows that p and q divide x. Ie. $x/p=qn$ and likewise for q.
Comment: "We have pq|x which means x = pqn, where n is some integer

Where do I go from here?"  $x = pqn = p(qn)=q(pn)$.  $qn$ and $pn$ are both integers so......
Answer: Here is a short proof which "goes in both directions", but which doesn't directly use our OP Atlecx's "theorem", mentioned the beginning of the question:
It is relatively easy to see that
$pq \mid x \Longrightarrow p \mid x, q \mid x, \tag 1$
since we have
$p \mid pq \mid x, \; q \mid pq \mid x; \tag 2$
going the other way, we note that since $p$ and $q$ are distinct primes, they are relatively prime:
$\gcd(p, q) = 1; \tag 3$
thus via Bezout's identity we affirm
$\exists a, b \in \Bbb Z, \; ap + bq = 1; \tag 4$
we multiply by $x$ and obtain
$apx + bqx = x; \tag 5$
now $q \mid x$ implies
$pq \mid apx, \tag 6$
and likewise, from $p \mid x$,
$pq \mid bqx; \tag 7$
we conclude that
$pq \mid (apx + bqx) = x.  \tag 8$
$OE\Delta$.
Answer: You've proven the hard part.  The other part is trivial.
If $pq|x$ then there is an integer $n$ so that $pqn = x$.  So $p(nq)=x$ and $q(np)=x$.  And $nq$ and $np$ are both integers, $p|x$ and $q|x$.


Accents in strings, how to store accented characters in a single char

Question: I have to write a small program to remove accents from a string given as input. I also have to create a function that replaces each single character with accent to the corresponding one without accent, and I have a loop that calls the function for each character in my main:
char func (char c)
{
    string acc = "èé";
    string norm = "ee";
    char ret = c;

    for(int i = 0; i < acc.size(); i++)
    {
        if(c == acc[i])
            ret = acc[i];
    }
    return ret;
}

The problem is that if I provide the string "é" as input inside the main, the string is seen as a string of size 2 (see example below), and the function above is called two times instead that once. Moreover the char given as input to the function is not the correct one. I guess I have the same size problem inside my function. Shouldn't this accent be seen as a single character? (I am using UTF-8)
string s = "e";
cout << "size:" << s.size() << endl;
s = "è";
cout << "size:" << s.size() << endl;

OUTPUT
size:1
size:2

I have solved the problem using the wchar_t ans wstring types, but I need to insert this function in a more complex program and possibly I would like to avoid to change all the code to deal with wstring.
Do I need to change the file encoding? The actual one is:
text/x-c; charset=utf-8

Is it possible to write such a function using normal strings and chars?
Comment: advice to use single byte encoding is 2k18?
Comment: Use `wstring` and `wchar_t`.
Comment: `è` is not an ascii character and therefore is not represented with a single byte in UTF-8. Also `std::string` is not capable of dealing with UTF-8 text. Subscript and other size related functions won't work properly. If you wan't to store `è` in `std::string` then you should probably use windows-1252 or other single byte encoding.
Comment: This may help you converting between 8 and 16 bit string formats [poss duplicate](https://stackoverflow.com/questions/7232710/convert-between-string-u16string-u32string)
Comment: Is  ISO-8859-1 single byte encoding? How can I change the encoding? Is it the file encoding or do I need to change the code? Thanks
Comment: Possible duplicate of [std::wstring VS std::string](https://stackoverflow.com/questions/402283/stdwstring-vs-stdstring)
Comment: The linked Q&A is high quality (500+ score)
Answer: You should not attempt to do this yourself using simple loops, especially if the code is security-sensitive. There is often more than one way to represent the same character in Unicode, so you might have a single codepoint or you might have two codepoints. For example:
const wchar_t text1[] = { L'e', 0x0301, 0 };
const wchar_t text2[] = { 0x0e9, 0 };

These two strings appear equivalent when printed (they both show é), but they are obviously not the same and a simple == check will fail. You should normalize the strings before searching, or use an existing function that automatically does that for you.
Windows provides NormalizeString and FindStringOrdinal and ICU provides unorm_compare or usearch_first for this purpose.
const wchar_t text1[] = { L'e', 0x0301, 0 };
const wchar_t text2[] = { 0x0e9, 0 };

// Using Windows APIs, try to normalize the string first
int size = NormalizeString(NormalizationKC, text1, -1, nullptr, 0);
if (size == 0)
  throw std::exception("Can't normalize");

auto text3 = std::make_unique<wchar_t[]>(size);
NormalizeString(NormalizationKC, text1, -1, text3.get(), size);

// Print out the three strings - they all look the same
std::wcout << text1 << std::endl;
std::wcout << text2 << std::endl;
std::wcout << text3.get() << std::endl;

// Verify if they are (or are not) equal
if (CompareStringOrdinal(text1, -1, text2, -1, false) == 2)
  std::wcout << L"Original strings are equivalent\r\n";
else
  std::wcout << L"Original strings are not equivalent\r\n";

if (CompareStringOrdinal(text3.get(), -1, text2, -1, false) == 2)
  std::wcout << L"Normalized strings are equivalent\r\n";
else
  std::wcout << L"Normalized strings are not equivalent\r\n";

// Verify if the string text2 can be found
if (FindStringOrdinal(FIND_FROMSTART, text1, -1, text2, -1, TRUE) != -1)
  std::wcout << L"Original string contains the searched-for string\r\n";
else
  std::wcout << L"Original string does not contain the searched-for string\r\n";

if (FindStringOrdinal(FIND_FROMSTART, text3.get(), -1, text2, -1, TRUE) != -1)
  std::wcout << L"Normalized string contains the searched-for string\r\n";
else
  std::wcout << L"Normalized string does not contain the searched-for string\r\n";

// Using ICU APIs, try to compare the normalized strings in one go
// (You can also manually normalize, like Windows, if you want to keep the
// normalized form around)
UErrorCode error{ U_ZERO_ERROR };
auto result = unorm_compare(reinterpret_cast<const UChar*>(text1), -1,
  reinterpret_cast<const UChar*>(text2), -1, 0, &error);
if (!U_SUCCESS(error))
  throw std::exception("Can't normalize");

if (result == 0)
  std::wcout << L"[ICU] Normalized strings are equivalent\r\n";
else
  std::wcout << L"[ICU] Normalized strings are NOT equivalent\r\n";

// Try searching; ICU handles the equivalency of (non-)normalized
// characters automatically.
auto search = usearch_open(reinterpret_cast<const UChar*>(text2), -1,
  reinterpret_cast<const UChar*>(text1), -1, "", nullptr, &error);
if (!U_SUCCESS(error))
  throw std::exception("Can't open search");

auto index = usearch_first(search, &error);
if (!U_SUCCESS(error))
  throw std::exception("Can't search");

if (index != USEARCH_DONE)
  std::wcout << L"[ICU] Original string contains the searched-for string\r\n";
else
  std::wcout << L"[ICU] Original string does not contain the searched-for string\r\n";

usearch_close(search);

This produces the following output:
é
é
é
Original strings are not equivalent
Normalized strings are equivalent
Original string does not contain the searched-for string
Normalized string contains the searched-for string
[ICU] Normalized strings are equivalent
[ICU] Original string contains the searched-for string

Answer: Store the character in a wchar_t like so
wchar_t text = L'é';

You can also store special characters in wstring:
wstring text = L"étoile";

If you still need to compare a potential special character in a wchar_t (or wstring) with a char or (string), this thread explains how to quite well.


Is updating the composer.json file & consequently composer.lock in Drupal 8 considered a good practice or hacking the core?

Question: I have been working with another developers on a scaffolding tool for Drupal8 based on Symfony Console component.
The current setup process includes updating composer.json using composer CLI:
COMPOSER_BIN_DIR=bin php composer.phar require hechoendrupal/drupal-app-console:dev-master
Maybe writing to core/vendors is not the best practice any suggestions
Answer: Modifying anything in core is generally not recommended.
Unlike other projects that use composer, Drupal already has its composer packages included in core/vendor and you are not supposed to change them, nor the composer.json. Updates to Drupal 8 core would wipe your changes.
There is a module Composer manager that will open a second vendor directory in sites/sitename/vendor (I think). There is some discussion going on in the issue queue, e.g. Is it okay to have duplicates of symfony, guzzle, etc... in sites/all/vendors?. I imagine a future where sites/sitename/vendor could replace core/vendor. But we are not there yet.
I think you should participate in the composer vendor issue queue, this is all work in progress.
EDIT:
It should be mentioned that the way Drupal 8 is using Composer is not the way it is recommended. The recommended way is that the user should download Drupal and vendor packages via Composer. Instead, it is all pre-packaged. One reason for this is to support shared hosting where you don't have a commandline available, and just want a complete package to upload.


Code First Migration - SQL Update column with data from another row in same table

Question: Situation:
Given is the following table:

Id
Price
ProductId
ValidFrom

1
1,00
1
01-01-01

2
1,00
1
01-01-15

3
1,00
1
01-02-01

4
1,00
2
01-01-01

5
1,00
2
01-01-11

6
1,00
2
01-01-28

7
1,00
2
01-02-01

8
1,00
2
01-01-08

Now I want to add a new column "ValidUntil" to the table. Because Data already exist the new column should be prefilled for existing entries.
The table should look like this after the change:

Id
Price
ProductId
ValidFrom
ValidUntil

1
1,00
1
01-01-01
01-01-15

2
1,00
1
01-01-15
01-02-01

3
1,00
1
01-02-01

4
1,00
2
01-01-01
01-01-11

5
1,00
2
01-01-11
01-01-28

6
1,00
2
01-01-28
01-02-01

7
1,00
2
01-02-01
01-02-08

8
1,00
2
01-02-08

I use Entity Framework Core Code First Migration to update the data.
Problem:
I rename the column first, thereafter I use the following line to prefill the column:
migrationBuilder.Sql("UPDATE Prices p1 SET p1.ValidUntil = (SELECT TOP 1 ValidFrom FROM Prices p2 WHERE p2.ValidFrom > p1.ValidFrom ORDER BY DATEDIFF(day, p2.ValidFrom, p1.ValidFrom))");

Runing the update I get the following errors:

Incorrect syntax near 'p1'.

Incorrect syntax near ORDER-Keyword.

Question:
I have less experience with SQL Statements so I would appreciate any help to understand what's wrong with this statement.
Also if anyone has a statement which would fit better for this case he is welcome too.
Thank you for your help.
Comment: Tag your question with the database you are using.
Comment: Oh, sorry. Sure.
Answer: You can use lead() to get the until date:
select p.*,
       lead(validfrom) over (partition by productid order by validfrom) as validuntil
from prices p;

In SQL Server, you can incorporate this into an update:
with toupdate as (
      select p.*,
             lead(validfrom) over (partition by productid order by validfrom) as new_validuntil
      from prices p
     )
update toupdate
    set validuntil = new_validuntil
    where new_validuntil is not null;

Comment: Great! Thank you for the very fast response and great help. Worked for me!


Question based on finding the area of canvas

Question:
The slant height of a conical tent made of canvas is $14/3$m. The radius of the tent is $2.5$m. The width of the canvas is $1.25$m. If the rate of canvas per metre is Rs. $33$ what is the total cost of canvas required?

I calculated the lateral surface area of cone which is $22/7\times2.5\times14/3\times$ and then multiplied the answer with the rate which is $33$ but my answer isn't correct. Correct answer is $968$. Does width play any role here? Please help me out guys
Comment: The cost of the per square meter is not $33$, but $33\cdot4/5$ instead so the final answer is $22/7\cdot5/2\cdot14/3\cdot4/5\cdot33=968$.
Comment: why 33*4/5. What is the role of width @MichaelHoppe
Comment: Well, if the cost $1\cdot1.25=5/4$ square meter is $33$, the how much does one square meter cost?
Answer: Here we need to compare the lateral  area of Canvas and tent
So, $22/7*2.5*14/3 = (L) (1.25)$
$\Rightarrow L = 29.33$
Now, per length it's Rs. $33$.
Therefore for length $= 29.33 \times 33 =968$


Series convergence of $\sum_1^\infty\frac{(n!)^2+(2n)^n}{n^{2n}}$

Question: $$\sum_1^\infty\frac{(n!)^2+(2n)^n}{n^{2n}}$$
Is there a way to test convergence of this series wihout splitting it ? (in case splitting is correct)
Comment: I deleted my answer because I do not answer the question about splitting. I apologize. Cheers :-)
Comment: Find out the order of the numerator: is $(n!)^2\ge (2n)^n$ in general?  Then you can compare the greatest of the two with the denominator.
Answer: Show, using Stirling's approximation, that for $n\ge10$, we have $0\le(2n)^n\le(n!)^2$, and then use squeezing.


Can the second-to-last defender cause an offside by leaving the field of play?

Question: I had a little conversation one of my football friends and we had this interesting situation come up during the conversation.
As I understand the offside rule, the offending player should not be closer to the goal than the second-to-last defender.
But, what if at the point of the player receiving the ball, one of the defenders go out of play? Like for example, the goal keeper or the other defender is injured or goes out of the field. Would it still be considered an offside because there is only a single defender between the offending player and the goal? If yes, why can't this rule be exploited to effectively nullify the goal scored, if any?
Comment: 2008 example: http://www.orato.com/sports/euro-2008
Answer: You count all the players on the field. It doesn't matter if they are lying on the field, looking anywhere else or what are they doing.

If the defender goes outside of the field because of a situation of the game (e.g. can't stop his run), he is still counted.
If the defender is outside of the field receiving medical attention, he is not counted (he was out of the field before the ball was in play).
If the defender steps out of the field on purpose, then he is not only counted, he should be cautioned (shown a yellow card) for unsporting behaviour.
Comment: A reference to Laws would help your last point - a player is cautioned (yellow card) if they "[d]eliberately  leave[]  the  field  of  play without  the referee's  permission". Also, this is definitively not a ban, nor even necessarily a suspension or dismissal. Just a caution.
Comment: There is a somewhat famous example where this was applied: https://www.youtube.com/watch?v=73hkEDIR9e8 (Netherlands against Italy at the Euro 2008). The goal counted because the Italien defender was one of the two players 'closer to the goalline'. (Bernhard probably mentions this too, but the link is dead).


Why we cast android Activity to Interface in Fragment onAttach()?

Question: As documentation we must cast Activity to Interface in onAttach() to communicate between Fragment-to-Fragment.
OnHeadlineSelectedListener mCallback = (OnHeadlineSelectedListener) activity;

After this we can implement that interface in Activity class and use it's methods.
But, i want to know that, as that interface is implemented by Activity class.
Then, why don't we instantiate it in Fragment onAttach() like below:
OnHeadlineSelectedListener mCallback = new ActivityClass();// After this all methods are also available in fragment class.

Using this way we can also pass the data by using Interface methods. But, why don't we use this?
Thanks.
Answer: You cannot create a new instance of an Android component (Activity, Service, BroadcastReceiver, Provider) using the new keyword. Only the Android framework can create these components, because they need to have their Context set up by the Android framework during construction. Although the compiler will let you do this, and your code will run, at some point you will get crashes because the methods in these components always assume that they have a valid Context.
Comment: Thanks David, But, i am confused a bit. If i have my data(returned from Fragment class through instantiated interface function) in Activity class, then why it through NullPointerException while setting it to text view. Even i am using it in the activity class. It should not matter from where i got this data.
Comment: You have 2 instances of your `Activity`. One that Android created properly and one that you created using `new`. The one that you created isn't set up properly. The `Context` hasn't been set up and `onCreate()` hasn't been called. That instance has no `TextView`s, because `setContentView()` hasn't yet been called.
Comment: Oh, got it now. My confusion is clear now. I have got a down vote for a worth question. lol Thanks David.


DDD Value Object: How to persist entity objects without tons of SQL joins?

Question: Obviously I am wrong in saying that DDD is similar to EAV/CR in usefulness, but the only difference I see so far is physical tables build for each entity with lots of joins rather than three tables and lots of joins.
This must be due to my lack of DDD understanding.  How do you physically store these objects to the database without significant joins and complication when importing data?  I know you can simply create objects that feed in to your repository, but it's difficult to train tools like Microsoft Sql Server Integration Server to use your custom C# objects and framework.  Maybe that should be my question, how do you use your DDD ASP.NET C# framework with Microsoft SQL Server Integration Services and Report Services? LOL.
In an EAV/CR database, we can setup a single Person table with different classes depending on the type of person: Vendor, Customer, Buyer, Representative, Company, Janitor, etc.  Three tables, a few joins, attributes are always string with validation before we insert, just like ModelValidation in MVC where the object accepts any value but won't persist until it's valid.
In a standard relational model, we used to create a table for each type of entity, mixing in redundant data types like City.
Using Domain Driven Design, we use objects to represent each type of entity, nested objects for each type of ValueObject, and more nested objects still as necessary.  In my understanding, this results in a table for each kind of entity and a table for each kind of information set (value object).  With all these tables, I see a lot of joins.  We also end up creating a physical table for each new contact type.  Obviously there is a better way, so I must be incorrect in how I persist objects to a database.
My Vendor looks like this:
public class Vendor {
    public int vendorID {get; set;}
    public Address vAddress {get; set;}
    public Representative vRep {get;set;}
    public Buyer vBuyer {get; set;}
}

My Buyer:
public class Buyer {
   public int buyerID {get; set;}
   public Address bAddress {get; set;}
   public Email bEmail {get; set;}
   public Phone bPhone {get; set;}
   public Phone bFax (get; set;}
}

Do we really reference things like Vendor.vBuyer.bPhone.pAreaCode?  I would think we would reference and store Vendor.BuyerPhoneNumber, and build the objects almost like aliases to these parts: Vendor.Address1, Vendor.Address2, Vendor.BuyerPhoneNumber ... etc.
Answer: You could serialize your objects to xml and save it to an xml column in you Sql Server. After all, you are trying to represent a hierarchical data structure, and that's where xml excels.
Answer: Domain-driven design proponents often recommend keeping the data model as close to the object model as possible, but it isn't an ironclad rule.
You can still use a EAV/CR database design if you create mappings in your object-relational mapping layer to transform (project) your data into your objects.
Deciding how to design your objects and provide access to child values is really a separate question that you have to address on a case-by-case basis. Vendor.BuyerPhoneNumber or Vendor.vBuyer.bPhone.pAreaCode? The answer always depends, because it's rooted in your specific requirements.
Answer: The real answer is to match your SQL normalization strategy to your objects.  If you have lots of duplicate addresses and you need to associate them together, then normalize the data to a separate table, thus creating the need for the value object.
Answer: One of the best ways to store Domain Objects is actually a document database. It works beautifully because the transactional boundary of the document matches perfectly the consistency boundary of the Aggregate Root. You don't have to worry about JOINs, or eager/lazy loading issues. That's not strictly necessary, though, if you apply CQRS (which I've written about below).
The downside is often with querying. If you wish to query directly the persisted data behind your Domain Objects, you can get into knots. However that is a complexity that CQRS aims to solve for you, where you have different parts of your application doing the queries than the parts loading/validating/storing Domain Objects.
You might have a complex "Command" implementation that loads Domain Objects, invokes the behaviour on them (remembering that Domain Objects must have behaviour and encapsulate their data, or else risk becoming "anaemic"), before saving them and optionally even publishing events about what happened.
You might then use those events to update some other "read store", though you don't have to. The point is you have a totally different vertical slice implemented in your application that doesn't have to bother with that complex object model/ORM business, and instead goes straight to the data, loads exactly what it needs and returns it for displaying to the user.
CQRS is not hard, and is not complex. All it does is instruct you to have separate code for:

Handling commands (which mutate state and therefore need the business rules/invariants involved).
Executing queries (which do not mutate state and therefore don't need all the complex business rules/invariants involved, and so can "just" go get the data in an efficient way.


$G$ conex planar graph, the total number of faces

Question: Let $G$ be a conex planar graph with n more or equal than $3$ vertices, so that each face will contain in its frontier a circuit of length at least $5$.So, the number of faces will be at most $(2n-4)$$/$$3$.
Can someone pleae help me with this problem?
Answer: Lemma: If $G$ is a planar graph with $V$ vertices, $E$ edges, and finite girth $g$ then, $$E \leq \frac{g(V−2)}{V−2}$$
Look here: girth in planar graph

So $g=5$ and thus $3E\leq 4V-10$. Using Euler theorem: $$V-E+F =2$$ we have $$3V+3F -6 \leq 4V-10$$ so $$F\leq {V-4\over 3}$$
which is much better bound.
Answer: From the given, $5f\le 2e$. Use $n+f=e+2$ to eliminate $k$.


Awkward return behaviour in php - slashes mix

Question: I have an If-statement that converts JPG or PNG to base64 string:
$data = file_get_contents($path);
//separator is fine
$base64_image = 'data:image'.DIRECTORY_SEPARATOR.'jpeg;base64,' . base64_encode($data);

$output = [];
$output = $base64_image;
echo json_encode(array('response' => $od1));
return;

This code outputs something like
 {"response":["data:image/jpeg;base64 ... ] }
and that's perfectly fine.
But I need the output to be separate method, because I use it several times :
public function returnOutput($message)
{
        $output_upload = [];
        $output_upload[] = $message;

        echo json_encode(array('response' => $output_upload));
        return;

}

... and the calling:
$this->returnOutput($base64_image);

Mixes the slashes like this :
{"response":["data:image\/jpeg;base64 ... "]}

Is there a problem to use return from another method ?
EDIT :
I want to send the response straight to the browser, yes. Removed the DIRECTORY_SEPARATOR
Here what I changed and now is fine :
public function returnOutput($message)
{
    $output_upload = [];
    $output_upload[] = $message;

    return json_encode(array('response' => $output_upload));

}

And the calling :
...
echo $this->returnOutput($base64_image);
//I want to terminate the program after the response
return;

Is this better ? So I can not use one method return for everywhere?
Comment: Exactly, nothing is returned from the method. Having that return there doesn't do anything. I get that you want to echo it to the browser as JSON and this does that. As I said, would just make more sense to me. If you wanted to use that same method to get the output and store it in a variable (to cache or something maybe) instead of send strait to the browser you couldn't do that this way. Isn't particularly important though.
Comment: Echo your method call `echo $this->returnOutput($base64_image);` not the json.
Comment: Not sure if it will solve you problem but would make more sense to me to 'return json_encode(array('response' => $output_upload));' then 'echo $this->returnOutput($base64_image);'
Comment: It passes it to JS, so it should be echoed
Comment: But your method is called "returnOutput", yet it doesn't *return* anything.
Answer: That's a perfectly valid JSON encoded slash. There's nothing wrong with return or anything, it's JSON encoding.
As a side note: DIRECTORY_SEPARATOR is meant to stand in for / or \ depending on your system. It is not synonymous with / and there's no need to use it here. Write image/jpeg just like that.


Organizing query results from Microsoft sql server 2008

Question: I would like to organize the results I am getting from the following query without having repetitions. I would show you in a second what I mean.
So I have this part of the  query that I currently have
select ownername,
       hotel,
CASE
    WHEN owner = salescashier and drinksales ='pepsi' then 'y'
    else 'n'
END as pepsi,
CASE
    WHEN owner = salescashier and drinksales ='mountaindew' then 'y'
    else 'n'
END as mountainDew
FROM HotelDrinksOrders

GROUP BY ownername,hotel,totaldrinks,salescashier

and this is my table
 ownername   hotel    drinksales       salescashier
 ---------   -----    ----------       ------------
 Carlos      hotel1     pepsi           Michael
 Carlos      hotel1    pepsi            Michael
 Carlos      hotel1    pepsi            Michael
 Carlos      hotel1   mountaindew       Michael
 Carlos      hotel1   mountaindew       Michael
 Carlos      hotel2     pepsi           Michael
 Carlos      hotel2   mountaindew       Carlos
 Carlos      hotel2   mountaindew       Michael
 Maria       hotel3   mountaindew       Maria
 Maria       hotel3     pepsi            Maria
 Maria       hotel3     pepsi            Maria

The following is what I am getting from my query, I am getting repeated data(hotel) that I don't need
    ownername       hotel      pepsi     mountaindew
    -----           ------      -----     -----------
    Carlos           hotel1      N             N
    Carlos           hotel1      N             N
    Carlos           hotel2      N             Y
    Carlos           hotel2      N             N
    Maria            hotel3      N             Y
    Maria           hotel3      Y             N

This is the data I want,
I want to group them by name and hotel, and only have 'Y' if the ownername matches the salescashier
    ownername       hotel      pepsi     mountaindew
    -----          ------      -----     -----------
    Carlos         hotel1      N             N
    Carlos         hotel2      N             Y
    Maria          hotel3      Y             Y

I heard somewhere I can use pivot operator but I am not sure how that would work on my case. Thanks in advance
Answer: Remove the unneeded items from the group by and use an aggregate. Y sorts later than N so max will work correctly.
select ownername,
       hotel,
MAX(CASE
    WHEN ownername = salescashier and drinksales ='pepsi' then 'y'
    else 'n'
END) as pepsi,
MAX(CASE
    WHEN ownername = salescashier and drinksales ='mountaindew' then 'y'
    else 'n'
END) as mountainDew
FROM HotelDrinksOrders
GROUP BY ownername,hotel

Comment: if i group them that way I will get an error
Something like this column 'salescashier' is invalid in the select list because it is not contained in either an aggregate function or the group clause
Answer: Add the DISTINCT keyword to your SELECT statement.
Comment: This won't return the desired results. It will return two rows for Carlos, hotel2 and Maria, hotel3. They need to be collapsed into one for each.


How to go about solving this question?

Question: Problem - An open-top box is made from $14$ inch by $32$ inch piece of cardboard, as shown below. $V= L * W * H$, and the height of the box is $x$.

I attached an image with a picture of the box. My questions are:

How would I begin to write and equation in factored form? I was thinking of making it:
$(x-32)(x-32)(x-14)(x-14)$
and factoring that. However I am not sure if that is correct.
The exact question was:
"Write an equation in factored form"

2.Also, there is another question asking to:
  "Write the volume of the polynomial function in standard form"
how would I go about doing that part as well?
3.The final question on the page is:
 "Find the volume of the box if the height is $2$ inches"
However, I'm pretty sure once I understand the first $2$ parts I can just plug this in easily. This doesn't need to be explained just thought I'd add it to show you what rest was leading up to.
Thanks in advance to whoever can help
Answer: Simply you can write $V=(32-2x)(14-2x)x$ (factored form). Then you must multiply expressions in the brackets and you will obtain polynomial form.
Comment: Classical supplementary question is: For which $x$ the volume of the box is maximal?
Answer:
$L=32-2x$, $W=14-2x$, $H=x$, so $V=(32-2x)(14-2x)x$. This is a factored form.
Expand the product.
Substitute $x=2$. The computing is easier if you use the factored form.
Comment: Thanks for help. Both answers were correct and very helpful, however this one seemed like the best.

How to go about solving this question?


Testing angular websocket controller

Question: I'm very new to angular, or maybe just stupid. But how do I test a controller that uses angular-websocket?
It certainly isn't this:
describe('controllers', function(){
    beforeEach(module('myapp.controllers'));

    it('should ....', inject(function($controller) {
        //spec body
        var mycontroller = $controller('mycontroller', {
                                          $scope: {} ,
                                          WebSocket: WebSocket
    });
    expect(mycontroller).toBeDefined();
}));

Answer: If what you're after is a unit test, then I would create a mock WebSocket (a bit like you use a mock $httpBackend to test $http communication). This mock object would have the same methods as the real WebSocket object but would allow checking that you have sent something to it, and would allow manually triggering the sending of a message or the opening of a connection:
var mockWebSocket = new MockWebSocket();
var mycontroller = $controller('mycontroller', {
                                      $scope: {} ,
                                      WebSocket: mockWebSocket
});
mockWebSocket.openConnection(); // that internally calls all the registered onopen callbacks
expect(mockWebSocket.send).toHaveBeenCalledWith('hello');
mockWebSocket.sendMessage('goodbye'); // that internally calls all the registered onmessage callbacks
expect($scope.lastReceivedMessage).toBe('goodbye');

Too bad the module doesn't come with such a mock.
Answer: if you were using ngSocket, then you could do the following:

it('should ....', inject(function($controller, ngSocket) {
        //spec body
        var myController = $controller('mycontroller', {
                                          $scope: {} ,
                                          ngSocket: ngSocket
                                      });

        expect(mycontroller).toBeDefined();
    });

Testing angular websocket controller


Add custom submission buttons to navigate through different wizard pages

Question: I need to navigate the user through different pages of a multistep webform. I have added additional submit button to the webform using following code.
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if($form_id == 'mywebform_id') {
    $form['actions']['submit_button_step_1'] = array(
      '#type' => 'submit',
      '#value' => t('Go to Step 1'),
      '#submit' => array('custom_navigation'),
    );
    $form['actions']['submit_button_step_2'] = array(
      '#type' => 'submit',
      '#value' => t('Go to Step 2'),
      '#submit' => array('custom_navigation'),
    );
}
}

But now How could I navigate the user to the pages based on user clicks on which button?
I found this in community website. But not able to understand where should I put this code in my custom module.
How to programmatically skip pages in wizard forms
Answer: I used another more durty way. I just hide pages which must be skipped
function my_module_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id)
{
  if (!isset($form['#webform_id']) || $form['#webform_id'] != 'my_form') {
    return;
  }

  $pages = &$form_state->get('pages');

  if (some_statement) {
    $pages['skipped_page_name']['#access'] = FALSE;
  }
}

but it works only in forward direction. And if user clicks "previous page" it may cause unexpected behaviour. So you also need "show" pages again on each step:
$pages = &$form_state->get('pages');
foreach ($pages as &$page) {
  $page['#access'] = TRUE;
}


How do I import a library from Github when the module is installed

Question: I want to add https://github.com/googleads/googleads-php-lib library to my module Drupal 8 I try to add composer. json in the folder module but is not load when I installed module this is solution to upload this library without command "composer update "?
this is my composer.json
{
  "name": "drupal/googleads-php-lib",
  "description": "Integrates the googleads-php-lib library into Drupal",
  "type": "drupal-module",
  "require": {
    "googleads/googleads-php-lib": "25.0.0"
  }
}

Answer: composer.json has no bearing when you enable a module in the Drupal admin. Drupal only looks at the info.yml of a module to ensure any listed dependency (module only) exists and has been met. Using drush also won't work. You need Composer for this.
You would need to require your module via composer require drupal/mymodule - at which point any dependencies listed in require would also be pulled in. For that to work, your module would need to be posted on drupal.org, with the Drupal packages repository added to your root composer.json file.
You could also add a repository endpoint pointed at GitHub, Bitbucket or any other VCS service, add a baseline composer.json file to your project and require it that way, too.
You can also do composer require googleads/googleads-php-lib:25.0.0 from your Drupal root to pull in that package, but I would go the module route (so that package is always tied with the module).
Comment: You could also do that, sure. I guess the most generic approach would be a sandbox project on drupal.org, and you could offload it later to a private repo once you learn a bit more about Composer.
Comment: Would it definitely need to be posted on Drupal.org? Is there a reason you couldn't point composer at a private repo to download a custom module? I guess there would be some effort involved to make it land in the right folder, but it kinda feels like composer would be able to handle that
Comment: Yeah good point
Comment: Updated my answer, I literally just did that moments ago with a private pattern lab repo.
Comment: If it's a custom module for that site then adding the dependency to the main composer.json is fine. Or you can use the merge plugin like explained here: http://drupal.stackexchange.com/questions/217810/loading-dependencies-from-the-vendor-directory-in-a-module-using-composer/217826#217826. merge plugin supports wildcards, so you can include all custom composer.json files with web/modules/custom/*/composer.json. If it should be a reusable module then any private or public git repository (e.g. github) should work, you just need to add a composer repository.


an example of a non convex ideal

Question: As an example of a non convex ideal we have in Gillman and Jerison, Rings of Continuous Functions, 1976, Exercise 5E(1), the ideal $I= (|\operatorname{id}_{\mathbb R}|)$ in $C(\mathbb R)$. I need to get some details as a verification of this example.
Comment: What is a convex ideal?
Comment: @QiaochuYuan The definition of a convex ideal $I$ in $C(X,\mathbb{R})$ appears to be: if $0\leq f \leq g$ and $g\in I$, then $f\in I$.
Answer: We need to find a function $f(x)$ that is not a multiple of $|x|$ such that $0\leq f(x) \leq | x|$.
One way to do this is to define $f(x)=0$ for $x\leq 0$ and $f(x) = |x|$ for $x\geq 0$.  Then, if there is a function $g(x)$ such that $g(x)|x| = f(x)$, we have $g(x) = 0$ for $x<0$ but $g(x)=1$ for $x>0$, so $g$ cannot be continuous.
Comment: @Slade thank you so much, such a suitable verification example :)

an example of a non convex ideal


GroupWise 8.0.2 Linux PO Setup and SDD Problem

Question: Have a bit of a GW problem, and I'm a bit stumped using the usual sources ( forums, TIDs, etc. ) even though the issue is theoretically quite straightforward.
The primary problem: I cannot set up a new PO on an OES2 sp 2 server that is already running an MTA.
The secondary problem: The reason I cannot set up the PO appears to be an issue with setting up an SDD that the Linux server can access.
Platforms: OES 2 sp2 with GroupWise 8.0.2 (without the hot patch released a couple of days ago). All but one of my existing POs is hosted on Netware. The non-Netware PO is also on OES2 sp2 but I set it up about two years ago and my memory of the process has faded ....
My problem appears to be identical to this forum posting:
http://forums.novell.com/novell-product-support-forums/groupwise/groupwise-8x/gw8-agents/423407-can-not-create-po.html
In Detail:
I am trying to set the PO up at path /media/nss/MAIL/gwpost
The gwpost directory is writable by both root and the eDirectory user I am using with ConsoleOne.
I have attempted to use ConsoleOne (as installed from GW 8.0.2 media) from both the OES server itself and Windows 7 to create the PO.
Everything goes well until I get to the last stage of the PO creation screens -- after clicking "Finish" the GroupWise installer tells me that it cannot access the SDD and gives me a warning. Even if I ignore the warning, it dumps me back to the first PO creation screen.
I do not have a standard SDD for Linux GroupWise so I am creating a new one for this particular project.
So, all indications are that I have a bad SDD, but given the forum post I am not ruling out a GroupWise bug (that said, the recent hot patch does not seem to have any fixes listed that would solve this issue). I do know that Linux SDDs can be tricky.
Novell TID 7005157 goes into some of these issues:
http://www.novell.com/support/php/search.do?cmd=displayKC&docType=kc&externalId=7005157&sliceId=1&docTypeID=DT_TID_1_1&dialogID=182591620&stateId=0%200%20182593086
I have tried the following:
1. Using the GroupWise installer and ConsoleOne to create an SDD at /media/nss/MAIL/software and attempted to access it via NCP share.
2. Using the GroupWise installer and ConsoleOne to create an SDD at /media/nss/MAIL/software and attempting to access it via the Linux path (with and without values in the UNC path per the TID)
3. Using the GroupWise installer and ConsoleOne to create an SDD at /opt/novell/groupwise/software and attempting to access it via the Linux path (without values in the UNC path per the TID)
All of these SDDs have resulted in the same error, per my description and the forum post above. I have checked the rights for both root and the eDirectory user for all of the SDDs above.
I've been working on this for two days and am stumped. Any ideas? Has anyone seen this?
Comment: If you've stumped the Novell forums, your chances of an answer here are small. @geoffc is probably the only one here who can tackle this. I haven't done enough GW on linux to help.
Comment: Stupidly, I didn't post to the forums, only searched them and found that previous post with the same issue. Now I've cross-posted there (and also sent it to a mailing list). If you are stumped (I've been reading your blog for a couple of years), then this is starting to look like an SR. Thanks.
Comment: Sorry I do more Identity Management and other Novell stuff.  Not a huge GW guy.  Though I do suggest the forums as there are some really good GW resources there.
Answer: Novell solved this one for me. Answering for posterity.
I was not connected to the primary domain for the system, and the secondary domain I was connected to did not have the wpoffice/nwguard.dc file available. Once that was added, the PO added fine. Hopefully a TID will come out of this.


Splitter value as interval for retrieving label?

Question: I'm learning C# and Unity3D for a few months and now I stumbled on a logic, which hopefully somebody can describe to me.
(I already googled for hours and even looked up if other languages use enums that way.)
This code is from a free asset from the unity asset store, which I try to anatomize.
Everything is fine and understandable for me, but then it comes to the functions GetSliderData() and SetSliderData().
My Question: How does the modulo part works?
Why dividing anyway, when it comes to getting and setting values? Or is it some kind of syntax, like the lambda expression "=>" which is not ">="(less or equal sign)
Thank you in advance for your time!
Dom
public class SliderData : ScriptableObject
{
    // Data storage
    public List<float> sliderData;

    /* Use a single enum as retrieval label for any slider by using a splitter
     * value as interval. */
    private const int ENUM_INTERVAL = 16;
    public enum SliderField
    {
        // Customizer sliders
        DEPTH_MIN,
        DEPTH_MAX,
        PERLIN_SPEED,
        PERLIN_LEVEL,
        ZONE_PERLIN_SPEED,
        ZONE_PERLIN_LEVEL,
        MAP_PERLIN_SPEED,
        MAP_PERLIN_LEVEL,
    }

    /// Retrieves the value of the slider belonging to the given field constant.
    public float GetSliderData(SliderField field)
    {
        return sliderData[(int)field % ENUM_INTERVAL];
    }

    /// Sets the value of the slider belonging to the given field constant.
    public void SetSliderData(SliderField field, float value)
    {
        sliderData[(int)field % ENUM_INTERVAL] = value;
    }
}

Comment: This is to get the remainder after the division... the value will alwayd be within 0 and the number you are dividing with
Answer: The % seems to have the purpose of wrap-around the given field value onto the existing indices of the sliderData list.
If the value reaches/exceeds the ENUM_INTERVAL it will instead start over from 0.
For your methods indeed this seems a bit redundant if using the enum values since there are only 8 of them anyway. But it could be triggered via type casting e.g. (SliderField)17 .. but why would someone do that?
Anyway this seems to simply assume that the sliderData list contains at least 16 elements ...

In general to be honest I wouldn't use such a structure but rather store and access the values via actual fields instead of this kind of "dictionary" List.
Ofcourse depends on the use-case and how exactly your asset is used later. It seems there is some behavior involved you didn't share here.
But instead of going through the magic enum and list indices - why not simply have
public class SliderData : ScriptableObject
{
    public float DEPTH_MIN;
    public float DEPTH_MAX;
    public float PERLIN_SPEED;
    public float PERLIN_LEVEL;
    public float ZONE_PERLIN_SPEED;
    public float ZONE_PERLIN_LEVEL;
    public float MAP_PERLIN_SPEED;
    public float MAP_PERLIN_LEVEL;
}

Comment: The only reason I could see the model in the question being useful is if there was some additional custom handler for getting or setting the properties, such as a PropertyChanged event, that they wanted to avoid writing repetitious code for - that said, that is clearly not the case there.
Comment: wow! many thanks for both answers! that cleared it up for me!
I'm also not a big fan of enums, since I've first heard of scriptable objects in a unite2016 video. Just like in your code example!

And yes, it is part of a custom handler, you were right, Zaelin!

thanks! :)


Mark Knopfler picking finger patterns — Sultans of Swing intro

Question: I know Mark Knopfler plays fingerstyle, but What combination of finger/thumb picking patterns does he use when playing lead?
Here is an example from the Sultans of Swing intro (from here):

e-------------------5-8-5----------------
B-----------6------6-----6---5h6p5---------
G-----7------7----7---------------7--5-7---
D--5h7-----7----------------------------7--
A------------------------------------------
E------------------------------------------

And here's my guess at how he plays it, using the PIMA system:

e-------------------5-8-5----------------
B-----------6------6-----6---5h6p5---------
G-----7------7----7---------------7--5-7---
D--5h7-----7----------------------------7--
A------------------------------------------
E------------------------------------------
   p  i    pmi    pim m m i  i    p  i ip

Does anyone have any advance on this, or any further examples of Knopfler-esq patterns?
Comment: Also reference the first track on the first Dire Straits album, "Down to the Waterline". It's another clear example of that distinctive Knopfler arpeggiation and finger-picking style.
Answer: YouTube - iConcertsTelevision - Mark Knopfler - Sultans of Swing (Live)
In the above video, they zoom in pretty frequently on the guitar which should allow you to check his finger picking at different moments throughout the song. This might help you if you want to learn more of it...
Comment: Thanks. It looks like he just uses thumb and first finger for picking, plus a wired kind of brush strike with the back of his first finger.
Answer: I think your probably right; though he may use the (a)finger for the high E string on the Am7 arpeggio:
<code>                     h p
-------------------5-8-5--
-----------6------6-----6-
-----7------7----7--------
--5h7-----7---------------
--------------------------
--------------------------
   p  i    pmi    ima    i
</code>
But I think the way you have it figured is more likely.
Comment: If you watch videos of Knopfler - especially the early ones - you'll notice he never uses the 'a' finger but rather places it on the body of the guitar...
Answer: I think, having watched him do this a number of times, playing it around a 5-8th fret box is unlikely. Consider the following:
<code>--------------------------------------------
------------------10--13--10----------------
------7----10-----10----------10--9h10p9-\7-
--5s7---5-----7---10------------------------
--------------------------------------------
--------------------------------------------
   p  i p  i      pmi  i   i  p   p       p
</code>
This may seem a bit odd, when compared to playing it in the 5-8th fret box, but Mark Knopfler moves all over the fretboard and he uses the Dm on the 10th fret a ton in this song. BTW: I did this tab real quickly, so it's pretty loose. You'll have to figure out where he pauses (like on the 3rd note). Every live video is different from the original recorded version, so if you want to sound like Dire Straits, this seems more like it. In the videos, it's, as I said, different from performance to performance because he knows his scales so incredibly well he can just make magic come out of the air (no really, it's all about his skill).
Answer: I cheat when playing the arpeggio, I just use my thumb and mute the strings as I go down. It sounds ok to me.

This guy has it pretty much down as I play it, however the bit after the arpeggio isn't quite right but you'll pick that up listening to the song. I don't like his his arpeggio sounds but he's got the technique right. I do the same sort of thing for Down to the Waterline and the one near the end of Tunnel of Love, for example. It's really hard to tell you're just using your thumb, but it does really put you out of position so you have to make a little quicker once you come out of it.


JDBC ODBC delete query error issue?

Question: i want to delete customer's perticular news paper from database instead of full detail of customer??
one customer having multiple paper in their record but i want to delte any paper from multiples papers.
i am enter customer id and selecting whch paper i want to delete
thanks for the help in advanced...
<code>enter code here:
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.swing.*;

public abstract class delete_paper extends JFrame implements ActionListener
{
JTextField textFieldId;
JLabel l1;
JLabel l3;
JLabel l5;
JLabel l6;
    JComboBox combo;
    String course[] = {"Navakal","SandhyaKal","Pudhari",
      "MidDay","Inqlab","BusinessLine","MumbaiSamachar",
       "GujrajSamachar","KarnatakMalla","Vartahar","PunyaNagari"};
JButton b2;
Container c = getContentPane();
delete_paper()
{
    super("Shree DattaDigambar Samarth");
    setBounds(140,250,777,555);
    c.setLayout(null);
    textFieldId = new JTextField();
    l1 = new JLabel("New Customer Entry");
    l3 = new JLabel("Customer Name");
    l5 = new JLabel("Paper");
            combo = new JComboBox(course);
    l1.setBounds(10,10,340,20);
    l3.setBounds(110,20,140,70);
    l5.setBounds(400,50,140,20);
    textFieldId.setBounds(10,70,70,20);
            combo.setBounds(400,70,130,20);
    b2 = new JButton("Ok");
    b2.setBounds(10,160,50,20);
            c.add(combo);
    c.add(b2);
    c.add(l1);
    c.add(l3);
    c.add(l5);
    c.add(textFieldId);
            setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
            b2.addActionListener(this);
}
    public static void main(String[] args)
    {
        delete_paper ap=new delete_paper() {};
    }
     public void actionPerformed(ActionEvent e)
        {

            System.out.println("You clicked the button");
            if(e.getSource()==b2)
            {
                try
                {
                    Connection con;
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    con = DriverManager.getConnection("jdbc:odbc:devendra");
                    try
                    {

                        java.sql.Statement st = con.createStatement();
                        PreparedStatement ps = con.prepareStatement("delete
                        from   Customer where Customer_Id = ? and Paper_Name in (?) ");
                        ps.setString(1,textFieldId.getText());
                        ps.setString(4,combo.getSelectedItem().toString());
                        ps.executeUpdate();
                        JOptionPane.showMessageDialog(null,
                       "You successfully Enter the Entry");
                    }
                    catch (SQLException s)
                    {
                        System.out.println("SQL code does not execute.");
                        JOptionPane.showMessageDialog(null,"Please Enter
                        the Detail Correctly");
                    }
                }
                catch (ClassNotFoundException | SQLException ee)
                {
                    System.out.println("Error:connection not created");
                    JOptionPane.showMessageDialog(null,"Please
                    Enter the Detail Correctly");
                }
            }
        }
         }
</code>
Comment: Use java naming convention for classes. Don't use null layout and setBounds. Define correct Layoutmanager. Don't use null parent in dialogs and JOptionPanes. Name variables with some reasonable names not label1, label2. SQLException should be catched just once. Don't prepare statement on each click. Prepare it just once and reuse. Use capital letters in you text to help readers split you text. Post SSCCE and as much details as possible (reasonable). Than ask for help.
Comment: add stacktrace message.
Comment: @StanislavL  Wow!  The 8 (if I counted correctly) point 'great tips for questions' ..as a comment..  Well done.  :)
Comment: Please refine your question, as @StanislavL suggests, and comment on the proposed answer; don't just ask a vague, new [question](http://stackoverflow.com/q/17270019/230513).
Answer: You need not to use the index of table column while setting the values in Prepared statement. It is only the index of ? which is set :
Use
<code>                ps.setString(2,combo.getSelectedItem().toString());
</code>
instead of
<code>                ps.setString(4,combo.getSelectedItem().toString());
</code>
Comment: @Devendra_Ghag If it helped then you can accept the answer by clicking on the arrow on the left of the answer

JDBC ODBC delete query error issue?


Depurador Just-In-Time - Dev C++

Question: Crio um código básico no Dev C++ e no momento que tento compilar e executar é apresentado a mensagem abaixo.
Sistema operacional: Windows 8 pro
Versão Dev C++: 126.96.36.199
Comment: O Dev-C++ é uma bomba então a melhor sugestão que posso dar é trocar de IDE.
Answer: Após realizar download da versão 18.104.22.168 o problema não retornou.

Depurador Just-In-Time - Dev C++


Future não é reconhecida no Flutter (Dart)

Question: Estou estudando Flutter e recentemente tive um problema um tanto quanto chato. Estava usando o Future para minha programação assíncrona e fiz o código todo, tal qual o exemplo que estava vendo. Todavia, percebi que o Future não estava sendo reconhecido, e havia uma recomendação para que eu fizesse o import do pacote async. Fiz isso, porém mesmo assim o problema não resolveu.
Future<int> insertAgendamento(Agendamento agendamento) async {
    Database db = await this.database;

    var resultado = await db.insert(agendaTable, agendamento.toMap());

    return resultado;
}

Acontece que eu já fiz o import e coloquei uma dependência no pubspec.yaml.
import 'dart:async';

Quando passo o mouse por cima do meu "Future" aparece a seguinte mensagem:

Future isn't a type.
Try correcting the name to match an existing type.

E nesse import, aparece o aviso que eu não estou o utilizando... Talvez seja alguma coisa boba, que por falta de atenção, não consegui achar. Mas gostaria da ajuda de vocês.
Comment: Olá! Poderia **[edit]** a sua pergunta para incluir a mensagem de erro que você está recebendo? :)
Comment: Olá Luiz! Fiz a edição que você pediu. O erro que aparece, é no Visual Studio, quando passo o mouse por cima do Future.
Comment: Qual a versão do seu flutter e dart?
Comment: Leandro, minha versão do Flutter é (Channel stable, 1.22.6) eu a atualizei recentemente, pois achei que era esse o problema. Já a versão do Dart é SDK version: 2.10.5 (stable).
Answer: Consegui resolver o problema, o que eu precisei fazer foi configurar o meu import para ser chamado por Fut: import 'dart:async' as Fut;
Logo em seguida, fui até meu código e coloquei:
Fut.Future<int> insertAgendamento(Agendamento agendamento) async {
Database db = await this.database;

var resultado = await db.insert(agendaTable, agendamento.toMap());

return resultado;}

Após isso, meu problema foi resolvido.
Achei esta alternativa nesta discussão no github, cuja solução foi apresentada pelo usuário yringler.
Comment: Por mais que tenha 'funcionado', eu não consideraria isso como uma solução válida. Tem que funcionar sem precisar utilizar destes artifícios, limpe o cache, reinicie a IDE, verifique se vc não criou outra classe com o nome Future..
Comment: Obrigado pela dica Julio, fiz esses passos (limpar o cache e reiniciar a IDE) e resolveu.


Drawing Pacman's Face in Tkinter

Question: So I'm coding Pacman in Python just for fun and I want to create pacman's open face (when he is eating food) using Tkinter graphics. How exactly do I draw an open face? I was thinking about using canvas.create_arc to create the open mouth but it doesn't work properly :(
Any help? Thanks!
Comment: What did you try? How did it fail?
Comment: More importantly, how do you draw the bow for Mrs. Pacman?
Answer: You are correct that you would use the create_arc method. Set the start to 45 and the extent to 270 and it will look like pacman is facing to the right with his mouth open.
Since you are just learning I'll not post the exact code so you'll have a chance to figure it out on your own.
Answer: This would work:
import sys
if sys.hexversion > 0x02ffffff:
    from tkinter import *
else:
    from Tkinter import *

class Application(Frame):

    #Creates an arc
    def draw_pieslice(self, canv,x,y,rad):
        return canv.create_arc(x-rad, y-rad, x+rad, y+rad, fill='yellow', style=PIESLICE, start=self.start_angle, extent=self.stop_angle)

    #To toggle the start and extent values of the arc, such that the pacman opens and closes the mouth
    #Initially the mouth will be completely closed, but as the value is toggled we will get a 45deg space (mouth opens)
    def toggle_mouth(self):
        if self.start_angle is 1:
            self.start_angle = 45
            self.stop_angle  = 270
        else:
            self.start_angle = 1
            self.stop_angle  = 359

    #moves the pacman body horizontally
    def movecircle(self):
        self.repeat = self.repeat - 1           #sets a limit to horizontal movement
        self.canvas.move(self.PacMouth,1,0)
        if (self.repeat % 10) is 0:             #Adjusting the value in here, will help to adjust the mouth movement speed with the horizontal body movement
            self.toggle_mouth()
            self.canvas.itemconfig(self.PacMouth, start = self.start_angle, extent = self.stop_angle)
        if self.repeat is not 0:
            self.after(10, self.movecircle)     #By adjusting the time, we can adjust the horizontal movement speed

    def __init__(self, master=None):
        Frame.__init__(self, master)

        self.start_angle = 1
        self.stop_angle  = 359

        self.canvas = Canvas(width=800, height=480, bg='black')
        self.canvas.pack(expand=YES, fill=BOTH)
        text = self.canvas.create_text(50,10, text="Pacman! Yeah!", fill="white")
        self.PacMouth = self.draw_pieslice(self.canvas,100,240,20)
        self.repeat = 600

        self.movecircle()

root = Tk()
root.config(bg = "black")
root.title("Im on stack overflow")
root.geometry('{}x{}'.format(800, 480))
root.resizable(width=False, height=False)

app = Application(master=root)
app.mainloop()

Drawing Pacman's Face in Tkinter


$3x+11y$ has remainder $2$ and $9x+5y$ has remainder $3$ when divided by $7$ then the remainder when $x-y$ is divided by $7$

Question: If $x > y$ are positive integers such that

$3x + 11y$ leaves a remainder $2$ when divided by $7$ and
$9x + 5y$ leaves a remainder $3$ when divided by $7$,

then the remainder when $x – y$ is divided by $7$, equals?
The answer to this question is $6$ (provided in the answer key) but I am getting something different
$\begin{align} 3x+11y &=7m+2\tag{i}\\
9x\ +5y\ &=7n+3\tag{ii}\\
\hline
3\times(i)-(ii)\Rightarrow\ 28y &=7(3m-n)-3
\end{align}$
But how is this possible as the LHS is divisible by $7$ but the RHS is $3.$
Comment: Welcome to Mathematics Stack Exchange !! We are here to help you with any kind of mathematical problems, but you have to show what you have tried !!
Comment: Your title was not consistent with your question so I changed the title
Comment: Thank you @Henry
Answer: Use congruences mod. $7$:

$3x+11y\equiv 3x-3y=3(x-y)$, and $3^{-1}\equiv 5\mod 7$ so
$$3x+11y\equiv 2\iff x-y\equiv 5\cdot2=10\equiv 3\mod 7.$$
$9x+5y\equiv 2(x-y)$ and $2{-1}\equiv 4\mod 7$, so
$$9x+5y\equiv 3\iff x-y\equiv 4\cdot 3=12\equiv 5 \mod 7.$$
Therefore the two congruences are inconsistent (indeed the determinant of the system of congruences is equal to $0$).
Answer: Given:
$$\begin{cases}3x+11y\equiv 2 \pmod{7} \\ 9x+5y\equiv 3 \pmod{7}\end{cases}$$
Note that:
$$3x+11y\equiv 3x+4y\equiv  2 \pmod{7} \Rightarrow \\
3(3x+4y)\equiv 3\cdot 2 \pmod{7} \Rightarrow 9x+12y\equiv 9x+5y\equiv 6 \pmod{7}.$$
So:
$$\begin{cases}9x+5y\equiv 6 \pmod{7} \\ 9x+5y\equiv 3 \pmod{7}\end{cases} \Rightarrow \emptyset.$$
Answer: Correct: $\bmod 7\!:\,\ 0\equiv \underbrace{\overbrace{9x\!+\!5y}^{\Large\color{#c00} 3}-3(\overbrace{3x\!+\!11y}^{\Large\color{#c00} 2})}_{\Large{\rm eliminate}\ x\ }\equiv \color{#c00}{-3},\,$ contradiction, so the system is inconsistent


Create a virtual tar file

Question: The use case I am in mind is to make a backup of some data. I would like to create a tar file, mainly because there are tens of thousands of small files.
I use a cloud storage service which basically will keep polling the files on the hard drive to know when new files should be uploaded to the server. The files to back-up are on a Linux server, while the storage service has Windows client. Files from Linux server to Windows machine are shared using Samba. The service has a Linux client, which is compiled for x86 and can't be run on my server, as I use Raspberry Pi, which is ARM-based. The service is Asus Web Storage
Is there a way to create a virtual tar file, which will not be written to disk, for example, using fuse?
Or any other simple solution?
Comment: I know one possibility would be to just create the tar file or pick a storage service that has better Linux support. I was wondering if some better solution may exist.
Answer: There are at least two solutions that comes to my mind:
1 - Use a ramdisk
For example :
mkdir /media/backupramdisk
mount -t tmpfs -o size=512M tmpfs /media/backupramdisk

You can then create a tar in this ramdisk, then you can transfer this file to a remote system.
I hardly see a benefit of doing that except that it won't take space on storage device, but it will take RAM. According to the resources available on your machine, you'd better create a real tar on disk.
2 - Tar to stdout
The output of tar can be directly transmitted over network. For example over ssh:
tar zcf - /dir/to/backup | ssh user@remoteserver "cat > /backup/backup.tgz"

Pros: no RAM and no disk space used.
Not knowing what you would like to do with the backup I can't elaborate much more. I hope this still helps.

Create a virtual tar file