OGNL Exception using Thymeleaf

Question: I'm trying to use a list of enum in thymeleaf and i'm facing a OGNL Exception problem each time i attempt to get attribute of the enum
Using basic loop like this

Summary is a list of enum, my enum looks like this
public enum FollowupPdfSummaryEnum {
   COVER("coverAnchor", "templates/firstPageInclude.html", "Couverture", FollowupBlocEnum.COVER_PAGE),
   SUMMARY("summaryAnchor", "templates/summaryInclude.html", "Sommaire"),
   SITUATION_PLAN("situationPlanAnchor", "templates/situationPlanInclude.html", "Plan de situation", FollowupBlocEnum.SITUATION_PLAN),
   BUILDING_VISUAL("buildingVisualAnchor", "templates/visualInclude.html", "Visuels", FollowupBlocEnum.BUILDING_VISUAL),
   HEALTH_BOOK("healthBookAnchor", "templates/healthBookBatInclude.html", "Carnet de santé", FollowupBlocEnum.HEALTH_BOOK),
   IDENTITY_CARD("identityCardAnchor", "templates/identityCardInclude.html", "Fiche d'identité", FollowupBlocEnum.IDENTITY_CARD),
   COUNTER_SITUATION_PLAN("counterSituationAnchor", "templates/counterSituationPlanInclude.html", "Plan des compteurs", FollowupBlocEnum.COUNTER_SITUATION_PLAN),
   DANGEROUS_MATERIAL("dangerousMaterialAnchor", "templates/dangerousMaterialInclude.html", "Diagnostic Matières Dangereuses", FollowupBlocEnum.DANGEROUS_MATERIAL_DIAGNOSIS),
   RECAP_WORK_TODO("workDoneAnchor", "templates/workTodoListInclude.html", "Récapitulatif des travaux à réaliser", FollowupBlocEnum.WORK_DONE_REPORT),
   VISIT_REPORT("visitReportAnchor", "templates/visitReportInclude.html", "Rapport de visite", FollowupBlocEnum.VISIT_REPORT),
   VISIT_REPORT_OCCUPATION("visitReportOccupationAnchor", "templates/occupationVisitReportInclude.html", "Rapport de visite : Occupations", FollowupBlocEnum.OCCUPATION_VISIT_REPORT),
   ANNEXE("annexeAnchor", "templates/annexeInclude.html", "Annexes");

   private final String anchor;
   private final String path;
   private final String title;
   private final FollowupBlocEnum block;

   private FollowupPdfSummaryEnum(String anchor, String path, String title, FollowupBlocEnum block) {
      this.anchor = anchor;
      this.path = path;
      this.title = title;
      this.block = block;
   }
   private FollowupPdfSummaryEnum(String anchor, String path, String title) {
      this.anchor = anchor;
      this.path = path;
      this.title = title;
      this.block = null;
   }

   public String getPath() {
      return path;
   }
   public String getTitle() {
      return title;
   }
   public FollowupBlocEnum getBlock() {
      return block;
   }
   public String getAnchor() {
      return anchor;
   }
}

here's the stack trace
2022-07-15 13:58:22,359 ERROR [http-bio-8080-exec-15] [org.thymeleaf.TemplateEngine : 1136] - [THYMELEAF][http-bio-8080-exec-15] Exception processing template "followUpExport.html": Exception evaluating OGNL expression: "item.title" (template: "templates/summaryInclude.html" - line 26, col 11)
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating OGNL expression: "item.title" (template: "templates/summaryInclude.html" - line 26, col 11)
    at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.evaluate(OGNLVariableExpressionEvaluator.java:201)
    at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.evaluate(OGNLVariableExpressionEvaluator.java:105)
    at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166)
    at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66)
    at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109)
    at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138)
    at org.thymeleaf.standard.processor.AbstractStandardExpressionAttributeTagProcessor.doProcess(AbstractStandardExpressionAttributeTagProcessor.java:144)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
    at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95)
    at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314)
    at org.thymeleaf.engine.OpenElementTag.beHandled(OpenElementTag.java:205)
    at org.thymeleaf.engine.Model.process(Model.java:282)
    at org.thymeleaf.engine.Model.process(Model.java:290)
    at org.thymeleaf.engine.IteratedGatheringModelProcessable.processIterationModel(IteratedGatheringModelProcessable.java:367)
    at org.thymeleaf.engine.IteratedGatheringModelProcessable.process(IteratedGatheringModelProcessable.java:221)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleCloseElement(ProcessorTemplateHandler.java:1640)
    at org.thymeleaf.engine.CloseElementTag.beHandled(CloseElementTag.java:139)
    at org.thymeleaf.engine.Model.process(Model.java:282)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1587)
    at org.thymeleaf.engine.OpenElementTag.beHandled(OpenElementTag.java:205)
    at org.thymeleaf.engine.TemplateModel.process(TemplateModel.java:136)
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:661)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1059)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1048)
    at fr.bluepad.site.back.util.pdf.PdfGenerator.parseHtmlThymeLeafToString(PdfGenerator.java:50)
    at fr.bluepad.site.back.util.pdf.PdfGenerator.generatePdf(PdfGenerator.java:28)
    at fr.bluepad.site.back.service.followup.impl.FollowupCreationPdfServiceImpl.generateFollowupBatPdf(FollowupCreationPdfServiceImpl.java:143)
    at fr.bluepad.site.back.service.followup.impl.FollowupCreationPdfServiceImpl.generateFollowupBatPdf(FollowupCreationPdfServiceImpl.java:49)
    at fr.bluepad.site.front.actions.clients.followup.FollowupAuditAction.downloadPreviewPdf(FollowupAuditAction.java:148)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:871)
    at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1294)
    at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68)
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:117)
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:108)
    at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1370)
    at ognl.ASTMethod.getValueBody(ASTMethod.java:91)
    at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
    at ognl.SimpleNode.getValue(SimpleNode.java:258)
    at ognl.Ognl.getValue(Ognl.java:467)
    at ognl.Ognl.getValue(Ognl.java:431)
    at com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:352)
    at com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:404)
    at com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:350)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:430)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:290)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:251)
    at org.apache.struts2.interceptor.DeprecationInterceptor.intercept(DeprecationInterceptor.java:41)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:168)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:76)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:229)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:229)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:125)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:253)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:140)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:575)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:81)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:165)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1195)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:319)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:744)
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating OGNL expression: "item.title"
    at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.evaluate(OGNLVariableExpressionEvaluator.java:201)
    at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.evaluate(OGNLVariableExpressionEvaluator.java:187)
    ... 118 more
Caused by: java.lang.UnsupportedOperationException
    at java.util.AbstractMap.put(AbstractMap.java:209)
    at ognl.OgnlContext.put(OgnlContext.java:579)
    at com.opensymphony.xwork2.ognl.accessor.ObjectAccessor.getProperty(ObjectAccessor.java:19)
    at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2417)
    at ognl.ASTProperty.getValueBody(ASTProperty.java:114)
    at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
    at ognl.SimpleNode.getValue(SimpleNode.java:258)
    at ognl.ASTChain.getValueBody(ASTChain.java:141)
    at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
    at ognl.SimpleNode.getValue(SimpleNode.java:258)
    at ognl.Ognl.getValue(Ognl.java:467)
    at ognl.Ognl.getValue(Ognl.java:431)
    at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.executeExpression(OGNLVariableExpressionEvaluator.java:336)
    at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.evaluate(OGNLVariableExpressionEvaluator.java:180)
    ... 119 more

i populate my hashmap variables with the summary list this way
private ByteArrayInputStream generateFollowupBatPdf(FollowupAuditStruct auditStruct) {
      //generate pdf
      String pathHtml = "followUpExport.html";
      String baseuri = "/";

   // Summary
      List<FollowupPdfSummaryEnum> summary = new ArrayList<>();
      summary.add(FollowupPdfSummaryEnum.COVER);
      summary.add(FollowupPdfSummaryEnum.SUMMARY);
      summary.add(FollowupPdfSummaryEnum.SITUATION_PLAN);
      summary.add(FollowupPdfSummaryEnum.BUILDING_VISUAL);
      variables.put("summary", summary);

      try (
              ByteArrayOutputStream outputStream = (ByteArrayOutputStream) PdfGenerator.generatePdf(pathHtml, baseuri, variables);
      ){
         return new ByteArrayInputStream(outputStream.toByteArray());
      } catch (IOException e) {
          System.out.println("Error : " + e);
      }
      return null;
   }

I don't understand what is an OGNL Exception neither how to solve it
Comment: You need to edit your question and add the full stack trace of the exception
Comment: The problem is probably hidden in `PdfGenerator.generatePdf`. I can take your enum and your Thymeleaf template and I can generate a PDF successfully using your data and my own `PdfRendererBuilder`. First I generate the rendered HTML as a string (using Thymeleaf's `TemplateEngine`) and then I use the PDF generator. Bottom line: Your enum and Thymeleaf are correct (except for the fact that you cannot actually put a `href` attribute inside a `li` element - the `href` will have no effect).
Comment: yep sorry forgot to add exception message thanks
Answer: Here is my code, as mentioned in my comment in the question:
For reference, here is the comment:

The problem is probably hidden in PdfGenerator.generatePdf. I can take your enum and your Thymeleaf template and I can generate a PDF successfully using your data and my own PdfRendererBuilder. First I generate the rendered HTML as a string (using Thymeleaf's TemplateEngine) and then I use the PDF generator. Bottom line: Your enum and Thymeleaf are correct (except for the fact that you cannot actually put a href attribute inside a li element - the href will have no effect).

Here is the Thymeleaf renderer code and PDF generator code:
// imports include:
// import org.thymeleaf.TemplateEngine;
// import org.thymeleaf.context.Context;

model.put("summary", summary);

TemplateEngine templateEngine = ThymeleafConfig.templateEngine();
Context thymeleafCtx = new Context();
thymeleafCtx.setVariable("summary", summary);
String html = templateEngine.process("enum_to_pdf.html", thymeleafCtx);

try (OutputStream os = new FileOutputStream("C:/temp/out.pdf")) {
    PdfRendererBuilder builder = new PdfRendererBuilder();
    builder.useFastMode();
    builder.withHtmlContent(html, null);
    builder.toStream(os);
    builder.run();
}

The ThymeleafConfig.templateEngine() is a static helper method I use:
public static TemplateEngine templateEngine() {
    TemplateEngine templateEngine = new TemplateEngine();
    //templateEngine.addDialect(new Java8TimeDialect());
    templateEngine.addTemplateResolver(htmlTemplateResolver());
    return templateEngine;
}

This, in turn, uses the following (you may want to place your template somewhere else with a different resolver):
public static ITemplateResolver htmlTemplateResolver() {
    ClassLoaderTemplateResolver templateResolver
            = new ClassLoaderTemplateResolver(Thread
                    .currentThread().getContextClassLoader());
    templateResolver.setTemplateMode(TemplateMode.HTML);
    templateResolver.setPrefix("/thymeleaf/");
    templateResolver.setSuffix(".html");
    templateResolver.setCharacterEncoding("UTF-8");
    return templateResolver;
}

My full Thymeleaf template:
<!DOCTYPE html>

The end result:
Answer: You can't use Struts AND Thymeleaf, beacause they both use OGNL.
You have to create an other service to use Thymeleaf

OGNL Exception using Thymeleaf


How to select default option in Material-UI Autocomplete component dynamically?

Question: I am looking for a way to pre-set a default option in a Autocomplete component, just when the ajax call completes loading the list of options.
So the use case would be this: when the user opens the page, in the background a list of options would be loaded into state from the ajax response. I want to select the first retrieved option from the list, as soon as it gets loaded. Currently, I just have a basic way to offer a list of options:
  <Autocomplete
     options={defaultProps.options}
     getOptionLabel={option => option.name}
                 renderInput={params => (
                  <TextField {...params} variant="outlined" fullWidth />
     )}
  />

but don't know to select the first one when it gets loaded.
Answer: I'm using useEffect to demonstrate an ajax request on component mount.
You can use the value property to set the value after the component has been rendered.
While waiting for the ajax request to resolve, you can use the loading prop to change the component mode to loading
const [options, setOptions] = useState([]);
  const [def, setDef] = useState(null);

  useEffect((()=>{
    setTimeout(()=>{
      const tempArr = [{name:'Subject'},{name:'Another Subject'}];
      setOptions(tempArr);
      setDef(tempArr[0]);
    }, 1000);
  }), []);

  return (

Autocomplete

      {<Autocomplete
        options={options}
        loading={!def}
        value={def}
        getOptionLabel={option => option.name}
          renderInput={params => (
              <TextField {...params} variant="outlined" fullWidth />
        )}
      />}

  );

Answer: In latest version of Material UI theres an autoHighlight prop.
<Autocomplete
    options={defaultProps.options}
    getOptionLabel={option => option.name}
        renderInput={params => (
        <TextField {...params} variant="outlined" fullWidth />
    )}
    autoHighlight // add this
/>

See the API for Autocomplete


What is the difference between the classical and contemporary method of teaching instruments?

Question: Ever since I learned that you could learn to play instruments through a classical or contemporary method, and that musical teachers are taught classically or contemporarily, I've been asking myself the question, "What's the difference?" What's the difference between the two methods? Is it simply a matter of the music being taught or does it have a deeper meaning? Is it in the way you play? Or how you feel when playing? What is the difference, really?
Answer: I would say personally that it's mostly a matter of the music being taught.  The main exception to that is voice; all you have to do is listen to, say, Pavarotti and Frank Sinatra to tell the difference.  They are obviously each going after a very different sound.  Operatic singing doesn't use a microphone and emphasizes natural volume.  The sound is stylized with a good deal of vibrato as well.
Interestingly, if you listen to Caruso's 100-year-old recordings, you will notice that his use of vibrato is not as consistent as with more modern operatic singers.  He usually used it mostly when hitting high and loud notes.  This suggests the possibility that the difference between popular and operatic styles became more divergent during the 20th century.
As for other instruments, it is also a matter of going for a different type of sound.  "Classical" piano spans 300 years and has a wide range of sounds and techniques.  Just to take one example, Mozart's music makes much less use of the sustain pedal than Debussy's.  So does pretty much all of Jazz, for that matter.  Listen to Art Tatum, pay attention to the left hand, and you'll see that there's very little pedaling.  You'll also perhaps notice that all of his fast runs have a sort of detached, non legato sound, meaning each tiny note has an even tinier space of silence between it and the next note.
The reason that popular musicians often mention that they are "classically trained" is to convey that they have "chops", meaning that they have a solid grounding in technique and theory.  It's hard to improvise your way very far in classical music; it's sort of like when you were a kid and sat around pretending to read, and your older sister called you out and said you were just looking at the pictures and making stuff up.  (Well, that happened to me when I was a kid, anyway.)
Answer: I think the 'classical' approach is much more 'proper', as in in dots the t-s and crosses the i-s. Attention to the written detail is very important. Take any music played in a 'classical' exam. Every note must be given its exact timing, dynamics need to be followed, etc. Whilst there certainly is nothing wrong with this concept, it makes each performance of a particular piece very similar.
The 'contemporary' approach is to personalise each piece more. As in, use the music as a guideline rather than a blueprint. One is allowed to interpret what the composer has written in one's own manner, style, etc. Rather than saying ' That's what he wanted', it's more of a 'Maybe he didn't think to do it like this. Let's try.'
Theory still has a very important part in each, though, as slightly different timings, or harmonies, will need to obey certain rules, usually.Of course, sometimes tunes are pushed and pulled so much that they become unrecognisable, but that's another story...
For some reason, comments can't be left, but for my first para., I was trying to point out that for classical composers who wanted their works to sound the same as they wrote, they needed to put in as much information for the player as possible, and if all that was adhered to, each performance should be pretty similar.
Comment: I don't think you should say "it makes each performance of a particular piece very similar". It's rather that the classical approach gives freedom in other, more subtle aspects of music than the contemporary approach, e.g. you'll generally consider a much wider spectrum of dynamic and tempo changes, vibrato varieties, and there are even multiple ways to intonate individual notes. Of course, in both schools there are teachers who'll tell their students there's only one "correct" way (basically like a MIDI computer program would play it), but that is just wrong IMO.
Comment: I should also mention, to be fair, that a school of thought advocating rigid adherence to the score evolved in the 19th century, and was pretty much the standard by the 20th. This has in the last 50 years begun to be relaxed, as it clearly wasn't the composer's intention in much of the music out there. So, I wouldn't characterize your "contemporary" approach as contemporary. It's been around for a very long time!
Comment: To demonstrate very clearly leftaroundabout's point, compare [this](https://www.youtube.com/watch?v=RjKtEvOz6gk) and [this](https://www.youtube.com/watch?v=GXjM2hrqO54). Also, [here](http://symposium.music.org/index.php?option=com_k2&view=item&id=1903:exploring-cadenzas-to-beethovens-piano-concertos&Itemid=124) is a most interesting essay on "classical" performance practices, which shows that actual practice is far less rigid than you suggest. You'll see that in the day, performers got their "solo" and were applauded much as, say, a jazz soloist gets applause after playing his bars.
Comment: Whilst it's all interesting stuff - really! - , the OP is asking about teaching in the two ways. My answer comes from preparing people for ABRSM exams, where strict adherence to the dots seems, to me, to be de rigeur. Especially in the earlier grades. Your examples are great, but they are perhaps at the opposite end of the spectrum, where some diversity is allowable due to the propensity of the performer - musical licence, if you like.
Comment: Well, yes, if you are referring to ABRSM exam prepration, I would agree unqualifiedly. Given the British educational system's thoroughness, uniformity, and emphasis on drilling (please understand that I'm a big fan of British education--there's no substitute for a thorough grounding in fundamentals), I would think that performances in those exams would be very similar indeed. However, generalizing that characterization to the entire body of classical piano pedagogy rather overstates the case. As for strict adherence to the dots, I will mention the Courante from Bach's first Partita. :)


PayPal: "The email address for the business is not present in the encrypted blob. Please contact your merchant". How to fix?

Question: My code for my PayPal integration has worked for a decade or so with no problems.
Today I've generated a new public certificate as the old one was due to expire.  I did it exactly the same (documented) way that I've always done it, and uploaded it to PayPal.  Stupidly, I deleted the old one before testing the new one.
And now I get this message when I try to make a purchase:
<code>The email address for the business is not present in the encrypted blob. Please contact your merchant.
</code>
Any idea what's happened?  My only thought is that PayPal are trying to force me into using a more modern way of integrating their payment gateway with my site, and are giving this error based on me having a newer public cerficiate now.  But PayPal, if that's really what it's about, have a link to a help article on the subject FFS!
I'm stumped, any suggestions welcomed.
Answer: If you have this problem it might be worth checking the file permissions of your new private key.  Mine was 600 and needed to be changed to 644 to match the old outgoing file.  Problem solved.


Compiling a simple header with inline methods

Question: I have a base class Student, and an inheriting class StudentAtA.
I define StudentAtA inside StudentAtA.h, and it overides some of the methods of Student.
For example, if Student has:
string returnUni()
{
 return NULL;
};

Then I define inside  StudentAtA.h an overriding method:
string returnUni()
{
 return "A";
};

Since all the methods in StudentAtA are short, they're all implemented in the header file (I didn't create a StudentAtA.cpp file).
Now I have a Driver.cpp file which uses StudentAtA, and contains a main function. This is the executor.
Is it possible to compile Driver without having StudentAtA.cpp (just using the header)?
Comment: yes even then: http://stackoverflow.com/a/4955288/3060253   this guy summed up the reasons
Comment: as long as your compiler can find the definition for your methods it's happy. However it's not recommended to put the method bodys inside the header file.
Comment: Even if the methods are 1-2 lines long? (I'm new to c\c++ and aren't familiar with the standards)
Comment: @Glandy The discussion behind that link is, fortunately, a bit more balanced than your summary. There's nothing absolutely wrong with method bodies in header files, it's a balance between tighter coupling and giving the compiler more options for optimization. Obviously, the method listed above should be `virtual`, and in that case, there's probably no reason to have it in a header, since it will hardly ever be eligible for inlining.
Answer: yes possible. Just make sure you include StudentAtA.h in your Driver.cpp


How to hide certain products on WooCommerce cart page

Question: I have changed the main WooCommerce cart page using CSS to hide the products on this page.
The reason for the change, I am attempting to dedicate the cart page to only show the product "Thank You For The Tip" if it is in the cart, without changing any of the WooCommerce product settings to hidden.
All other products that have been added to the cart need to be hidden on the main WooCommerce cart page.
I see that I can not achieve this with CSS as the changes I made to the CSS will hide all products that have been added to the cart.
The closest I have come to finding a PHP solution is the following snippet:
add_filter( 'woocommerce_cart_item_visible', 'bbloomer_hide_hidden_product_from_cart' , 10, 3 );
add_filter( 'woocommerce_widget_cart_item_visible', 'bbloomer_hide_hidden_product_from_cart', 10, 3 );
add_filter( 'woocommerce_checkout_cart_item_visible', 'bbloomer_hide_hidden_product_from_cart', 10, 3 );
add_filter( 'woocommerce_order_item_visible', 'bbloomer_hide_hidden_product_from_order_woo333', 10, 2 );

function bbloomer_hide_hidden_product_from_cart( $visible, $cart_item, $cart_item_key ) {
    $product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
    if ( $product->get_catalog_visibility() == 'hidden' ) {
        $visible = false;
    }
    return $visible;
}

function bbloomer_hide_hidden_product_from_order_woo333( $visible, $order_item ) {
    $product = $order_item->get_product();
    if ( $product->get_catalog_visibility() == 'hidden' ) {
        $visible = false;
    }
    return $visible;
}

However, this does not give the desired result. Any advice?
Answer: To hide certain WooCommerce products only on the cart page and nowhere else, it suffices to just use the woocommerce_cart_item_visible filter hook.
In the $targeted_ids array you can indicate which productIDs should remain visible. This also works for variationIDs
function filter_woocommerce_cart_item_visible( $true, $cart_item, $cart_item_key ) {
    // The targeted product ids
    $targeted_ids = array( 30, 53 );

    // Computes the intersection of arrays
    if ( ! array_intersect( $targeted_ids, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
        $true = false;
    }

    return $true;
}
add_filter( 'woocommerce_cart_item_visible', 'filter_woocommerce_cart_item_visible', 10, 3 );

To apply the reverse, and hide the productIDs that occur in the array
Replace
if ( ! array_intersect(..

With
if ( array_intersect(..


If $f_A(x) \ne m_A(x)$ and $A^3=I$ then $A=I$?

Question: Suppose $A \in M_{3\times3}(\mathbb R)$ and $f_A(x) \ne m_A(x)$ where $f_A(x)$ is the characteristic polynomial of $A$ and $m_A(x)$ is the minimal polynomial of $A$.
If we were to assume that $A^3=I$, would we get that $A=I$ ?
Would the result be different in case $A$ was $2\times2$ matirx?
If it possible to find such $A$ which isn't $I$, please explain how to do it.
Otherwise, please explain why it isn't possible.
My current work:
I started with the case where $A$ is $3 \times 3 $ matrix.
From the assumption that $A^3=I$ we know that the polynomial $g(x)=x^3-1$ annihilates $A$.
From there I tried to construct $A \in M_{3\times3}(\mathbb R)$ such that $A^3=I$ while keeping in mind that any eigenvalue $c$ of $A$ must satisfies $g(c)=c^3-1=0$ . The only matrices I were able to look for were the rotating matrices and the projection matrices which didn't satisfy  $A^3=I$.
Is there any other way to be able to construct such matrix?
Where $A$ is a $2 \times 2 $ matrix I had the same problem to construct the matrix I want, but I was able to try different combinations. None of them matched the $A$ I was looking for, therefore I'm almost sure it is impossible to find such a matrix when $A$ is $2 \times 2$ matrix.
Thank you
Comment: Yes you are correct. I don't know how I missed it. But if I wanted to find $A$ which isn't a rotating or a projection matrix, is it also possible? And what about the case where $A$ is $2 \times 2$ matrix?
Comment: Oh wait a second, @OfirSchnabel might be correct. we should make sure $f_A(x) \ne m_A(x)$ ...
Comment: Thank you @Ale and thank you Ofir for noticing this.
Answer: In the $3\times 3$ case we have $$x^3 -1 = (x-1)(x^2+x+1) $$ and $x^2+x+1$ is irreducible in $\mathbb{R}[x]$.
Thus the minimal polynomial of $A$ can be $x-1$ or $(x^2+x+1) $ because $f_A(x) \neq m_A(x)$.
But if $m_A(x) = x^2+x+1$ then $f_A(x) \not\in \mathbb{R}[x]$ because the roots of $x^2+x+1$ are complex coniugate, the minimal and the characteristic polynomial have the same roots and $\deg f_A(x) = 3$. Thus $m_A(x) = x-1$ and $A=I$.
In $2 \times 2$ case if $m_A(x) = x^2+x+1$ then $f_A(x) = m_A(x)$. Thus  $m_A(x) = x-1$ and $A=I$ also in this case.
Comment: Very good explanation. I still don't understand one thing. $m_A(x) = x^2+x+1$ implies that $f_A(x) \notin R[x]$ but then you wrote there that deg $f_A(x)=3$, Why?
Comment: Oh forget it. I understood. Thank you very much!!
Comment: In the $3 \times 3$ case $\deg f_A(x) = 3$, so if the roots of $m_A(x)$ are $\alpha_1, \alpha_2 \in \mathbb{C}$ we have $$f_A(x) = m_A(x) ( x-\alpha_i)$$ and this isn't in $\mathbb{R}[x]$
Comment: Yes, I understand. Thank you very very much for the detailed explanation.
Answer: Since $m_A(x)\neq f_A(x)$ then the degree of $m_A(x)$ is $1$ or $2$.
But $m_A(x)$ must devide $x^3-1=(x-1)(x^2+x+1)$.
From here show that $m_A(x)=x-1$ and hence $A=I$.
Comment: Why the fact that $m_A(x)$ must divides $x^3-1=(x-1)(x^2+x+1)$ implies that $m_A(x) = x-1$ ?
Comment: I think you should try to show that. Notice that your matrix is real so each complex eigenvalue $z$ comes along with $\bar{z}$. So $A$ must have a real eigenvalue which must be a root of $m_A(x)$.
Comment: I understand it now. Thank you!
Answer: The minimal polynomial $m_A$ always divides the characteristic polynomial $f_A$, which always divides a power of $m_A$ (because $f_A$ is the product of the invariant factors associated with $IX-A$). So if $m_A\neq f_A$, then some irredicible factor of $m_A$ divides $f_A$ twice. Given that $X^3-1$ is an annihilating polynomial, the only possible irredicible factors of $m_A$ are $X-1$ and $X^2+X+1$. But the latter squared cannot divide $f_A$ which is of degree$~3$, so $(X-1)^2$ divides $f_A$. But now there is no room (degree) left for a quadratic factor, $X^2+X+1$, so it doesn't divide $f_A$, nor $m_A$. Then $m_A$ is a positive power of $X-1$ that divides $X^3-1$, in other words $m_A=X-1$, which only happens when $A=I$. Also of course $f_A=(X-1)^3$.
In the $2\times2$ case the same argument works, even easier. In the $4\times 4$ case there are easy counterexamples.


How to share a menu across more website

Question: I've got a main website where it's possible to create and change menu items and I need to share this menu with other websites and programmatically(once per week or once per day) the other websites will import and override the menu.
This is very useful when a company has got more websites and wants to use the same footer menu for all its websites.
Do I need to use just Feeds and Rules to achieve it?
Is it possible to achieve it without adding the main website db menu in settings.php in all the other websites?
Thanks in advance
Answer: I think the idea of using a feed is an attractive one. I don't think there's any way to push a menu definition out as a feed using existing modules, though.
I'd write a very simple module to provide a single callback that would fetch the menu definition and theme it as xml or json (easier). That could then be fetched at intervals by your other sites.
Comment: Yes, something like print `json_encode(menu_tree('my_menu'))` would be the simplest code to do it.
Comment: Yes, is it possible to create a menu view with json format?
Comment: It looks interesting. I will test it in these days. Thanks Alfred.

How to share a menu across more website


Inverse Wishart Prior for linear model

Question: I know some bayesian methods employ an inverse wishart distribution for the prior distribution of the covariance matrix in a linear regression. I.e. for the model:
$$Y=X\beta+\epsilon$$
Where $\epsilon \sim N(0, \Sigma)$, some methods will use $\pi(\Sigma)\sim W^{-1}(A,v)$. My question is however, what should the matrices/values $A$ and $v $ be? I read somewhere that $v$ was degrees of freedom but could not work out of what... should $v$ be $n-p$ where $X$ is $(n \times p)$ and how should $A$ be chosen?
Answer: A textbook sort of answer would be that you as the data analyst should choose $A$ and $\nu$ to best capture your prior beliefs about the unobserved covariance $\Sigma$. Here's one approach to doing that:
You first recognize that if an $n\times n$ matrix $\Sigma$ has the Inverse Wishart distribution $W^{-1}(A,\,\nu)$, then its mean is
$$E[\Sigma]=\frac{1}{\nu-n-1}A\quad \text{if }\nu>n+1.$$
So for starters, you might want to pick $\nu>n+1$ so that the mean of your prior exists. Then, you could decide what you believe about the "average behavior" of $\Sigma$ in your application and then select
$$A=(\nu-n-1)\bar{\Sigma},$$
where $\bar{\Sigma}$ is what you think the mean is.
Furthermore, you can look up expressions for the variances and covariances of the elements of $\Sigma$. In all cases, you will notice that as the degrees of freedom $\nu$ increase, the variances shrink. So if you believe that the prior distribution for $\Sigma$ should be diffuse, you might want to keep $\nu$ low. If you think it should be tight, you'll want to pick a bigger $\nu$.
Update: picking $\bar{\Sigma}$
One approach is to set the prior mean of $\Sigma$ to some "reasonable" estimate taken from past research. Perhaps there are important papers in the literature related to your application which will give you an idea of where it makes sense to center $\Sigma$.
If you don't have such knowledge, but you have a moderate to large dataset, another approach is to take your dataset $(y_i,\,x_i)_{i=1}^N$ and break it into two subsets: a "training" set $(y_j,\,x_j)_{j=1}^{N_{tr}}$ and a "test" set $(y_k,\,x_k)_{k=1}^{N_{te}}$, where $N_{tr}$ is small compared to $N_{te}$ and $N_{tr}+N_{te}=N$. You can use the training dataset to compute, for example, the MLE estimate of $\Sigma$, use that as the prior mean of $\Sigma$, and then conduct your data analysis using the remaining test data. That is, you are setting aside a portion of your data in order to "train" the prior, and you are then ignoring it when you do the main estimation. You wouldn't train the prior on a portion of the data but then also include that data in the main estimation.
Comment: I see thank you, that is very helpful!

Inverse Wishart Prior for linear model


in Sankey diagram: make paths "as short as possible"?

Question: I am interested in using Sankey diagrams, like http://bost.ocks.org/mike/sankey/
Specifically, I am using the block that enables cycles: http://bl.ocks.org/cfergus/3956043
But, each "start-node" is drawn on the far left and each "end-node" drawn on the far right.
Ascii example:
|A ----> B ----> C ----> D|
|E-------------> C        | <-- starts far left
|F --------------------> D| <-- starts far left
|G ----> B ------------> H| <-- finishes far right

What I prefer (in my specific case) is to keep the paths as short as possible, e.g.:
|A ----> B ----> C ----> D|
|        E-----> C        |  <-- don't start far left
|                F ----> D|  <-- don't start far left
|G ----> B ----> H        |  <-- don't finish far right

Any d3js experts that know if this is easy to modify in the position calculation algorithm?
At the moment I manually move the nodes after they have been rendered.
from:

to:
Answer: Yes, it is possible to achieve what you want, with a simple change in Sankey code plugin.
There is a line in function computeNodeBreadths() within Sankey plugin:
moveSinksRight(x);

It should be changed to:
moveSourcesRight(x);

This is illustrated in following two examples:
Example 1
(original Sankey plugin)
jsfiddle

Example 2
(with proposed change)
jsfiddle

Example 3
(with both MoveSinksRight() and MoveSourcesRight())
jsfiddle

Example 4
(without both MoveSinksRight() and MoveSourcesRight())
jsfiddle
Comment: Excellent, exactly what I was looking for. Thanks! It seems you used the same jsfiddle for example 2 and 3?
Answer: This is my approach:
http://bl.ocks.org/danharr/af796d91926d254dfe99
I'm explicitly setting the x co-ordinates using graph.links[3].source.x = 200 etc.  This could be linked to a dataset rather than being hard coded I guess
Comment: Your response is appreciated, but I'm looking for what to change in the algorithm, not how to hardcode the coordinates.


jekyll does not work in my windows 7

Question: I have installed jekyll in my windows 7, but it does not work. I have created a folder called jekyllSite and have included the necessary files in the folder, then I open Command Prompt and and cd in that folder and run jekyll code. It generates the following message. I can not understand what is wrong?
←[1mNAME←[0m:

    jekyll

  ←[1mDESCRIPTION←[0m:

    Jekyll is a blog-aware, static site generator in Ruby

  ←[1mCOMMANDS←[0m:

    build                Build your site
    default
    docs                 Launch local server with docs for Jekyll v1.2.1

    doctor               Search site and print specific deprecation
warnings
    help                 Display global or [command] help documentation.

    import               Import your old blog to Jekyll
    new                  Creates a new Jekyll site scaffold in PATH

    serve                Serve your site locally

  ←[1mALIASES←[0m:

    hyde                 doctor
    server               serve

  ←[1mGLOBAL OPTIONS←[0m:

    -s, --source [DIR]
        Source directory (defaults to ./)

    -d, --destination [DIR]
        Destination directory (defaults to ./_site)

    --safe
        Safe mode (defaults to false)

    -p, --plugins PLUGINS_DIR1[,PLUGINS_DIR2[,...]]
        Plugins directory (defaults to ./_plugins)

    --layouts DIR
        Layouts directory (defaults to ./_layouts)

    -h, --help
        Display help documentation

    -v, --version
        Display version information

    -t, --trace
        Display backtrace when an error occurs

Comment: Well? Did you run it with any of the command line parameters that it tells you about?
Comment: I can not understand you. I only cd in the folder and run jekyll code.
Answer: The output you've provided is just a description of what jekyll executables can do. To have any results you should use jekyll command either to build the site (to prepare static files instantly) or to host the site.
So, in those cases you just either use:
jekyll build

or
jekyll serve

respectively.
Comment: Well, frankly saying your question tells that you might just be a bit not fully sure how jekyll basicly works, so I would recommend to read just a bit more of documentation. (Even though, jekyll was really not born for Windows, its basics are pretty simple even on this platform).

jekyll does not work in my windows 7


Equal output values given for Multiclass Classification

Question: I'm trying to build a CNN for predicting the number of fingers in an image, using PyTorch. The network:
class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()

        self.Layer1 = nn.Sequential(
        nn.Conv2d(in_channels=3, out_channels=16, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.MaxPool2d(kernel_size=(2, 2)),
        nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=64, out_channels=128, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=128, out_channels=256, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.MaxPool2d(kernel_size=(2, 2)),
        nn.Conv2d(in_channels=256, out_channels=16, kernel_size=(1, 1)),
        nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=64, out_channels=128, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=128, out_channels=256, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.MaxPool2d(kernel_size=(2, 2)),
        nn.Conv2d(in_channels=256, out_channels=16, kernel_size=(1, 1)),
        nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=64, out_channels=128, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.MaxPool2d(kernel_size=(2, 2)),
        nn.Conv2d(in_channels=128, out_channels=16, kernel_size=(1, 1)),
        nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=64, out_channels=128, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.MaxPool2d(kernel_size=(2, 2)),
        nn.Conv2d(in_channels=128, out_channels=16, kernel_size=(1, 1)),
        nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=64, out_channels=128, kernel_size=(3, 3)),
        nn.ReLU(),
        nn.Conv2d(in_channels=128, out_channels=256, kernel_size=(3, 3)),
        nn.ReLU(),
        )

        self.Layer2 = nn.Sequential(
        nn.Linear(1536, 100),
        nn.Tanh(),
        nn.Linear(100, 6),
        nn.Softmax()
        )
        self.optimizer = optimizers.Adadelta(self.parameters())

    def forward(self, X):
        X = self.Layer1(X)
        print(X.shape)
        X = self.Layer2(X.reshape(1, 1536))
        X = X.squeeze()

        return X

    def calc_loss(self, X, num):
        out = self.forward(X).unsqueeze(dim=0)
        print("Output: "+str(out))
        target = torch.tensor([num], dtype=torch.int64).cuda()
        criterion = nn.CrossEntropyLoss()
        loss = criterion(out, target)
        return loss

    def train_step(self, X, Y):
        loss = self.calc_loss(X, Y)
        print(loss)
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

However, after the training is complete, all predictions have almost the same values (around 0.15 ~ 0.18).
It appears as though the network averages out the output probabilities to minimize loss, instead of learning the actual values.
I get the same result whether I use Softmax for the last layer with cross-entropy loss, or Sigmoid with binary cross-entropy, MSE, or SmoothL1Loss.
In case of using Adam optimizer, I get similar results, only in the range of 1e-12 ~ 1e-14.
What am I missing?
Comment: ok, I looked once again at your problem and for `CrossEntropyLoss` you need raw output w/o Softmax.
Comment: To be honest, your implementation is a little bit confusing, why not to split off the model implementation and the training loop? It will make your debugging much easier
Comment: I wanted to keep all network operations separate from the data operations. All data is loaded from a different file and fed to the model from that file.
Comment: `train_step` is called multiple times in a loop for different values of X and Y for the file mentioned in the above comment.
Comment: I see.. Did you try to overfit your model on a single batch? just for testing, to be sure that the everything works fine?
Comment: Yes, I have tried that. For a single class, it works fine. When I introduce more classes, the output gets averaged over those classes. For example, if I overfit for classes 1 and 5, the output is of the form ~ [0, 0.5, 0, 0, 0, 0.5]
Comment: Are you using `torch` `DataSet`? If not, did you one-hot your labels, because if it works for one class, and fails for more, maybe the problem is in labels encoding.
Comment: I'm not using torch DataSet. However, using one-hot for `CrossEntropyLoss` gave errors. After some search, I found that PyTorch's CrossEntropyLoss takes an integral value as the target, representing the class index. For other loss functions, I have used one-hot encodings.
Comment: Oh, yeah, you are right, for `CrossEntropyLoss` targets should be 1D Tensor with values of class index from 0 to C-1. Are your classes started from 0?
Comment: Yes, they index from 0
Comment: Ok, I am worrying about criterion, looks like you initialize new one every time she you compute loss. I think it is better to init it once in __init__(), like optimizer. I am not sure, but CrossEntropy performs onehot encoding anyway, and in your model you initialize new loss for each new batch, maybe this is the problem?
Comment: You're right! I overlooked this mistake.
Comment: However, it does not change the result...
Comment: `CrossEntropyLoss` already includes `softmax`
Answer: If you are using CrossEntropyLoss, you don't need to use Softmax in your forward. It is already included to CrossEntropyLoss, so you need the "raw" output. But, if you need Softmax during inference time, use NLLLoss + 'Softmax' instead.
You can find more info here
Comment: Oh, I did not know that. Thank you!
Comment: You welcome! Sorry I didn't notice it from the first look. My bad)


How to get escaped file description from node?

Question: I enabled file description for node and I want to display descriptions close to the download links.
I would like the description be secure. I tried
$items = field_get_items('node', $node, 'field_files');
foreach ($items as $item) {
  echo $item['description'];
}

but there is html code parsed.
I can use just check_plain() function on the description, but is there any way to do it better?
Answer: As stated in the comments to official documentation:

It is worth noting that field_get_items() returns raw values the use of which can be a security risk. Passing the raw values through field_view_value() handles the sanitizing of the values.

Links added by me.
Comment: You are passing whole item to field_view_value(), right? can you `dpr()` it's result? For `$display` settings, see [this](https://api.drupal.org/api/drupal/modules!field!field.module/function/field_view_field/7) - you need to set proper formatter, I guess you want something like `'text_summary_or_trimmed'`. Or just use check_plain and don't bother ;)
Comment: OK, looks promising, but it gives me a link if I use `render()` to it and insecure value if I use `echo $value['#file']->description`


How to determine whether a separate status bar exists in android?

Question: My app has an option for going to fullscreen mode, i.e. hiding the status bar via
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                     WindowManager.LayoutParams.FLAG_FULLSCREEN);

However, on Honeycomb tabs the status bar is combined with the bar that has the softkeys (home, back, ...) and can thus not be hidden. To avoid confusion, I would like to hide the fullscreen option on these devices. I could not find how to determine whether the device I am running on has a separate status bar or not.
Answer: Perhaps this post will help. There is a hidden API method in the IWindowManager class called canStatusBarHide and one called hasNavigationBar both of which return booleans and have names that are pretty self-explanatory. You'll need to use Reflection to access them asd they are not available in the SDK.


Uniform Continuity of a Continuous Function on $[0, \infty)$

Question:
If a function, $f:[0,\infty) \rightarrow \mathbb{R}$ is continuous, and converges to $L \in \mathbb{R}$ as $x \rightarrow \infty$, is the function uniformly continuous on $[0, \infty)$? If so, what is the proof?

I think so, and I was thinking something along the following... Let $\epsilon > 0$ be given. Then, because the function converges, we can find $k \in \mathbb{R}$ such that if $x \geq k$: $| f(x) - L | < \frac{\epsilon}{2}$. Then, $f$ is continuous on $[0, k]$, therefore it is uniformly continuous because $[0, k]$ is a closed, bounded interval. That means, there exists $\delta$ such that if $x, a \in [0,k]$ and $| x - a | < \delta$, we have that $|f(x) - f(a)| < \epsilon$. Notice that this $\delta$ also works for $[k, \infty)$, because all points in $[k, \infty)$ are within $\epsilon$ of each other!
Thus, we've shown $f$ is uniformly continuous on $[0,k]$, and $[k, \infty)$. How can I finish the proof? Is this approach correct?
Answer: Almost there! You have to inspect what happens when you have two points $x,y$ such that $\lvert x-y\rvert<\delta$ and $x<k<y$. In this case $$\lvert f(x)-f(y)\rvert\le \lvert f(x)-f(k)\rvert+\lvert f(k)-f(y)\rvert\le 2\varepsilon$$
So, technically a $\delta$ that works for $\varepsilon$ is $$\widehat \delta:=\min\left\{\delta_{\varepsilon /2}^{[0,k]},\delta_{\varepsilon /4}^{L,\,[k,\infty)}\right\}$$
Answer: Your basic idea is correct but I don't understand what you mean by "all points in $[k,\infty)$ are within $\varepsilon$ of each other".
Note that to show that $f$ is uniformly continuous, you need to say something about $|f(x) - f(y)|$ whenever $x,y$ are close enough. If you divide $[0,\infty)$ as $[0,k] \cup [k,\infty)$ then you'll be able to use uniform continuity to estimate $|f(x) - f(y)|$ when $x,y$ are both in $[0,k]$ and use the existence of a limit and the triangle inequality (you didn't write this part out) to estimate $|f(x) - f(y)|$ in where $x,y$ are both in $[k,\infty)$ but you are still left with the problem of estimating $|f(x) - f(y)|$ when one of the points is in $[0,k)$ and the other is in $[k,\infty)$. Here, the triangle inequality comes again to your rescue and you have
$$ |f(x) - f(y)| \leq |f(x) - f(k)| + |f(k) - f(y)| \leq |f(x) - f(k)| + |f(k) - L| + |L - f(y)| \\
< \varepsilon + \frac{\varepsilon}{2} + \frac{\varepsilon}{2} = 2\varepsilon $$
(where here we assume that $x \leq k \leq y$).


Nested grid does not stay expanded after PageIndexChanged event

Question: I am trying to figure out how to keep my nested grid expanded after I move to the next page.
This is my markup:
<asp:ScriptManager ID="scriptMger" runat="server"></asp:ScriptManager>
<asp:GridView ID="UserGroupGridView" runat="server" AutoGenerateColumns="False">
  <Columns>
  <asp:TemplateField>
    <ItemTemplate>
    <a href="javascript:DivExpandCollapse('div<%# Eval("GroupID")%>');">
    <img id="imgdiv<%# Eval("GroupID")%>" alt="" width="25px" border="0" src="Images/plus.png" />
    </ItemTemplate>
  </asp:TemplateField>
  <asp:TemplateField HeaderText="GroupID">
    <ItemTemplate>
    <asp:Label ID="uggvLblGroupID" runat="server" Text='<%# Bind("GroupID") %>'></asp:Label>
    </ItemTemplate>
  </asp:TemplateField>
  <div id="div<%# Eval("GroupID") %>" style="display:none">
  <asp:UpdatePanel ID="updatePnlNestedGrid" runat="server" UpdateMode="Conditional">
  <ContentTemplate>
  <asp:GridView ID="GroupMemberGridView" runat="server" AutoGenerateColumns="false" OnRowDeleting="GroupMemberGridView_RowDeleting"
  OnRowCommand="GroupMemberGridView_RowCommand" CssClass="grid" ShowFooter="true" AllowPaging="true" PageSize="5"                         onpageindexchanging="GroupMemberGridView_PageIndexChanging" onpageindexchanged="GroupMemberGridView_PageIndexChanged">
  <Columns>
  <asp:TemplateField HeaderText="MemberID">
    <ItemTemplate>
    <asp:Label ID="mggvLblMemberID" runat="server" Text='<%# Bind("MemberID") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Member Name" ItemStyle-Wrap="false">
    <ItemTemplate>
    <asp:Label ID="mggvLblMemberName" runat="server" Text='<%# Bind("MemberName") %>'></asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:DropDownList ID="mggvDDLMemberName" runat="server"
    class="chosen-single" data-placeholder="Choose member…">
    </asp:DropDownList>
    </FooterTemplate>
    </asp:TemplateField>
 </Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>

</Columns>
</asp:GridView>

This is my javascript that is at the top of the page:

This is the PageIndexChanged method that calls the javascript:
protected void GroupMemberGridView_PageIndexChanged(object sender, EventArgs e)
{
 GridView tgvGroupMember = (GridView)sender;
 int tiGroupID = Convert.ToInt32((tgvGroupMember.Parent.FindControl("uggvLblGroupID") as Label).Text);
 UpdatePanel updatePnl = (UpdatePanel)tgvGroupMember.Parent.FindControl("updatePnlNestedGrid");
 string strJavascriptFnCall = "ExpandGrid(" + tiGroupID.ToString() + ")";
 ScriptManager.RegisterStartupScript(updatePnl, updatePnl.GetType(), "ExpandGrid", strJavascriptFnCall, true);
}

In debug, when the ExpandGrid() javascript function is called, I get the error:  ExpandGrid() is not defined.
The function is between  tags and at the top of the page.
Why is it not defined?
Thanks.
Answer: I got my nested grid to remain expanded after paging.
This is how I fixed it...
First, I removed Sys.WebForms.PageRequestManager.getInstance().add_endRequest from the javascript so that the function looked like this:
function ExpandGrid(groupID) {
        var div = document.getElementById(groupID);
        alert("groupID: " + groupID + " div: " + div);
        var img = document.getElementById('img' + groupID);
        div.style.display = "inline";
        img.src = "Images/minus.png";
        $(div + ".chosen-single").chosen("destroy");
        $(div + ".chosen-single").chosen({
            search_contains: true,
            width: "100%",
            no_results_text: "Sorry, no match!"
        });

Then within the PageIndexChanged I correctly named the parameter and surrounded it in single quotes:
string strJavascriptFnCall = "ExpandGrid('div" + tiGroupID.ToString() + "')";

Finally, I put the UpdatePanel outside the div, not inside it as shown above.
That got it to work.
I hope this can help someone.


Firefox plugin for a web developer that shows all resources (js, css, html) as a single unified file?

Question: I'm developing with a really complex cms system, and sometimes I need to know if something was sent to my html rendering.
Since this is a huge cms system, I have at least 30 resources linked to a page (js, css), and going through each one, clicking and searching for a string is not the best way to do it.
I would like to have a plugin that gets all the resources from a page, merges them as text, so i can search only once. Is this possible? Does something like this exists?
(I know Firebug can inspect an element and such, but a search option for an specific scenario - like a type=submit somewhere in a css file - is faster and more useful).
Answer: The plugin you need is the Web Developers toolbar addon for Firefox.

You can search all JavaScript files in plain text by clicking Information -> View JavaScript
You can search all CSS files in plain text by clicking CSS -> View CSS
Comment: I would like to have to click just once, but having to click 3 times instead of 30 is still a good idea. I'm going to waut for more suggestions. :)
Answer: In firebug, when you inspect an element it shows all CSS rules applying to it and a link to the source file involved. I think it is away more powerful then what you want.
Comment: I'm already using firebug. In some situations a search approach is faster and more useful.


Selecting a suitable model for time-series prediction problem

Question: I'm relatively new to machine learning and data science so please be understanding :)
I'm building a simple model for time-series prediction using feedworward neural network, my data is continous.
What I did until now is: built and trained few neural networks (differing in number of hidden layers and neurons) and compared their accuracy in predicting the values for my test set.
I'm wondering if there is any better way to determine the size of my neural network, instead of building so many models and simply comparing their MSE over the test set. How is it typically done?
Comment: This question is accumulating close votes, because it is to general. Please tell us more context, specifics of the problem.
Answer: A general rule of thumb is that if the complexity of your data is low, then you probably don't need a complex model for those data. Meaning, if your time series is a short series or not very noisy, it may be better to choose a simpler model than neural networks (very simple models often do pretty well in a lot of time series cases). Naive methods, moving averages, and linear models are far more common over neural networks in practice for simple forecasting tasks.
As for choosing the best neural network, what you have been doing is often called hyperparameter tuning or model tuning: finding the combination of parameters that give you the best model (like number of neurons and number of layers). The most straightforward method is to do what you're doing. Train a bunch of models and compare the metric. This is typically done by creating a test set or holdout set from your and testing the models on that. If you have 24 months of data, train your networks on the first 18 months and then test them to see how they perform on the last 6 months of unseen data.
For most deep learning tasks in practice, no more than 2 or 3 layers are really needed (most data in practice, especially time series, will need more complexity than that). But again, it always depends on the data and situation. See what works best.


How many types of mathematical information are there?

Question: I am aware of at least two types of mathematical information:

Shannon Information, which is the negative of entropy (i.e. a loss of entropy by $n$ bits is precisely a gain of Shannon information of $n$ bits). One also has mutual and conditional information of two random variables, and information theory is named for this type.
Fisher information. This type is apparently very commonly used and considered in statistics, to the best of my limited knowledge. It is also supposed to be the source of the name for information geometry (since the Fisher information metric is the Riemannian metric).

My question:
Are there any other mathematical concepts of information which I am missing? How many types of mathematical information exist?
Comment: There is also [Kolmogorov complexity](https://en.wikipedia.org/wiki/Kolmogorov_complexity) which is linked to [algorithmic information theory](https://en.wikipedia.org/wiki/Algorithmic_information_theory). This differes from the other two in that it does not require a statistical model.
Answer: Certainly the two you mentioned are important, and perhaps the most
widely known.
For categorical data there is Sorenson's similarity index. (Roughly,
the probability that a randomly selected individual in my population
will belong to the same category as I.) See Wikipedia on categorical data for
several more.
In a sense random data have less structure or 'information' than
data with some nonrandom structure. Runs tests and autocorrelation
functions are ways of judging randomness.
In his famous assertion that
it takes about 7 shuffles to put a deck of cards into something like random order,
Persi Diaconis used the concept of rising sequences as a measure of
information that might be exploited by a player. (Rising sequences
have been used by magicians doing card tricks for over a century.)
Google Diaconis shuffle to find a NYT article on this topic and
the paper by Bayer and Diaconis with wonderful mathematical details.

Digression: I will leave the definition of 'rising sequence' to Bayer and Diaconis.
A deck in order from 1 through 52 has one rising sequence. One shuffle
(cut and riffle) results in two rising sequences, two shuffles usually
in four. A randomly permuted deck averages 26.5 rising sequences. The
figure below, based on simulations, shows how the distribution of the
number of rising sequences comes closer to the distribution for a
random deck (lower right) as the number of shuffles increases.

Code makers and breakers have several measures of information content
in a string of characters. Some of these can be found in readily
available books and papers on cryptology. I would not be surprised if some of the
most useful ones may have been discovered by mathematicians at government
agencies and not publicly available.
There is a sense in which a Markov Chain can contain more information
than a sequence of independent random variables. The whole idea of
a Markov Chain is that the current observation may be useful in
predicting the next one.
This is a list of a few kinds and measures of and viewpoints on information that are in
practical use. I suppose that some of them can be shown to be related
to (perhaps even equivalent to) Fisher or Shannon information and that some are not. My purpose is not to give you an exhaustive list, but just to suggest
that the list of measures of information is quite large and may be endless.
As big data analysis becomes increasingly popular (and one hopes better focused and
organized), I suspect that measurement of information content in large datasets
will become a substantial field of investigation.


How to convert an English sentence that contains "can't take more than 2" into predicate calculus sentence?

Question: The example is :
A student can't take more than 2 courses with the same instructor
Comment: What have you translated so far?
Comment: The word _can't_ has a somewhat inexact meaning until you decide exactly what it means. "You can't do that!" "Really? It seems to me that I _am_ doing it."
Comment: amWhy
∀c∃x∃y∃z∃q(takes(x,y,q)^takes(x,z,q) → ¬takes(x,c,q)) Where c,y,z are courses ; x is student ; q is instructor
Comment: If $C$ is the set of courses, $I$ the instructors, and $f\subset C\times I$ the relation that assigns instructors to courses, then you can say $$\neg\left[ \exists x,y,z\in C, \exists a\in I:((\neg(x= y))\wedge (\neg(x= y))\wedge(\neg(y= z))\wedge((x,a)\in f)\wedge((y,a)\in f)\wedge((z,a)\in f))\right]$$
Comment: Everybody seems to be translating, "No student takes more than $2$ courses from any instructor," which is not what the sentence says.  I would say that the sentence means something like, "It is a rule of the college that no student may take courses from any instructor."  It seems quite possible that some student is taking $3$ courses from a single instructor, in violation of the rules.  Perhaps I'm saying the same thing David K says in his comment.
Answer: Hint: To say "there can't be more than 2 things" it is sufficient to say "there are not 3 distinct things".
Comment: ∀c∃x∃y∃z∃q(takes(x,y,q)^takes(x,z,q) → ¬takes(x,c,q))
Where c,y,z are courses ; x is student ; q is instructor
Is it correct?


A property of Darboux sum

Question: I'm trying to show that:
$$\overline{I}:=\inf _P S(f;P)=\lim_{\lambda (P)\to 0}S(f;P)$$
where $P$ is a generic partition (made by $n$ points) of the interval $[a,b]$, $f$ is bounded on $[a,b]$, $S(f;P):=\sum _{i=1}^n\sup_{\Delta_i}f(x) \cdot \Delta x_i $ upper Darboux sum of $f$ on partition $P$ with mesh $\lambda (P)$.
Facts already known and proved:
a) $s(f;P_1):=\sum _{i=1}^{n_1}\inf_{\Delta_i}f(x) \cdot \Delta x_i \leq S(f;P_2)$, for all partitions $P_1$ and $P_2$.
b) $0\leq S(f;P)-S(f;\widetilde{P})\leq \omega (f;[a,b])\cdot (\Delta x_{k_1}+...+\Delta x_{k_m}) $, where $\widetilde{P} $ is a generic refinement of $P$, $ \omega (f;[a,b]):=\sup _{x',x'' \in [a,b]}|f(x')-f(x'')| $ and $\Delta x_{k_1},...,\Delta x_{k_m} $ are all the intervals of $P$ which contain points only in $\widetilde{P} $.
My attempt to demonstrate the statement:
$ \overline{I} $ is well defined thanks to a). Being an $\inf $, this implies that $\forall \epsilon >0$ there exists a partition $P_\epsilon $ such that:
$$\overline{I} \leq S(f;P_\epsilon) \leq \overline{I} + \epsilon$$
to conclude, it would be enough for me to show that any partition $ P $ with a mesh that is narrower than that of $ P_\epsilon $ leads to $S(f;P) \leq S(f;P_\epsilon) $, but all I managed to get (using also b)) was this:
$$S(f;P) \leq S(f;P_\epsilon) +\omega (f;[a,b])\cdot m\cdot \lambda (P)$$
where $m$ is the number of points in $P_{\epsilon} $ and $\lambda (P) $ is the mesh of the new partition $P$.
I can't do better.
A little help, please?
Thanks in advance.
Comment: See https://math.stackexchange.com/a/2047959/72031
Comment: See [here](https://math.stackexchange.com/a/3023282/148510) for a proof when the integral exists. The part of the argument for the upper sums converging to the upper Darboux integral is all you need for this question.
Comment: You will see you are almost there. Take the partition $P$ with sufficiently small mesh and form a common refinement with $P_\epsilon$ to make the needed estimates.
Comment: I have not understood the way I should follow.
I already obtained the last inequality using a refinement of $P_\epsilon$.
Comment: Interesting, thank you @ParamanandSingh.
Answer: You are on the right track.  To help you finish, recall that it is to be shown for any $\epsilon > 0$ there exists a partition $P$ such that $|S(f;P) - \bar{I}| < \epsilon$ or equivalently
$$\tag{*}\bar{I} \leqslant S(f;P) \leqslant \bar{I} + \epsilon,$$
when $\lambda(P) < \delta$.
As you showed, now using $\epsilon/2$ instead of $\epsilon$, there exists a partition $P_\epsilon$ such that
$$\overline{I} \leqslant S(f;P_\epsilon) \leqslant \overline{I} + \frac{\epsilon}{2}$$
We want to introduce any partition $P$,  not necessarily a refinement of $P_\epsilon$, and produce $\delta$ such that (*) is satisfied if $\lambda(P) < \delta$. Next, we construct a partition $\widetilde{P}$ that is a common refinement of $P$ and $P_\epsilon$ by adding the $m$ interior points of $P_\epsilon$ to $P$. Now, as you came close to reasoning, it follows that
$$S(f;P) \leqslant S(f;\widetilde{P}) + \omega (f;[a,b])\cdot m\cdot \lambda (P)$$
Further insight into why this is true can be obtained either by drawing a picture or following my argument here.
Since $\widetilde{P}$ is a refinement of $P_\epsilon$, we have $S(f;\widetilde{P}) \leqslant S(f;P_\epsilon)$, and it follows that
$$S(f;P) \leqslant S(f;P_\epsilon) + \omega (f;[a,b])\cdot m\cdot \lambda (P) \leqslant \overline{I} + \frac{\epsilon}{2}+ \omega (f;[a,b])\cdot m\cdot \lambda (P)$$
By choosing $\delta = \epsilon/ (2 \cdot m \cdot \omega (f;[a,b]))$, it follows that if $\lambda(P) < \delta$, then
$$\bar{I} \leqslant S(f;P) \leqslant \bar{I} + \epsilon$$
Comment: Thank you very much. (+1)
Comment: @Nameless: You're welcome.

A property of Darboux sum


Using Kerberos between two seperate domains

Question: We run SharePoint 2007 in our envirnoment and currently have a non-transitive, external trust setup between the two domains because were planning on migrating to SharePoint 2010. Our SQL Server is in the domain 2, while domain 1 has the front end web servers. We have setup a SharePoint 2010 instance but are using NTLM, I'd like to change that to use Kerberos but having a hard time finding specific information on setting it up between the two seperate forest domains. Don't get me wrong there's a lot out there, its just informational overload and was hoping someone might be able share any experinces they've had with a simliar setup and/or point me to some specific doc, blog, or whatever they've used and works.
Thanks..
Comment: What is your AD level?
Comment: Both Domains are at 2003
Answer: Surprisingly, I've found the best documentation was from microsoft. The O'Reilly book on Kerberos also has an Advanced topics section on kerberos trusts, but things have changed in the 8 years since it was published.
Basically, make sure all windows boxes know about both domains. They'll know about the forest they're on, but a reg key can let them know about the other.
Comment: That doc talks about "Configure the UNIX host".  We do not have any Unix host, all machines are 2003, with a couple of 2008 boxes.  I haven't read all the way through it yet, hopefully its in there somewhere.. Thanks.
Comment: There should be a AD GUI admin tool for you then, but worst case scenario you can probably set it up manually.


Send a new config to gtag when a new "page" is loaded in an SPA does not show the new path in realtime analytics

Question: I have React SPA when I use gtag to track users in Google Analytics. I am confused with data which I see in Real-Time Google Analytics. When app starts or user is routed to new react route I fired event like this to set correct page and log pageView
window.gtag('config', UA-123456789-1, {
        groups: 'MYGROUP',
        page_path: '/contacts',
    })

When user click on button or make some interesting action I fire event like this
window.gtag('event', 'Some button click', {
        sendTo: 'MYGROUP',
        event_category: 'buttons on main page',
    })

Many events is button click on page one and this click move user to another page (on this new page is fired gtag configure). When I watch events in Real-Time Analytics page view, pages is shown like one page delayed. For example gtag events flow and RealTime result

gtag Configure page "/about" -> in GA is showing /about
gtag Event "signIn click" (move user to sign in)
gtag Configure page "/signin" -> in GA is showing /about
gtag Event "contacts click" (move user to contacts)
gtag Configure page "/contacts" -> in GA is showing /signIn

Do you know why this happens? Do I need log both events and pageView. I am not sure where this delay starts. In some cases I see for example first two pages correctly and third is delayed, sometimes is delayed from first event. Event and configure is fired close together.
Comment: Check if the acquired data is as you expected it, real time is not reliable.
Comment: This affected me, turns out there was just a delay on realtime reporting that looked like it offset the current page as you describe in my case
Answer: Given it's an SPA, you should manually send the pageview as prescribed here: https://developers.google.com/analytics/devguides/collection/gtagjs/pages#page_view_event.


A question about function of independent random variable and Law of large number

Question: Suppose we know $X_1, X_2, X_3, ..., X_n$ are identical and independent random variable, and $\overline{X}$ denote $\frac{X1+X2+...+Xn}n$. Is it necessarily true that $|X_1-\overline{X}|$ and $|X_2-\overline{X}|$ be independent random variable? I don't think it is true, because the fact that functions of independent random variables are still independent random variables cannot apply here as $X_1-\overline{X}$ is not just function of $X_1$, but also function of $X_2$.
If they are not independent random variables, that means that we cannot assert that because of law of large number $\frac{\sum|Xi-\overline{X}|}n$ converge in probability to $E(|X-\overline{X}|)$ right?
Answer: Indeed they are not independent and strong law cannot be applied to $\frac {|X_i - \bar {X}|} {n}$. For example take $no2$ and consider $|X_1- \bar{X}|= \frac {|X_1 -X_2|} 2$ and $|X_2- \bar{X}|= \frac {|X_2 -X_1|} 2$. Hence $|X_1 -\bar {X}|=|X_2 -\bar {X}|$ and independence fails unless $|X_1 -X_2|$ is a constant. There are many ways of showing that this can happen only if X_i is a constant random variable.


Internet Explorer: How to modify CSS at runtime for printing?

Question: Imagine a webpage which enables users to show an hidden element, using javascript to modify css a CSS style at runtime.
After his decision (which includes the modification of the stlyesheet) the user uses the printing functionality of his browser.
It seems that Internet Explorer does not respect the changes made in the stylesheet before during printing if the original css definition is located in an external file.
In other Browsers everything works as expected.
Please have a look at the example below, which changes a style class from its initial definition display:none to display:inline at runtime hence the element will be displayed.
But when printing this page, the element remains hidden in internet explorer (tested with IE 6,7,8).
Do you have a solution or workaround?
Minimalistic example (html file):

<LINK rel="stylesheet" type="text/css" href="minimal.css">

This is hidden by default.

minimal.css
.col0 {
  display:none;
}

UPDATE:
Please note that the decision if the object should be displayed or not is made by the user - it's not known at runtime!
Comment: it not work because the style is applied on visible screen and not for printing (when you click on print preview, web page is reloaded an prepare for printing using default css as value). I suggest you to use a css with media="print" and conditional if to use particular version for internet explorer.
Comment: @RoBYCoNTe I've updated the question - the decision if the object should be displayed is done by the user. if he decides to show the object displayCol() will be invoked - but it only shows the object on the screen but not on the printer.
Comment: @MR: did you ever solve this problem? I am having the same issue. I use jquery's .toggle() method to toggle the visibility of a section post page load. that section does not print on FF/Chrome (as expected) but still prints on IE. Do you have a solution for this? (I hate IE)
Answer: Have you considered using the media=print way of getting the browser to use a stylesheet specifically for printing?
<link rel="stylesheet" href="print.css" media="print" />
If the css changes you are making are always the same, i.e. you can technically store them on a separate css file, then you can use this.
For non-static CSS, in IE (not sure about other browsers/later versions of IE), you could consider using the onbeforeprint event.
See here: http://www.javascriptkit.com/javatutors/ie5print.shtml
Comment: Yes. Unfortunately, introducing media="print" styles also doesn't help me. Please note that the decision if an object should be displayed or not is made by the user - it's not static! I am sorry that this was not clearly pointed out in the question.
Comment: @MRal: Ah, I see. Did you try messing with the DOM? (Not that I recommend it).
Comment: @MRal: Apparently IE supports an onbeforeprint event. You could try using that (see the link in my answer).
Comment: @Moron: This doesn't help me, because I don't need to intercept printing. The css is already altered correctly, before the user decides to print. The problem is that IE seems not respect changes made to stylesheets for printing.
Comment: @Mral: It is possible that any changes you make during this event will be respected by IE for printing. Of course I haven't tried it. After all, this event was specifically made for dynamically figuring out the content to be printed. If that does not work, you can probably alter the DOM during this event. Caveat: Again, I haven't tried it myself.
Answer: Instead of using javascript to change the stylesheet rules, use scripting to apply and remove classes to the elements that need to be displayed. Remember that an element can have more than one class applied to it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <title>Demo</title>

This is hidden by default.

This answer to another question does a great job laying out different ways to do this with scripting: Change an element's class with JavaScript
Comment: Although this seems to work - this means I have to find and traverse all objects in the DOM tree and change their classes which might be resource intensive. Because of this I find it quite elegant to simple change the CSS defintion.
Comment: @MRalwasser It would depend on your specifics, but find an element via its ID is really low impact. If you are changing many elements, perhaps they have a parent element in common to which a class could be applied?
Answer: You could try using a specific style sheet for printing, for example:
<link rel="stylesheet" type="text/css" href="print.css" media="print" />

EDIT - too slow :)
Comment: this does not solve my problem. Please have a look at the updated question.
Answer: Javascript is not being evaluated when printing. It will look just like when Javascript is turned off. You need an extra media=print stylesheet and make any necessary changes there.
If that is not an option, you could create a link that will generate a static page that will look like it's supposed to for that particular user.
Comment: I am not trying to evaluate JavaScript during printing but before. In Firefox, everyting works as expected so this is a browser problem.
Answer: Based off your example scenario - in your style sheet add:
.col0 {
    display: none;
}

body.showColumn .col0 {
    display: inline;
}

Then simply toggle the .showColumn class on your body, and the column's visibility will be toggled accordingly.


Como saber quais teclas são apertadas em C# ConsoleApp e definir eventos

Question: Como posso "ler" qual tecla é apertada e definir um evento para tal tecla caso seja apertada.
Exemplo: se apertar F1 Soma, F2 subtrai e por ai vai
Encontrei no site de ajuda do C# este exemplo, mas não entendi como ele funciona:
    using System;

class Example
{
   public static void Main()
   {
      ConsoleKeyInfo cki;
      // Prevent example from ending if CTL+C is pressed.
      Console.TreatControlCAsInput = true;

      Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
      Console.WriteLine("Press the Escape (Esc) key to quit: \n");
      do {
         cki = Console.ReadKey(true);
         Console.Write("You pressed ");
         if ((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
         if ((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
         if ((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
         Console.WriteLine("{0} (character '{1}')", cki.Key, cki.KeyChar);
      } while (cki.Key != ConsoleKey.Escape);
   }
}

Mas este código apenas imprime as teclas apertadas
// This example displays output similar to the following:
//       Press any combination of CTL, ALT, and SHIFT, and a console key.
//       Press the Escape (Esc) key to quit:
//
//       You pressed CTL+A (character '☺')
//       You pressed C (character 'c')
//       You pressed CTL+C (character '♥')
//       You pressed K (character 'k')
//       You pressed ALT+I (character 'i')
//       You pressed ALT+U (character 'u')
//       You pressed ALT+SHIFT+H (character 'H')
//       You pressed Escape (character '←')

Agradeço pela ajuda
Comment: Tente usar isso: Console.ReadKey(true).Key == ConsoleKey.F1; //isso irá comparar se o caracter digitado é igual a F1
Comment: Isso funcionou.
Answer: Basicamente você pode utilizar a classe ConsoleKeyInfo para obter as teclas pressionadas, veja abaixo um exemplo:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExemploKey
{
    class Program
    {
        static void Main(string[] args)
        {
            ConsoleKeyInfo key;

            do
            {
                key = Console.ReadKey();
                Console.WriteLine(key.Key + " foi pressionada.");

            } while (key.Key != ConsoleKey.X);
        }
    }
}

Neste caso a aplicação vai exibir no console todas as teclas que você pressionar menos a tecla X, quando a tecla X for pressionada o programa será encerrado. Para verificar as teclas funcionais basta seleciona-las através da enumeração ConsoleKey, veja mais alguns exemplos:
ConsoleKey.F1;
ConsoleKey.F10;
ConsoleKey.F13;

Esta enum possui todas as teclas que serão utilizadas por você.
Fontes:
ConsoleKeyInfo.
ConsoleKey.
how to handle key press event in console application.


Damper pedal for Requiem for a Dream

Question: This has been bothering me for some time. I have been playing the piano for 3 years so far, and despite all my efforts I am unable to find an answer. It's a bit of a difficult question to phrase, so bare with me.
In "Requiem for a Dream" by Clint Mansell(the difficult version), almost right from the beginning you are required to play whole notes or half notes with your left hand. The right hand is supposed to play alternating A and Bb notes as well as a series of notes an octave lower (Bb, A, G, D). I assume, since it is pysically impossible to stretch my right hand that far that I am supposed to use my left hand for (A, G, D), but then how do I maintain the whole notes or half notes without using the damper pedal? Or am I missing something and am totally wrong in my thinking?
Thank you in advance.
Comment: Can we please see the music, if possible with your fingerings on it? :)
Answer: I presume this is the passage?

Under the circumstances, I don't think you can play it dry: you'll need to play the latter three quavers (eighth notes) of each group of quavers with the left hand. You will have to pedal with the LH semibreves (whole notes) and minims (half notes), although you can delay the onset of pedal until slightly after the start of each group.
Comment: Ahh, much obliged. It's a relief to know I've been playing it right all this time.
Comment: See here: https://www.youtube.com/watch?v=vBSUwU8Cp_Q

Damper pedal for Requiem for a Dream


Problem getting rid of theme error

Question: Fatal error: Unsupported operand types in `includes/theme.inc on line 980`

In my homepage im getting that error. I have no idea why I keep getting that error.
I'm on the process of upgrading my Drupal 6 to Drupal 7.
Thanks
Comment: Do you still have the old theme in your new installation? If so try deleting the old theme folder and the error *should* go away.
Comment: @stefgosselin no I don't have I already deleted them all
Answer: It's hard to impossible to know where this error come from without adding some debug statements before the line 980.
Try enabling devel.module and adding following code on line 977:
dpm(func_get_args());
dpm($info);

This will reveal which theme hook is being called and its parameters (variables). It should give enough clues to help you find where the error comes from.

Problem getting rid of theme error


Error during sysprep

Question: I have a recurring problem using sysprep on our Windows 10 machines. I use sysprep with an answer file. When I send our windows image on machines with almost the same hardware, everything works perfectly.
However, lets say my source machine is a ASUS and I decide to sysprep my Windows 10 installation and send it to a HP machine, I get this message:
+++
Error message "The Computer Restarted unexpectedly or encountered an unexpected error" after System Startup
+++
Normally, I can open regedit using Shift+F10 and change the child completion parameter to 3 instead of 1 nd it works but I want to understand and fix this error. I never found any reason why I get this error and how to fix it permanently...
Anybody have an idea?
Answer: I found it!
To fix this error, delete any settings in the specialize phase of your sysprep answer file (unattend.xml).
Basically, this phase (4 if I remember) should NOT be used anymore. I moved my settings to phase 7 OOBE system and everything works like a charm on any machine.
Hope this helps others!

Error during sysprep