JSF Portlets in Liferay on JBoss

Question: I'm currently looking at working with and deploying JSF portlets into Liferay 6.0.5, sitting on JBoss 5.1.0. I ran into a lot of trouble trying to port some JSF-y/Seam-y/EJB-y stuff I had lying around, so I thought I'd start simple and work my way up.
I could generate generic portlets using the NetBeans Maven archetype for Liferay portlets absolutely fine, but it's rather irrelevant because I wanted JSF portlets
I took an example JSF portlet from http://www.liferay.com/downloads/liferay-portal/community-plugins/-/software_catalog/products/5546866 and attempted to deploy into a clean, vanilla installation of Liferay 6.0.5/JBoss 5.1.0 to no avail. The log messages are reproduced at the end of this.
This particular example was actually tested for GlassFish and Tomcat, so it's not particularly helpful considering I'm deplying into JBoss. I tried ripping it apart and removing the jsf implementation contained within as there is a jsf implementation shipped with JBoss (Mojarra 1.2_12, in this case).

03:16:17,173 INFO  [PortletAutoDeployListener] Copying portlets for /usr/local/[REDACTED]/liferay/liferay-portal-6.0.5/deploy/richfaces-sun-jsf1.2-facelets-portlet-1.2.war
    Expanding: /usr/local/[REDACTED]/liferay/liferay-portal-6.0.5/deploy/richfaces-sun-jsf1.2-facelets-portlet-1.2.war into /tmp/20110201031617188
    Copying 1 file to /tmp/20110201031617188/WEB-INF
    Copying 1 file to /tmp/20110201031617188/WEB-INF/classes
    Copying 1 file to /tmp/20110201031617188/WEB-INF/classes
    Copying 47 files to /usr/local/[REDACTED]/liferay/liferay-portal-6.0.5/jboss-5.1.0/server/default/deploy/richfaces-sun-jsf1.2-facelets-portlet.war
    Copying 1 file to /usr/local/[REDACTED]/liferay/liferay-portal-6.0.5/jboss-5.1.0/server/default/deploy/richfaces-sun-jsf1.2-facelets-portlet.war
    Deleting directory /tmp/20110201031617188
  03:16:20,075 INFO  [PortletAutoDeployListener] Portlets for /usr/local/[REDACTED]/liferay/liferay-portal-6.0.5/deploy/richfaces-sun-jsf1.2-facelets-portlet-1.2.war copied successfully. Deployment will start in a few seconds.
  03:16:23,632 INFO  [TomcatDeployment] deploy, ctxPath=/richfaces-sun-jsf1.2-facelets-portlet
  03:16:24,446 INFO  [PortletHotDeployListener] Registering portlets for richfaces-sun-jsf1.2-facelets-portlet
  03:16:24,492 INFO  [faces] Init GenericFacesPortlet for portlet 1
  03:16:24,495 INFO  [faces] Bridge class name is org.jboss.portletbridge.AjaxPortletBridge
  03:16:24,509 INFO  [faces] The bridge does not support doHeaders method
  03:16:24,510 INFO  [faces] GenericFacesPortlet for portlet 1 initialized
  03:16:24,555 INFO  [PortletHotDeployListener] 1 portlet for richfaces-sun-jsf1.2-facelets-portlet is available for use
  03:16:24,627 SEVERE [webapp] Initialization of the JSF runtime either failed or did not occurr.  Review the server''s log for details.
  java.lang.InstantiationException: org.jboss.portletbridge.context.FacesContextFactoryImpl
          at java.lang.Class.newInstance0(Class.java:340)
          at java.lang.Class.newInstance(Class.java:308)
          at javax.faces.FactoryFinder.getImplGivenPreviousImpl(FactoryFinder.java:537)
          at javax.faces.FactoryFinder.getImplementationInstance(FactoryFinder.java:394)
          at javax.faces.FactoryFinder.access$400(FactoryFinder.java:135)
          at javax.faces.FactoryFinder$FactoryManager.getFactory(FactoryFinder.java:717)
          at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:239)
          at javax.faces.webapp.FacesServlet.init(FacesServlet.java:164)
          at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1048)
          at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:950)
          at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4122)
          at org.apache.catalina.core.StandardContext.start(StandardContext.java:4421)
          at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:310)
          at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:142)
          at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
          at org.jboss.web.deployers.WebModule.startModule(WebModule.java:118)
          at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
          at sun.reflect.GeneratedMethodAccessor286.invoke(Unknown Source)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
          at java.lang.reflect.Method.invoke(Method.java:597)
          at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
          at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
          at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
          at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
          at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
          at org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206)
          at $Proxy38.start(Unknown Source)
          at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:42)
          at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:37)
          at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62)
          at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71)
          at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51)
          at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
          at org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:286)
          at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
          at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
          at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
          at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
          at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
          at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
          at org.jboss.system.ServiceController.doChange(ServiceController.java:688)
          at org.jboss.system.ServiceController.start(ServiceController.java:460)
          at org.jboss.system.deployers.ServiceDeployer.start(ServiceDeployer.java:163)
          at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:99)
          at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:46)
          at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62)
          at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50)
          at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171)
          at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439)
          at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157)
          at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1178)
          at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098)
          at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
          at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
          at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
          at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
          at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
          at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
          at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
          at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781)
          at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:702)
          at org.jboss.system.server.profileservice.repository.MainDeployerAdapter.process(MainDeployerAdapter.java:117)
          at org.jboss.system.server.profileservice.hotdeploy.HDScanner.scan(HDScanner.java:362)
          at org.jboss.system.server.profileservice.hotdeploy.HDScanner.run(HDScanner.java:255)
          at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
          at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:317)
          at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:150)
          at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:98)
          at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:181)
          at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:205)
          at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
          at java.lang.Thread.run(Thread.java:619)
  03:16:24,629 INFO  [2-facelets-portlet]] Marking servlet FacesServlet as unavailable
  03:16:24,630 ERROR [2-facelets-portlet]] Servlet /richfaces-sun-jsf1.2-facelets-portlet threw load() exception
  javax.servlet.UnavailableException: Initialization of the JSF runtime either failed or did not occurr.  Review the server''s log for details.
          at javax.faces.webapp.FacesServlet.init(FacesServlet.java:172)
          at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1048)
          at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:950)
          at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4122)
          at org.apache.catalina.core.StandardContext.start(StandardContext.java:4421)
          at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:310)
          at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:142)
          at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
          at org.jboss.web.deployers.WebModule.startModule(WebModule.java:118)
          at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
          at sun.reflect.GeneratedMethodAccessor286.invoke(Unknown Source)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
          at java.lang.reflect.Method.invoke(Method.java:597)
          at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
          at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
          at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
          at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
          at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
          at org.jboss.system.microcontainer.ServiceProxy.invoke(ServiceProxy.java:206)
          at $Proxy38.start(Unknown Source)
          at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:42)
          at org.jboss.system.microcontainer.StartStopLifecycleAction.installAction(StartStopLifecycleAction.java:37)
          at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62)
          at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71)
          at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51)
          at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
          at org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:286)
          at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
          at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
          at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
          at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
          at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
          at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
          at org.jboss.system.ServiceController.doChange(ServiceController.java:688)
          at org.jboss.system.ServiceController.start(ServiceController.java:460)
          at org.jboss.system.deployers.ServiceDeployer.start(ServiceDeployer.java:163)
          at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:99)
          at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:46)
          at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62)
          at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50)
          at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171)
          at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439)
          at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157)
          at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1178)
          at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098)
          at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348)
          at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1631)
          at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934)
          at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1082)
          at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984)
          at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822)
          at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553)
          at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781)
          at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:702)
          at org.jboss.system.server.profileservice.repository.MainDeployerAdapter.process(MainDeployerAdapter.java:117)
          at org.jboss.system.server.profileservice.hotdeploy.HDScanner.scan(HDScanner.java:362)
          at org.jboss.system.server.profileservice.hotdeploy.HDScanner.run(HDScanner.java:255)
          at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
          at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:317)
          at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:150)
          at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:98)
          at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:181)
          at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:205)
          at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
          at java.lang.Thread.run(Thread.java:619)
Answer: This particular problem arose because the JBoss that comes bundled with Liferay is severely cut down, but also includes some other things you wouldn't find in a vanilla Jboss 5.1.0 instance.
In this case, there was a problem with the versions of the Portlet Bridge. I was packaging one, and there was one provided by Liferay's Jboss.
I presume that sorting this out would have fixed it, but I've decided that the JSF lifecycle and the Portlet lifecycle really don't mesh well together, so it's time to look at other types of Portlets for me.

JSF Portlets in Liferay on JBoss


new Date() sem fuso horário

Question: Tenho que enviar uma data javascript para o meu controller através do FullCalendar. Na minha action, estou recebendo um DateTime e preciso enviar através do arquivo javascript com o new Date(minha_variavel).
Porém quando faço isso, ele vêm com o fuso horário de -3 horas, ou seja se eu seleciono dia 10/08/2015 00:00:00 no FullCalendar, eu recebo no controller a seguinte data: 09/08/2015 21:00:00.
Tem algum jeito de passar data sem que aconteça isso?
Comment: Ele pode estar usando o GMT. Tente alterar para UTC ou alterar seu time zone no OS, acho que poderia dar certo.
Comment: essa  página da documentação pode ajudar: http://fullcalendar.io/docs/timezone/timezone/
Comment: tlz ajude http://pt.stackoverflow.com/questions/72294/string-para-date [errei o link]
Comment: Você já pensou em usar a momentjs pra gerenciar isso?
Answer: quando for trabalhar com datas a melhor alternativa é trabalhar com momentjs
mas voce poderia utilizar:
var d = new Date('10/08/2015 00:00:00');
d.toLocaleString() // 08/10/2015 00:00:00
d.toString(); //Thu Oct 08 2015 00:00:00 GMT-0300 (Hora oficial do Brasil)
d.toGMTString();  //Thu, 08 Oct 2015 03:00:00 GMT
d.toUTCString();  //Thu, 08 Oct 2015 03:00:00 GMT

new Date() sem fuso horário


just_audio/audio_service: Gapless playback doesn't work with FLAC, but only on the first song for the first playthrough

Question: apologies for the less-than-perfect question, but I've exhausted every option and I have no idea what left to do.
When playing FLACs from a file on iOS, the first transition from song 1 to 2 has a ~100ms hitch, even when playing from a ConcatenatingAudioSource. I cannot reproduce this by modifying the audio_service playlist example, and skipping back and listening to the transition again works fine (is gapless).
Playing the same songs over HTTP is gapless.
I don't have a minimal example but here are a few links to my code:

My BaseAudioHandler (note that this has been around since pre-0.18, which probably doesn't help)
Where I create MediaItems and set the queue

It's fine if there's no clean answer here (I don't have a good example, which kind of gets in the way of that). I'd just like to know if there's anything I could possibly do here. I might try hacking in a thing to force-load the next item ~5 seconds before the next song, but that's a bad solution which clearly isn't required.
Comment: Random thought - I may potentially be getting frame drops caused by switching songs (images loading and stuff like that). That's the only explanation I have, will have to investigate further
Answer: Disclaimer: I'm a complete beginner - so anything below could be completely irrelevant to the question you are asking.
I found your question when I was seeking a solution for my issue with a 1 to 2 ~100ms hitch between mp3s when playing from a  ConcatenatingAudioSource with just_audio.  Hopefully from the below, you can extrapolate a solution.
Basics of my app: Load five loops, when the user reached the beginning of the fifth, load five more loops, repeat for a long as the user is listening.  My loops are 30 seconds long, and I have a timer that controls other actions while the loops are playing.
My app would consistently play the first five loops flawlessly.  However, each of the additional loops had a ~100ms hitch in-between them.
Two things I did to resolve:

Stopped trying to append multiple loops to a playing list
Stopped trying to load at the first second of the timer

Here is a snippet of my code.
      int timerCounter = 0;
      late Timer timeControl;

      void loadLoops() {
        timeControl = Timer.periodic(Duration(seconds: 1), (timer)    async {
          if (timerCounter <= 30) {

            timerCounter++;

            /// next commented out line consistently causes a glitch if
            // timerCounter == 1 ? addMultipleLoops(storedPlaylist) : null;

            // my fix to get rid of glitch
            timerCounter == 6 ? addSingleLoop(loopPlayer.currentIndex! + 1): null;
            timerCounter == 31 ? timerCounter = 0: null;
          }
        });
      }

      void addMultipleLoops(List<int> storedPlaylist) {

        storedPlaylist.forEach((loop) {
          {
            loopPlaylist
                .add(AudioSource.file('${directory}/${loop}.mp3'));
          }
        });
      }

      void addSingleLoop(int indexPosition) async {
        /* my loop names are numbers starting at 1 (ex: 1.mp3, 2.mp3, 3.mp3... etc)
        ... Adding 1 to indexPosition references
        the first loop (1.mp3) when my index position is at 0.
        */

        int loop = indexPosition + 1;
        if(indexPosition == 4) {
          loop = 1;
        }

        loopPlaylist.add(AudioSource.file('${directory}/${loop}.mp3'));
      }
    }

Comment: Thanks :) I've found another solution, which I have posted.
Answer: My issue has been fixed by switching to the feature/treadmill branch of just_audio. It's not ready for production yet, but hopefully it gets released soon.


Slickgrid - dataView.setGrouping is not a function

Question: I am trying to follow the code in the example:
http://mleibman.github.io/SlickGrid/examples/example-grouping
I am getting the error:
dataView.setGrouping is not a function
Am I missing a js include? Does anyone know where this function is defined?
Comment: Apparently I have the wrong version of slickgrid.

I looked at the slick.dataview.js file on the site and seems my file is outdated, the setGrouping function is present there.

Thanks!
Comment: https://github.com/mleibman/SlickGrid/commit/90964ce5541bc2f381b6c60893f60029f24f907b
Answer: Apparently I have the wrong version of slickgrid.
I looked at the slick.dataview.js file on the site and seems my file is outdated, the setGrouping function is present there.
https://github.com/mleibman/SlickGrid/commit/90964ce5541bc2f381b6c60893f60029f24f907b


jquery validating html (remove p tags inside h1 tags etc) Remove tags keep the content

Question: can any one help me with this jquery, i need to remove tags inside other tags eg if a p tag is inside an h1 tag remove the p tag but keep the content, I have tried a few ways but the best i can come up with is to remove the content as well
$("#textEditor").contents().find("h1:has(p)").find("p").remove();

Edit here is the mark up i would like to validate

This is an example  of bad markup

need to remove these p tags but keep content

Answer: Use unwrap() to remove a tag, but keep it's content in the DOM. Also, your call to the contents() function isn't required.
$("#textEditor").find("h1:has(p)").find("p").unwrap();

More details on unwrap()
Comment: Thank you for the help, unwrap seems to be removing the h1 tags and keeping the p tags
Comment: Could you please edit your OP and post the HTML you're using so I can see how it's structured.
Answer: Thank you i just worked it out
 $("#textEditor").contents().find("h1:has(p)").find("p").contents().unwrap();

Thank you for pointing out the unwrap, the contents was needed because the #textEditor is in a iframe


What constitutes the "engine" in the Formula 1 per-season engine replacement limit?

Question: I'm not necessarily talking about the "engine" vs "power unit" debate with the new energy recovery systems and whatnot, though that is part of the problem. I'm more interested in the realm of the Grandfathers Axe / Ship of Theseus Paradox.
If I replace a blown MGU-K seal, is it the same engine? What about a rod bearing? The block? An oil pump?
Comment: In case it's helpful, the FIA seems to publish a document before each race indicating the how many power unit elements have been used to date by each driver. For example, in the [2019 season documents](https://www.fia.com/documents/championships/fia-formula-one-world-championship-14/season/season-2019-971) you'll find for each race a "PU elements used per driver up to now" document.
Answer: From the Formula 1 website:

Unless he drives for more than one team, each driver may use no more than four power units during a championship season.
The power unit is deemed to consist of six separate elements, of which five of each are available to a driver during the season before they are penalised. The elements are [various defined items].
Each driver is permitted to use only four of each of the above six elements during a championship season and any combination of them may be fitted to a car at any one time. Should a driver use more than four of any of the six power unit elements during the course of a season, a grid penalty will be imposed.

In simpler language: an "engine" consists of six different "parts". Each driver may replace each part four times before receiving a penalty. They are further limited so that they cannot replace all parts four times.
Thus for the purposes of the engine replacement limit, the "engine" is counted as one complete set of the engine components available. When you've used one complete set of components, you've used one engine. When you've used four complete sets of components, regardless of the order in which you replaced any specific components, you've used four engines and won't be allowed any more.
In terms of the Racecar of Theseus, it's all still the same engine until you've replaced everything at least once - then for the purpose of counting engines, that's when it becomes a new one!
Comment: Thank you for the link and the explanation!  It's interesting that they place seals on the major components.


keycloak 18 + React logout issue

Question: I'm using keycloak-react/web and keycloak-js packages in my React project. This is what I have in my keycloak.js
import Keycloak from 'keycloak-js'

const host = window.location.host

const keycloak = new Keycloak({
  url: `http://localhost:8080/auth`,
  realm: 'demo',
  clientId: 'demo',
})

export default keycloak

And this is how I logout the sso-logged-in user
{
  !!keycloak.authenticated && (

       keycloak.logout()}>Logout

  )
}

This used to work fine till I switched to keycloak v18.x.x Quarkus. Now, it doesn't even logout the user, let along redirect them to the homepage. What I understand from their documentation, which is stated in this answer, is that they've changed the mechanism to logout. But what I don't understand is how and where do I use this post_logout_redirect_uri
Update: I updated the JavaScript adapter (keycloak-js) to v19.0.1 which at least logs-out the user now but still haven't figured out how to redirect back to the login page
Answer: Update the JavaScript adapter (keycloak-js) to V19.0.1 as mentioned in the question and then make your code like this:
{
  !!keycloak.authenticated && (

       keycloak.logout({ redirectUri: 'http://localhost:3000/' })}>Logout

  )
}

Hope this helps!

keycloak 18 + React logout issue


C# OutOfMemoryException Image.Save

Question: I want to create for every image in a folder a thumb with 200px height and width. The images which should be proceeded vary in their size, nothing wider or higher than 1200px
List<string>ls=System.IO.Directory.GetFiles("C:\\sampleDir\\").ToList();
foreach( string  c in ls)
{
   var fu=new Bitmap(Image.FromFile( c), new Size(200, 200));
   fu.Save("\\thumbs\\"+c);
   //delete image from memory.
   fu.Dispose();
}

After several iterations, it crashes @ fu.Save(...) with an OutOfMemoryException , the exception says Error in GDI+.
After I got this exception the first time, I added fu.Dispose();.
The big question is, why it doesn't work.
Note through adding GC.Collect(); to my loop it works, but it seems not to be the proper solution.
The solution which worked for me was- thanks @Daniel Hilgarth:
List<string>ls=System.IO.Directory.GetFiles("C:\\sampleDir\\").ToList();
foreach( string  c in ls)
{
   var fu1=Image.FromFile(c);
   var fu=new Bitmap(fu1, new Size(200, 200));
   fu.Save("\\thumbs\\"+c);
   //delete image from memory.
   fu.Dispose();
   fu1.Dispose();
}

Comment: Good rule of thumb - if you use anything that implements `IDisposible`, wrap it up in a `using { }`.
Comment: It's worth noting - the .Net bindings to GDI+ are notorious for giving up on analysing root causes and instead stating "I've eliminated half of the possible reasons for an error, everything else I'll report as Out of Memory". If the answers given don't help, you need to dig in and find the actual original error codes before .Net gave up.
Answer: You should dispose the Image that is returned from Image.FromFile as well:
List<string>ls=System.IO.Directory.GetFiles("C:\\sampleDir\\").ToList();
foreach( string  c in ls)
{
    using(var image = Image.FromFile(c))
    using(var fu=new Bitmap(image, new Size(200, 200)))
    {
        fu.Save("\\thumbs\\"+c);
    }
}

Answer: First off, this is a perfect example of where it makes sense to use using.
List<string>ls=System.IO.Directory.GetFiles("C:\\sampleDir\\").ToList();
foreach( string  c in ls)
{
    using (var fu=new Bitmap(Image.FromFile( c), new Size(200, 200)))
    {
        fu.Save("\\thumbs\\"+c);
    }
}

A using statement will call Dispose for you, even if the code inside throws an exception.
But it appears you also have an Image object that you are not freeing. To free that object as well, the code above can be updated as shown below.
List<string>ls=System.IO.Directory.GetFiles("C:\\sampleDir\\").ToList();
foreach( string  c in ls)
{
    using (var img = Image.FromFile(c))
    using (var fu=new Bitmap(img, new Size(200, 200)))
    {
        fu.Save("\\thumbs\\"+c);
    }
}

Comment: "Are you saying it works okay when you added fu.Dispose()?" - Nope, that's not what he is saying. He says that even with this it *doesn't* work.
Comment: You may also need to help the Bitmaps use of the file serialization itself as well and do a using on the file serialization that the bitmap instance uses by calling close or dispose on a file stream you explicitly create. - If the Dispose on the Bitmap seems to not fully fix this for you.
Comment: @DanielHilgarth: Well, I didn't think he said that but I've updated my answer.
Comment: @JonathanWood: OK, here is why I think that's exactly what he said: "After I got this exception the first time, I added fu.Dispose();. The big question is, why it doesn't work."
Comment: @DanielHilgarth: I believe you are right, but when I read that I wondered if he meant the big question was why it didn't work without calling `Dispose()`.

C# OutOfMemoryException Image.Save


Label cannot be fully displayed in bar chart

Question: The bar chart I currently have can be found here https://ibb.co/mcrdV8R. The problem is, because some of the labels on the y-axis are relatively long, they are truncated to the left. Is there a way to display them in full (eg. shrink the bar chart part, etc) because I cannot make the labels shorter. In addition, how to make the bars thinner? Thanks in advance!
plt.barh(posBP, -np.log10(p_BP), color='#FF8000')
plt.barh(posMF, -np.log10(p_MF), color='#FF3333')
plt.barh(posCC, -np.log10(p_CC), color='#FFB266')
plt.yticks(np.arange(len(BP)+len(MF)+len(CC)),des_CC[::-1]+des_MF[::-1]+des_BP[::-1])
plt.xlabel('-$\log_{10}(p\_value)$')

Comment: Can't you add a 'line feed' ('\n') to your labels?
Answer: You can adjust your barh container thickness with the width argument manually and simply use matplotlib function tight_layout()  which automatically adjusts the figure area :
import matplotlib.pyplot as plt
import numpy as np

# random data
x = np.arange(1,13,1)
y = np.random.random(len(x))
# Adjust width of your bars here
width = 0.1

fig, ax = plt.subplots(figsize=(11.69,8.27))
ax.barh(x, y, width, color='r')
ax.set_xlabel('-$\log_{10}(p\_value)$')
ax.set_title('GO terms, Genes biased towards Nsyl in Root')
ax.set_yticks(x)   # set the position of the y ticks
ax.set_yticklabels(('5-triphosphate 6-kinase thingy which is important to know','other tick','and so on...'))
# matplotlib automatically adjusts the layout
plt.tight_layout()
plt.show()

which gives :
Comment: Nice! Thanks for the tip


Display two products as two radio buttons with a single Add to Cart Form

Question: I am having trouble deciding how to tackle this problem.  I have two products (indeed, one could be made as an attribute of another, which may help) which are basically two ticket options, only one of which can be purchased by a customer.  Therefore I would like to display them as two radio buttons with a single add to cart button (which I would then configure with Rules to send them straight to checkout).
Right now I have this:

Again, I would like to basically have two buttons, only one of which can be selected, with a single Add to Cart form.
Any ideas?
Answer: Drupal commerce was designed to do exactly this without going through lots of hoops, but it might be a bit tricky to get into.
Instead of making one an argument of another I'd create one product display with two different attached products, for which you can set an attribute field and a price. You can do so by having a node content type to act as a 'product display'. To do so you require inline_entity_form and commerce_product_reference (part of the commerce package).

On the product-type add a field the distinguish 'premium' product and make sure to hit the 'Enable this field to function as an attribute' checkbox.
Add a product reference field to a (new) content type you call 'product display' (or if you plan on selling more different kinds of products you can use a more specific name line 'event ticket' or something).
For the field widget choose 'inline entity form (multiple)'.
Create a node of the 'product'-type and add the two different products and their properties; for the 'premium' product make sure to change the price and the attibute field we created earlier.
Save the node.

If all went well you should end up with a selection box on the 'product display' node, allowing the users to select which version of the product they want to buy.
If you find this too vague, there is a detailed explanation (with pictures) on it here: Product Attributes & Variations. It does not use inline entity form so the 'attach products' involves a drop down on the images, whereas inline entity form will allow you to create and edit the entities directly on the node.


Metric spaces and the support of a random variable

Question: Does the use of metric spaces to describe the support of a random variable provide any greater illumination? I ask this after reading about how metrics spaces have been used to unify the mathematical measure theoretic nature of probability and the physical intuition that most associate with probability. You can read my inspiration here: http://www.arsmathematica.net/archives/2009/02/14/complete-metric-spaces-and-the-interpretation-of-probability/
Answer: Interesting reference.  Its value for me lies in questioning the ability of measure theoretic probability to capture an "intuition" about probability (whatever that might mean) and going on to propose an intriguing distinction; namely, between a set of measure zero having a measure zero neighborhood and a set of measure zero all of whose proper neighborhoods have positive measure.
It is not apparent that separable metric spaces are the "right" way to capture this idea, though, as the comment by Matt Heath points out.  It sounds like we only need a predefined subcollection of measurable sets (not necessarily even satisfying the axioms of a topology).  Such a collection is conveniently obtained in a separable metric space but there are other ways to create such collections, too.  Thus it appears that the idea presented here illuminates the connection between abstract measure theory and using random variables in models, but the use of metric spaces may be a bit of a red herring.
Answer: Here are some technical conveniences of separable metric spaces
(a) If $X$ and $X'$ take values in a separable metric space $(E,d)$ then the event $\{X=X'\}$ is measurable, and this allows to define random variables in the elegant way: a random variable is the equivalence class of $X$ for the "almost surely equals" relation (note that the normed vector space $L^p$ is a set of equivalence class)
(b) The distance $d(X,X')$ between the two $E$-valued r.v. $X, X'$ is measurable; in passing this allows to define the space $L^0$ of random variables equipped with the topology of convergence in probability
(c) Simple r.v. (those taking only finitely many values) are dense in $L^0$
And some techical conveniences of complete separable (Polish) metric spaces :
(d) Existence of the conditional law of a Polish-valued r.v.
(e) Given a morphism between probability spaces, a Polish-valued r.v. on the first probability space always has a copy in the second one


Boas praticas Codeigniter

Question: Vejo diversos programadores chamarem todas as views para construção de uma página no controller exemplo:
$this->load->view('head',$var);
$this->load->view('home');
$this->load->view('script');
$this->load->view('fim_html');

  <?php $this->load->view('head');?>

    <?php echo $conteudo ;?>

    <?php $this->load->view('script');?>

Eu sei que funciona do mesmo jeito, mas isso atrapalha em algo? (além da organização do código)
Qual a melhor forma de utilizar a inserção dos códigos no Controller?
Answer: Realmente adicionar muitas view na controller não é muito bom, por isso acabei encontrado uma library bem simples que utilizo.
Para utilizar a library crie o arquivo Template.php em application/views/Template.php e adicione o seguinte código:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Template {
    var $template_data = array();

    function set($name, $value)
    {
        $this->template_data[$name] = $value;
    }

    function load($template = '', $view = '' , $view_data = array(), $return = FALSE)
    {
        $this->CI =& get_instance();
        $this->set('contents', $this->CI->load->view($view, $view_data, TRUE));
        return $this->CI->load->view($template, $this->template_data, $return);
    }
}

Adicione no arquivo application/config/autoload.php a library para carregar com aplicação
$autoload['libraries'] = array('template');

Crie o arquivo template.php (ou a nomenclatura que quiser) na pasta view e adicione o seguinte código como teste:

<?= $contents ?>

A variável $contents é onde a view que deseja será inserida.
Como exemplo, cri uma view com o nome about.php com o seguinte código:

About

I'm so human!

Agora para utilizar o template adicione na controller:
$this->template->load('template', 'about');

Onde:

template : Nome do arquivo do template criado na pasta view;
about : Nome do arquivo que contem o conteúdo que deseja inserir na variável $contents.

Caso queira adicionar dados que serão utilizados na view, só adicionar o array como terceiro parâmetro, como mostra o exemplo:
$this->template->load('template', 'about', array('titulo'=> "Titulo da pagina"));

Espero ter ajudado.
Comment: A tudo bem, faço sim, irei editar a resposta
Answer: Não existe uma melhor forma. Há n forma de fazer algo. Eu particularmente acho que fica ruim ficar carregando muitas Views no Controller.
Eu comecei estudar CodeIgniter vindo do background ASP.NET MVC. Lá tem o conceito de MasterPage/Layout. Eu consegui fazer algo próximo disso com o CodeIgniter.
Tenho uma página masterpage que tem a estrutura básica do HTML, ela irá carregar uma View para Menu, Rodapé, e também irá carregar uma outra View que é conteúdo em si.
masterpage.php
<?php
  defined('BASEPATH') OR exit('No direct script access allowed');

?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?=$viewtitle?></title>
    <link href="<?=base_url('/assets/css/bootstrap.min.css')?>" rel="stylesheet">

    <?php $this->load->view("menu"); ?>

        <?php
          // aqui serão carregadas as views parciais
          $this->load->view($viewname);
         ?>

    <?php $this->load->view("rodape"); ?>

Para isso criei um Controller na pasta Core
MY_Controller.php
class BaseController extends CI_Controller {

  // variavel que será retornada para as views
  // irá conter as informações necessárias para a view manipular as informações
  protected $data;

  function __construct() {
    parent::__construct();

    // declara o array que contem as informacoes que vao para a view
    $this->data = array();
  }

  public function setData($nome, $valor) {
    $this->data[$nome] = $valor;
  }

  protected function setView($nome, $titulo) {
    $this->setData("viewname", $nome);
    $this->setData("viewtitle", $titulo);
  }

  public function loadView($nome, $titulo) {
    $this->setView($nome, $titulo);
    $this->load->view("masterpage", $this->data);
  }

}

Utilizo assim
class Produto extends BaseController {

   public function listarProdutos(){
      $this->load->model("ProdutoModel");
      $this->setData("produtos", $this->ProdutoModel->listar());

      // criei uma view chamada listagemProdutos.php
      // ela será carregada dentro da masterpage.php
      $this->loadView("listagemProdutos", "Listagem de Produtos");
   }
}

listagemProdutos.php

<?php foreach($produtos as $produto) {?>

<?=$produto->nome?>

<?php } ?>

Boas praticas Codeigniter


How to find the preimage of a set

Question: I'm trying to prove continuity of two different functions $f\colon A\to B$. I know that to find continuity, the inverse of all open subsets in $B$ must be open in $A$. I also know that to find the inverse of an open subset you have to find the preimage. I just don't know how to find the preimage. How do you find the preimage?
For example, if the set is the discrete topology of $\{1,2,3\}$, how would you find the preimage of $\{1\}$, $\{2\}$, etc. The same for the indiscrete topology. How would you find the preimage of the null set and the whole set? Thank you!
Comment: Do you understand what "preimage of a set under a function" means? You need a set and a function.
Comment: A couple more comments: 1) the set is $\{1,2,3\}$ *with* discrete topology, not "the set **is** the discrete topology of" 2) preimages have *nothing* to do with topology, 3) we don't say "the inverse of all open sets", we say directly "the preimages of all open sets"
Answer: Let $f:A\to B$ be a map and let $S$ be a subset of $B$, then the preimage of $S$ under $f$ is
$$f^{-1}(S)=\{a\,|\,f(a)\in S\}.$$
For example if $A=\{1,2,3\}$, $B=\{a,b,c\}$ and $f$ is map defined by $f(1)=f(2)=a$, $f(3)=b$, then
$$f^{-1}(\emptyset)=\emptyset,\\
f^{-1}(\{a\})=\{1,2\},\
f^{-1}(\{b\})=\{3\},\
f^{-1}(\{c\})=\emptyset,\\
f^{-1}(\{a,b\})=\{1,2,3\},\
f^{-1}(\{a,c\})=\{1,2\},\
f^{-1}(\{b,c\})=\{3\},\\
f^{-1}(\{a,b,c\})=\{1,2,3\}.$$

How to find the preimage of a set


Can I use the middle piano pedal to sustain a repetitive melody line?

Question: The piece I am learning has a highly repetitive melody line for the left hand (always the same 4 notes, but not all at once), and I want to apply "sustain" for them, while not applying sustain for the more complex melody played with the right hand at the same time.
Looks like a good case for the middle piano pedal, just that there is no time moment when all four keys on the left are depressed down. Sustain "locks" for me only for the keys that were down when I press the middle pedal.
Ok, then I press the keys slowly at the beginning of the piece (slowly enough to produce no sound), then the middle pedal, and keep the middle pedal down until the end of the piece. But this is my own invention.
How is the middle pedal supposed to be used? Can it be applied for the melody line, or must one play a chord first when all relevant piano keys are pressed, giving you a chance to press the pedal at this time?
Answer: There is no rule requiring you to use the sostenuto pedal only for notes that have already sounded. In a composition that works as you described, capturing them in advance is a perfectly fine and obvious solution. (In fact, modern compositions sometimes use silent keypresses and the sostenuto pedal for notes that are never sounded, just made to resonate by other notes.)
Comment: This question is about the middle 'sostenuto' pedal found on some pianos.  You seem to be talking about the sustain pedal.
Comment: @LaurencePayne Wow, English distinguishes between "sustain pedal" and "sostenuto pedal"?? How... quaint. Fixed.
Comment: I'm still not convinced that you realise they're two different pedals that do two different things.
Answer: What you suggest will, indeed do what you describe.  If the 4 notes sound good sustained together - which probably means they form a chord rather than a scale - and if that chord doesn't conflict with other harmonies in the piece, you may have invented a useful technique!   Give it a try.  But listen carefully to the result!
Comment: They sound nice together, they probably form a chord of some kind.
Answer: The middle pedal is called the sostenuto pedal.  It works as you discovered, holding the dampers off for notes that were sounding when the pedal was pressed. You may find more in the Wikipedia article on piano pedals.
Answer: I need to warn you that you should only make people hold down the sostenuto pedal for as long as you want all the held-down notes to sound. This means that, unless you have people let go of the sostenuto pedal, "not all at once" will eventually no longer apply, and listeners will hear all 4 left-hand melody notes at the same time.
Comment: this would be more appropriate as a comment than an answer
Comment: @Some_Guy, I'm mainly trying to answer the question's "How the middle pedal is supposed to be used?" I'm willing to edit this answer to make this more clear.


Replace funcionando só no console log

Question: Oi, estou utilizando o REPLACE e ele está funcionando apenas no console.log, e não está alterando o valor na minha página
Esse é o p:

Monika é notada pelos outros personagens
como inteligente, confiante e atlética. Ela não é tão falante quanto as  outras garotas, mas isso está
implícito para não ser uma escolha. Monika também é conhecida por ser popular, o que faz com que o
protagonista tenha uma admiração por ela. Ela sempre tem uma expressão calma e gentil e é retratada como
madura e trabalhadora.

 Monika já fazia parte do Debate Club, mas foi embora devido a toda a
política e drama internos, destacando o desejo de ordem, liberdade de tópicos e simpatia. O Clube de
Literatura, que ela fundou após deixar o Clube de Debate, é muito importante para ela. Ela aspira a ser
um lugar para mostrar e aumentar a paixão de todos pela literatura.

este o código js:
function Substituir(){
    let monika = document.getElementById('textMonika').innerHTML;
    momo = monika.replace("notada", "MONIKA");
    console.log(momo);
}

o que pode estar acontecendo?
Answer: Da mesma maneira que usas document.getElementById('textMonika').innerHTML para ler o conteúdo tens também de repôr o conteúdo. Ou seja, esse valor que tens em momo tem de ser reescrito com document.getElementById('textMonika').innerHTML = momo.
Uma nota, o replace só substitui a primeira referência, podes usar regex para substituir mais do que uma referência.

function Substituir() {
  let monika = document.getElementById('textMonika');
  momo = monika.innerHTML.replace(/notada/g, "MONIKA");
  monika.innerHTML = momo
}

Monika é notada pelos outros personagens como inteligente, confiante e atlética. Ela não é tão falante quanto as outras garotas, mas isso está implícito para não ser uma escolha. Monika também é conhecida por ser popular, o que faz com que o protagonista
  tenha uma admiração por ela. Ela sempre tem uma expressão calma e gentil e é retratada como madura e trabalhadora.

 Monika já fazia parte do Debate Club, mas foi embora devido a toda a política e drama internos, destacando o desejo de ordem,
  liberdade de tópicos e simpatia. O Clube de Literatura, que ela fundou após deixar o Clube de Debate, é muito importante para ela. Ela aspira a ser um lugar para mostrar e aumentar a paixão de todos pela literatura.

Replace funcionando só no console log


Azure resource creation issue - "The subscription is not allowed to create or update the serverfarm"

Question: I have done the traditional such as affirm my subscription is active and that microsoft.web is registered.  I'm getting the following error when trying to create web app resource, but looks like same issue with any resource.
<code>The subscription is not allowed to create or update the serverfarm.
</code>
I am doing it through the azure portal.  I was expecting that it would successfully deploy it.
Answer: This is a transient issue on the Azure
platform, As per the this MS Q & A suggestion by VenkateshDodda-MSFT where the same issue was resolved by the customer by referring the solution below:-

Retry the deployment of the Web app and the issue will be fixed.

Log out of your Azure account and Log in again via Incognito Window Chrome or InPrivate Tab Edge, And try the deployment of Fresh Web app again.

Retry the deployment of the Web App in another region.

If the issue persists, Raise an Azure Support request to get this issue resolved from the backend.

I tried the deployment of the Web app in Australia East region and it was successful:-


Update to Search API 1.18 causes HTML to be displayed as plaintext

Question: A security update to Search API (7.x-1.18) adds new sanitation as a security measure.  Great!  ..Except it now causes my custom field to be displayed as plaintext instead of HTML.
Here is the relevant code that was added to Search API:
/**
 * Sanitizes field values returned from the server.
 *
 * @param array $values
 *   The field values, as returned from the server. See
 *   SearchApiQueryInterface::execute() for documentation on the structure.
 *
 * @return array
 *   An associative array of field IDs mapped to their sanitized values (scalar
 *   or array-valued).
 */
function search_api_get_sanitized_field_values(array $values) {
  // Sanitize the field values returned from the server. Usually we use
  // check_plain(), but this can be overridden by setting the field value to
  // an array with "#value" and "#sanitize_callback" keys.
  foreach ($values as $field_id => $field_value) {
    if (is_array($field_value)
      && isset($field_value['#sanitize_callback'])
      && ($field_value['#sanitize_callback'] === FALSE || is_callable($field_value['#sanitize_callback']))
      && array_key_exists('#value', $field_value)
    ) {
      $sanitize_callback = $field_value['#sanitize_callback'];
      $field_value = $field_value['#value'];
    }
    else {
      $sanitize_callback = 'check_plain';
    }
    if ($sanitize_callback !== FALSE) {
      $field_value = search_api_sanitize_field_value($field_value, $sanitize_callback);
    }
    $values[$field_id] = $field_value;
  }
  return $values;
}

Question
Because it says
  // Sanitize the field values returned from the server. Usually we use
  // check_plain(), but this can be overridden by setting the field value to
  // an array with "#value" and "#sanitize_callback" keys.

I know I need to set the field value to an array with #value (my custom HTML) and #sanitize_callback keys, but where do I set this, and what do I use for #sanitize_callback?
My Custom Code
I'm using a callback to generate my field with custom HTML:
<?php

/**
 * @file
 * Contains SearchApiAlterAddViewedEntity.
 */

/**
 * Search API data alteration callback that adds an URL field for all items.
 */
class MySearchAlterAddUsercacheEn extends SearchApiAbstractAlterCallback {

  /**
   * Only support indexes containing entities.
   *
   * @see SearchApiAlterCallbackInterface::supportsIndex()
   */
  public function supportsIndex(SearchApiIndex $index) {
    return (bool) $index->getEntityType();
  }

  public function alterItems(array &$items) {
    // Prevent session information from being saved while indexing.
    drupal_save_session(FALSE);

    // Force the current user to anonymous to prevent access bypass in search
    // indexes.
    $original_user = $GLOBALS['user'];
    $GLOBALS['user'] = drupal_anonymous_user();

    foreach ($items as &$item) {
      // Since we can't really know what happens in entity_view() and render(),
      // we use try/catch. This will at least prevent some errors, even though
      // it's no protection against fatal errors and the like.
      try {
        $render = user_view($item, 'ensearch', 'en-US');
        $text = render($render);
        if (!$text) {
          $item->search_api_viewed_en = NULL;
          continue;
        }
        $item->search_api_viewed_en = $text;
      }
      catch (Exception $e) {
        $item->search_api_viewed_en = NULL;
      }
    }

    // Restore the user.
    $GLOBALS['user'] = $original_user;
    drupal_save_session(TRUE);
  }

  public function propertyInfo() {
    return array(
      'search_api_viewed_en' => array(
        'label' => t('Entity (en-US) HTML output'),
        'description' => t('The whole HTML content of the entity when viewed.'),
        'type' => 'text',
      ),
    );
  }

}

Answer: check_plain() encodes special characters that has special meaning in HTML (such as < and &) into plain text entities (i.e. < and & respectively) that will make these be rendered literally (not interpreted as HTML) when that string that is then displayed as part of a page with HTML-markup.
filter_xss() filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities.
In other words, filter_xss() takes care of security, while not plain-texting HTML.
I propose you to patch the Search API function with 'filter_xss' as a callback instead of 'check_plain', create an issue on drupal.org and explan that case.
Answer: The fix is described in this d.o issue.
function MODULE_search_api_results_alter(array &$results, SearchApiQueryInterface $query) {
  if (!empty($results['results'])) {
    foreach ($results['results'] as $id => $result) {
      if (!empty($result['fields']['search_api_viewed'])) {
        $results['results'][$id]['fields']['search_api_viewed'] = array(
          '#value' => $result['fields']['search_api_viewed'],
          '#sanitize_callback' => FALSE,
        );
      }
    }
  }
}


Nome do usuário com ficheiro Excel aberto - VBA

Question: Objetivamente:
Como é possível saber, com VBA, qual o nome do usuário que tem um ficheiro em excel aberto, ficheiro esse que está algures num servidor e não no disco local?
Contexto
Tenho procurado por uma função, em VBA, que me informe se um arquivo em excel esta aberto por um usuário e, em caso afirmativo, qual é o nome do usuário.
Consegui encontrar uma rotina que faz isso, porém apenas se o arquivo aberto estiver no disco local, o que não é o meu caso, segue a função citada:
Function Excel_File_in_use_by(FilePath As String) As String
    Dim strTempFile As String
    Dim iPos As Integer, iRetVal As Integer
    Dim objFSO As Object, objWMIService As Object, objFileSecuritySettings As Object, objSD As Object
    iPos = InStrRev(FilePath, "\")
    strTempFile = left(FilePath, iPos - 1) & "\~$" & Mid(FilePath, iPos + 1)
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    If objFSO.FileExists(strTempFile) Then
        Set objWMIService = GetObject("winmgmts:")
        Set objFileSecuritySettings = objWMIService.Get("Win32_LogicalFileSecuritySetting='" & strTempFile & "'")
        iRetVal = objFileSecuritySettings.GetSecurityDescriptor(objSD)
        If iRetVal = 0 Then
            Excel_File_in_use_by = objSD.Owner.Name
        Else
            Excel_File_in_use_by = "unknown"
        End If
        Set objWMIService = Nothing
        Set objFileSecuritySettings = Nothing
        Set objSD = Nothing
    Else
        Excel_File_in_use_by = vbNullString
    End If
    Set objFSO = Nothing
    End Function

Eu precisava de uma função para verificar se um arquivo específico, neste caso um arquivo excel365, colocado em um servidor específico, está aberto por um usuário e, em caso afirmativo, qual é o nome do usuário.
É possível fazer isso no VBA?
Como implementar isso?
Comment: Legal as respostas, mas o pessoal deveria se atentar a pergunta feita.
A Pergunta feita, que inclusive é mesma duvida minha, é querer saber qual é o usuário da rede que está com a planilha aberta.
Todos os metodos respondidos são baseados no computador, mas dessa forma sempre vai retornar
Answer: O nome de usuário do computador Windows pode ser visualizado da seguinte maneira:
Dim usuarioPC As String, usuario As String

usuario = Environ("username")
usuarioPC = Application.UserName

MsgBox "O usuário deste PC é o " & usuarioPC
MsgBox "O usuário é o " & usuario

Em que é utilizado o Application.UserName ou o Environ
Ou utilizar a seguinte função com a referência wScript para obter o nome do Computador em que o Excel foi aberto:
Public Function ComputerName() As String
'' Returns the host name

'' Uses late-binding: bad for performance and stability, useful for
'' code portability. The correct declaration is:
'' https://stackoverflow.com/a/10108951/7690982

'   Dim objNetwork  As IWshRuntimeLibrary.WshNetwork
'   Set objNetwork = New IWshRuntimeLibrary.WshNetwork

    Dim objNetwork As Object
    Set objNetwork = CreateObject("WScript.Network")

    ComputerName = objNetwork.ComputerName

    Set objNetwork = Nothing

End Function

Para um teste visualize a saída da função numa MsgBox:
MsgBox ComputerName()

Ou outra função para obter o usuário do Computador:
Public Function UserName(Optional WithDomain As Boolean = False) As String
'' Returns the user's network name
'' https://stackoverflow.com/a/10108951/7690982

'' Uses late-binding: bad for performance and stability, useful for
'' code portability. The correct declaration is:

'   Dim objNetwork  As IWshRuntimeLibrary.WshNetwork
'   Set objNetwork = New IWshRuntimeLibrary.WshNetwork

    Dim objNetwork As Object
    Set objNetwork = CreateObject("WScript.Network")

    If WithDomain Then
        UserName = objNetwork.UserDomain & "\" & objNetwork.UserName
    Else
        UserName = objNetwork.UserName
    End If

    Set objNetwork = Nothing

End Function

Ou a função GetUserName da biblioteca "advapi32.dll":
' Access the GetUserNameA function in advapi32.dll and
' call the function GetUserName.
Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
 (ByVal lpBuffer As String, nSize As Long) As Long

' Main routine to retrieve user name.
Function GetLogonName() As String

 ' Dimension variables
 Dim lpBuff As String * 255
 Dim ret As Long

 ' Get the user name minus any trailing spaces found in the name.
 ret = GetUserName(lpBuff, 255)

 If ret > 0 Then
 GetLogonName = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)
 Else
 GetLogonName = vbNullString
 End If
End Function

Comment: O que se pretende não é o nome de usuário do computador Windows, mas o nome do usuário que tem um determinado ficheiro aberto num determinado servidor.
Comment: Seu pacote Office é o 2016? Não funciona muito bem no VBA desta versão e também depende da versão do Windows Server... Mas há muitos exemplos de realizar isso de formas não seguras, muitos abrem vulnerabilidades e dependem da forma que seu servidor está configurado e da versão...
Comment: Uso o Office365 com Windows10. Não consegui encontrar nenhum exemplo que indique qual o nome do usuário que tem o ficheiro aberto, só consigo arranjar exemplos que me indicam se o ficheiro está ou não aberto.


Como aumentar ou diminuir div proporcional a 720x540?

Question: Estou tentando solucionar essa questão pois tenho um slide em .ppt com dimensões de 720w e 540h e minha página é liquida, por isso o motivo de aumentar ou diminuir proporcionalmente.
Exemplo:
Answer: A forma mais simples de se criar esse efeito é adicionando o estilo padding-bottom com o percentual equivalente da altura dividido pela largura pretendida.
div#slide {
  padding-bottom: 75%; /* 540/720 */
}

Assim, mesmo após redimencionar a janela, o tamanho da div será sempre proporcional a 720:540.
Exemplo: JSFiddle.
Comment: +1 Realmente bacana e simples essa solução. Vivendo e aprendendo. :)
Comment: +1 Pelo belo truque, esse eu não conhecia.
Comment: Como dou um min-height nesse caso?
Answer: Com um pouquinho de Javascript você pode garantir que o elemento tem a proporção 4:3 fixando uma das dimensões (isto é, ou a largura ou a altura).
Fiz um exemplo (que pode ser testado nesse JSFiddle - basta arrastar a borda do painel Result para ajustar as dimensões da exibição) em que a largura do div é ajustada à área de exibição da janela do navegador e a altura é calculada com base nessa nova largura e na proporção desejada (3/4 = 0,75).
O div (que representa o elemento em que você exibe o seu PPT):

    Olá mundo!

Tem o estilo definido assim (inclui o estilo da "página" de exemplo):
body {
    margin: 5px;
    background-color: black;
    overflow: hidden;
}

#teste {
    background-color: red;
    display:inline-block;
    width: 720px;
    height: 540px;
    color: white;
    text-align: center;
    line-height: 540px;
}

E o código Javascript que ajusta a proporção é esse:
var adjustSize = function() {
    var oDiv = document.getElementById("teste");

    var iWidth = window.innerWidth - 10; // Desconta duas vezes o tamanho da borda
    var iHeight = iWidth * 0.75; // Mantém o aspecto 4:3 para a largura (width) fixa

    oDiv.style.width = iWidth.toString() + "px";
    oDiv.style.height = iHeight.toString() + "px";
    oDiv.style.lineHeight = oDiv.style.height;
}

window.onresize = adjustSize;
adjustSize();

Answer: Você pode determinar as dimensões em porcentagem, sendo assim fica adaptável ao redimensionamento do navegador:
div { width: 80%; height: 80%; border: 1px solid black; }

Comment: Ok Igor, ja tentei isso. Só que preciso diminiur ou aumentar proporcionalmente a 720x540 em ratio de 4:3, que ele faca isso tanto se a pessoa diminua ou aumente em width ou height
Answer: Você pode utilizar um Framework CSS para este fim, como por exemplo o Twitter Bootstrap, cujos exemplos você pode encontrar neste link:
http://getbootstrap.com/css/#grid-example-fluid
Por exemplo:
(...)
<--! inclui o css do twitter-bootstrap, você também pode baixar ele e instalar direto no seu site -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
(...)

Comment: Estou usando o bootstrap, só que idéia não é essa, tenho duas div uma do lado esquerdo que é meus menus e outra do lado direito.. a do lado esquerda é fixa. Tenho outra div dentro da do lado direito e essa div deve crescer ou diminuir proporcionalmente ao tamanho de 720x540 conforme a div do lado direito aumente.
Comment: Como tu estás publicando o ppt no site? Copia parte do código que representa teu problema e cola aqui pra gente ver.
Answer: Se o seu slide é uma imagem você pode colocar o img com width: 100% e height: auto, ficaria assim:
img { width: 100%; height: auto; }

Mas se não for uma imagem, se for, por exemplo, uma div que contem uma chamada para um flash, você terá que fazer em js.
Em jQuery ficaria assim:
Primeiro o css.
div { width: 100%; }

Depois o js, de acordo a proporção indicada, a altura vai ser sempre 75% da largura.
$(function(){

    var largura = $('div').width();
    var altura  = ( 75 * largura ) / 100;

    $('div').css('height', Math.round(altura) + 'px');

});

Caso você queira que quando a janela mude de tamanho, a div acompanhe, adicione o código abaixo ao js
$( window ).resize(function() {

    var largura = $('div').width();
    var altura  = ( 75 * largura ) / 100;

    $('div').css('height', Math.round(altura) + 'px');

});

Exemplo no jsfiddle, se você redimencionar a janela, verá que aparece a div vermelha por trás da preta.


Variance of a combination of two uniform distribution

Question: Suppose a variable $X$ is uniformly distributed over (1,5) with probability 0.9 and is uniformly distributed over (2,44) with probability 0.1, what would be the variance of $X$?
I guess it would be something more than just a weighted sum of the variance of unif(1,5) and unif(2,44), but I have no idea how to solve it.
Thanks!
Comment: You can say that $E[X]$ is the weighted sum of the means and $E[X^2]$ is the weighted sums of the raw second moments.  The variance is not the weighted sum of the variances but can be found from  $E[X^2] - (E[X])^2$
Answer: Let $Y \sim \operatorname{Bernoulli}(p = 0.1)$.  Then note $$\operatorname{E}[X \mid Y = 0] = \frac{1+5}{2} = 3, \\ \operatorname{E}[X \mid Y = 1] = \frac{2+44}{2} = 23.$$  Similarly, $$\operatorname{Var}[X \mid Y = 0] = \frac{(5-1)^2}{12} = \frac{4}{3}, \\ \operatorname{Var}[X \mid Y = 1] = 147.$$  We in turn can write these as $$\operatorname{E}[X \mid Y] = 3 + 20Y,$$ and $$\operatorname{Var}[X \mid Y] = \frac{4}{3} + \frac{437}{3}Y.$$
Hence
$$\begin{align*}
\operatorname{Var}[X]
&= \operatorname{Var}[\operatorname{E}[X \mid Y]] + \operatorname{E}[\operatorname{Var}[X \mid Y]] \\
&= \operatorname{Var}[3 + 20Y] + \frac{1}{3}\operatorname{E}[4+437Y] \\
&= 400\operatorname{Var}[Y] + \frac{1}{3}(4 + 437 \operatorname{E}[Y]) \\
&= 400(0.1)(0.9) + \frac{1}{3}(4 + 437(0.1)) \\
&= \frac{519}{10}. \end{align*}$$
Alternatively, we can perform the computation directly by expressing the unconditional density of $X$ as $$f_X(x) = \begin{cases}\frac{9}{40}, & x \in [1,2) \\
\frac{191}{840}, & x \in [2, 5) \\
\frac{1}{420}, & x \in [5,44] \end{cases}$$ and performing the integration $$\operatorname{E}[X^k] = \int_{x=1}^{44} x^k f_X(x) \, dx,$$ for $k \in \{1, 2\}$ and then using the usual variance formula to compute the variance.
Comment: Thank you so much for your answer! This is really helpful.
Comment: By the way, I wonder where the 44 in the last equation comes from? Is that a typo?
Comment: @Juan Yes, it was a typographical error which has been fixed.


Debugging as administrator

Question: I'm sure that this question has already been answered somewhere, but it seems that I am unable to find the answer.
I created a manifest file for my project and set the requestedExecutionLevel to requireAdministrator. When I double click my binary in Windows Explorer, then the UAC opens and asks me for admin privileges. But when I want to debug my application within Visual Studio, it doesn't ask for admin privileges. It simply runs as "normal" user.
I already wrote a little script into the startup of my application that determines whether the application has admin privileges or not and restarts itself (with "runas" as verb), if it hasn't got admin privileges. The disadvantage of this method is that the debugger isn't attached to the restarted application. Is there a way to debug an application with admin rights? (Maybe without starting VS with admin rights)
Answer: If you are using Visual Studio 2013 Update 2, I have experienced exactly the same problem and actually, it is an known issue of VS2013.

Manifest does not force Visual Studio 2013 to restart under Admin when running application in Debug mode

I updated to VS2013.3 RC and then the problem has gone. So I think this issue is fixed in Update 3.
Comment: Thank you for this information. I never would have come to the idea this being a bug of VS.

Debugging as administrator


Manter histórico da branch ao mover ou renomear pasta

Question: Tenho necessidade de reorganizar uma estrutura em que os códigos-fonte das minhas aplicações são mantidos, porém, quando faço a movimentação da branch para uma nova pasta, seu histórico de modificações é perdido.
Como posso mover ou renomear uma branch dentro do meu repositório sem perder o histórico de modificações?
Answer: Olá,
Você pode renomear usando -m.
1) git checkout "branch"
2) git branch -m "rename_branch"
Um abraço
Obs: Me deixe saber se isso lhe ajudou.
Comment: Infelizmente não estou usando o git como repositório. Eu consigo mover e renomear a branch, porém quando faço o commit, o histórico das modificações é perdido.


Select com o último registro

Question: Preciso valorizar o inventário da empresa em que trabalho e para isso vou pegar o último valor dos itens. Estava usando o MAX, mas percebi que se fizesse isso, ele iria me retornar o maior preço e não o último cadastrado na tabela. Então mudei o MAX pra coluna de data, só que ele me traz várias linhas de resultados, e preciso apenas da última mas ainda com o campo de código e valor para depois jogar em uma planilha.
Código:
SELECT irec.pro_in_codigo Codigo,
       irec.rci_re_vlunitario Valor_unitario,
       max(irec.rcb_dt_documento) Data
FROM mgadm.est_itensreceb irec
WHERE irec.pro_in_codigo = 701
GROUP BY irec.pro_in_codigo, irec.rci_re_vlunitario

Comment: Você quer obter o último registro da tabela?
Answer: Veja se assim funciona:
select irec.pro_in_codigo Codigo,
       irec.rci_re_vlunitario Valor_unitario,
       irec.rcb_dt_documento Data
from mgadm.est_itensreceb irec
where irec.pro_in_codigo = 701
    and irec.rcb_dt_documento = (select max(irec.rcb_dt_documento) Data
            from mgadm.est_itensreceb irec
            where irec.pro_in_codigo = 701
            )

Comment: Provavelmente seu código não irá funcionar já que o `alias` `irec` está sendo utilizado para mais de uma tabela
Comment: @Sorack, com oracle funciona, já fiz esse teste algumas vezes, agora não sei em outros SGBD's.
Answer: Faça o select conforme exemplo abaixo.
SELECT IREC.PRO_IN_CODIGO CODIGO,
   IREC.RCI_RE_VLUNITARIO VALOR_UNITARIO,
   IREC.RCB_DT_DOCUMENTO
FROM MGADM.EST_ITENSRECEB IREC
INNER JOIN (
            SELECT IREC.PRO_IN_CODIGO, /* CAMPOS CHAVES DA TABELA */
                MAX(IREC.RCB_DT_DOCUMENTO) AS MAXDT
            FROM  MGADM.EST_ITENSRECEB IREC
            GROUP BY  IREC.PRO_IN_CODIGO
       ) TV_MAX ON (TV_MAX.PRO_IN_CODIGO = IREC.PRO_IN_CODIGO AND IREC.RCB_DT_DOCUMENTO = TV_MAX.MAXDT)
WHERE IREC.PRO_IN_CODIGO = 701

Answer: No firebird faço assim:
SELECT   FIRST 1
         VALOR_UNITARIO
FROM     ESTOQUE
WHERE    CODIGO = :CODIGO
ORDER BY DATA DESC

Select com o último registro


Unable to install Xuni.CollectionView using NuGet in Xamarin Forms

Question: while installing Xuni.CollectionView using Nuget of portable option of Project it showing the error below:
<code>"Could not install package 'Xuni.CollectionView 2.1.20161.86'. You are trying to install this package into a project that targets '.NETPortable,Version=v4.5,Profile=Profile111', but the package does not contain any assembly references or content files that are compatible with that framework."
</code>
Answer: I was able to install this package without any problems in my Xamarin.Forms Shared Project -> Add Packages... in a specific iOS or Android project search for the package and install it, see image attached:


Xamarin.Forms open downloaded pdf directly

Question: I'm able to save a pdf file locally on the phone in the downloads folder. Now I want to be able to open the file in the generic pdf viewer. This is the file I have for example:

When opening directly from the downloads folder I'm getting this view:

How can I open the document in the same viewer as soon as the document is downloaded?
I tried this:
    Device.OpenUri(new System.Uri("file:///storage/emulated/0/Download/740067_Invoice_Food.pdf"));

But nothing is happening.
Comment: Try this reference https://blog.verslu.is/xamarin/xamarin-forms-xamarin/showing-pdf-files-xamarin-forms/
Comment: Thanks but from what I can see this still uses as view, its not opening up in the native pdf viewer
Comment: @Laziale, Do you try to use dependencyService to open PDF, take a look:https://stackoverflow.com/questions/27820246/how-to-view-pdf-file-using-xamarin-forms
Answer: Try this approach, maybe you'll need to change folder path using Environment.SpecialFolder
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var filename = Path.Combine(documents, "MyPDF.pdf");
            Device.OpenUri(new Uri(filename));

Comment: Thanks, doesn't really work since the documents path points to the app folder not to the downloads
Answer: First specify fileprovider into android manifest file
Something like this
 <application android:label="The name of your project" android:supportsRtl="true" android:icon="@drawable/register">
  <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true">
    <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"></meta-data>
  </provider>
 </application>

Next, add provider_paths.xml file into xml folder
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

Now you should call native method for each platform by 'DependencyService' to open pdf file
Do it according to this GREAT Doc
https://officialdoniald.azurewebsites.net/2019/09/24/xamarin-forms-save-and-open-pdf-file/


Compute $\sum_{k=0}^{180} \cos^22k^\circ $

Question: I'm trying to compute the following:
$$\sum_{k=0}^{180} \cos^22k^\circ $$
Answer: Hint:
Observe that for the first quadrant, we have
\begin{align}
&\cos^22^\circ+\cos^24^\circ+\cdots+\cos^288^\circ+\cos^290^\circ\\
&\quad=\cos^22^\circ+\cos^24^\circ+\cdots+\cos^244^\circ
+\sin^244^\circ+\sin^242^\circ+\cdots+\sin^22^\circ+0\\
&\quad=22.
\end{align}
Comment: Well, this one is $22$, not $44$. Then for the final result you must be careful about not counting some of them twice.
Answer: $$\sum_{r=0}^{180}\cos^22r^\circ=1+\sum_{r=0}^{179}\cos^22r^\circ$$
$$S=\sum_{r=0}^{179}\cos^22r^\circ$$
$$=\sum_{r=0}^{44}\cos^22r^\circ+\sum_{r=45}^{89}\cos^22r^\circ+\sum_{r=90}^{134}\cos^22r^\circ+\sum_{r=135}^{179}\cos^22r^\circ$$
As $\cos(180^\circ\pm A)=-\cos A,\cos(360^\circ-A)=+\cos A,$
$$S=4\sum_{r=0}^{44}\cos^22r^\circ$$
Finally,
$$\dfrac S2=2\sum_{r=0}^{44}\cos^22r^\circ=\sum_{r=0}^{44}\cos^22r^\circ+\sum_{r=0}^{44}\cos(90-2r)^\circ=45$$
Answer: Remark that:
$cos(x+90°) = sin(x)$
And that:
$cos^2(x) + sin^2(x) = 1$
So you can group your terms:
$$
\begin{align*}
\sum_{x=0}^{180} cos^2(x.2°) &=  \sum_{x=0}^{44} cos^2(x.2°) \\
                             & + \sum_{x=45}^{89} cos^2(x.2°) \\
                             & + \sum_{x=90}^{134} cos^2(x.2°) \\
                             & + \sum_{x=135}^{179}{cos^2(x.2°)} \\
                             & + cos^2(180.2°) \\
\\
&= \sum_{x=0}^{44}{cos^2(x.2°)+cos^2(x.2°+90°)} \\
& + \sum_{x=90}^{179}{cos^2(x.2°)+cos^2(x.2°+90°)} \\
& + cos^2(360°) \\
\\
&= \sum_{x=0}^{44}{cos^2(x.2°)+sin^2(x.2°)} \\
& + \sum_{x=90}^{134}{cos^2(x.2°)+sin^2(x.2°)} \\
& + 1 \\
\\
&= \sum_{x=0}^{44}{1} \\
& + \sum_{x=90}^{134}{1} \\
& + 1 \\
&= 91
\end{align*}
$$
See the approximate results at wolfram alpha
Comment: The answer would be 90.
Comment: @TakahiroWaki Can you pinpoint where I missed something in my proof ? The approximate answer is 91 for wolfram alpha too ...
Comment: By solmilkyu's answer,$22*4+2=90$  point is $cos^2(0)=1.$
Comment: @TakahiroWaki Let's call solumilkyu's sum: $S$, then by symetry we know it appears $4$ times, this would sum twice cos²(90) and cos²(270) but these are $0$ so it's not a problem . But this left out the following values: cos²(0), cos²(180) and cos²(360). So you must add $3$ and not $2$ to get the final result.
Comment: Well,that's right.
Answer: $$S=\sum_{r=0}^{180}\cos^22r^\circ$$
$$2S=\sum_{r=0}^{180}(1+\cos4r^\circ)=181+\sum_{r=0}^{180}\cos4r^\circ$$
Using $\sum \cos$ when angles are in arithmetic progression,
$$\sum_{r=0}^{180}\cos4r^\circ=\dfrac{\cos(2\cdot180^\circ)\sin(2\cdot181^\circ)}{\sin2^\circ}=+1$$
Answer: $$S(n)=\cos^2 0°+ \cos^2 2°+ \cos^2 4°+....+ \cos^2 2n°$$
1) $\cos^2 \alpha =\frac{1+\cos 2 \alpha}2$. Then
$$S=\frac{1+n+\left(\cos 4°+ \cos 8°+....+ \cos 4n°\right)}2$$
2) Let $S_1=\cos a_1+ \cos a_2+....+ \cos a_n$, where $(a_n) -$ arithmetical progression ($d\not=2\pi k, k \in \mathbb Z$)
Then
$$S_1=\frac{\sin\frac{nd}{2}\cdot \cos\frac{2a_1+d(n-1)}2}{\sin \frac d2}$$


Is there a symbol for always less than (or just always?)

Question: For e.g, the quotient of $\frac{1}{n}$, $q$, where $n \gt 1$, $q$ will always be less than $1$.
$$\frac qn\le n$$
etc.
I can't really write $\frac {q}{n} < n$, because whilst true, it doesn't help provide much context. I am trying to write up proofs so I want to use mostly mathematical symbology.
Thanks :)
Comment: "Am trying to write up proofs so I want to use mostly mathematical symbology." No!!! If you want to learn to write up proofs instead you should be learning to express yourself clearly in English.
Comment: $a 1$.
Comment: One way of doing it is to write $\forall n> 1, 1/n < 1$. But if you want a single symbol similar to $\equiv$ ("identically equal") as used in for instance $\sin^2(x) + \cos^2(x) \equiv 1$ , only for _inequalities_ instead, then I think you're out of luck.
Comment: There's nothing "groundbreaking" about writing proofs using English words. That's how mathematics is done most of the time! (With other natural languages instead of English, as appropriate, of course).
Comment: You could use temporal logic which has symbols for always and eventually.
Comment: Ok cool, so... use concise English, maybe use the 'all' sign,  ∀, and look into temporal logic. Sweet thanks (not being sarcastic, I apprec it)
Comment: @user108262: **In no circumstances** use the $\forall$ symbol _outside_ the syntax of formal symbolic logic it was made to be used in. It **is not** a drop-in replacement for the English words "for all", and should never be used surrounded by words.
Answer: The context is provided by what you write next to the equation (that is, what you write in words).
If you want to say "For all integers $n>1$ and all real $q<1$, we have $\frac q n<1$", then it is expected of you to write that.
If you are intent on using "symbols" then the "for all" symbol $\forall$ (whose partner "there exists", $\exists$, also comes in handy) is what you seek:
$$\forall n\in\mathbb{Z},q\in\mathbb{R},\,\left(n>1,\,q<1\implies \frac qn<1\right)$$
However, as I hope is evident, it is often easier just to use words.
Comment: And "easier just to use words" goes for the reader as well as for the writer.
Answer: A proof, if you want to be formal, usually starts with given information. For example,

Given: a shape has $3$ sides

Then continues with steps to reach a goal; perhaps proving the shape is a triangle. These step have reasons, and as long as the reasons are sound, it is assumed when you give these steps, you are saying that they are always true within your given conditions:

Given: a shape has $3$ sides. The shape is a triangle, because of the definition of triangle, "a shape with $3$ side."

Again, we're not saying every shape is a triangle, but that every shape that fits our given conditions is a triangle. For your example,

Given $\frac qn$ such that $q = \frac 1n$ and $n>1$,
$\frac qn<n$ because...

You are stating in that case not that $\frac qn<n$ is always true, but that within your given conditions it is always true. You simply need to back it up with reasons that are already accepted as true or previously proven.
Hope that helps!


Código para manipular componentes de video

Question: Estou com um problema no meu código que manipula o meu vídeo com mute e o volume porem nao esta funcionando segue o meu código:
<!doctype html>

        <meta charset="utf-8">
        <title>Nova Era Team</title>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <meta name="description" content="" />
        <meta name="keywords" content="" />
        <link rel="stylesheet" href="css/reset.css">
        <link rel="stylesheet" href="css/style.css">

Home

Sobre

Games

Eventos

Team

Contato

Ajuda

Forum

            <video id="Video1" width="100%" height="100%" loop>
                <source src="video/League-warrios.mp4" type="video/mp4" />
            </video>

Lorem Ipsum Dolor

dolor sit amet, consectetur adipiscing elit. Sed at risus neque.
Cras sit amet ligula
            ut justo commodo porta id ut enim. Nulla est lectus, mollis sit amet vehicula id, volutpat eget mauris.

             <button id="volDn"></button>
             <button id="volUp"></button>
             <button id="mute"></button>

O js:
function init() {
    var video = document.getElementById("Video1");
    if (video.canPlayType) {
        document.getElementById("buttonbar").style.display = "inline";

        function setVol(value) {
            var vol = video.volume;
            vol += value;
            if (vol >= 0 && vol <= 1) {
                video.volume = vol;
            } else {

                video.volume = (vol < 0) ? 0 : 1;
            }
        }
        document.getElementById("volDn").addEventListener("click", function () {
            setVol(-.1); // down by 10%
        }, false);

        document.getElementById("volUp").addEventListener("click", function () {
            setVol(.1);  // up by 10%
        }, false);

        document.getElementById("mute").addEventListener("click", function (evt) {
            if (video.muted) {
                video.muted = false;
                evt.target.innerHTML = ""
            } else {
                video.muted = true;
                evt.target.innerHTML = ""
            }
        }, false);
    }
                video.muted = true;
    }

Answer: A sua lógica para aumentar/reduzir o volume está funcionando corretamente. O problema é que na última linha da função init(), você deixa o vídeo como mudo:
    video.muted = true;
}

Basta remover esta linha e o controle de som irá funcionar.
Comment: ola amigo entao o video tem que iniciar mudo eu achei o problema eu esqueci de chamar meu init(); na tag body por isso não estava funcionando acabei de perceber isso de qualquer forma obrigado pela sua ajuda mesmo assim acho que vou deixar esse  post aqui para quem tiver o mesmo problema ou ate mesmo ultilizar este codigo para manipular um video =3


Show that a triangle delimited by parallel lines to the sides of another triangle is similar to said triangle.

Question: I was looking at geometric constructions of similar triangles, and at one point I came across the statement in the question.

A triangle delimited by vertices which are intersections of lines parallel to the sides of some other triangle is similar to said triangle.

I drew an example of the statement as follows:

Where the small green triangle's vertices are given by the intersections of some lines which are parallel to the sides of the blue triangle. The statement seems intuitively obvious, but I can't seem to find a way to justify it. I tried using the intercept theorem which is what I normally see is used to prove statements about similar triangles, but since I'm not sharing a side in both triangles I didn't think I could use it. Does anyone know a simple argument to justify this? Thank you!
Answer: The angle between two lines is the same as the one between two lines parallel to the original ones. Therefore the 3 angles of the deduced triangle are the same than the ones of the original triangle and the triangles are similar.
Answer: An easy way to make the connection:
Given triangle $ABC$, and through external points $D$, $E$, $F$ parallels drawn to $AB$, $BC$, $CA$, respectively, forming triangle $GHJ$.
For explicit proof that $\triangle ABC\sim\triangle GHJ$, extend $AB$ to meet the parallels to $CA$ and $BC$ at $K$ and $L$. Since by parallels$$\angle CAB=\angle JKL$$and$$\angle JKL=\angle JGH$$therefore$$\angle CAB=\angle JGH$$For the same reason$$\angle CBA=\angle JLK=\angle JHG$$Therefore remaining angles$$\angle ACB=\angle GJH$$ and$$\triangle ABC\sim\triangle GHJ$$
Comment: This is exactly what I was looking for, thank you!


Prove that a sequence of random variables is almost surely a Cauchy sequence

Question: Let $ \left(X_{n}\right)_{n} $ be a sequence of random variables such that for any $ \varepsilon >0 $  we have:
$ \lim_{n,m\to\infty}\mathbb{P}\left(|X_{n}-X_{m}|>\varepsilon\right)>0 $
I want to prove that $ X_n $ has a subsequence wich is Cauchy.
So, here's what I've tried:
For any $ k $ we'll choose $ n_k $ such that for any $ n,m \geq n_k $ we have:
$ \mathbb{P}\left(|X_{n}-X_{m}|>2^{-k}\right)<2^{-k} $.
We could also choose the $ n_k$'s such that $ n_{k+1} > n_k $. So denote: $ Y_k=X_{n_k}$.
I want to show that $ (Y_k)_k $ is a cauchy sequence.
Define $ F=\limsup_{k}\left\{ |Y_{k}-Y_{k+1}|>2^{-k}\right\} =\bigcap_{n}\bigcup_{k\geq n}\left\{ |Y_{k}-Y_{k+1}|>2^{-k}\right\}  $
(This is the event which $ \left\{ |Y_{k}-Y_{k+1}|>2^{-k}\right\}  $ occurs infinitly many times).
I proved, using Borel-Cantelli Lemma, that $ \mathbb{P}\left(F\right)=0 $.
All I have left to do is to conclude that $ Y_k $ is cauchy, so it sufficies to show that the probability that $ Y_k $ is not cauchy is $ 0 $. Denote the event that $(Y_k) $ is not a Cauchy sequence as $ B $.
If I'll show that $ B\subset F $ that will finish the proof. But actually I cannot see how's this even true; Given a sequence, such that for any $ n\in \mathbb{N} $ we can find $ k\geq n $ such that $ |Y_{k+1}-Y_{k}|>2^{-k} $ dosent seem to imply that $ Y_k $ is not Cauchy.
So what can I do to conclude the desirable conclusion?
Thanks in advance.
Answer: Indeed $B \subset F$ but it seems you are trying to prove that $F \subset B$...
You might find it easier to check that $F^c \subset B^c$. Namely, assuming $F^c$ means that only finitely many bad events $|Y_k-Y_{k+1}|>2^{-k}$ hold. Now given $\epsilon$ choose $k_0$ larger than the indices of all  these bad events such that also $2^{-k_0}<\epsilon$ and now you can verify $|Y_n-Y_m| <\epsilon$ for $n,m>k_0$.


Number Theory Practice Questions

Question: Can anyone please suggest a book or a link to website where I can find Practice questions  (and there solutions) on Number Theory. More specifically questions on the following topics:

Divisibility
Greatest Common Denominator
Congruences
Fermat's Little Theorem
The RSA crptosystem
El Gamal cryptosystem
Comment: http://www.google.co.in/url?sa=t&rct=j&q=santos%20number%20theory&source=web&cd=1&cad=rja&ved=0CDAQFjAA&url=http%3A%2F%2Fwww.fmf.uni-lj.si%2F~lavric%2FSantos%2520-%2520Number%2520Theory%2520for%2520Mathematical%2520Contests.pdf&ei=s0q6UJPEE4TqrAer2YDADA&usg=AFQjCNGoL4iUUQOyTwbW37GyRWSGlHcMzw
Answer: If you're looking for challenging exercises:

See this link to contest problems in number theory.
You might also be interested in exploring some of the resources offered through
The Art of Problem Solving (AOPS).
E.g., see Introduction to Number Theory (AOPS)

For practice in mastering some of the concepts needed in elementary number theory,

see the Kahn Academy for videos and exercises related to divisibility, gcd, congruences, etc. Under "applied math" there you can also explore cryptography problems.
Abstract Algebra Study Guide Chapter 1: integers: divisors/divisibility, primes, congruences, integers modulo n; Chapter 2: equivalence relations, permutations. Both chapters have both problems and solutions.
250 problems in number theory has both problems and solutions.
Answer: I would categorize all of the books below as applied. There are many wonderful books on theoretical number theory and cryptography also and those can be added too - those were left off as you were looking for more applied books. None are in any specific order.
You also may want to visit your college library and see other examples. Lastly, you may want to search out books that are posted online (legal ones of course) and open course-ware in these areas (like MIT, Berkeley and many others).
Elementary Number Theory Related Books

Elementary Number Theory [Hardcover] David Burton (Author)
Elementary Number Theory: Second Edition (Dover Books on Mathematics) [Paperback] Underwood Dudley (Author)
Elementary Theory of Numbers (Dover Books on Mathematics) [Paperback] William J. LeVeque (Author)
Number Theory (Dover Books on Mathematics) [Paperback] George E. Andrews (Author)
An Introduction to the Theory of Numbers [Paperback] G. H. Hardy (Author), Edward M. Wright (Author), Andrew Wiles (Author), Roger Heath-Brown (Editor), Joseph Silverman (Editor)
Elementary Number Theory (Springer Undergraduate Mathematics Series) [Paperback] Gareth A. Jones (Author), Josephine M. Jones (Author)
Number Theory and Its History (Dover Books on Mathematics) [Paperback] Oystein Ore (Author), Mathematics (Author)
Friendly Introduction to Number Theory, A (3rd Edition) by Joseph H. Silverman (Mar 31, 2005)
Elementary Number Theory (6th Edition) by Kenneth H. Rosen (Apr 9, 2010)
Basic Number Theory (Classics in Mathematics) by André Weil (Feb 15, 1995)
Excursions in Number Theory (Dover books explaining science) by C. Stanley Ogilvy (Nov 1, 1988)
An Adventurer's Guide to Number Theory by Richard Friedberg (Jan 9, 1995)
A Course in Number Theory and Cryptography (Graduate Texts in Mathematics) [Hardcover] Neal Koblitz (Author)
Number Theory for Computing by Song Y. Yan and M.E. Hellmann (Dec 10, 2010)
Elements of Number Theory (Undergraduate Texts in Mathematics) [Paperback] John Stillwell (Author)
Number Theory: A Lively Introduction with Proofs, Applications, and Stories [Hardcover] James Pommersheim (Author), Tim Marks (Author), Erica Flapan (Author)
Computational Intro. to Number Theory... (2ND 09) Shoup (Hardback | ISBN10: 0521516447; ISBN13: 9780521516440)
Elementary Number Theory with Applications, Second Edition [Hardcover] Thomas Koshy (Author)
Elementary Number Theory in Nine Chapters [Paperback] James J. Tattersall (Author)
Elementary Number Theory, Cryptography and Codes (Universitext) [Paperback] M. Welleda Baldoni (Author), Ciro Ciliberto (Author), G.M. Piacentini Cattaneo (Author), Daniele Gewurz (Translator)

Cryptography Related Books

An Introduction to Mathematical Cryptography (Undergraduate Texts in Mathematics) [Hardcover] Jeffrey Hoffstein (Author), Jill Pipher (Author), J.H. Silverman (Author)
Cryptanalysis of Number Theoretic Ciphers (Computational Mathematics) by Samuel S. Wagstaff (Dec 10, 2002)
Cryptological Mathematics (Mathematical Association of America Textbooks) [Paperback] Robert Edward Lewand (Author)
The Mathematics of Ciphers: Number Theory and RSA Cryptography by S. C. Coutinho
An Introduction to Cryptography (Discrete Mathematics and Its Applications) by Richard A. Mollin
Lawrence C. Washington – Elliptic Curves: Number Theory and Cryptography ISBN 1-58488-365-0
A. J. Menezes, P. C. van Oorschot, and S. A. Vanstone – Handbook of Applied Cryptography ISBN 0-8493-8523-7
Understanding Cryptography: A Textbook for Students and Practitioners [Hardcover] Christof Paar (Author), Jan Pelzl (Author), Bart Preneel (Foreword)
An Introduction to Mathematical Cryptography (Undergraduate Texts in Mathematics) [Hardcover] Jeffrey Hoffstein (Author), Jill Pipher (Author), J.H. Silverman (Author)
Cryptanalysis: A Study of Ciphers and Their Solution [Paperback] Helen F. Gaines (Author)
Understanding Cryptography: A Textbook for Students and Practitioners [Hardcover] Christof Paar (Author), Jan Pelzl (Author), Bart Preneel (Foreword)
Applied Cryptography Second Edition Bruce Schneier
Guide to Elliptic Curve Cryptography, Darrel Hankerson, Alfred J. Menezes, Scott Vanstone

Try the following problem sets:

http://www.math.muni.cz/~bulik/vyuka/pen-20070711.pdf
http://f2.org/maths/250probs/
http://www.staff.science.uu.nl/~beuke106/getaltheorie/pen0795.pdf
http://www.mai.liu.se/~pehac/kurser/TATM54/booktot.pdf

Web Sites

http://en.wikibooks.org/wiki/Cryptography

Enyoy! `Amzoti
Comment: Yes, please that would be very helpful
Comment: @amWhy: that is a pretty nice list! Thanks

Number Theory Practice Questions


Finding a Metric for Resampling a Distribution

Question: I have a distribution of a large group. It's uniform, and looks like this:

I have experimental results, where I look to observe members of this group. I don't in any way expect a majority of them to be present.
My experimental results have a sampling distribution that looks like this:

To me, this looks like a nonrandom sample from the main group. And I'd like to show this.
I want to resample random selection from the main group, but my problem is I don't know what kind of metric to assess.
Mean/standard deviation/variance all look rather similar. Is there a better metric I could use to assess what my random resampled groups look like, and show that the distribution of the sampled group is nothing like my resampled groups?
Or is there a test I could use in this case?
Comment: Kolmogorov-Smirnov tests are used for comparing distributions.
Comment: Ordinarily, it would be a little dicey to propose the metric after noting there might be a difference: you would have to work a little to show this doesn't skew the conclusion.  But in this case, with such a large sample where it is blatantly obvious the distribution is different, you don't need a test at all.  For those who insist on testing, a simple test, making few assumptions, whose results are not strongly dependent on these issues, is the chi-squared.  Four bins with cutpoints at $1/4,2/4,3/4$ would work fine.
Comment: One difference between the two histograms you show is skewness. The first is neither uniform nor symmetrical; the second  seems symmetrical. Have you tried looking at a measure of skewness as metric for a permutation test?
Comment: The skew was 0.081 and 0.053, it seems different enough. I've heard of the kolmogorov-smirnov test before. I'll try that as a comparator.
Comment: Another possibility is to compare their entropies. Check this question https://stats.stackexchange.com/questions/28178. NRH's answer explains how to compute the entropy of an empirical distribution.
Answer: There is little information in your question ... a good metric would be one you cares about, which is important for your use of this. You did not tell us ... But you seem to have large samples (as judged by the y-axis on your histograms). So for a general test, you can base it on the KS (Kolmogorov-Smirnov) statistic.
Neither did you tell if you used smpling with or without replacement, but assuming the last: You can find the null distribution of the KS statistic, for your data, by simulation. Repeat:

Draw (without replacement) a sample size N (= sample size for your experimental results)

Calculate the KS statistic for comparing distribution of your group (from first histogram) to distribution of simulated sample

After repeating $R$ times, draw the histogram based on the $R$ KS values, and overplot ( a red point) the KS value based on your two histograms.
You can calculate a simulated p-value from this! One often uses a value such as $R=9999$, including the KS value from your data, this gives a total sample for calculation pf p-value $R+1=10000$. The p-value is the fraction of values larger or equal to the one from the experiment (the red point).


How to check if string is a valid postgres name?

Question: How to check if provided string is a valid name in postgres ?
I know that it is possible to use any string as name when it is quoted, but I want to know is string can be used without quotes i.e. as role name.
I have idea to do it like this:
BEGIN; CREATE ROLE ; ROLLBACK;
Is is good idea ?
Answer: You can use the function quote_ident() which will quote a string only if necessary.
So if the "quoted" value is the same as the input, it's a legal identifier:
select quote_ident('foobar') = 'foobar'

returns true, however
select quote_ident('foo bar') = 'foo bar'

returns false.


Error "'System.Data.SqlClient.SqlException' happened when trying to debug application

Question: I'm creating an application where I store my inputs (name, age, phone) from the textbox and when I click Submit, it should store whatever I input onto the textbox into the database but I keep getting this error.

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code. Additional Information: Incorrect syntax near the keyword 'Table'.

Here is the following code:
protected void Button1_Click(object sender, EventArgs e)
    {
        String p = UniqueNumber();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings
            ["ConnectionString"].ConnectionString);
        con.Open();
        String str = "insert into Table(uniqueno, name, age, number) values( '"
            + Label1.Text + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtNumber.Text + "')";
        SqlCommand cmd = new SqlCommand(str, con);
        cmd.ExecuteNonQuery();
        con.Close();
        Session["id"] = Label1.Text;
        Session["name"] = txtName.Text;
        try
        {
            Response.Redirect("unique.aspx");
        }
        catch
        {
            Label1.Text = "Please enter correct details....";
            this.Label1.ForeColor = Color.Red;
        }
    }

Comment: sql injection vulnerability. use parameterized queries
Comment: Do you really mean the error happens only when trying to debug the application, rather than when running it? If it happens on any run, change your question to "when trying to insert into a table"
Comment: also change this line `Response.Redirect("unique.aspx");` to `Response.Redirect("~unique.aspx");` also I hope you are familiar with PostBacks and how they work.. make sure when debugging that the values you are passing to SQL Insert command are not null or empty and read up on `Parameterized Query's` and how to use them and if `Table` is the name wrap it around brackets like this `[Table]` since Table is a Reserved Word in SQL
Comment: As others have mentioned, you shouldn't name your table as 'Table' and you should not create the statement with string concatenation (it is vulnerable to SQL injection attack). I see that you are passing all of the values as string types. If their actual type is different (for example if you have defined the type of column 'age' as 'int'), then you are getting the error because of the single quotes that you are putting next to the values.
Answer: "Table"  is keyword, although you may have stored data into the Table, I don't think SQL server would allow you to query that.
Surprisingly, it allows us to have a table named Table but when we try to select, it throws an error. And as @seth flower mentioned, try avoiding SQL injection vulnerabilities.