Problema com Controllers

Question: Estou com problema ao implementar o padrão MVC apresentando o erro abaixo:
TypeError: application.app.controllers.admin.noticias_salvar is not a function

const { check, validationResult } = require('express-validator')
module.exports.formulario_inclusao_noticia = function(application, req, res){
    res.render('admin/form_add_noticia',{validacao:{},noticia:{}});
}

module.exports.noticias_salvar = [

        check('titulo','Título é obrigatório').not().isEmpty(),
        check('resumo','Resumo é obrigatório').not().isEmpty(),
        check('resumo','Resumo tem que ter entre 10 a 100 caracteres').isLength({ min: 10, max: 100 }),
        check('autor','Autor tem que ter entre 10 a 100 caracteres').isLength({ min: 10, max: 100 }),
        check('autor','Autor é obrigatório').not().isEmpty(),
        check('data_noticia','Data é obrigatório').not().isEmpty(),
        check('noticias','Noticia é obrigatória').not().isEmpty()
      ], (req, res) => {
        let noticia = req.body

        const errors = validationResult(req);

        console.log(errors);

        if(!errors.isEmpty()){
          return res.render('admin/form_add_noticia', { validacao: errors.array(), noticia: noticia });

        }

        let conn = app.config.dbConnection();
        let noticiasModel = new app.app.models.NoticiasDAO(conn)

        noticiasModel.salvarNoticia(noticia, (error, result) => {
          res.redirect('/noticias')
        })
}

module.exports = (application) => {

  application.get('/formulario_inclusao_noticia', (req, res) => {
    res.render('admin/form_add_noticia',{validacao:{},noticia:{}});
    application.app.controllers.admin.formulario_inclusao_noticia(application, req, res);
  });

  application.post('/noticias/salvar', (req, res) => {
     application.app.controllers.admin.noticias_salvar(req, res);
  });
}
Answer: As suas opções de check são middlewares portanto devem ser declaradas junto às rotas:
application.post('/noticias/salvar', [
  check('titulo','Título é obrigatório').not().isEmpty(),
  check('resumo','Resumo é obrigatório').not().isEmpty(),
  check('resumo','Resumo tem que ter entre 10 a 100 caracteres').isLength({ min: 10, max: 100 }),
  check('autor','Autor tem que ter entre 10 a 100 caracteres').isLength({ min: 10, max: 100 }),
  check('autor','Autor é obrigatório').not().isEmpty(),
  check('data_noticia','Data é obrigatório').not().isEmpty(),
  check('noticias','Noticia é obrigatória').not().isEmpty()
], (req, res) => {
  application.app.controllers.admin.noticias_salvar(req, res);
});

E então a função noticias_salvar passa a ser uma função:
module.exports.noticias_salvar = (req, res) => {
  let noticia = req.body

  const errors = validationResult(req);

  console.log(errors);

  if(!errors.isEmpty()){
    return res.render('admin/form_add_noticia', { validacao: errors.array(), noticia: noticia });
  }

  let conn = app.config.dbConnection();
  let noticiasModel = new app.app.models.NoticiasDAO(conn)

  noticiasModel.salvarNoticia(noticia, (error, result) => {
    res.redirect('/noticias')
  });
};

Problema com Controllers


How do I get this CSS/jQuery menu to open only on click, rather than hover?

Question: Here is the codepen: http://codepen.io/anon/pen/pvQYog
The code laid out:
HTML

Category

1

2

3

4

5

6

7

More...

8

9

10

11

12

CSS
/* clearfix */
/**
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    contenteditable attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that are clearfixed.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */
.cf:before,
.cf:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.cf:after {
    clear: both;
}

/**
 * For IE 6/7 only
 * Include this rule to trigger hasLayout and contain floats.
 */
.cf {
    *zoom: 1;
}

ul.navbar {

  background:white;
  border-style:solid;
  border-color:gray;
  border-width:1px;
  width: 200px;
  border-radius: 4px;

}

.ActiveListItem:after {
    content: '\25BC';
    float:right;
    font-weight:bold;
    padding: 0px 0px;
    font-size:100%;

}

ul.navbar li a.ActiveListItem {
    background:white !important;
    color:black;
    border-style:solid;
    border-color:white;
    border-radius:14px;
    padding:3px 5px !important;
    font-weight:normal !important;
    margin-left:14px;/* got the activeitem centered with the list text this way*/
    margin-right:0px;

}

ul.navbar li {

    position: relative;
}

ul.navbar li a {

    display: block;
    color: white;
    padding:10px 5px;
    text-decoration:none;
    transition: all .2s ease-in;

}

ul.navbar li a:hover,
ul.navbar li:hover > a {
    background:#a6d0e1;
    color: #333;
    font-weight:900;
}

ul.navbar li ul {

    margin-top: 1px;     /*Dictates how far away textbox is from list items*/
    position: absolute;
    background: #222;
    left: em;
    font-size: 14px;
    min-width: 200px;
    opacity: 0;
    visibility: hidden;
    z-index: 99;
    box-shadow: inset 0 2px 3px rgba(0,0,0,.6),
                            0 5px 10px rgba(0,0,0,.6);
    /*transition: all .1s ease-in-out;*/              /*the sideways opener*/
}

ul.navbar li:hover > ul { opacity: 1; visibility: visible; left: 0; }

ol, ul { list-style: outside none none; }

.hidden { display: none; }

JS:
// sub menus identification
$(function() {
  $('.navbar ul li a').click(function(){
    $('.navbar > li:first-child > a').text($(this).text());
    $('.navbar > li > ul').addClass('hidden');
  });
  $('.navbar > li').mouseenter(function(){
    $(this).find('ul').removeClass('hidden');
  });
});

Also, a second less important question: Is there a way to make TWO items appear per row, rather than one item per row?
Answer: Replace your ul.navbar li ul with this. And also remove ul.navbar li:hover > ul.
ul.navbar li ul {
    margin-top: 1px;
    position: absolute;
    background: #222;
    font-size: 14px;
    min-width: 200px;
    display: none;
    z-index: 99;
    box-shadow: inset 0 2px 3px rgba(0,0,0,.6),
    0 5px 10px rgba(0,0,0,.6);
}

And script would be -
$(function() {
    $('.ActiveListItem').click(function(){
        $('.navbar li ul').toggle();
    });
});

This is the sample using your codes. You will need to modify to get what you need. Hope this might help you.
http://codepen.io/khay/pen/bNQZBN
Answer: You need to use onclick function for your requirment, i ll give you an example below.

              tester

This function will open a new window for you when you click on the text.
Comment: Apart from _"You need to use onclick function for your requirment"_ being nonsense, you are also generating invalid HTML – `span` is not allowed to contain `p`.


Unable to access XACML policy in wso2is-5.6.0 from wso2am-2.5.0 getting error

Question: i following link
Created XACML policy in wso2is.
Accessing from wso2AM created one POST type function.
While sending request in wso2AM store getting an error
I have update  "jndi.properties" file by commenting second "/test" url line.
After that i am getting error.

<code> ERROR - EntitlementMediator Error occurred while evaluating the policy
org.wso2.carbon.identity.entitlement.proxy.exception.EntitlementProxyException: Cannot initialize EntitlementServiceStub with null Axis2 configuration context.
        at org.wso2.carbon.identity.entitlement.proxy.soap.basicAuth.BasicAuthEntitlementServiceClient.getEntitlementStub(BasicAuthEntitlementServiceClient.java:246)
        at org.wso2.carbon.identity.entitlement.proxy.soap.basicAuth.BasicAuthEntitlementServiceClient.getDecision(BasicAuthEntitlementServiceClient.java:122)
        at org.wso2.carbon.identity.entitlement.proxy.PEPProxy.getDecision(PEPProxy.java:94)
        at org.wso2.carbon.identity.entitlement.proxy.PEPProxy.getDecision(PEPProxy.java:66)
        at org.wso2.carbon.identity.entitlement.mediator.EntitlementMediator.mediate(EntitlementMediator.java:185)
        at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:108)
        at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:70)
        at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158)
        at org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.mediate(APIManagerExtensionHandler.java:66)
        at org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler.handleRequest(APIManagerExtensionHandler.java:75)
        at org.apache.synapse.rest.API.process(API.java:325)
        at org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:90)
        at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:69)
        at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:303)
        at org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:92)
        at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
        at org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:337)
        at org.apache.synapse.transport.passthru.ServerWorker.processEntityEnclosingRequest(ServerWorker.java:383)
        at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:151)
        at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
[2019-01-14 22:28:24,402]  INFO - JMSConnectionFactory JMS ConnectionFactory : jmsEventPublisher initialized
[2019-01-14 22:28:24,429]  INFO - LogMediator STATUS = Executing default 'fault' sequence, ERROR_CODE = 0, ERROR_MESSAGE = Error occurred while evaluating the policy
[2019-01-14 22:28:25,476] ERROR - JMSConnectionFactory Error acquiring a Connection from the JMS CF : jmsEventPublisher using properties : {transport.jms.ConcurrentPublishers=allow, java.naming.provider.url=repository/conf/jndi.properties, java.naming.factory.initial=org.wso2.andes.jndi.PropertiesFileInitialContextFactory, transport.jms.DestinationType=topic, transport.jms.ConnectionFactoryJNDIName=TopicConnectionFactory, transport.jms.Destination=throttleData}
javax.jms.JMSException: Error creating connection: Unable to Connect
        at org.wso2.andes.client.AMQConnectionFactory.createConnection(AMQConnectionFactory.java:346)
        at org.wso2.andes.client.AMQConnectionFactory.createConnection(AMQConnectionFactory.java:53)
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSUtils.createConnection(JMSUtils.java:387)
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSConnectionFactory.createConnection(JMSConnectionFactory.java:268)
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSConnectionFactory$PoolableJMSConnectionFactory.makeObject(JMSConnectionFactory.java:356)
        at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1181)
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSConnectionFactory.getConnectionFromPool(JMSConnectionFactory.java:286)
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSMessageSender.send(JMSMessageSender.java:86)
        at org.wso2.carbon.event.output.adapter.jms.JMSEventAdapter$JMSSender.run(JMSEventAdapter.java:284)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.wso2.andes.AMQConnectionFailureException: Unable to Connect
        at org.wso2.andes.client.AMQConnection.<init>(AMQConnection.java:485)
        at org.wso2.andes.client.AMQConnectionFactory.createConnection(AMQConnectionFactory.java:328)
        ... 13 more
[2019-01-14 22:28:25,482] ERROR - JMSConnectionFactory Error acquiring a Connection from the JMS CF : jmsEventPublisher using properties : {transport.jms.ConcurrentPublishers=allow, java.naming.provider.url=repository/conf/jndi.properties, java.naming.factory.initial=org.wso2.andes.jndi.PropertiesFileInitialContextFactory, transport.jms.DestinationType=topic, transport.jms.ConnectionFactoryJNDIName=TopicConnectionFactory, transport.jms.Destination=throttleData}
org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterRuntimeException: Error acquiring a Connection from the JMS CF : jmsEventPublisher using properties : {transport.jms.ConcurrentPublishers=allow, java.naming.provider.url=repository/conf/jndi.properties, java.naming.factory.initial=org.wso2.andes.jndi.PropertiesFileInitialContextFactory, transport.jms.DestinationType=topic, transport.jms.ConnectionFactoryJNDIName=TopicConnectionFactory, transport.jms.Destination=throttleData}
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSConnectionFactory.handleException(JMSConnectionFactory.java:197)
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSConnectionFactory.createConnection(JMSConnectionFactory.java:278)
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSConnectionFactory$PoolableJMSConnectionFactory.makeObject(JMSConnectionFactory.java:356)
        at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1181)
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSConnectionFactory.getConnectionFromPool(JMSConnectionFactory.java:286)
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSMessageSender.send(JMSMessageSender.java:86)
        at org.wso2.carbon.event.output.adapter.jms.JMSEventAdapter$JMSSender.run(JMSEventAdapter.java:284)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: javax.jms.JMSException: Error creating connection: Unable to Connect
        at org.wso2.andes.client.AMQConnectionFactory.createConnection(AMQConnectionFactory.java:346)
        at org.wso2.andes.client.AMQConnectionFactory.createConnection(AMQConnectionFactory.java:53)
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSUtils.createConnection(JMSUtils.java:387)
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSConnectionFactory.createConnection(JMSConnectionFactory.java:268)
        ... 10 more
Caused by: org.wso2.andes.AMQConnectionFailureException: Unable to Connect
        at org.wso2.andes.client.AMQConnection.<init>(AMQConnection.java:485)
        at org.wso2.andes.client.AMQConnectionFactory.createConnection(AMQConnectionFactory.java:328)
        ... 13 more
[2019-01-14 22:28:25,486] ERROR - JMSMessageSender
java.lang.NullPointerException
        at org.wso2.carbon.event.output.adapter.jms.internal.util.JMSMessageSender.send(JMSMessageSender.java:88)
        at org.wso2.carbon.event.output.adapter.jms.JMSEventAdapter$JMSSender.run(JMSEventAdapter.java:284)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
</code>
Am getting above given error. After update "jndi.properties" file.
Answer: Based on the log you have shared, it looks like there are 2 separate errors in your setup. First one is related to XACML mediator configuration and the second one is related to JMS transport configuration. To understand the problem with the XACML mediator, can you share the mediation extension (synapse) configuration you have used with the API?
For the second error, please share the APIM_HOME/repository/conf/axis2/axis2.xml file and axis2_blocking_client.xml files.
Without looking at these configuration files, it is not possible to provide you with an answer.
Comment: before this problem i have another question [here](https://stackoverflow.com/questions/54370691/unable-to-create-fixed-remote-mounts-in-wso2-api-manager-2-5-0), I am unable to share registry.
Comment: [here](https://stackoverflow.com/questions/54365427/not-able-to-install-xacml-and-xacml-mediation-in-wso2am-2-5-0) i have one more question. how to install XACML and XACML Mediation in WSO2AM-2.5.0.
Comment: [here] https://stackoverflow.com/questions/54351535/unable-to-create-access-token-grant-type-in-wso2-api-manager-store-to-test-api)i am able to create access token but that tell invalid token help me in this also.


Twig whitespace controls have no effect on fields

Question: I am trying to iterate over a Paragraph field and apply a comma after each Paragraph item.
In the field template that outputs the Paragraph, I am trying:
{%- for item in items %}
  {{ item.content }}{{ not loop.last ? ', ' }}
{% endfor -%}

This puts the comma out, but there is a ton of whitespace all over:

I have tried many whitespace control combinations and none seem to have any effect.
How can I remove this sort of behavior entirely? The paragraph field is an entity reference, that renders a view mode, so I don't want to install field delimeter plugin.
edit: Tried the solutions mentioned here:
How remove whitespace on field in twig?
and here:
https://craftcms.stackexchange.com/questions/2789/whitespace-created-when-using-if-statements
as well as in the documentation.
The structure is as follows:
Node -> Paragraph field -> Paragraph (Entity) -> User Reference + Plain text field + rich text
In this context, only the user field is being rendered, and I want to put a comma at the end of each linked name.
Comment: If you switch to the Bartik theme, does the same issue persist?
Comment: You should provide the white space control combos u alrdy tried.
Comment: Is this paragraph field inside a view?
Comment: Nope, field on a node.
Answer: Although the whitespace control modifier is supposed to work for all {{ … }} prints, {% … %} statements and {# … #} comments I'd expect to make your sample work it needs to be put directly into the print like that:
{% for item in items %}
  {{- item.content -}}{{- not loop.last ? ', ' -}}
{% endfor %}

Alternatively you could try to use the {% spaceless %} tag. But again, I'd expect this only works right when placed inside the loop:
{% for item in items %}
  {% spaceless %}
    {{ item.content }}{{ not loop.last ? ', ' }}
  {% endspaceless %}
{% endfor %}

As of Twig 1.38, use the |spaceless filter instead.


Yes/No . Is $f$ bounded in a neighbourhood of $(0,0) ?$

Question: $f(x,y) =\begin{cases} \frac {x^2-y^2}{x^2+y^2} & \text{for }  (x ,y)
\neq (0,0)\\ 0 \  & \text {for }    (x,y) =(0,0)  \end{cases}$
Is  $f$   bounded  in a neighbourhood  of $(0,0) ?$
My attempt : I think $f$ is   bounded  in a neighbourhood  of $(0,0) $
take $x= r \cos \theta$  and $y= r\sin \theta$
$$\Big|\frac {x^2-y^2}{x^2+y^2}\Big|=\Big|\frac {r^2 \sin^2 \theta -r^2 \cos^2 \theta }{r^2 \sin^2 \theta +r^2 \cos^2 \theta}\Big|\le \Big|\frac {r^2 (\sin^2 \theta - \cos^2 \theta) }{r^2( \sin^2 \theta + \cos^2 \theta)}\Big|\le |\sin^2 \theta - \cos^2 \theta |\le |1+1|\le 2$$
Also, $\lim_{(x,y) \to (0,0)}f(x,y)=\lim_{(x,y) \to (0,0)}\frac {x^2-y^2}{x^2+y^2}=\frac{0-0}{0+0}=0$
Comment: In that link, the question says "I will attempt to prove $0/0=1$", and you are tasked with finding the flawed logic...
Comment: $0/0$ is NOT $0$. This is an indeterminant form, one that cannot be evaluated because one cannot divide by zero. So the last limit calculation is incorrect.
Comment: okay @ndhanson3
Comment: Also, the inequality $|\sin^2\theta-\cos^2\theta| \leq |1+1|$ is only true luckily. You need to use the triangle inequality: $|\sin^2\theta-\cos^2\theta|\leq |\sin^2\theta| + |\cos^2\theta|\leq 1+1$.
Comment: @ndhanson3 on this [link](https://brilliant.org/wiki/what-is-0-0/)  it is given that $0/0 =1$
Comment: @ndhanson3 .  If you tell 10 people that 0/0  is an indeterminate form and then ask them to explain what that means, at least 5 of them  can't...... I prefer to be more blunt and say 0/0 doesn't exist.
Comment: Your link does NOT say 0/0=1. Click on the box "Reveal the correct answer".
Answer: Yes, $f(x)$ is actually bounded everywhere, not just in a neighborhood of $(0,0)$. Every point that is not $(0,0)$ can take advantage of the argument using $x=r\cos\theta$ and $y=r\sin\theta$, which you have almost correct. Some of the inequalities are in fact equalities, and as I mentioned in the comments, one of your inequalities is only luckily correct:
$$\left|\frac{x^2-y^2}{x^2+y^2}\right|
=\left|\frac{r^2\cos^2\theta-r^2\sin^2\theta}{r^2\cos^2\theta+r^2\sin^2\theta}\right|
=\left|\frac{r^2(\cos^2\theta-\sin^2\theta)}{r^2(\cos^2\theta+\sin^2\theta)}\right|
=|\cos^2\theta-\sin^2\theta|\\\leq|\cos^2\theta|+|\sin^2\theta|\leq1+1=2
$$
Comment: In fact, $\cos^2-\sin^2\theta=\cos2\theta$, so $|\cos^2\theta-\sin^2\theta|=|\cos2\theta|\leq 1$, so the whole function is bounded by $-1$ and $1$.
Answer: If $(0,0)\ne(x,y)\in\Bbb R^2$ then $$|f(x,y)|=\frac {|x^2+(-y^2)|}{x^2+y^2}\le \frac {|x^2|+|(-y^2)|}{x^2+y^2}=\frac {x^2+y^2}{x^2+y^2}=1.$$


Bootstrap confidence intervals on parameters or on distribution?

Question: Excuse what may be an obvious question about bootstrapping. I got sucked in the Bayesian world early and never really explored bootstrapping as much as I should have.
I ran across an analysis in which the authors were interested in a survival analysis related to some time to failure data.  They had about 100 points and used regression to fit a Weibull distribution to the data. A result of this they obtained estimates of the scale and shape parameters. A very traditional approach. However, they next used bootstrapping to sample from the original data set and, for each new sample, performed a regression and came up with a new Weibull distribution.  The results of the bootstrapping was then used to construct confidence intervals on the survival distribution.
My intuition is a bit conflicted. I'm familiar with bootstrapping confidence intervals on parameters, but not seen it used for constructing distribution confidence intervals.
Can anyone point me toward a reference/source that might provide some insight? Thanks in advance.
Comment: There are at least two ways to bootstrap. The simplest way is to simply draw a random sample from the given observations and estimate the model b times (bootstrapping "pairs"). You can also bootstrap using the residuals from a model ("residuals" bootstrap). The first neglects the error structure in the data, which the second method implicitly assumes your model is correct. Efron & Tibshirani (1993). "An Introduction to the Bootstrap" is the place to start.
Comment: The question actually is more general than you suppose, because it really doesn't matter how the parameters were estimated.  The crux of the matter is that the parameters completely determine the distributions.  Thus, a set of simultaneous CIs on the parameters *is* a CI for the distributions.
Comment: I understand that and perhaps it is that straightforward. Maybe what's nagging at me is that bootstrapping comes with it's own baggage and I was wondering if there was something about the procedure that introduces additional issues when used for this next step. On the other hand, it could just be what I had for breakfast that's gnawing.  Thanks for the quick comment.
Comment: Gotta be the breakfast :-)
Answer: Basically, if you have a joint confidence interval for the parameters that uniquely describe a distribution, then you have a distribution confidence interval.  So your problem vanishes... as per whuber's comment.


Setting up a transparent proxy server a la unblock-us.com

Question: I have a Windows Server set up in America (I'm from the UK), and am thinking of setting it up so I can mask my IP like http://www.unblock-us.com. Basically what it does is make it look like my IP is in North America when really it's in the UK.
Is it a transparent proxy I would need to do this? Am I able to do this with just the server?
I have only just started looking at this, so just really looking to see if it's possible first.
Thanks
Answer: You wouldn't need a transparent proxy(which is something you'd run between your network and the internet, well, transparently), you'd need a proxy (which is a system sitting somewhere passing through traffic - some configuration needed). You'd need a server in the country in question (vps do fine), and a proxy software - tinyproxy is simple enough for this, since we're not talking caching.
If you wanted to run a transparent proxy I THINK you could run tinyproxy at the router, and point it at a second proxy through the upstream proxy directive in the config file, but I've not tried it yet.


Binary strings to Hex strings java

Question: I have this code here, which get a plain text, and turns it to a 512-bit binary string.
Then, I would like to turn each 32-bit piece of the string to 8-bit of Hex string, but that part gives me a java.lang.NumberFormatException
// ----- Turning the message to bits
        byte[] binaryS = s.getBytes("UTF-8");
        String mesInBinary = "";
        for (byte b : binaryS) {
            mesInBinary += '0' + Integer.toBinaryString(b);
        }
        // ----- Message padding & Pre-Processing
        // Binary representation of the length of the message in bits
        String mesBitLength = Integer.toBinaryString(mesInBinary.length());
        // We need the size of the message in 64-bits, so we'll
        // append zeros to the binary length of the message so
        // we get 64-bit
        String appendedZeros = "";
        for (int i = 64 - mesBitLength.length() ; i > 0 ; i--)
            appendedZeros += '0';
        // Calculating the k zeros to append to the message after
        // the appended '1'
        int numberOfZeros = (448 - (mesInBinary.length() + 1)) % 512;
        // Append '1' to the message
        mesInBinary += '1';
        // We need a positive k
        while (numberOfZeros < 0)
            numberOfZeros += 512;
        for (int i = 1 ; i <= numberOfZeros ; i++)
            mesInBinary += '0';
        // append the message length in 64-bit format
        mesInBinary += appendedZeros + mesBitLength;
        System.out.println(mesInBinary);
        // ----- Parsing the padded message
        // Breaking the message to 512-bit pieces
        // And each piece, to 16 32-bit word blocks
        String[] chunks = new String[mesInBinary.length() / 512];
        String[] words = new String[64 * chunks.length];
        for (int i = 0 ; i < chunks.length ; i++) {
            chunks[i] = mesInBinary.substring((512 * i), (512 * (i + 1)));
            // Break each chunk to 16 32-bit blocks
            for (int j = 0 ; j < 16 ; j++) {
                words[j] = Long.toHexString(Long.parseLong(chunks[i].substring((32 * j), (32 * (j + 1)))));
            }
        }

The last code line is the problematic one and of which I get the execption. Any suggestions?
Comment: The last line of code is a `}`...
Comment: God knows I meant words[j] = Long.toHexString(Long.parseLong(chunks[i].substring((32 * j), (32 * (j + 1)))));
Answer: The last statement* should specify a radix of 2, I think:
words[j] = Long.toHexString(
    Long.parseLong(chunks[i].substring((32 * j), (32 * (j + 1))), 2));

*Not the last line of code, MДΓΓ :-)
Answer: From the Long docs:
public static long parseLong(String s) throws NumberFormatException:

Parses the string argument as a signed decimal long. The characters in the string must all be decimal digits...

public static long parseLong(String s, int radix) throws NumberFormatException:

Parses the string argument as a signed long in the radix specified by the second argument. The characters in the string must all be digits of the specified radix...

You're calling the first version of Long.parseLong(), which expects a decimal number, not a binary one. Use the second version with a radix of 2 to indicate binary.
EDIT: The reason being that a 32-digit decimal number won't fit into a Long, but a binary one will.
Answer: for (int i = 0 ; i < chunks.length ; i++)
{
     chunks[i] = mesInBinary.substring((512 * i), (512 * (i + 1)));
     // Break each chunk to 16 32-bit blocks
     for (int j = 0 ; j < 16 ; j++)
     {
         words[j] = Long.toHexString(Long.parseLong(chunks[i].substring((32 * j), (32 * (j + 1))),2));
     }
 }

Binary strings to Hex strings java


Algorithm for setting opacity according to the date

Question: My client has asked me to set the opacity (alpha) for various different MKPlacemarks depending on what the date was.
For the oldest half of the place marks, he would like the opacity to be set to 0.5.
I can do this by working out the index of the place mark and checking to see whether it is in the last half of the array.
int indexOfPlacemark = [fixes indexOfObject:fix]; //fixes is the array of Placemarks (named fix).

if (index <= [fixes count] / 2) {
    [annotationView setAlpha:0.5];
} else {
    // do something with fix.date to work out the opacity.
    // an example of the date is Sun, May 15, 2011 - 12:00:44
}

But then he wants me to raise the opacity for every other place mark depending on its date. I.e the latest date will have an opacity of 1.0, and the oldest date in the first half of the array will be ~0.5.
What I would like to know is how I can work out the opacity depending on its date.
Answer: if we'll relate to the date as a long value, then the oldest date and the newest date form an Interval, this Interval can be rescaled and moved.
try this method
newval = (((oldval - oldestdate) / (newestdate - oldestdate)) * (0.5)) + 0.5

Answer: Simply find the "oldest half" of the array, count the items, then linearly scale from 0.5 to 1.0 in increments of 0.5 / count. For example, if you have five items in the oldest half, then your increment will be 0.5 / 5 = 0.1, and so you give opacities 0.5, 0.6, ..., 0.9.
This depends on you being able to find the "oldest half" easily, as well as you having a sorted array of that half (so you can assign opacities sequentially).


I can't run tensorflow with GPU

Question: I am a beginner in deep learning and I've been trying to pip install tensorflow and run it using my laptop's GPU (NVIDIA GeForce RTX 3060). So I tried following the steps on the following website: https://towardsdatascience.com/setup-an-environment-for-machine-learning-and-deep-learning-with-anaconda-in-windows-5d7134a3db10
I downloaded GeForce Experience, already had anaconda, installed CUDA toolkit and cuDNN. I'm currently using windows 11 so upon installing I chose the matching versions. for Cuda, I tried both 11 and 12. When I check if the install went well with nvcc --version, the following appears(Coda12):
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2023 NVIDIA Corporation
Built on Tue_Jun_13_19:42:34_Pacific_Daylight_Time_2023
Cuda compilation tools, release 12.2, V12.2.91
Build cuda_12.2.r12.2/compiler.32965470_0
I installed everything that I believed was needed but then when I check weither the GPU is being used, by entering:
tf.config.list_physical_devices("GPU")
I get an empty list as an output.
I tried both with and without creating an environment but the result doesn't change.
Can someone help with that please?
I downloaded everything that I believed was needed and was expecting tensorflow to use the laptop's GPU.
Comment: Latest TensorfFlow requires cudatoolkit 11.8 and cuDNN 8.6. Check the version of what you installed, and change it if needed.
Comment: Thanks for the answer.. I'm on windows11 and so when check that box the only version of CUDA I'm allowed to download seems to be CUDA12.2.0 and then when cuDNN website says cuDNN v8.9.3 is the version compatible for CUDA12. Should I still find a way to download  cudatoolkit 11.8 and cuDNN 8.6?
Comment: [Cuda Toolkit 11.8](https://developer.nvidia.com/cuda-11-8-0-download-archive) and the list of [cuDNN archives](https://developer.nvidia.com/rdp/cudnn-archive) (look for cudnn 8.6 for CUDA 11.x)
Answer: Since I cannot find the specific Tensorflow version mentioned above, I highly suspect that the problem is the unsupported version of the Tensorflow-GPU library for Windows OS.
According to the official Tensorflow website(https://www.tensorflow.org/install/source_windows#gpu), you can find the notice: GPU support on native-Windows is only available for 2.10 or earlier versions.

I can't run tensorflow with GPU


Sections of a Borel set in the product space

Question: I have a Polish (completely metrizable and separable) space $X$ and a Borel subet $A \subseteq X\times X$, i.e. $A \in \boldsymbol{\mathcal{B}}(X\times X)$. Given a Borel set $C\subseteq X$ is it true that $$\{x \in X \mid A_x = C\} \in \boldsymbol{\mathcal{B}}(X)?$$
By $A_x$ I mean the section of $A$ along $x$, i.e. $A_x = \{y\in X \mid (x,y) \in A\}$
In case it is, is it also the case for projective sets?
Thanks
Answer: No. If $B \subseteq \mathbb{R} \times \mathbb{R}$ is a closed set, then $\{x : B_x \neq \emptyset\}$ is an analytic set and all analytic sets take such a form. Thus $\{x : B_x = \emptyset\}$ is a coanalytic set. There are coanalytic subsets of $\mathbb{R}$ which are not Borel (for instance the set of reals coding wellorderings on $\omega$.)
Given $B \subseteq \mathbb{R} \times \mathbb{R}$ and $C \subseteq \mathbb{R}$. Let $A = \{x \in \mathbb{R} : B_x = C\}$. Note that $x \in A \Leftrightarrow (\forall y)((x,y) \in B \Leftrightarrow y \in C)$. So if $B$ and $C$ belonged to some pointclass closed under existential real quantifers and complements (like the class of projective sets), then $A$ would also be in the pointclass (i.e. be projective).
Comment: Lebesgue actually made the erroneous assertion that the projection $p_1(x,y)=x$ of a Borel $B\subset \Bbb R^2$ is Borel in $\Bbb R.$ His"proof" incorrectly assumed that if $F$ is a countable family of Borel subsets of $\Bbb R^2$ and $p_1[f] $ is Borel for each $f\in F$ then $p_1[\cap F]$ is Borel.
Answer: Let $X = \mathbb R$.  There is a Borel set $A \in \mathcal B(\mathbb R^2)$ whose projection onto the first coordinate
$$
\pi_1(A) = \{x : \exists y, (x,y) \in A\}
$$
is not a Borel set.  (Result due to Suslin.)
But that means the complement is also non-Borel
$$
\pi_1(A)^c := \mathbb R^2 \setminus \pi_1(A) \notin \mathcal B(\mathbb R).
$$
We have
$$
A_x = \{y \in \mathbb R : (x,y) \in A\}
$$
so
\begin{align}
A_x = \varnothing \quad&\Longleftrightarrow\quad\not\exists y, (x,y) \in A
\\&\Longleftrightarrow\quad x \notin \pi_1(A)
\\&\Longleftrightarrow\quad x \in \pi_1(A)^c
\end{align}
But take $C = \varnothing$.  Thus
$$
\{x : A_x = C\} = \pi_1(A)^c \notin \mathcal B(\mathbb R)
$$


What happens what you print the variable of an object in java?

Question: public class test
{
        public static void main (String[ ] args )
        {
            TheClass one = new TheClass(); constructor
            TheClass two = new TheClass(str , doubleNum); // I: calling the parameter constructor to //pass: "David William" and 3.5 to the object
            System.out.println( one );
            System.out.println( two );

            // call the method staticMethod
            System.out.print(two.staticMethod());
        }
}

class TheClass
{

     private String str;
     private static int intNum = 0;
     private double doubleNum ;

     public TheClass()
     {
          str = "unknown";
          doubleNum = 0.0;
     }

     public TheClass (String s, double d)
     {
          str = s;
          doubleNum = d;
     }

     public static void staticMethod ()
     {
          intNum ++;
     }
}

Would it make sense to do "System.out.println( one );" & "System.out.println( two );" since they are only constructors?
What would the output be for these 2 lines?
Comment: What do you mean by `System.out.println(one);` being a constructor? Also, did you run your code to see what happens?
Comment: it calls the toString() method, just override the toString() method and see the differences :)
Answer: Since you haven't defined a toString() method, the output of "printing" an instance of you class will be not useful to a human.
Assuming you defined a meaningful toString() method, there is nothing wrong with the concept of printing an object just constructed, such as:
System.out.println( new TheClass(str , doubleNum) );

It just means that you wouldn't have a reference to the object after that line (and thus it would be available for garbage collection).
Try the same code but add this method to your class:
@Override
public String toString() {
    return str + " " + doubleNum;
}

Answer: If the class has an overridden toString() implementation, then that will be used and whatever string is returned by that implementation will be printed out. Otherwise, the JVM will try to see if it can find a toString() implementation for an ancestor of that class and use that.
Eventually, that is, if the JVM is not able to find a suitable overridden implemenation of .toString(), Object#toString() is called (every class in Java derives from Object). This results in an output that isn't very useful.


Convergence of a filter defined in a subspace

Question: I am reading about convergence of filters in topological spaces and cluster points. My doubt is the following: let $X$ be a topological space, $A\subset X$ and $\mathcal F$ a filter on $A$. Given $x \in \overline A$, what is the meaning of $\mathcal F \longrightarrow x$?
Bourbaki defines the convergence of a filter (page 68 - topology 1) which is defined in the whole space $X$. Of course that is not the case of $\mathcal F$ if $A\ne X$. But in Proposition 6 of page 70 they use this kind of convergence. I am assuming that this means that  $\mathcal F$ is finer than $\mathcal B(x)_A$, which is the trace of the filter of the neighborhoods of $x$. Is that correct? I found it very strange since Bourbaki's book (as far as I know) does not make this kind of imprecision (to work with a not given definition).
In Dugundji's book only the definition of convergence of a filterbase is given (Def. 2.1 of Chapter 10). So his Theorem 4.1 (that is the cited proposition of Bourbaki's book) is coherent.
Answer: $\mathscr F\to x$ means that $\mathcal{N}_x\subset\mathscr F$, where $\mathcal N_x$ is the filter of neighbourhoods of $x$.
The fact that $x\in \overline A$ can be characterized in terms of convergence of filters. Indeed, $x\in \overline{A}$ iff there is some filter $\mathscr{F}\to x$ such that $A\in \mathscr{F}$.
$\Rightarrow$) Let $x\in \overline{A}$. For every $N\in\mathcal N_x$, $N\cap A\neq \emptyset$, so that $\{N\cap A:N\in\mathcal N_x\}$ is a filter base. Let $\mathscr F$ be the filter generated by it. Obviously, $A\in\mathscr F$.
$\Leftarrow$) Let $N\in\mathcal N_x$. Then $N\cap A\in\mathscr F$, so that $N\cap A\neq\emptyset$. This says that $x\in \overline A$.
Comment: What I do not understand is the following phrase of Bourbaki's result: " and conversely, every point of $\overline A$ is a limit point of a filter on $A$". So you are saying that "a filter on $A$" is a filters that contains $A$? For me it is a filter such that the elements are contained in $A$.
Comment: @mathnewbie I go into that in my answer.
Answer: If $\mathcal{F}$ is a filter on $X$ that contains $A \subseteq X$, then $\mathcal{F}_A:= \{B \subseteq A\mid B \in \mathcal{F}\}=\mathscr{P}(A) \cap \mathcal{F}$ is a filter on $A$ (it's clear that $\emptyset \notin \mathcal{F}_A \subseteq \mathcal{F}$, and $\mathcal{F}_A$ is also clearly closed under intersections and enlargements "within $A$"). And clearly any filter on $A$ contains $A$ and is a filterbase for a filter $\mathcal{F}^\uparrow$ (still containing $A$) on $X$ that obeys $\mathcal{F}^\uparrow_A = \mathcal{F}$ again.
So there is a natural correspondence between them.
It's also easy to see that for such a filter $\mathcal{F}$ on $X$ that contains $A$, and any $x \in A$, $\mathcal{F} \to x$ in $X$ iff $\mathcal{F}_A \to x$ in the subspace topology on $A$.
If $\mathcal{F}$ is a filter on $A$ then $\mathcal{F} \to x$ is defined as the convergence of a filterbase. So as $\mathcal{F}^\uparrow \to x$ if you want to restrict yourself to convergence of (full) filters on $X$. But IIRC Bourbaki defines convergence for filter bases in general anyway.
"Every point of $x$ of $\overline{A}$ is a limit point of a filter on $A$" is true as we can take that filter to be $\mathcal{F}:=\{N \cap A: N \in \mathcal{N}_x\}$, which is a filter on $A$ and a filterbase on $X$ for which $\mathcal F \to x$ is true and makes sense.
Comment: The problem here is that $x \in \overline A$, so we may have $x \in X\setminus A$. I agree with you that Bourbaki defines convergence for filter base in general way, but in "and conversely, every point of $\overline A$ is a limit point of a filter on $A$" the claim is about a filter and not a filter base, right? Note that just before this claim he take a filter base in $A$, so for me he wanted to distinguish these things
Comment: @mathnewbie I added a remark about it.
Comment: Ok. Thanks for the answer :)
Answer: I agree with you that a filter on $A$ is a filter of subsets of $A$. However, if we denote by $\Bbb F(Y)$ the set of filters on a set $Y$, then $\Bbb F(A)=\{\mathscr{F}\cap\wp(A):A\in\mathscr{F}\in\Bbb F(X)\}$, so there is a natural correspondence between filters on $A$ and filters on $X$ that contain $A$.
But you don't actually need to make this explicit for Prop. $6$. The first part of the proposition is clear: if $\mathfrak{B}$ is a filter base on $A$, then it is automatically a filter base on $X$ for a filter that contains $A$, so by the remark following Definition $2$ every cluster point of $\mathfrak{B}$ is in $\overline{A}$. Conversely, if $x\in\overline{A}$, then every nbhd of $x$ in $X$ meets $A$, so the trace on $A$ of the nbhd filter of $x$ in $X$ is a filter on $A$ and therefore a filter base on $X$; clearly every nbhd of $x$ in $X$ contains a member of this filter base, so by Prop. $1$ of $7.1$ this filter base converges to $x$ in $X$.
Comment: I agree that the first part do not need this notion of convergence. But in the second part he is explicit when he says 'is a limit poin of a FILTER' and not a 'filter base'. That is the reason of my doubt (Dugundji goes with you when he works only about filter base). But there is a kind of interpretation in Bourbaki's proposition, isn't? I did not find the precise definition of this convergence..
Comment: @mathnewbie: But we already know that a filter base converges to $x$ if and only if the filter that it generates converges to $x$; this is explicit in Definition $1$ of $7.1$. I dislike Bourbaki and do not think it a good book from which to try to learn topology, but there is absolutely nothing wrong here.


Form looses focus after single character input?

Question: I created a form with a state attached to it , but after every character input the form looses focus.
i realize its because the state cause the form to re render how do i escape this?
import axios from 'axios'

const App = () => {
  const [countries,setCountries] =useState([])
  const [ newName,setnewName ] = useState('')

  useEffect(()=>{
    axios.get('https://restcountries.eu/rest/v2/all')
    .then(response=>{
      setCountries(response.data)
    })
  },[])

  const handleChange = (event) =>{
    setnewName(event.target.value)
  }
  const Finder = ()=>{

    return(

        <form>

            Find country : <input value={newName} onChange={handleChange} />

        </form>

    )
  }

  return(

Meow

    <Finder/>

  )

}

export default App```

Answer: As you are rendering Finder as a component and it  will be create a new function on each and every render instead as you are rendering it inside a component invoke it as a function like below
try changing  the return statement as
return(

Meow

   {Finder()}

)

Please go through this sandbox for reference


Merging one query as parameter into another query

Question: How to combine Query2 In Query1 as second parameter along with the existing Select count(*) statement with an or condition.
-------------------Query 1--Main Query to retireve sources & table count--------
Select
pathSuffix,
              (Select count(*) from Sources with(nolock)
              where level = 2 and
              (
                     (parent like '%raw%' and type= 'DIRECTORY' AND  parent like '/prod/' + s.pathSuffix + '/raw') or
                     (parent like '%archive%' and type='DIRECTORY' and parent like '/prod/' + s.pathSuffix + '/archive')
              )) as filecount,
modificationTime,
owner,
type
from Sources s with(nolock) where level = 0
order by pathSuffix

----------Query2--Gets the Count of Snapshot_rpx files as 495----------------
select Count(distinct(SUBSTRING(pathSuffix,
                           CHARINDEX('-', pathSuffix)+1,
                           LEN(pathSuffix)- (CHARINDEX('-',REVERSE(pathSuffix)) + CHARINDEX('-', pathSuffix)))))
from Sources s with(nolock)
where parent like '/prod/snapshot_rpx/archive%' and  type='FILE' and level=2

Answer: You can use a sub-query:
select Count(distinct(SUBSTRING(pathSuffix, CHARINDEX('-', pathSuffix)+1, LEN(pathSuffix)- (CHARINDEX('-',REVERSE(pathSuffix)) + CHARINDEX('-', pathSuffix))))), (Select count(*) from Sources with(nolock) where level = 2 and ( (parent like '%raw%' and type= 'DIRECTORY' AND parent like '/prod/' + s.pathSuffix + '/raw') or (parent like '%archive%' and type='DIRECTORY' and parent like '/prod/' + s.pathSuffix + '/archive') )) as filecount, modificationTime, owner, type
from Sources s with(nolock) where level = 0 order by pathSuffix) from Sources s with(nolock) where parent like '/prod/snapshot_rpx/archive%' and type='FILE' and level=2

Comment: I am getting errors with your new code.Can someone help me in fixing this issue.
Comment: Paste the query you are running and the output it produces.


Add a 'Buy-it-Now' button to an ApacheSolr View

Question: So I have built a View that uses Apache Solr to display products on my Ubercart site from the Solr index.  Swell.  Now Ubercart typically lets me add a 'Buy-it-Now'/ Add to Cart button as a field in most views but for some reason in this view that is not possible.
How do I add a 'Buy-it-Now'/ Add to Cart field to this view?
Answer: You can use one of the hooks provided by apache solr to alter your search results : hook_apachesolr_process_results
and you could append 'Buy it Now' button as well by using hook_theme()
Apache solr hooks
Comment: I did not get a chance to attempt your answer; however, I feel like if my problem was a little more complicated these options would have come in handy.
Answer: Okay so I was not able to try out gj. 's answer because I figured this out using the Views Field View module.
I created a sub view called 'Buy it now Button'.  This view displays just a buy it now button field with one result that takes a contextual filter with Node ID as an argument.  I added the view 'Buy it now Button' as a field in my faceted search view and everything works fine.
The only thing extra to note was that I had to add an invisible Node ID field to the search view which I could then pass as an argument to the View Field (conditional arguments are supported by Views Field View)


Contents in Kubernetes pod gets empty when persistent volume is mounted

Question: persistent volume claim and persistent volume yaml file
apiVersion: v1
kind: PersistentVolume
metadata:
  name: my-volume
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 5Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/mnt/datatypo"

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: my-claim
spec:
  storageClassName: manual
  volumeName: my-volume
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 3Gi

Deployment yaml file
apiVersion: v1
kind: Service
metadata:
  name: typo3
  labels:
    app: typo3
spec:
  type: NodePort
  ports:
    - nodePort: 31021
      port: 80
      targetPort: 80
  selector:
    app: typo3
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: typo3
spec:
  selector:
    matchLabels:
      app: typo3
  replicas: 1
  template:
    metadata:
      labels:
        app: typo3
    spec:
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: app
                operator: In
                values:
                - typo3
      containers:
      - image: image:typo3
        name: typo3
        imagePullPolicy: Never
        ports:
        - containerPort: 80
        volumeMounts:
         - name: my-volume
           mountPath: /var/www/html/
      volumes:
           - name: my-volume
             persistentVolumeClaim:
                 claimName: my-claim

Note: if the persistent volume is not added, then contents were showing inside the pod (in var/www/html). But after adding the persistent volume then it's not showing any contents inside the same folder and the external mount path /mnt/datatypo.
Comment: do you have content in `/mnt/datatypo` on the host itself? It won't get copied from your container `/var/www/html/`.
Answer: This is expected behaviour: when persistent volume is mounted, it overwrites content of the folder which is specified in mountPath.
Therefore you have two options:

have content of that directory presented on your host machine already
mount hostPath into another directory in container and then copy content to the final destination folder. (Can be achieved with command in container)

Also you can mount a single file, there are different options of hostPath types. Please get familiar with hostPath types.
Note! Using hostPath mount can be used only for testing some features locally, it's very insecure approach in production systems:

Warning: HostPath volumes present many security risks, and it is a
best practice to avoid the use of HostPaths when possible. When a
HostPath volume must be used, it should be scoped to only the required
file or directory, and mounted as ReadOnly

Volumes - hostPath.


Adding an entity to a dataset

Question: It would be helpful if you could help me add a GPA entity to Spacey Model for the named entity since there is no GPA entity in the resume dataset.
Answer: Assuming that you do have the resume dataset which is already annotated without GPA available with you.
You may annotate the entire train dataset for GPA and then train a new spacy model. Training a spacy model is straight forward please check https://spacy.io/usage/training#quickstart
If you do not have the resume dataset, you might want to create your own smaller resume dataset where you would only annotate GPA  and train a new spacy model which only detects GPA. Then you can use your existing model to detect other entites and this model to detect GPAs. Note with this method you would parse your production data over 2 models.
To aid with your annotation process you can use any free annotation tools like Docanno(https://github.com/doccano/doccano) or Acharya(https://github.com/astutic/Acharya).

Adding an entity to a dataset


how to show 2 form from same table in search

Question: I want to ask, how to show 2 forms from the same table with a related table in yii2,
example
<?php
    $label1 = app\models\AppFieldConfigSearch::getLabelName(Location::tableName(), "Location");
    ?>
    <?= $form->field($model, 'id_location')->label($label1) ?>

    <?php
        $label1 = app\models\AppFieldConfigSearch::getLabelName(LocationUnit::tableName(), "label1");
    ?>
    <?= $form->field($model, 'label1')->label($label1) ?>

    <?php $dataListAssetMaster2 = ArrayHelper::map(Owner::find()->asArray()->all(), 'id_owner', 'name');
    echo $form->field($model, 'id_owner')->widget(Select2::classname(), [
        'data' => $dataListAssetMaster2,
        'pluginOptions' => [
            'allowClear' => true
        ],
        'options' => [
            'prompt' => 'Pilih Nama']
    ])->label("Name");
    ?>
    <?php $dataListAssetMaster4 = ArrayHelper::map(Location::find()->asArray()->all(), 'id_location', 'address');
    echo $form->field($model, 'id_location')->widget(Select2::classname(), [
        'data' => $dataListAssetMaster4,
        'pluginOptions' => [
            'allowClear' => true
        ],
        'options' => [
            'prompt' => 'Status Pembebasan']
    ])->label("location address");

//       my search model
public function rules()
{
    return [
        [['id_location_unit', 'id_location', 'id_owner','id_mst_status1'], 'integer'],
        [['label1', 'label2', 'label3', 'keterangan1', 'keterangan2', 'keterangan3','address'], 'safe'],
    ];
}

I want to display the same 2 tables on 1 search form, but I have a problem when I use the code, one of the forms does not appear
Comment: In the above code you mentioned only one form object $form, please paste more code to debug the issue.
Answer: You can combine 2 of your model/form into 1 search model. Let your search model decide on the search logic.


Powershell: multiple wildcards in Get-ChildItem path

Question: I'm trying to use Get-ChildItem in powershell (I'm using the ls alias) to return only files within a specific folder structure.
As an example, say I'm trying to list all files whose names end in .foobar.txt that reside within a folder called src, which in turn resides in a folder called even. I've tried using the command ls -r *\even\src\*.foobar.txt | % FullName. I thought the first wildcard * in the path would allow any path that ends in \even\src\ and that the second one would match only files that end in .foobar.txt. But it isn't returning all the files I expect. Here's the structure of the directory I'm testing it in:
root
|- project1
|  |- odd
|     |- src
|     |  |- a.foobar.txt
|     |  |- b.foobar.txt
|     |  |- c.snafu.txt
|     |
|     |- temp
|        |- a.foobar.txt
|        |- b.foobar.txt
|        |- c.snafu.txt
|
|- project2
|  |- folder1
|     |- folder2
|        |- folder3
|           |- folder4
|              |- even
|                 |- src
|                 |  |- a.foobar.txt
|                 |  |- b.foobar.txt
|                 |  |- c.snafu.txt
|                 |
|                 |- temp
|                    |- a.foobar.txt
|                    |- b.foobar.txt
|                    |- c.snafu.txt
|
|- project3
|  |- odd
|     |- src
|     |  |- a.foobar.txt
|     |  |- b.foobar.txt
|     |  |- c.snafu.txt
|     |
|     |- temp
|        |- a.foobar.txt
|        |- b.foobar.txt
|        |- c.snafu.txt
|
|- project4
   |- even
      |- src
      |  |- a.foobar.txt
      |  |- b.foobar.txt
      |  |- c.snafu.txt
      |
      |- temp
         |- a.foobar.txt
         |- b.foobar.txt
         |- c.snafu.txt

The output of the above command is
root\project4\even\src\a.foobar.txt
root\project4\even\src\b.foobar.txt

However, I was expecting
root\project2\folder1\folder2\folder3\folder4\even\src\a.foobar.txt
root\project2\folder1\folder2\folder3\folder4\even\src\b.foobar.txt
root\project4\even\src\a.foobar.txt
root\project4\even\src\b.foobar.txt

How can I change my command so it also finds the files in the project2 folder?
Answer: Break it up into 2 steps. First recurse all the directories, filtering out the ones you want, then pipe that result through another get-childitem that filters out the filenames you want:
ls -Recurse -Directory | where {$_.FullName -like "*\even\src"} | ls -filter  *.foobar.txt

Answer: Was thinking of string match:
gci * -R | ? { $_.FullName -like '*\even\src\*.foobar.txt' }

Comment: Both solutions work, but I like this one slightly better for its simplicity. Thank you!
Comment: @inejwstine Yes it will work, but may be slower depending on your directory tree. But if this works fine for you - then go for it.
Comment: Agree - it's not optimised for speed, or memory. I was thinking about readability, mostly.


If the product of 2 matrices is symmetric is one of them diagonalizable?

Question: Let S be a diagonal matrix with entries > 0. Let A be a matrix with diagonalelements <= 0 and off-diagonalelements >=0. A's largest eigenvalue is 0. That is all that is known about A.
We assume that SA is symmetric and thus can be diagonalized by an orthonormal set of eigenvectors. Given this fact, can we say anything about the diagonalizability of A? E.g. could we state that diagonlizability of A follows from diagonalizability of SA? Could it be that both statements are equivalent?
Any help is deeply appreciated !
George
Answer: Let $\langle \cdot,\cdot \rangle$ be the Euclidean inner product and define $(x,y)=\langle x,Sy \rangle$. From the given properties, $S$ is positive definite, therefore this function is an inner product, which I will call the $S$-inner product.
Now given a matrix $A$, $SA$ is symmetric if and only if $A$ is self-adjoint with respect to the $S$-inner product. Therefore we can apply the spectral theorem to $A$ and the $S$-inner product. In the process we $S$-orthogonally diagonalize $A$. This diagonalization is in general not $I$-orthogonal (i.e. Euclidean-orthogonal), but it is still a diagonalization.
By the way, this property has useful applications. For example, consider an irreducible Markov chain on a finite state space, with generator $L$. (In discrete time, we have a transition matrix $P$ and let $L=P-I$). Such a chain has a unique stationary distribution. Let $S$ be the diagonal matrix whose diagonal entries are the probabilities in the stationary distribution. We say the chain is reversible if $L$ is self-adjoint with respect to the $S$-inner product. This property has physical meaning: it means that if the system is at equilibrium, then each possible transition is equilibrated by its reverse transition.
If we have a reversible Markov chain then, by the above discussion, $SL$ is symmetric. Therefore, if we are interested in the eigenproblem for $L$, we can instead consider the eigenproblem for $S^{1/2} L S^{-1/2}$. This matrix is symmetric (since $SL$ is symmetric), which makes its eigenproblem easier, and it is easy to match up eigenpairs for $S^{1/2} L S^{-1/2}$ with eigenpairs for $L$.
Comment: thanks for the quick response. Let me try to sum up what I've understood:If SA is symmetric then \[S^{1/2}FS^{-1/2}=TDT^{^{-1}}\]
is symmetric and has an orthonormal set of eigenvectors in T. As \[S^{(-)+1/2}\]
is invertible I can set \[Q=S^{-1/2}T\]
and set \[F=QDQ^{-1}\]. As T has full rank and det(S)\neq 0 Q is invertible.
Comment: It's simpler than that. If $A$ is symmetric then $A=T D T^{-1}$, where $T$ is an $S$-orthogonal matrix, meaning that $T^* S T = I$. This follows from the spectral theorem. If you prefer a purely algebraic proof (the spectral theorem is really a geometric statement), you can first change coordinates to the natural coordinates for the $S$-inner product, which are $e'_i = S^{-1} e_i$.
Comment: Oh, never mind, you just mixed up $F$ and $A$. Yes, you had it right: $S^{1/2} A S^{-1/2}$ is symmetric, so $S^{1/2} A S^{-1/2} = Q D Q^*$, now rearrange to solve for $A$ and you get $A=S^{-1/2} Q D Q^* S^{1/2}$, which is a diagonalization of $A$.


Hazelcast Jet - Use Cases

Question: What are the use-cases of Hazelcast Jet? Has anyone started using it?
Our project uses Hazelcast for Distributed Map holding Key-Value pair and Distributed computing on those Keys to run the task at the node holding the Key. We use NearCache solution as well.
I was curious to know how different is Hazelcast Jet and what problems does it solve?
Answer: As of current version (0.3), Jet's advantage over just submitting a Runnable to each partition is the ability to perform grouping by a key other than the one used in the Hazelcast map. For this to work in a distributed environment you have to send each item to the processing unit responsible for its grouping key, and this is something that is easy to get from Jet.
Further from that, you can build a multistage cascade of groupBy operations, you can have forks in your data stream to reuse the same intermediate result in more than one way, you can build a pipeline where an I/O task distributes the processing of the data it reads across all CPU cores, etc... in short, all the advantages that a full-blown DAG computation engine offers.
By the time it reaches 1.0 Jet will also support fault-tolerant infinite stream processing, event time-based windows, and more.
Answer: 2021 answer for use cases:

Change data capture streaming - Use Debezium/Hazelcast to detect changes to your database and stream to other microservices (if data is common), stream changes to a data lake, or update a search engine
Real time analytics - Take market data stream and perform technical analysis in realtime or twitter analysis
Async job processing - PDF conversion service

Hazelcast Jet - Use Cases


Laravel datatable fixed columns

Question: How can i set fixed right column(action) in laravel datatables like  this simple example  - not work in laravel). Thanks
tableWatches = $('.datatable-watches').DataTable({
        orderCellsTop: true,
        fixedHeader: false,
        dom: "Bfrtip",
        "pageLength": 50,
        "processing": true,
        "serverSide": true,
        scrollY:        true,
        scrollX:        true,
        scrollCollapse: true,

    paging:false,
    fixedColumns:   {
        leftColumns: 1,
        rightColumns: 1
    },
        "ajax": {
            url: "/admin/watches/all-watches",
            data: {
                condition: condition,
            }
        },
        "searchCols": [
       .................
        ],
        columns: [
       ..................
        ],

    });

Method, which created table content
And this part (
fixedColumns:   {
            leftColumns: 1,
            rightColumns: 1
    },

not worked, without errors and warnings, columns still arent fixed.
Answer: Need more explanation!
Totally there is no difference between plain js datatable and yajra/laravel-datatables-oracle.
If you wanna use it locally, just need a 100% with table:

And a js script to feed datatable by jso data:
$('#users').DataTable({
    responsive: true,
    "data": [
     {
         "first_name": "the first name1",
         "last_name": "the last name1"
     },
     {
         "first_name": "the first name2",
         "last_name": "the last name2"
     },
    ]
    "columns": [
     {
         data: "first_name", title: 'first_name',
         width: '10%', // You can define each column width in the table
         sortable: true,
         searchable: false
     },
     {
         data: "last_name", title: 'last_name',
         width: '10%',
         sortable: true,
         searchable: false
     }
    ]
});

Also for server side feeding datatables, Just use ajax:
$('#users').DataTable({
        responsive: true,
        "columns": [
         {
             data: "first_name", title: 'first_name',
             width: '10%', // You can define each column width in the table
             sortable: true,
             searchable: false
         },
         {
             data: "last_name", title: 'last_name',
             width: '10%',
             sortable: true,
             searchable: false
         }
        ]
        ajax: {
            url: your_post_url_returning_datatable_object_json,
            type: 'POST'
        },
    });

As i mentioned, you can define each column of table or make horizontally scrollable:
scrollX: '100%',

Laravel datatable fixed columns


Proving there doesn't exist a subgroup of order $2$

Question: I'm trying to follow an argument made in one of Benedict Gross's online abstract algebra lectures.
He first proves that given $W \subset V$ a subspace of dimension $m$ (ambient vector space $V$ has dimension $n$), then it can be extended to a basis by adding vectors $v_{m+1}, \ldots, v_n$. The claim is then that if $f$ is the canonical homomorphism $V \to V/W$, then $f(v_{m+1}), \ldots, f(v_n)$ is a basis for $V/W$. (I haven't proved this, but for the moment I'm taking it for granted.) So $W' = \mathrm{span}(v_{m+1}, \ldots, v_n)$ is isomorphic to $V/W$, so $V/W$ can be thought of as a subgroup of $V$.
The key insight is that this cannot be done with groups, but I don't fully understand the details. First, we notice that
\begin{align*}
\mathbb{Z}/2\mathbb{Z} \cong \frac{2\mathbb{Z}}{4\mathbb{Z}} \leq \mathbb{Z}/4\mathbb{Z},
\end{align*}
which is fine. Call $H = \frac{2\mathbb{Z}}{4\mathbb{Z}}$ and $G = \frac{\mathbb{Z}}{4\mathbb{Z}}$. The argument is that, then, unlike in the case of vector spaces, I can't find another cyclic group of order $2$, $H'$ s.t. $G/H' \cong G/H$ because $H \to 0$ in the homomorphism $f$.
I'm only understanding bits and pieces of this. I'm hoping someone can clarify this.
Comment: The quotient group $\;2\Bbb Z/4\Bbb Z\;$ is *not* subgroup of $\;\Bbb Z/4\Bbb Z\;$ , as written there...
Answer: Every quotient vector space $V/W$ is isomorphic to a vector subspace of $V$, by the argument you cite.
Gross' point is that the analogous claim does not hold for groups: not every quotient group $G/H$ is isomorphic to a subgroup of $G$.  But some quotient groups do admit such an isomorphism!  Your example is one of them: you have $G/H\cong H\leq G$.
When there exists such an isomorphism, we say the quotient map "splits".
For an example that does not split, consider $G=\mathbb{Z}$ and $H=2\mathbb{Z}$. Then $G/H$ contains an element $x$ such that

$x+x=0_{G/H}$ but
$x\neq 0_{G/H}$.

Any group isomorphic to $G/H$ must contain such an element, so any group containing an isomorphic copy of $G/H$ must hold such.  But $G$ contains no such element.


Ornaments in ABRSM theory, start on the note or the note above?

Question: I know that depending on the era you can either start on the note or note above in some ornamentation such as a turn or mordent.
For Abrsm grade 8 theory do you start on the note or the note above so for example for a turn on a C would it be?
C D C B C
Or D C B C
Answer: Baroque music was the only era were you would start on the upper-auxiliary note. All the other eras you should start on the principal note. The turn must fit in the note values that are given. A slow piece may have more notes in a trill for instance and a faster trill less.
As is the way with these things you have certain amount of artistic licence in the playing of ornaments, as long as it fits and it leads neatly to the next note, you should be ok.
Answer: Ornaments in general begin on the written note.  A turn written above C would be played C-D-C-B-C; a reverse turn would be C-B-C-D-C.
Most ornaments have a shape that sort of describes how you play it - the turn curls up, then down to its lowest point, then back to a point horizontal with its start.  It's going to sound like the shape: up, back, down, back.


InvalidOperationException: Cannot create a DbSet for 'ApplicationUser' because this type is not included in the model for the context

Question: Já tenho um database criado no Sql Server, então executei comando:
PM> Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Teste;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Entities

Depois do comando, criou uma pasta "Entities", depois disso segue código em DbContext:
TesteContext : DbContext
public partial class TesteContext : DbContext
{
    public virtual DbSet<AspNetRoles> AspNetRoles { get; set; }
    public virtual DbSet<AspNetUserClaims> AspNetUserClaims { get; set; }
    public virtual DbSet<AspNetUserLogins> AspNetUserLogins { get; set; }
    public virtual DbSet<AspNetUserRoles> AspNetUserRoles { get; set; }
    public virtual DbSet<AspNetUsers> AspNetUsers { get; set; }

    etc ...
}

ApplicationDbContext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}

Startup.cs:
// Add framework services.
services.AddDbContext<TesteContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<TesteContext>()
    .AddDefaultTokenProviders();

AccountController:
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
            // Send an email with this link
            //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            //var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
            //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
            //    $"Please confirm your account by clicking this link: link");
            await _signInManager.SignInAsync(user, isPersistent: false);
            _logger.LogInformation(3, "User created a new account with password.");
            return RedirectToLocal(returnUrl);
        }
        AddErrors(result);
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

O problema está na linha:
var result = await _userManager.CreateAsync(user, model.Password);

Erro:

InvalidOperationException: Cannot create a DbSet for 'ApplicationUser'
  because this type is not included in the model for the context.

Eu tento criar uma nova linha no bando de dados "Teste".
Alguma solução ?
Answer: Você definiu dois contextos diferentes: TesteContext e ApplicationDbContext.
Vou focar no contexto da Identity.
Startup
Use o ApplicationDbContext para AddEntityFrameworkStores:
services.AddIdentity<ApplicationUser, IdentityRole>()
   .AddEntityFrameworkStores<ApplicationDbContext>()
   .AddDefaultTokenProviders();

No método Configure adicione ( só confirmando ):
app.UseIdentity();


Justification of algebraic manipulation of infinitesimals

Question: As an engineering student, I regularly see people making arguments like this:
Consider a rectangle of dimensions $x\times 4x$. If we make $x$ bigger by a small quantity $dx$ then this will make $4x$ bigger by $4\cdot dx$ so the area of that $x \times 4x$ rectangle will change from $4x^2$ to $$(x+dx)(4x+4dx)=4(x^2+2x\cdot dx+(dx)^2)\approx4x^2+8x\cdot dx$$
with the final step justified because $dx$ is a 'small' quantity so $(dx)^2$ will be so small as to be ignorable in some mathematically rigorous way. Thus the change in area $dA$ would be $8x\cdot dx$.
Arguments like this are very common. Another random example would be in Wikipedia's proof of the brachistochrone problem which starts with the statement
$$ds^2=dx^2+dy^2$$
and proceeds to manipulate these infinitesimals as if they were ordinary constants or variables.
I'm wondering if there's a simple, analytically rigorous justification for all of this manipulation. While I feel perfectly comfortable with the idea of the derivative of a function (considered as a limit), I've never seen a similar, rigorous justification for the algebraic manipulation of infinitesimals and the cancellation of 'small' terms (like $(dx)^2$). Any thoughts or help would be appreciated.
Thankyou
Comment: This is what gave calculus a bad reputation. An infinitesimal is arbitrarily small, therefore in your above example $8x.dx$ should also be neglected. In SIA for example lone infinitesimals always cancel out so such situations never arise. If someone doing actual physical measurements has a *finite* i.e. practical definition of 'infinitesimal' they should say so and not pretend it's genuine mathematics.
Answer: I will just throw a few buzzwords at you :-)
The mathematically precise concept of "infinitesimal" is called "differential form". If we fix the Euclidean plane $\mathbb{R}^2$ and think of it as a "differentiable manifold", then every point in the plane has a tangential space that is "isomorph to" (or another copy of) $\mathbb{R}^2$. If we further fix a cartesian coordinate system with coordinates x and y, then a differential form is a gadget that assigns for every point p with coordinates $(x_p, y_p)$ to a tangent vector at that point a real number.
If you think of attaching a vector pointing upwards with the length of on, (0, 1), at every point in the plane, then in our example dx would spit out 0 at every point and dy would spit out 1 at every point.
This is the starting point for modern abstract "coordinate free" differential geometry.
From my experience, these concepts are usually not easy to understand for beginners, so don't worry if you don't understand everything on a first reading.
First note that you don't need the concept of a "differential form" to understand your first example:
Take a rectangle with side lengths a and b, then we have a function that gives the area,
$$
f: \mathbb{R}^2 \to \mathbb{R}
$$
$$
f: (a, b) \mapsto ab
$$
If you increase both of the coordinates by h, then this is just a directional derivative, and since $f$ is differentiable we know that
$$
f(a + h, b + h) - f(a, b) = df*(h, h) + o(h^2)
$$
holds. Here "dx" is just short hand notation for both "h" and "we know that f is differentiable and therefore that the remainder of the right hand side is $o(h^2)$, that is for smaller and smaller h the linear approximation gets better and better". The linear approximation is by definition given by applying the differential $df$ of $f$ to the vector $(h, h)$.
The second example is a little bit more complicated, here we'll really need the concept of "differential forms". To be mathematically precise, we'd have to write
$$
ds^2 := dx \otimes dx + dy \otimes dy
$$
That is, the left hand side is defined by the right hand side, and the right hand side consists for a fixed point of elements of the tensor product of the cotangential space $T^*_pM$ with itself.
This means this gadget eats two tangential vectors on any tangent space and spits out a real number, and this operation is bilinear (linear in both input variables). So, if you fix a point on the plane, you get an element of the space
$$
T^*_pM \otimes T^*_pM
$$
which has an algebraic structure that can be used.
If you would like to learn more about this, I'd recommend any textbook on differential geometry or differentiable manifolds.
Comment: ... Now differential forms a a wonderful thing but asserting that an infinitesimal "is" a differential form is a bit misleading.
Comment: Euclid's Elements in book V, definition 4 states that two magnitudes are comparable when they are capable of exceeding one another when multiplied sufficiently many times. Leibniz wrote in 1695 that his infinitesimals violate Euclid V.4. In modern terminology, this means that Leibnizian infinitesimals are "non-Archimedean" (this certainly does not mean that Leibniz was either familiar with or "anticipated" modern non-archimedean theories). At any rate the historic meaning of infinitesimal in analysis is clearly Leibniz's...
Answer: You will hear a lot about differentials, exterior algebra and maybe even about nonstandard analysis. But the sad fact is: In over 300 years of calculus we have not come up with an easy answer to your question. All one can say is: If in a particular case "all of this manipulation" leads to a correct result, then there is also an "analytically rigorous justification" for it.
If done with professional expertise, dealing with "differentials" of all sorts in a lighthanded way is definitely a successful heuristic technique, especially in an environment where one doesn't care so much about $\epsilon$'s and $\delta$'s. But some care is needed: When you argue about the area under a curve $\gamma\!: y=f(x)$ you don't have to bother about the increase of $f$ in an interval of length $dx$, but if you want to derive a formula for the length of $\gamma$, then this little increase of $y$ plays a decisive rôle.
Comment: 'All one can say is...' No, this is not all one can say. '[...] then there is also an "analytically rigorous justification" for it.' You seem to be using "rigorous" in contradistinction to "nonstandard analysis." There is nothing nonrigorous about nonstandard analysis.
Comment: @Ben Crowell: Of course not. What I'm saying is that the various frameworks invented to salvage our everyday handling of "infinitesimals" are no easy answers to the question posed by the OP.
Answer: There are various ways of answering your question. Tim van Beek has given one in terms of differential forms. Another nice way of looking at it is using nonstandard analysis (NSA). The nice thing about NSA, to my taste, is that it allows you say things the way that Leibniz and Gauss and Euler found it so useful to say them (i.e., with dx's and dy's), and it also allows you to be certain that what you're doing is logically rigorous. NSA doesn't have to be hard and scary. Jerome Keisler wrote a very nice freshman calculus book using NSA, now available online for free: http://www.math.wisc.edu/~keisler/calc.html My own book, using a similar approach, is here: http://www.lightandmatter.com/calc/ This is also a very nice treatment: http://www.math.uiowa.edu/~stroyan/InfsmlCalculus/InfsmlCalc.htm
The basic idea of NSA is that just as we expanded the integers to the rationals, and the rationals to the reals, we go one more step and expand the reals to the hyperreals. The hyperreals are a number system that includes the reals, but that also includes infinitesimals. The way you know whether you're doing something logically correct is that if you write down all of the elementary axioms of the real number system (x+y=y+x, etc.), then all of those are true in the hyperreals. "Elementary" means axioms that only say things like "for every number...," not ones that say "for every set of numbers..."
Comment: Thanks, I had wondered if NSA would pop up here, though I've only heard of them fleetingly. I'll finish Spivak, maybe do some conventional analysis, then get back to this :)
Answer: This stems from simple theorem regarding the change of variables, also called substitution, used for integration: $\int {f\left( {g\left( t \right)} \right)g'\left( t \right)dt}  = \int {f\left( y \right)dy} $. If we put $g\left( t \right) = y$ in $\int {f\left( {g\left( t \right)} \right)g'\left( t \right)dt} $, we have $\int {f\left( y \right)\frac{{dy}}
{{dt}}dt}  = \int {f\left( y \right)dy} $ which we know is true from the theorem. So, when we integrate, it's allowed for us to think that, when $y = g\left( t \right)$, then $dy = g'\left( t \right)dt$.
In your example, you have $y\left( x \right) = 4{x^2}$,  and want to calculate $y'\left( x \right)$. We have $y'\left( x \right) = \frac{{dy}}{{dx}} = 8x$ (you forgot to multiply by $x$ in your example). Now, we use abuse of notation to write $dy = 8xdx$.
Similar arguments can be made with integration of multivariate functions. Such consideration gives rise to differential forms.
Comment: Unfortunately, no. As Tim has diligently written, when there is more than one variable involved, differential forms come into play. But for univariate functions, that's the background for such abuse of notation. Another justification for using "d" notation is  , which can be understood that it is "valid" to cancel out terms in expressions like this $\frac{{dz}}
{{dy}}\frac{{dy}}
{{dx}} = \frac{{dz}}
{{dx}}$
Comment: thanks, I fixed it. So are you saying that all of the manipulation of infinitesimals I demonstrated can be justified using the substitution rule?
Comment: That does make some sense though - when we go from $\frac{dy}{dx} = f(y)g(x)$ to $\frac{dy}{f(y)}=g(x)\cdot dx$ we are really just applying the substitution rule in diguise
Answer: Synthetic differential geometry (abbreviated SDG, and also known as smooth infinitesimal analysis) is a rigorous approach to analysis and differential geometry using nilpotent infinitesimals. Grothendieck emphasized the importance of nilpotent infinitesimals in algebraic geometry, and synthetic differential geometry is often just axiomatizing his ideas, and making them more accessible to analysts and differential geometers. The algebraic side to SDG involves Artinian local rings, but the beauty of SDG is that the algebraic machinery is mostly hidden away from the user, making it much more accessible. Practical applications of SDG include automatic differentiation, which is used to efficiently calculate derivatives on computers (e.g. for the purposes of machine learning).
Robinson's nonstandard analysis has a similar goal to SDG, but is analytic rather than synthetic, and is less flexible in that it requires invertible infinitesimals. There are models of SDG which have invertible infinitesimals, but most models do not.
The main idea of SDG is that we work inside a "mathematical universe" where all our objects are smooth spaces and all functions are smooth. Such a universe is called a smooth topos, and there are many examples of such universe constructed for the purpose of algebraic and differential geometry. But the beauty is that you don't have to worry about the details of topos theory: you can just use familiar set-theoretic notation as long as you observe the axioms of the theory.
In our smooth mathematical universe, the number line $\mathbf{R}$ has been enriched with nilpotent infinitesimals, e.g., the subset $D = \{ \delta \in \mathbf{R} \mid \delta^2 = 0 \}$. A function $\gamma: D \to M$ is interpreted as an infinitesimal curve in a space $M$, and the set of such functions, $M^D$ is the tangent bundle to the space $M$. To make the magic of SDG happen, we require that every infinitesimal curve $\gamma: D \to \mathbf{R}$ is of the form
$$\gamma(\delta) = y + \delta y'$$
for unique $y,y' \in \mathbf{R}$. In other words, such curves are always given by polynomials of degree at most 1. This is called the Kock-Lawvere Axiom, and can be stated in algebraic language as:
Kock-Lawvere axiom: The evaluation homomorphism $\mathbf{R}[\varepsilon] \to \mathbf{R}^D$ given by $a + \varepsilon b \mapsto (\delta \mapsto a + \delta b)$ is an isomorphism of $\mathbf{R}$-algebras.
In particular, given any $f: \mathbf{R} \to \mathbf{R}$, the Kock-Lawvere axiom implies that
$$f(x+\delta) = f(x) + \delta f'(x)$$
for any $\delta \in D$. Since $\delta$ is nilsquare we don't have to worry about error terms in Taylor approximations: they become exact. We can then reason much more geometrically.
If you are interested in learning how to use infinitesimals rigorously, I'd recommend Anders Kock's SDG books. The first is available for free here. Lavendhomme has a nice SDG book as well, but it's quite expensive.


SQL Azure retry logic using EnterpriseLibrary.TransientFaultHandling

Question: Trying to implement a retry logic in a correct way, but couldn't find any good sample on how to properly leverage EnterpriseLibrary.TransientFaultHandling.
So far I found two samples:
First - using ReliableSqlConnection & conn.Open(retryPolicy)
var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1));
var retryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(retryStrategy);

retryPolicy.ExecuteAction(() =>
{
    using (var conn = new ReliableSqlConnection(datasetConnectionString))
    {
        conn.Open(retryPolicy);

        using (var command = conn.CreateCommand())
        {
            command.CommandText = insertToParameters;
            command.CommandTimeout = 0;
            conn.ExecuteCommand(command);
        }
    }
});

and second - without the ReliableSqlConnection:
var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1));
var retryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(retryStrategy);

retryPolicy.ExecuteAction(() =>
{
    using (var conn = new SqlConnection(datasetConnectionString))
    {
        conn.Open();

        using (var command = conn.CreateCommand())
        {
            command.CommandText = insertToParameters;
            command.CommandTimeout = 0;
            conn.ExecuteCommand(command);
        }
    }
});

So few questions:

which one is better and why?
Is the external retryPolicy.ExecuteAction really needed - in older samples I see people retrying only individual actions, like OpenConnectionWithRetries, ExecuteCommandWithRetries, etc, but not the whole thing - I wonder if that is possible that the connection could potentially be closed between those retries.
Answer: Answering my own question:
With newer transient error handling block, use SqlConnection with the provided extension methods, such as OpenWithRetry, etc.
Use retryPolicy.ExecuteAction(() => {...}) whenever there is no support for the retry in the API, such as SqlBulkCopy, filling the dataset table, async methods etc. Make sure to re-open connection in the retry block. You still can use the SqlConnection with retry-able extension methods inside the retry block.
UPDATE: edited to cause less confusion
Answer: The best pattern to use is RetryPolicy.ExecuteAction(() => .     Wrap your database interactions into an ExecuteAction() lambda and treat that as a unit of work.   This maintains the highest level of compatibility with ADO.Net's APIs.  It also allows you to work with the new Async methods in ADO.Net.
The ReliableSQLConnection is primarily offered for backward compatibility.
Comment: I wouldn't call ReliableSqlConnection as obsolete - it has its own usage with retry-able calls, where you don't have to re-open connection by yourself.


How to solve this fractional PDE?

Question: $F_x = F*F_y = F^2*Fz$,
where $F = F(x,y,z)$.
So far I could solve the reduced problem considering either of the equalities:
$F_x = F*F_y$
Which yields me:
$F(x,y) = \frac{-y}{x+c}$
Comment: This is not, strictly speaking, a "fractional PDE," unless your differential operators have some unstated fractional order.
Comment: try separation of variables - write $f(x,y,z)=X(x)Y(y)Z(z)$
Comment: @WW1 I couldn't find a solution of that form
Comment: @MichaelLee my bad, I didn't know how to classify this PDE so I thought fracional would be intuitive since the function itself equals the fraction of its partial derivatives
Answer: $$F_x = F*F_y = F^2*Fz$$
If I well understand, you have two dependent PDEs.
FIRST PDE :$\quad F_x - F*F_y=0$
With the method of characteristics, the system of characteristic equations is :
$$\frac{dx}{1}=\frac{dy}{-F}=\frac{dF}{0}$$
A first family of characteristic curves comes from $\quad dF=0 \quad\to\quad F=c_1$
A second family of characteristic curves comes from $\quad \frac{dx}{1}=\frac{dy}{-c_1} \quad\to\quad y+c_1x=c_2\quad\text{or}\quad y+xF=c_2$
The general solution of the PDE is expressed on the form of the implicit equation :
$$F=\Phi(y+xF)$$
where $\Phi(X)$ is an arbitrary differentiable function.
The particular solution that you found $\quad F=\frac{-y}{x+c}\quad$ corresponds to the case of the particular function $\quad \Phi(X)=-X/c$ .
Since $F$ includes an independent variable $z$, the correct writing is :
$$F(x,y,z)=\Phi\big(z\:,\:y+xF(x,y,z)\big)$$
where $\Phi$ is an arbitrary differentiable function of two variables.
SECOND PDE :$\quad F_y - F*F_z=0$
The same method leads to the general solution on implicit form :
$$F(x,y,z)=\Psi\big(x\:,\:z+yF(x,y,z)\big)$$
where $\Phi$ is an arbitrary differentiable function of two variables.
NOTE :
Alternatively we could solve the PDE : $\quad F_x = F^2*Fz\quad$ which leads to
$$F(x,y,z)=\Theta\big(y\:,\:z+xF^2(x,y,z)\big)$$
where $\Theta$ is an arbitrary differentiable function of two variables.
But the functions $\Phi$ , $\Psi$ and $\Theta$ are not independent. So only two of them are sufficient to solve the problem.
RESULT :
The general solution of the associated PDEs $\quad F_x = F*F_y = F^2*Fz \quad$ is :
$$F(x,y,z)=\Phi\big(z\:,\:y+xF(x,y,z)\big)=\Psi\big(x\:,\:z+yF(x,y,z)\big)$$
where $\Phi$ and $\Psi$ are two independent arbitrary differentiable functions, each one of two variables.
Usually the arbitrary functions are determined according to some boundary conditions. Since there is no boundary condition specified in the wording of the question, one cannot go further.
Comment: Could the boundary condition F(0,y,z) = -z/y determine the arbitrary functions?
Comment: Yes, with the condition $\quad F(0,y,z)=-z/y\quad$ the solution is : $$x\left(F(x,y,z)\right)^2+yF(x,y,z)+z=0$$which means:$$F(x,y,z)=\begin{cases}-\frac{z}{y}\quad\text{if}\quad x=0\\ \frac{-y+\sqrt{y^2-4xz}}{2x}\quad\text{if}\quad x\neq 0\quad\text{and}\quad y>0\\ \frac{-y-\sqrt{y^2-4xz}}{2x}\quad\text{if}\quad x\neq 0\quad\text{and}\quad y<0\end{cases}$$
Comment: great! Thanks :)

How to solve this fractional PDE?


Equation for trapezoidal wave equation

Question: I'm writing a c function to generate trapezoidal wave. Does any one know a mathematical equation to generate trapezoidal wave? Very similar idea as y=A*sin(B*x) generates a sin wave for different values of x.
Comment: I've seen this done by clipping a triangle wave.
Comment: The mathematical formula for a trapezoidal wave is

`f(x) = 0, if (0 < x < t1); a*(x-t1), if (t1 < x < t2); a*(t2-t1), if (t2 < x < t3); -b * (x-t3), if (t3 < x < p); f(x-p), if (p < x);`
Answer: There's an equation you can use instead of restrictions.
a/pi(arcsin(sin((pi/m)x+l))+arccos(cos((pi/m)x+l)))-a/2+c

a is the amplitude
m is the period
l is the horizontal transition
c is the vertical transition

Plus this is a direct trigonometric function, even though it could be longer,and a little more complicated.
Answer: A way of sending a single pulse of trapezoidal wave includes using the Heaviside Step Function http://en.wikipedia.org/wiki/Heaviside_step_function
Use it if you want the "pure" mathematical way of representing this kind of function. Just build your function "piece by piece", multiply the first piece by a heaviside that "activates" when x = the beginning of your pulse. For the next piece, first subtract the last function, then add the new piece mathematical function, multiply it by the adequate heaviside function and so on. It should end something like this (if you don't get it, go through the wikipedia article):
H(n) := (x >= n)?1:0;
y := H(0)*(x) + H(1)*(-x + 1) + H(2)*(-(-x + 1) + (3-x));

However, for code simplicity and efficiency, lets use an if statement. Consider a 45-degree trapezoidal wave, with constant unitary velocity.
float trapezoidalWave(float x, float t) {

    float y;

    if ( x <= t + 1 ) {
        // 45 degree ascending line
        y = x - t;
    } else if ( x <= t + 2) {
        // horizontal line
        y = 1;
    } else if (x <= t + 3) {
        // 45 degree descending line
        y = t + 3 - x;
    } else {
        y = 0;
    }

    return y;

}

If you want a "long wave" and not just one pulse, work with modules (%), if you don't need the time variable, just replace it by 0.

Equation for trapezoidal wave equation


Errors while changing unity3d movement to drag (c#)

Question: My errors are

'UnityEngine.Collider2D' is a 'type' but is used like a 'variable'
The best overloaded method match for 'UnityEngine.Vector3.Vector3(float, float, float)' has some invalid arguments
Argument '1': cannot convert from 'double' to 'float'
using UnityEngine;
using System.Collections;

public class MoveRacket : MonoBehaviour {
    public float speed = 30;
    public string axis = "Vertical";
    public object racket = "Racket";
    public bool touchInput = true;
    public Vector2 touchPos;

    void FixedUpdate () {

        //used to not have anything in parentheses
        //float v = Input.GetAxisRaw (axis);
        float v = Input.GetAxisRaw (axis);
        GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, v) * speed;
        if (Input.touchCount == 1)
        {
            Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            Vector2 touchPos = new Vector2(wp.x, wp.y);
            if (Touch = Physics2D.OverlapPoint(touchPos))
            {
                this.transform.position =  new Vector3 (3.94,wp.y,0);

        }
        }
    }
}

Answer: You have 2 issues here.  The first being you are trying to assign the Collider2D result of Physics2D.OverlapPoint(touchPos) to the unity struct type of Touch.  Not really sure what your intentions are here.  If you just want to test if the touchPos overlaps, then use this code:
public class MoveRacket : MonoBehaviour {
public float speed = 30;
public string axis = "Vertical";
public object racket = "Racket";
public bool touchInput = true;
public Vector2 touchPos;

void FixedUpdate () {

    //used to not have anything in parentheses
    //float v = Input.GetAxisRaw (axis);
    float v = Input.GetAxisRaw (axis);
    GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, v) * speed;
    if (Input.touchCount == 1)
    {
        Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
        Vector2 touchPos = new Vector2(wp.x, wp.y);
        if (Physics2D.OverlapPoint(touchPos) != null)
        {
            this.transform.position =  new Vector3 (3.94f,wp.y,0);

    }
    }
}
}

Your other issue was that the value of 3.94 is being treated as a double data type, when the vector3 constructor expects a float.  To interpret it as a float, add an "f" to the end of the number.
Comment: Just did sorry I forgot to earlier.


Having trouble with regular expression in javascript not validating when it should

Question: Hello i am trying to validate some form input where the format needs to be.
GBR (Exactly) followed by [1-9] for 1 digit then [0-9] for 2 digits and then nothing else.
I am using it inside some jquery.
<code>            jQuery(function(){
            jQuery("#P3_P_CODE").validate({
                expression: "if (VAL.match(/^\w[GBR]{1,3}[1-9]{1,1}\d[0-9]{1,1}$/)) return true; else return false;",
                message: "Should be a valid Project format"
            });
        });
</code>
Meaning that
<code>/^\w[GBR]{1,3}[1-9]{1,1}\d[0-9]{1,1}$/
</code>
is my regular expression.
The problem that i am having is that no matter what i type into the input box i am still presented with an error message meaning that my regular expression must be incorrect.
I have tried several different combinations in my REGEXP to no avail.
Any help would be appreciated
Comment: this page will probably help you http://stackoverflow.com/questions/280759/jquery-validate-how-to-add-a-rule-for-regular-expression-validation
Answer: <code>/^GBR[1-9]\d\d$/
</code>
<code>[GBR]</code> means one of those characters.
Comment: According to the documentation there is no "expression" option.
Comment: I see what you mean :) i have added your changes but it is still not accepting a value of GBR101 for instance.
Comment: The regular expression works: [example](http://jsfiddle.net/ZMXGe/). What plugin are you using for validation?
Comment: I am Using

Comment: Ahhh briliant, so obviously no matter what i entered mine would of returned false, my mistake i'll see if i can find a library that includes an expression option.