Statistical test to show the importance of one cluster

Question: I have one dataset of two variables (x,y). When the data is plotted in a 2D diagram, I see some data points create a good cluster, while the other data points are scattered randomly.
Here is an example:

(These data points were collected through an experiment. The weight is equal among all points. After plotting the data points, I found that some points can create a cluster. Then, I changed the color of these points to green color to show those better.)
Based on the plot, I have two clusters: (1) Green points (2) Red Points. Each data point in both clusters has two variables: X, Y.
My question is that:
How can I conduct a statistical test to (statistically) show that the Green cluster has lower entropy than the red cluster?

H0: No differences
Ha: Green cluster is statistically better (Less Entropy) than the red cluster.

I actually want to show that among all data points (Red + Green), the green data points create a good cluster.
Comment: How were the clusters identified, exactly?
Comment: These data points were collected through an experiment. The weight is equal among all points. After plotting the data points, I found that some points can create a cluster. Then, I changed the color of the points with green color to shows those better. I want to discuss that some data points (green data points) can create a cluster. To this end, I need to statistically show what I told in the question.
Comment: Because the identification of the cluster was subjective (albeit, no doubt, well informed by expertise) and irreproducible, no statistical test can provide reliable results--and in particular, you cannot sanctify your judgment by applying any such test.  Since it is self-evident that the green cluster has much lower entropy than the red points, why not just compute and report the resulting entropies?
Answer: It's more about the ability to apply an algorithm which can discern the two clusters.  Yes, you can see the two clusters, but typical statistical tests of e.g. means won't help since objects colored green are surrounded by red.   Thus, try K-nearest neighbors (kNN), with $k=3$.  This would essentially involve selecting each object one at a time, finding out the majority class (e.g. color)  among the 3 closest neighbors of the object based on Euclidean distance, and then assigning the majority class to the object.   (for example, if 2/3 of the 3 closest neighbors are green, then you assign the predicted class of green to the test object).  Here, you are predicting class membership based on the majority class (green or red) among the 3 closest neighbors.   Simply increment by 1 the elements in a confusion matrix to determine classification accuracy, call this $A$.  Since you know the true class (colors shown), you can rerun the same steps but only this time randomly shuffling the true class feature (red/green) over all objects.  Repeat this $B=10000$ times, calculate $A^*$ for each iteration, and the number of times the classification accuracy of objects after shuffling (the color feature) $A^*$ exceeds $A$ divided by $B$ is the statistical p-value.  This is merely called a randomization test, or empirical p-value testing.
FYI - kNN is the optimal first choice to identify a smaller cluster of objects buried inside of other objects in other clusters.  Linear discriminant analysis commonly won't pick this up -- and your dataset is the classic picture for which kNN can do better than many others.  Support vector machines (SVM) with a radial basis function (RBF) kernel can pick up the green cluster, but it's computationally more expensive than kNN, and therefore violates Occam's Razor - simpler is better.
Answer: Clustering is typically a very subjective exercise. Whether clusters are good or not depend on the problem you are solving.
If you want a numeric way to check for low entropy, you can try mean distance between observations or RMS distance between observations.
Final point is that it's not a good idea to do clustering on 2 variables. We do clustering because there are so many variables that we can't visualise. If we can plot then better to check visually and create.


Como substituir um teclado por um UIPickerView?

Question: Tenho um programa, que um trecho do formulário, no caso um UITextField, que precisa ser preenchido. Mas em vez de surgir um teclado, preciso que apareça um UIPickView, que já possui as opções para o preenchimento.
Então no momento que o usuário for iniciar a ediçaõ deste UITextField, preciso que em vez do teclado, apareça um UIPickView.
O programa é para iOS, usando Objective-C.
Comment: Não entendi o voto de fora de escopo. Entendo que a pergunta é ampla demais, ou até não esteja clara o suficiente. No escopo ela deve estar, pois aparenta ser uma pergunta de programação.
Comment: Vou editar para melhorar a explicação.
Comment: Fiz uma edição na pergunta para melhorar o entendimento. Espero que tenha ficado mais claro agora.
Answer: Basta você adicionar o seu UIPickerView na propriedade inputView do UITextField. Supondo que tenha algo assim ao iniciar sua View Controller:
_picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 270.0f)];
[_picker setDelegate:self];
[_picker setDataSource:self];

Adicione ao seu input:
[self.inputSelect setInputView:_picker];

Então, vai implementando o delegate apropriado para o seu caso.
Comment: Obrigado, vou testar aqui e ja digo se funcionou!
Comment: Desculpe esqueci do detalhe, era para iOS 8
Comment: Tudo bem, mas de qualquer forma o meu teste foi justamente no iOS 8, Xcode 6 GM.
Comment: O SOF poderia permitir mais de uma alternativa como resposta para o mesmo problema, já que tem coisas que podem ser feitas de 2 a 3 formas possiveis. :\
Answer: O problema esta no iOS 8. Para resolver
pickerView = [[UIPickerView alloc] init];

[pickerView setDataSource: self];
[pickerView setDelegate: self];

[pickerView setFrame: CGRectMake(xPoint, 50.0f, pickerWidth, 200.0f)];

pickerView.showsSelectionIndicator = YES;

[pickerView selectRow:2 inComponent:0 animated:YES];

[self.view addSubview: pickerView];
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0,xPoint , pickerWidth)]; // add autorelease if you don't use ARC

v.backgroundColor = [UIColor clearColor];
[v addSubview:pickerView];
editUFCRM.inputView = pickerView;


Custom form new user error in Alfresco

Question: How can I make a custom user profile ? I want to add a new field to the users in Alfresco...
I try to use this : http://ecmarchitect.com/archives/2012/02/27/1555, the code : http://ecmarchitect.com/images/articles/alfresco-people/someco-people.zip...
Important code:

SignUserFactory.java

package com.someco.share;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

import org.alfresco.web.site.SlingshotUserFactory;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.extensions.surf.FrameworkUtil;
import org.springframework.extensions.surf.RequestContext;
import org.springframework.extensions.surf.exception.ConnectorServiceException;
import org.springframework.extensions.surf.exception.UserFactoryException;
import org.springframework.extensions.surf.site.AlfrescoUser;
import org.springframework.extensions.surf.support.ThreadLocalRequestContext;
import org.springframework.extensions.surf.util.StringBuilderWriter;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.connector.Connector;
import org.springframework.extensions.webscripts.connector.ConnectorContext;
import org.springframework.extensions.webscripts.connector.HttpMethod;
import org.springframework.extensions.webscripts.connector.Response;
import org.springframework.extensions.webscripts.json.JSONWriter;

public class SomeCoUserFactory extends SlingshotUserFactory {

    public static final String SCP_BIRTH_DATE = "{http://www.someco.com/model/people/1.0}birthDate";
    public static String SCP_SHIRT_SIZE = "{http://www.someco.com/model/people/1.0}shirtSize";
    public static String SCP_SIGNIFICANT_OTHER = "{http://www.someco.com/model/people/1.0}significantOther";
    public static String SCP_LIKES_NEIL_DIAMOND = "{http://www.someco.com/model/people/1.0}likesNeilDiamond";
    public static String PROP_SCP_BIRTH_DATE = "birthDate";
    public static String PROP_SCP_SHIRT_SIZE = "shirtSize";
    public static String PROP_SCP_SIGNIFICANT_OTHER = "significantOther";
    public static String PROP_SCP_LIKES_NEIL_DIAMOND = "likesNeilDiamond";

    @Override
    protected AlfrescoUser constructUser(JSONObject properties, Map<String, Boolean> capabilities,
            Map<String, Boolean> immutability) throws JSONException {
        AlfrescoUser user = super.constructUser(properties, capabilities, immutability);
        user.setProperty(PROP_SCP_BIRTH_DATE, properties.has(SCP_BIRTH_DATE) ? properties.getString(SCP_BIRTH_DATE) : null);
        user.setProperty(PROP_SCP_SHIRT_SIZE, properties.has(SCP_SHIRT_SIZE) ? properties.getString(SCP_SHIRT_SIZE) : null);
        user.setProperty(PROP_SCP_SIGNIFICANT_OTHER, properties.has(SCP_SIGNIFICANT_OTHER) ? properties.getString(SCP_SIGNIFICANT_OTHER) : null);
        user.setProperty(PROP_SCP_LIKES_NEIL_DIAMOND, properties.has(SCP_LIKES_NEIL_DIAMOND) ? properties.getString(SCP_LIKES_NEIL_DIAMOND) : null);
        return user;
    }

    @Override
    public void saveUser(AlfrescoUser user) throws UserFactoryException {
        RequestContext context = (RequestContext)ThreadLocalRequestContext.getRequestContext();
        if (!context.getUserId().equals(user.getId())) {
            throw new UserFactoryException("Unable to persist user with different Id that current Id.");
        }

        StringBuilderWriter buf = new StringBuilderWriter(512);
        JSONWriter writer = new JSONWriter(buf);

        try {
            writer.startObject();

            writer.writeValue("username", user.getId());

            writer.startValue("properties");
            writer.startObject();
            writer.writeValue(CM_FIRSTNAME, user.getFirstName());
            writer.writeValue(CM_LASTNAME, user.getLastName());
            writer.writeValue(CM_JOBTITLE, user.getJobTitle());
            writer.writeValue(CM_ORGANIZATION, user.getOrganization());
            writer.writeValue(CM_LOCATION, user.getLocation());
            writer.writeValue(CM_EMAIL, user.getEmail());
            writer.writeValue(CM_TELEPHONE, user.getTelephone());
            writer.writeValue(CM_MOBILE, user.getMobilePhone());
            writer.writeValue(CM_SKYPE, user.getSkype());
            writer.writeValue(CM_INSTANTMSG, user.getInstantMsg());
            writer.writeValue(CM_GOOGLEUSERNAME, user.getGoogleUsername());
            writer.writeValue(CM_COMPANYADDRESS1, user.getCompanyAddress1());
            writer.writeValue(CM_COMPANYADDRESS2, user.getCompanyAddress2());
            writer.writeValue(CM_COMPANYADDRESS3, user.getCompanyAddress3());
            writer.writeValue(CM_COMPANYPOSTCODE, user.getCompanyPostcode());
            writer.writeValue(CM_COMPANYFAX, user.getCompanyFax());
            writer.writeValue(CM_COMPANYEMAIL, user.getCompanyEmail());
            writer.writeValue(CM_COMPANYTELEPHONE, user.getCompanyTelephone());

            // START SomeCo Specific properties
            writer.writeValue(SCP_BIRTH_DATE, user.getStringProperty(PROP_SCP_BIRTH_DATE));
            writer.writeValue(SCP_SHIRT_SIZE, user.getStringProperty(PROP_SCP_SHIRT_SIZE));
            writer.writeValue(SCP_SIGNIFICANT_OTHER, user.getStringProperty(PROP_SCP_SIGNIFICANT_OTHER));
            writer.writeValue(SCP_LIKES_NEIL_DIAMOND, user.getStringProperty(PROP_SCP_LIKES_NEIL_DIAMOND));
            // END SomeCo Specific properties

            writer.endObject();
        writer.endValue();

        writer.startValue("content");
        writer.startObject();
        writer.writeValue(CM_PERSONDESCRIPTION, user.getBiography());
        writer.endObject();
        writer.endValue();

        writer.endObject();

        Connector conn = FrameworkUtil.getConnector(context, ALFRESCO_ENDPOINT_ID);
        ConnectorContext c = new ConnectorContext(HttpMethod.POST);
        c.setContentType("application/json");
        Response res = conn.call("/slingshot/profile/userprofile", c,
                new ByteArrayInputStream(buf.toString().getBytes()));
        if (Status.STATUS_OK != res.getStatus().getCode()) {
            throw new UserFactoryException("Remote error during User save: " + res.getStatus().getMessage());
        }
    } catch (IOException ioErr) {
        throw new UserFactoryException("IO error during User save: " + ioErr.getMessage(), ioErr);
    } catch (ConnectorServiceException cse) {
        throw new UserFactoryException("Configuration error during User save: " + cse.getMessage(), cse);
    }
    }
}

share-config-custom.xml

<config evaluator="string-compare" condition="WebFramework" replace="true">
    <web-framework>
        <defaults>
            <user-factory>webframework.factory.user.someco</user-factory>
        </defaults>
    </web-framework>
</config>

custom-slingshot-application-context.xml

      <bean id="webscripts.resources" class="org.springframework.extensions.surf.util.ResourceBundleBootstrapComponent">
      <property name="resourceBundles">
         <list>
            <value>webscripts.messages.webscripts</value>
            <value>alfresco.messages.common</value>
            <value>alfresco.messages.slingshot</value>
            <value>alfresco.web-extension.messages.somecoPeople</value>
         </list>
      </property>
   </bean>

   <bean id="webframework.factory.user.someco" class="com.someco.share.SomeCoUserFactory" parent="webframework.factory.base" />

It gives me this error, when I try to make login in Alfresco:

SEVERE: Servlet.service() for servlet [Spring Surf Dispatcher Servlet]
  in context with path [/share] threw exception [Request processing
  failed; nested exception is java.lang.NullPointerException] with root
  cause java.lang.NullPointerException  at
  org.springframework.extensions.surf.ObjectPersistenceService.getObject(ObjectPersistenceService.java:128)
    at
  org.springframework.extensions.surf.ModelObjectService.getObject(ModelObjectService.java:552)
    at
  org.springframework.extensions.surf.ModelObjectService.getConfiguration(ModelObjectService.java:157)
    at
  org.springframework.extensions.surf.site.SiteUtil.getSiteConfiguration(SiteUtil.java:104)
    at
  org.springframework.extensions.surf.site.SiteUtil.getRootPage(SiteUtil.java:53)
    at
  org.springframework.extensions.surf.support.AbstractRequestContext.getRootPage(AbstractRequestContext.java:320)
    at
  org.springframework.extensions.surf.mvc.PageViewResolver.canHandle(PageViewResolver.java:109)
    at
  org.springframework.web.servlet.view.UrlBasedViewResolver.createView(UrlBasedViewResolver.java:386)
    at
  org.springframework.extensions.webscripts.servlet.mvc.AbstractWebScriptViewResolver.resolveViewName(AbstractWebScriptViewResolver.java:64)
    at
  org.springframework.web.servlet.DispatcherServlet.resolveViewName(DispatcherServlet.java:1240)
    at
  org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1181)
    at
  org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:986)
    at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:933)
    at
  org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
    at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
    at
  org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)     at
  org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)     at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
    at
  org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
    at
  org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
    at
  org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:389)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.alfresco.web.site.servlet.SecurityHeadersFilter.doFilter(SecurityHeadersFilter.java:168)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.alfresco.web.site.servlet.CSRFFilter.doFilter(CSRFFilter.java:322)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.alfresco.web.site.servlet.SSOAuthenticationFilter.doFilter(SSOAuthenticationFilter.java:447)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.alfresco.web.site.servlet.MTAuthenticationFilter.doFilter(MTAuthenticationFilter.java:74)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at
  org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at
  org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
    at
  org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at
  org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2466)
    at
  org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2455)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at
  org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
2016-03-09 18:47:06,039  ERROR [alfresco.web.site]
  [http-apr-8080-exec-2]
  org.springframework.web.util.NestedServletException: Request
  processing failed; nested exception is java.lang.NullPointerException
  java.lang.NullPointerException    at
  org.springframework.extensions.surf.ObjectPersistenceService.getObject(ObjectPersistenceService.java:128)
    at
  org.springframework.extensions.surf.ModelObjectService.getObject(ModelObjectService.java:552)
    at
  org.springframework.extensions.surf.ModelObjectService.getConfiguration(ModelObjectService.java:157)
    at
  org.springframework.extensions.surf.site.SiteUtil.getSiteConfiguration(SiteUtil.java:104)
    at
  org.springframework.extensions.surf.site.SiteUtil.getRootPage(SiteUtil.java:53)
    at
  org.springframework.extensions.surf.support.AbstractRequestContext.getRootPage(AbstractRequestContext.java:320)
    at
  org.springframework.extensions.surf.mvc.PageViewResolver.canHandle(PageViewResolver.java:109)
    at
  org.springframework.web.servlet.view.UrlBasedViewResolver.createView(UrlBasedViewResolver.java:386)
    at
  org.springframework.extensions.webscripts.servlet.mvc.AbstractWebScriptViewResolver.resolveViewName(AbstractWebScriptViewResolver.java:64)
    at
  org.springframework.web.servlet.DispatcherServlet.resolveViewName(DispatcherServlet.java:1240)
    at
  org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1181)
    at
  org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:986)
    at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:933)
    at
  org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
    at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
    at
  org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)     at
  org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)     at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
    at
  org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
    at
  org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
    at
  org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:389)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.alfresco.web.site.servlet.SecurityHeadersFilter.doFilter(SecurityHeadersFilter.java:168)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.alfresco.web.site.servlet.CSRFFilter.doFilter(CSRFFilter.java:322)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.alfresco.web.site.servlet.SSOAuthenticationFilter.doFilter(SSOAuthenticationFilter.java:447)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.alfresco.web.site.servlet.MTAuthenticationFilter.doFilter(MTAuthenticationFilter.java:74)
    at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at
  org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at
  org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at
  org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
    at
  org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at
  org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2466)
    at
  org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2455)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at
  org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Anyone can help me with this? Maybe when I add this to my all-in-one extension, the folders are incorrect. I need help with this!
I'm using Alfresco Community 5
Comment: Duplicate http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it
Comment: It is a duplicate, every NPE is caused by the exact same thing, a reference is `null`.
Answer: The tutorial from Jeff Potts which you are using as reference is for Alfresco 3.4.d and it wouldn't work directly on Alfresco 5.
The error thrown seems due to the reason that you missed deploying the content model i.e. scPeopleModel.xml as referenced in the tutorial.
I have converted the above tutorial to Alfresco 5.1 using Alfresco SDK 2.2 and this project resides here
You may download the code in zip format here
The major change in this project is the omission of file userprofile.get.head.ftl due to the reason that .head.ftl WebScript files has now been deprecated from WebScripts that render Share Components. Dependencies are now loaded through the use of the @script and @link tags in the main .html.ftl file.
So for the above reason you may find the below code section in userprofile.get.html.ftl
<@markup id="css" >
   <#-- CSS Dependencies -->
   <@link href="${url.context}/res/components/profile/profile.css" group="profile"/>
</@>

<@markup id="js">
   <#-- JavaScript Dependencies -->
   <@script src="${url.context}/res/components/profile/profile.js" group="profile"/>
   <@script src="${url.context}/res/modules/simple-dialog.js" group="profile"/>
   <@script src="${url.context}/res/components/profile/sc-profile.js" group="profile"/>
</@>

Answer: This is a simple NullPointerException, as per the very explicit error message, gives you the class and the exact line:

root cause java.lang.NullPointerException at
org.springframework.extensions.surf.ObjectPersistenceService.getObject(ObjectPersistenceService.java:128)

Nothing in the massive code/configuration dump you posted is going to help anyone here diagnose what is wrong, especially since there does not seem to be a single line of code that is yours.
After you look at the source of ObjectPersistenceService.java:128, you need to just step debug through the calls and you need to figure out how to make whatever it is complaining about being null not be.
Every NPE is solved the exact same way, make the reference not null.
Comment: Because there is something that is null that should not be at line `ObjectPersistenceService.java:128`
Comment: You can step debug into anything you have the source for. Source is available for Spring.
Comment: But in my code above I can't undestand why this error occurs.
Comment: Thanks for the reply, but this is in Alfresco environment, the problem is different, I can't do this "debug" like you said in this problem.
Comment: But this may be a problem with Alfresco, not specific with java... I need help with Alfresco

Custom form new user error in Alfresco


Directional Derivative Interpretation

Question: I'm trying to understand directional derivatives. If I have a function $f(x,y)$ then $\frac{\partial f}{\partial x}|_{x_0,y_0}=f_x$is the slope of a tangent line to a curve parallel to the X-Z plane
and $\frac{\partial f}{\partial y}|_{x_0,y_0}=f_y$is the slope of a tangent line to a curve parallel to the Y-Z plane at point $(x_0,y_0)$
$\implies \nabla f= <f_x,f_y>$
and now if I want to find the slope of a curve obtained by slicing $f(x,y)$ by a plane parallel to some vector $\overrightarrow u = <a,b>$ then we can get the parametric equation of the line parallel to $\overrightarrow u$ through the point $(x_0,y_0)$
as $$
\begin{matrix}
x=x_0+as\\
y=y_0+bs\\
\end{matrix}
$$
By using the chain rule,
$$
\begin{matrix}
\frac{df}{ds}=\frac{\partial f}{\partial x}\frac{dx}{ds}+\frac{\partial f}{\partial y}\frac{dy}{ds} \\
\frac{df}{ds}=\nabla f \cdot \frac{d\overrightarrow r}{ds}\\
\frac{df}{ds}=\nabla f \cdot \overrightarrow u\\
\end{matrix}
$$
But why is the professor considering $\frac{d\overrightarrow r}{ds}$ as to $\overrightarrow u$
And, why does $\overrightarrow u$ have to be a unit vector? What is the significance of this?
and how is $\frac{df}{ds}$ same as directional derivative.
It all seems muddled and awkward
Comment: Think of hiking on a mountainside. The directional derivative in a direction at a point is the rate of change of altitude when you move in that direction from that point. The algebraic formula follows from that understanding. If you have a contour map you can read that off as the rate at which you cross contour lines.
Answer: The directional derivative is meant to generalize the notion of partial derivatives - it's a rate of change in a specific direction, similar to how $f_x$ and $f_y$ are the rates of change in the $x$ and $y$ directions respectively. In order for the directional derivative to reduce to the usual partial derivatives when $\vec{u} = \hat{i}$ or $\hat{j}$, we require that $\vec{u}$ be a unit vector. As for why $df/ds$ is the same as the directional derivative, when you slice the graph of your function along a plane, you get a curve lying in that plane. The slope of that curve is the directional derivative, which coincides with the ordinary derivative of the function along the parametrized curve $\vec{r}(s)=\langle x_0 + as, y_0+bs\rangle$.
If we allowed $\vec{u}$ to have a magnitude, we would be scaling our rate of change by another quantity. A good example is the following: Let's say you're walking over a hot surface with temperature $T(x,y)$. One could ask how quickly the temperature you experience is changing with time (i.e. a derivative with respect to time), or the rate of change of temperature you experience per unit distance you've walked (i.e. a derivative with respect to space). The directional derivative is meant to capture the latter, since if $x$ and $y$ have the same units, the directional derivative will have the same units as $f_x$ and $f_y$.
To determine time rate of change, suppose you're walking with position $\vec{r}(t)$ and velocity $d\vec{r}/dt$. By the chain rule, we arrive at
$$\frac{d}{dt}f(\vec{r}(t)) = \left.\nabla f\right|_{\vec{r}(t)} \cdot\frac{d\vec{r}}{dt}$$
Which is almost a directional derivative, except now $d\vec{r}/dt$ may not be a unit vector. In fact, the time rate of change of temperature is precisely the directional derivative multiplied by your speed.
Comment: So directional derivative is the rate of change of a function along a certain direction given by the unit vector So $\frac{d f}{d s}$ can be interpreted as the directional derivative except

Directional Derivative Interpretation


Is 8.6.18 insecure? Will there be 8.6.19 etc.?

Question: I have a custom module that I think requires Drupal 8.6.x.
Is Drupal core 8.6.18 insecure? Will more 8.6.x versions be released?
Comment: TL,DR: 1) Yes. 2) No. For maintenance schedule see https://www.drupal.org/core/release-cycle-overview and for security advisories see https://www.drupal.org/security and
Comment: Actually, this is not an opinion-based question: It's possible to say if Drupal 8.6.x is secure by looking at the 8.7.x, 8.8.x, or 8.9.x versions released because of security issues. There isn't anything subjective in that. While the question is asking about the 8.6.18 version, the answer is still relevant for future versions, since it points out the release cycle is documented.
Comment: Thanks guys, I took the affected website offline. But, can someone explain to me what is "opinion-based" about this question and it was closed? There is a red banner displayed in Drupal that 8.6.18 has security problems (sounds like a fact to me). I could invest time now to update the problematic module, but a replacement website is already in the starting blocks without Drupal. :P
Answer: According to the Drupal core release cycle documentation, the last month for security coverage for 8.6 was November 2019. There is no more planned security coverage for 8.6.
Security releases only last through the next minor release cycle. I.e. 1.0 will receive patch and security releases until 1.1 is released. Then 1.0 will continue to receive security coverage until 1.2 is released. Once 1.2 is released (the second minor release since 1.0), 1.0 is considered unsupported.


Show realtime data with ng2-charts

Question: I am facing some problem when use ng2 charts to show realtime data, it always show 0 anytime. I have pasted my code snippet down below. Could anyone please help me by checking it and tell me where I have done wrong ?
temps: Array<number> = [];
public lineChartData: Array<any> = [[]];
custom: boolean = false;
report: boolean = false;
errMess: any;
keys: any[] = []

constructor(public dialog: MatDialog,
private dishService: DishService,){}
public lineChartLabels: Array<any> = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
public lineChartType: string = 'line';
ngOnInit() {
this.dishService.getTemp()
  .subscribe(temps => {
    for (let key in temps[0]) {
      for (var _i = 0; _i < temps.length; _i++) {
        this.keys.push(temps[_i][key]);
      }
    }
    console.log(this.keys);
    this.lineChartData.push(this.keys);
  });
 }

Answer: This is a known issue with ng2-charts, you need to manually let angular know that you have updated the data,
do something like this, after the below line,
this.lineChartData.push(this.keys);
this.forceChartRefresh();

and the function goes as,
 forceChartRefresh() {
    setTimeout(() => {
      this._chart.refresh();
    }, 10);
  }

and you need  a variable inside the component as,
@ViewChild(BaseChartDirective) private _chart;

EDIT
To see the chart updated every 5 minutes, you can use
this.interval = setInterval(() => {
    callyour function();
}, 5000);

Comment: import { BaseChartDirective } from 'ng2-charts';
Comment: you need to use $interval
Comment: Thank you so much, how to get BaseChartDirective ?
Comment: Hi, if i wanna use it to show realtime data, how to do that, if we use forceChartRefresh() the chart will refresh after 5s , it not good for eye. :))
Comment: Could you let me know step by step how to do that ? Thank you.

Show realtime data with ng2-charts


How to retrieve HTTP headers from a request in Rocket?

Question: I would do something like this using flask in Python:
@app.route('/login/', methods=['POST'])
def login():
    token = request.headers["token"]

I cannot figure out how to access the token header and store it as a String variable.
#![feature(proc_macro_hygiene, decl_macro)]

use rocket::{
    config::{Config, Environment},
    *,
};

fn main() {
    let config = Config::build(Environment::Production)
        .address("0.0.0.0")
        .port(PORT)
        .finalize()
        .unwrap();

    rocket::ignite().mount("/", routes![login]).launch();
}

#[post("/login")]
fn login() {

    // Retrieve headers from request.
}

Comment: see the [Rocket docs](https://rocket.rs/guide/requests/) for various ways to get info from a request
Answer: Rocket handlers are based on Request Guards. You do not directly access the request in your handler. Instead, you create a type that implements FromRequest.
You can create a token struct that holds a string:
struct Token(String);

And implement FromRequest for the token:
impl<'a, 'r> FromRequest<'a, 'r> for Token {
    type Error = Infallible;

    fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
        let token = request.headers().get_one("token");
        match token {
          Some(token) => {
            // check validity
            Outcome::Success(Token(token.to_string()))
          },
          // token does not exist
          None => Outcome::Failure(Status::Unauthorized)
        }
    }
}

Now you can use that Token as a request guard:
#[post("/login")]
fn login(token: Token) {
}

If the from_request method for Token fails, a Status::Unauthorized will be returned. Otherwise, your handler will be called, and you can handle the authentication logic.
Answer: Ibraheem Ahmed's answer was useful, but I could not figure out how to use Infallible. I solved the issue by doing:
struct Token(String);

#[derive(Debug)]
enum ApiTokenError {
    Missing,
    Invalid,
}

impl<'a, 'r> FromRequest<'a, 'r> for Token {
    type Error = ApiTokenError;

    fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
        let token = request.headers().get_one("token");
        match token {
            Some(token) => {
                // check validity
                Outcome::Success(Token(token.to_string()))
            }
            None => Outcome::Failure((Status::Unauthorized, ApiTokenError::Missing)),
        }
    }
}

Comment: `std::convert::Infallible` is just an empty enum representing an error that can never happen. I just used it for example purposes


How can I prevent Apache from logging 404 errors?

Question: So, whenever a user tries to fetch a file on my Apache server that doesn't exist I get a 404 line in the Access log:
<code>[29/Sep/2010:12:14:45 +0200] "GET /asdf HTTP/1.1" 404
</code>
And I also get this in the Error log:
<code>[Wed Sep 29 12:14:45 2010] [error] [client] File does not exist: /www/site/asdf
</code>
Is there a way to suppress 404 erros from showing up in the error log- only in the access log?
Answer: ErrogLog(http://httpd.apache.org/docs/2.2/mod/core.html#errorlog) have not conditional.
You can send the logs to syslog or script and filter it.
Answer: Yes, you can suppress them from the error log, but still have them in the access log. Just add these lines to .htaccess:
<code># Don't log missing files
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(content\asdf)$ - [R=404,L]
</code>
It uses mod_rewrite.
RewriteCond is there to make sure that file indeed doesn't exist. Files that do exist will be served as usual.
R=404 says to send 404 Not Found status code when client accesses any files that contain "asdf". You need to modify the expression in parenthesis, on the last line, to suit your needs.
This answer is also found here.
Answer: Try experimenting with LogLevel directive (http://httpd.apache.org/docs/current/mod/core.html#loglevel). It's not exactly what you want, but it can suit you needs, nevertheless
Comment: LogLevel seems to be set to always be notice when logging to a flatfile, though... :(
Answer: Error 404 is defined in defined in httpd.conf or .htacces like so:
ErrorDocument 404 /404.html
You can redirect to index page :
ErrorDocument 404 /index.html
or you can create a blank page blank.html and change config to :
ErrorDocument 404 /blank.html
Comment: I don't think you understand the question.


Necessary and sufficient conditions for $||f||_p = ||f||_q$ with $p \neq q$

Question: Let $0 < p < q \leq \infty$ and suppose $ E\subset \mathbb{R}^N$ with $m(E)=1$ (where $m$ is the Lebesgue measure). I am asked to find necessary and sufficient conditions for:
$$ ( \int_E{|f|}^pdx)^{1/p} = (\int_E{|f|}^qdx)^{1/q}$$
I know how to prove that that LHS $\leq$ RHS, this is done with Jensen's inequality in its measure-theoretic form, considering the function $\phi(t)=t^{q/p}$, which is convex, because $p<q$. This is how it works:
$$(\int_E{|f|^pdx})^{q/p}=\phi(\int_E{|f|^p}dx) \leq \int_E{\phi(|f|^p)dx}= \int_E{|f|^qdx }$$
I was guessing that the necessary and sufficient condition required in the excercize is that $f(x) = 0$ almost everywhere (EDIT as observed in the comments, the condition is also satisfied if $f$ is such that $|f|$ is constant a.e.), but I'm stuck trying to prove it. I tried manipulating the exponents, but nothing seems to work; maybe some result on the inverse implication in Jensen's inequality could help, but I can't find any.
I hope someone can point me in the right direction, thanks in advance!
Comment: Since $m(E)=1$, any $f$ such that $|f|$ is a.e. constant will give equality, not just a.e. zero.
Comment: Although I haven't tried this myself, I think a good idea would be to follow a proof of Jensen's inequality and track where the inequality emerges in the proof: then you might be able to find a condition which is necessary for equality to hold.
Comment: @CliveNewstead Thanks for your interest. I edited the question to include the proof I was alluding to. I know where the inequality is used in this proof, however I don't know how to use the inequality "backwards" in order to prove what the excercize is asking.
Comment: @ChrisEagle Thanks! I hadn't noticed this.
Answer: I don't know how to use Jensen's inequality. But that's what I can prove using Holder's inequality:
Holder's inequality says:
$$\int_E|f_1f_2|\leq\left(\int_E|f_1|^a\right)^{\frac{1}{a}}\left(\int_E|f_2|^a\right)^{\frac{1}{b}}$$
where $\displaystyle\frac{1}{a}+\frac{1}{b}=1$. Equality holds when $\alpha |f_1|^a=\beta |f_2|^b$ almost everywhere on $E$, where $\alpha$ and $\beta$ are constants.
Hence, if $1<p<q<\infty$, by Holder's inequality with $f_1=|f|^p$, $f_2=1$, $a=\frac{q}{p}$, $b=\frac{q}{q-p}$,  we have
$$\int_E{|f|}^p\leq \left(\int_E(|f|^p)^{\frac{q}{p}}\right)^{\frac{p}{q}}\cdot\Big(m(E)\Big)^{1-\frac{p}{q}}=\left(\int_E|f|^q\right)^{\frac{p}{q}}.$$
Taking $p$-th root, we have
$$\left(\int_E{|f|}^p\right)^{\frac{1}{p}}\leq\left(\int_E|f|^q\right)^{\frac{1}{q}}.$$
Therefore, if $\|f\|_p=\|f\|_q$, equality must hold when we apply the Holder's inequality, i.e.
$$\alpha(|f|^p)^{\frac{q}{p}}=\beta\mbox{ almost everywhere on }E.$$
That is to say,
$f$ is constant almost everywhere on $E$.
Comment: Note that, since ${q\over p}>1$, you can take $0<p<q<\infty$ in your second paragraph.
Comment: Thank you very much, this is the answer I was looking for.


Find the standard equation of the parabola which satisfies the given condition

Question:  vertex (0,7), vertical axis of symmetry, through the point P(4,5)
My answer:
(y-k)^2 = -4c(x-h)
(y-7)^2 = -16x
Please kindly correct me if I have any mistake.
Answer: So I think the most simple thing here is to use point slope.
Given the vertex $(h,k)$ of a parabola, we can write
$y=a(x-h)^2+k$.
Given vertex $(0,7)$, we have $\displaystyle y=ax^2+7$.
Now, we plug in the point $(4,5)=(x,y)$, to get $5=a(4^2)+7$.
We have $5=16a+7$, so $-2=16a$, and $\displaystyle a=-\frac{1}{8}$
We have $\boxed{\displaystyle y=-\frac{1}{8}x^2+7}$.
I am confused as to why you still have the variable $h$ in your answer.
Comment: I just based my answer on the standard equation (y-k)^2 = -4c(x-h)
Comment: but that's a horizontal parabola..
Comment: Oh, my mistake. I didn't notice.


What are good sources of information about non-standard tuning systems ("microtunings")?

Question: Prompted by answers and comments on this question, I'd like to collect up some online references for microtunings and microtonal music. This subject seems to be picking up ever more interest but it remains quite hard to learn about online.
Ideally I'm looking for sources that are substantial but still accessible to a musician with limited background in the theory of tunings. By "accessible" here I mean such a person should be able to get something of value from it, not that every part of it should be non-technical. By "substantial" I mean more than just a blog post or a list.
Areas of interest (to me) include, but are not limited to:

Active online communities
Sites / pages dedicated to the practicalities of making microtonal music
Introductory treatments of technical aspects of tuning theory
Accounts of actual music that uses unusual tunings (Western or non-Western, historical or contemporary)

I hope this is allowed here; I'm sure mods will let me know if not. IIRC "recommended reading" posts are allowed on mathematics se, which I'm moe familiar with, so I thought it was worth a shot. If it's allowed to stand I presume this would be a good candidate for community wiki?
Comment: Apart from being off-topic as search for resources, this is an _absurdly_ too-broad question. Do you consider anything "non-standard tuning" that's not 12-edo? Well, then it's basically like asking about "information on the political systems of countries outside of Switzerland".
Answer: Scientific papers in music theory and physics. Synthesis communities may have some interesting things. Harry Partch's "Genesis of a Music" is a must.
For temperament history, there are plenty materials as we have a prolific Worldly historic performance scene. Names are many, but Christensen have edited some books on this. Harpsichordists usually write about this, as well.


How to make a file downloader in C#?

Question: I want to code a simple file downloader in C#. I want to know how it works? eg. If I give it a URL, what will it do? I have a very rough idea about it.

It will send a HTTP request.
The server will reply and send the file.
The downloader will get the file and store it in hard drive.

This is my first time coding on web technology. So I hardly have any idea.

Can anybody please explain me the steps?
Answer: A snippet to get you started:
<code>using(var wc=new WebClient())
{
    wc.DownloadFile("http://some/internet/resource",@"c:\some\local\filename");
}
</code>
Comment: You've got to be kidding. It's that simple?
Comment: Just to be nitty, it should be "http://some/internet/representation_of_resource". Other than that, it is a nice small example ;)

How to make a file downloader in C#?


How to traverse on only a cycle in a graph?

Question: I'm attempting ch23 in CLRS on MSTs, here's a question:

Given a graph G and a minimum spanning tree T , suppose that we decrease the weight of one of the edges not in T . Give an algorithm for finding the minimum spanning tree in the modified graph.

A solution I found was to add this new changed edge in T, then exactly one simple cycle is created in T, traverse this cycle and delete the max-weight edge in this cycle, voila, the new updated MST is found!
My question is, how do I only traverse nodes on this simple-cycle? Since DFS/BFS traversals might go out of the cycle if I, say, start the traversal in T from one endpoint of this newly added edge in T.
One solution I could think of was to find the biconnected components in T after adding the new edge. Only one BCC will be found, which is this newly formed simple-cycle, then I can put in a special condition in my DFS code saying to only traverse edges/nodes in this BCC, and once a back-edge is found, stop the traversal.
Edit: graph G is connected and undirected btw
Answer: Your solution is basically good. To make it more formal you can use Tarjan's bridge-finding algorithm
This algorithm find the cut-edges (aka bridges) in the graph in linear time. Consider E' to be the cut-edges set. It is easy to prove that every edge in E' can not be on circle. So, E / E' are must be the cycle in the graph.
You can use hash-map or array build function to find the difference between your E and the cut-edges set
From here you can run simple for-loop to find the max weight edge which you want to remove.
Hope that help!
Comment: took me long enough to reply, but I see, this is much better, so once a cycle is created, all edges on that cycle will be non-bridges, and all other edges in T are bridges, so I can just find all bridges in T in linear time and then scan them to delete the max-weight bridge, right? I just overcomplicated my initial solution, thanks a lot!


How to set a fixed size for ListView that is laid inside a Dialog and elements are added dynamically

Question: I am trying to include a ListView within an Activity that is running inside a Dialog. The dialog is basically used to search for bluetooth devices, so I need two Button's, a TextView and a ListView. Here is my XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:padding="20dp">
    <TextView
        android:text="Bluetooth List"
        android:paddingTop="15dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content">
    </TextView>
    <ListView android:id="@+id/bluetoothPanel_lvBluetooth"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:layout_margin="10dip"
        android:drawSelectorOnTop="false">
    </ListView>
    <LinearLayout
        android:orientation="horizontal"
        android:paddingLeft="4.0dip"
        android:paddingTop="5.0dip"
        android:paddingRight="4.0dip"
        android:paddingBottom="1.0dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
            <Button
                android:id="@+id/bluetoothPanel_btnSearch"
                android:layout_width="0.0dip"
                android:layout_height="fill_parent"
                android:text="Search"
                android:layout_weight="1.0" />
            <Button
                android:id="@+id/bluetoothPanel_btnCancel"
                android:layout_width="0.0dip"
                android:layout_height="fill_parent"
                android:text="Cancel"
                android:layout_weight="1.0" />
    </LinearLayout>
</LinearLayout>

At the beginning, the ArrayAdapter that is within the ListView is empty, and I am dynamically add elements to it.
The problem is, I want to set a fixed size for the ListView so that it won't change its size upon adding elements dynamically (List of bluetooth devices are shown). Could you please help me to fix my XML?
EDIT:
I am not talking about array size. I am talking about the listview itself (the view), the height of the listview.
Answer: Set a custom ListAdapter for the list and override the getCount() method so it returns always your fixed size.
Example: http://jnastase.alner.net/archive/2010/12/19/custom-android-listadapter.aspx
Comment: Ah ok, misunderstood. You can set a fixed height for the list, if that is what you want to do: e.g. `layout_width="50dip"`
Comment: Oh, I am not talking about array size. I am talking about the listview itself (the view)
Comment: Usually the view size depends on the array size. If the array size is fixed, the view will stay at the same size.
Comment: but the array I am using is not fixed, and it depends on how many bluetooth devices are around :)
Comment: I tried this before but it does not change the size, maybe because I run the activity on a dialog.
Comment: Maybe you need to wrap your layout in a scroll view: http://stackoverflow.com/questions/4055537/android-linearlayout-scroll
Comment: I've tried this too, and this doesn't change the height but the scrollbar doesn't move
Comment: Did you set `android:layout_height="wrap_content"` for the LinearLayout when you wrapped it in a ScrollView?
Comment: Yes, and it displays only one element of the list
Comment: Weird :( You could try to use RelativeLayout, align the list below the TextView and above the buttons layout. I used this to have headers and footers on layouts. But no idea if it works on dialogs.
Answer: I think you are asking how to reserve a fixed-size space for a dynamically changing ListView.  In a similar situation, I wrapped the ListView in a LinearLayout, as shown below.  Note that this is the xml for the ListView itself, not for the cell contents.  The fixed height in this example is 100dip x 200dip.
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/background_image"
    android:layout_width="100dip"
    android:layout_height="200dip">

    <ListView   android:id="@+id/list_view"
                android:layout_width="100dip"
                android:layout_height="match_parent"
                android:cacheColorHint="#00000000"
    />
</LinearLayout>

Notice that the layout_width of the ListView also is set to the desired fixed width.  I'm not sure why, but this seems to be necessary.
Also notice that the background image or color is set on the LinearLayout, not on the ListView.  Setting the ListView's cacheColorHint to transparent makes the ListView play nicely.
If you were asking something else (perhaps, for example, fixing the scrollable height regardless of elements, which seems to be answered by @Stephen), you may want to clarify the question.


prevent multiple form submission on keyup ajax post

Question: I am currently working on a form for a retail outlet where in I need to submit form on enter keyup and redirect the form to the same page. On enter keyup the ajax post is being submitted to a php function and on successful data insert I am doing a page redirect. Which I am able to do currently, but in few instances the users are hitting the enter key multiple times (may be 3 to 4 times in a sec) because of which the for is being submitted multiple times. How do I prevent multiple submission. Have tried to generate a random number and pass as session token but, each submission is generating a new random number.
Here is my code
<code>    $(document).keyup(function(e){
    if (e.keyCode == 13) {
        var postData = $("#invoiceForm").serialize();
        $.ajax({
            url: "addsale()",
            type: "post",
            data: postData
        });
        e.preventDefault();
        return false;
    }
});
</code>
Answer: Use a flag variable to ignore the new request if not completed previous , it will work as a lock.
<code>var isOnWay=false;
$(document).keyup(function(e){
if (e.keyCode == 13) {
    var postData = $("#invoiceForm").serialize();
    $.ajax({
        url: "addsale()",
        type: "post",
        before:function(){
               if(isOnWay)
                  return false; // ignore request
               isOnWay=true;// start a lock flag
                },
        complete:function(){
                 isOnWay=false; //free up
                },
        data: postData
    });
    e.preventDefault();
    return false;
}

});
</code>
Answer: Catch the form onsubmit handler to prevent submission.
    Var isFormAlreadyPosted = false;
    $('form').submit(function(evt){
<code>    If(isFormAlreadyPosted){
        evt.preventDefault()
    }
    isFormAlreadyPosted = true;
});
</code>


How can I exit a function in powershell

Question: I have a function that I know will throw an error.  This error is expected, but when it's thrown I want to end the function.  I have a Trap section in my script, and I have used both the Return and the Break commands, but they don't do what I want.  I have the trap statement both in the Begin {} and the Process {} sections. I am using the command  Get-WmiObject, and I have the -ErrorAction set to stop. A sample of the code and their responses are below.
First Example w/ return:
Function Test {
Param {"Some Parameters"}
Begin {"Some beginning stuff"}
process {
    Trap
    {
        Add-Content $($SomeFile) $($ComputerName + "is Not There")
        return
    } #End Trap
    Get-WmiObject Win32_NTLogEvent `
        -ComputerName $ComputerName `
        -Credential $Cred - `
        -ErrorAction Stop
    }#End Process
End {"Some ending things"}
} #End Function

This one simply keeps going on, without exiting the function.
Second Example w/ break:
Function Test {
Param {"Some Parameters"}
Begin {"Some beginning stuff"}
process {
    Trap
    {
        Add-Content $($SomeFile) $($ComputerName + "is Not There")
        Break
    } #End Trap
    Get-WmiObject Win32_NTLogEvent `
        -ComputerName $ComputerName `
        -Credential $Cred - `
        -ErrorAction Stop
    }#End Process
End {"Some ending things"}
} #End Function

This one exits the entire script.
I have looked around, but I can't find anything specific to exiting just a function.  There is a lot more going on in the function, including another Get-WmiObject command.  I want it to exit the function if the first Get-WmiObject can't contact the computer.  I can't use a ping test, because many of the servers block ICMP.
Answer: The $?varible can be good for catching errors. It contains a boolean for the last executed command. If the command was excuted without errors $? = $true. The $? will be $false when the last executed command errored.
Create a boolean that gets set each time after the command that errors. Assuming that the command here is get-wmiObject:
$running = $true
While ($running) {
Get-WmiObject Win32_NTLogEvent -ComputerName $ComputerName -Credential $Cred
$running = $?
}

Since you probably have a conditional in your loop already, it would look something like while(<condition> -and $running)
And if you would like to add your error message in, just throw something after you set running like this
if(!$running){Add-Content $($SomeFile) $($ComputerName + "is Not There")  }

Comment: I updated the main post. This would prevent the second command from running, but I want the entire function to stop, not just prevent the next command(s).
Comment: I understand what you are trying to do, but I do not believe powershell has an equivalent for the return statement you may be use to in other coding languages. In powershell, everything that is not captured in a function is then returned. So I believe the only way to actually "return" is to get to the bottom of your function. You can do this in a couple of different of ways, you just have to go with a different route that your currently attempting. You can throw all of that `End {"Some ending things"}` in an if statement that checks if there was an error. Seperate into 2 functions for tidiness
Comment: Ok, since there is no easy way to exit the function in Powershell, what I ended up doing was in the begin {} block was assign a variable to the value of $?.  I used an If {} Else {} statement rather then while {}, but in the end this was the comment that gave the correct answer.
Answer: Return will in fact not help, but you can use break, the only requirement is to use it as it was designed - to get out of the loop... :)
Trick here is to build simple loop that will run only once no matter what and use break inside the loop:
# Script body...

do {
    Test-WithBreak
} until ($true)

# Other operations you want to perform even if Test-WithBreak breaks.

The reason behind it is the fact, that break is loop directive and in PowerShell it does not care for any limits (so break in script, run from script, run from script will be able to walk all the way up and kill whole thing, unless it find some loop to stop him).
I blogged about this issue a while ago.
Comment: I have wrapped my function call in a Do {} Until loop, but the break is still stopping the whole script. I ended up using the idea @cole9350 had.  I assigned $? to a variable and in the process block I check it before running any of the script. I just testing it and everything is working.
Answer: Try "Continue" as keyword
Trap [Exception] { "In PowerShell" }
Comment: continue it was

How can I exit a function in powershell


Counting basic operations in Quicksort algorithm

Question: I am trying to count the amount of basic operations done by Hoare's quicksort algorithm. I am wondering if I placed the counter in the correct position. My assignment is to count the number of basic operations on 100 randomly generated arrays of sizes 10,100,1k, and 10k.
Here is the algorithm with the counter placed (line 6):
    void QuickSort(int* array, int startIndex, int endIndex, int &counter) {
    int pivot = array[startIndex];                  //pivot element is the leftmost element
    int splitPoint;

    if (endIndex > startIndex)
    {
        counter++; //counting
        splitPoint = SplitArray(array, pivot, startIndex, endIndex);
        array[splitPoint] = pivot;
        QuickSort(array, startIndex, splitPoint - 1, counter);   //Quick sort first half
        QuickSort(array, splitPoint + 1, endIndex, counter);     //Quick sort second half
    }
}
void swap(int &a, int &b) {
    int temp;
    temp = a;
    a = b;
    b = temp;
}
int SplitArray(int* array, int pivot, int startIndex, int endIndex) {
    int leftBoundary = startIndex;
    int rightBoundary = endIndex;

    while (leftBoundary < rightBoundary)
    {
        while (pivot < array[rightBoundary]
            && rightBoundary > leftBoundary)
        {
            rightBoundary--;
        }
        swap(array[leftBoundary], array[rightBoundary]);

        while (pivot >= array[leftBoundary]
            && leftBoundary < rightBoundary)
        {
            leftBoundary++;
        }
        swap(array[rightBoundary], array[leftBoundary]);
    }
    return leftBoundary;

}

Do these results make sense?
Array[Amount]   Array[10]       Array[100]      Array[1k]       Array[10k]
MAX:                 8              72               682        7122
MIN:                 5              63               653        7015
AVERAGE:             6.36           66.54            667.87     7059.41

Or did I put the counter in the wrong place.
Answer: The counter is in the wrong place. Your assignment is to count basic operations. What is a basic operation in sorting? Typically we count the number of compare operations to measure complexity of sort.
We know that QuickSort is O(N Log N) on average where N is the number of items being sorted, while worst case it is O(N^2).
Your numbers are smaller than N, which is not possible since each of the N items must be compared to some other elemnt at least once, the cost of sorting cannot be less than N (otherwise at least one element was not compared to anything, so you could not guaranteed that it is sorted).
In your algorithm, the compare operation occurs when you compare the elements of the array to the pivot value. So increment your counter every time you compare an array element to Pivot. Your measured numbers should be at least N, and will typically be about N*log N, and rarely be be close to N^2.
See the suggested points below in SplitArray where to increment counter:
    void QuickSort(int* array, int startIndex, int endIndex, int &counter) {
    int pivot = array[startIndex];                  //pivot element is the leftmost element
    int splitPoint;

    if (endIndex > startIndex)
    {
        // counter++; // Don't count here
        splitPoint=SplitArray(array, pivot, startIndex, endIndex, counter);
        array[splitPoint] = pivot;
        QuickSort(array, startIndex, splitPoint - 1, counter);   //Quick sort first half
        QuickSort(array, splitPoint + 1, endIndex, counter);     //Quick sort second half
    }
}

No change to swap:
void swap(int &a, int &b) {
    int temp;
    temp = a;
    a = b;
    b = temp;
}

SplitArray does the comparisons, so the counter should be incremented here:
 int SplitArray(int* array,int pivot,int startIndex,int endIndex,int &counter) {
        int leftBoundary = startIndex;
        int rightBoundary = endIndex;

    while ((++counter) && (leftBoundary < rightBoundary))
    {
        while (pivot < array[rightBoundary]
            && rightBoundary > leftBoundary)
        {
            rightBoundary--;
        }
        swap(array[leftBoundary], array[rightBoundary]);

        while ((++counter) && (pivot >= array[leftBoundary])
            && leftBoundary < rightBoundary)
        {
            leftBoundary++;
        }
        swap(array[rightBoundary], array[leftBoundary]);
    }
    return leftBoundary;

}


How to set default value for entity reference field in hook_form_alter

Question: following snippet doesn't   set the default value.
<code> $form['field_image']['#default_value']='default';
</code>
I Have content type called image and I'm trying to set the default value for a reference to it in another content type.  The above code doesn't work.  Printing out the form variable doesn't make it seem like an easy task.
Comment: Sadly in D8 the method for doing this depends on the widget being used in the form. The answer $form['field_myfield']['widget'][0]['target_id']['#default_value'] = \Drupal\node\Entity\Node::load(2); only works if the widget is an autocomplete. If the widget is a select list, then you would need to use: $form['field_myfield']['widget']['#default_value'] = 2;
Answer: You need to first check the structure of your form. Mine worked with the following:
<code>$form['field_image']['widget'][0]['target_id']['#default_value'] = \Drupal\node\Entity\Node::load(2);
</code>
Cheers!
Comment: You can either use a `devel` module's function (`dsm()` or `dpm()`) or an IDE with a debugger. The debugger's breakpoint or the devel functions can be placed inside your own implementation of `hook_form_alter()` or directly inside the `drupal_prepare_form()` function.
Comment: How to check structure of the form :) ?
Comment: Hmm.  Great for D7,  it's a protected object in D8 and doesn't seem to kint() to that level.  (A debugger might work).  Trying to find a workable way to look at $form in D8,  right now.
P.S.  apologies that I may have thought this was a D8 thread ...
Comment: UPDATE:  you can $var=$form_state['variable'] then kint($var).
Comment: It's a D8 thread, my bad, thought it was D7.
Comment: UPDATE:  you can't always touch $form_state in D8 but you can see $form,  and that's where you'll want to make changes AFAICT.  Display widget structure appears to vary widely,  alas.
Comment: I needed to use ['#value'] rather than ['#default_value']...
Answer: I had trouble with the above on 8.6.1 when using the Entity browser widget - looking at the form edit values I found that this worked for me:
<code>      $form['field_business_partner']['widget']['target_id']['#default_value'] = 'node:18';
</code>
Simple string.  Note it didn't display the requisite node in the field but as this was being programmatically set it didn't matter in my use case.
Answer: You have to set three things,
1 - node default value,
2 - Entity browser default value , And
3 - Item , Which will show in edit form, Without Assigned the items it's not displayed in entity browser, While in backed it is set when we check by kint() var,
demo code in my case:
<code>    $form['field_related_stories']['widget']['target_id']['#default_value'] = "node:25507";
    $form['field_related_stories']['widget']['entity_browser']['#default_value'] = Node::load(25507);
    $form['field_related_stories']['widget']['current']['items'] = array();
</code>
Comment: None of these show the default value _selected_ in the entity browser...any idea how to make that happen?


Distributing CEFSharp Winforms (x86) - Trying to keep my application as AnyCPU

Question: I have a .NET Application (VB Winforms) that runs a main executable. On startup this executable will search for plugins and will load them in using System.Reflection.Assembly.Load()
I then use interfaces to add menu icons from the plugins into the main app's icon bar so forms from the plugins can be shown .. You get the idea.
Now, this application currently runs with a Target platform of AnyCPU. My thinking behind this was so the application would work on both x86/x64 platforms. If installed on x86 it would have the 2GB memory limitation, but would also be available on x64 and run freely (This is how it works - Right?)
Now, i want to show help files from my Website inside an embedded browser - I've chosen CEFSharp Chromium Browser and it works brilliantly, however CEFSharp MUST have a Target Platform of either x86 or x64 specifically set.
I've created a plugin to hold the browser and set this project to a target platform of x86 (64 bit operating systems can still run x86 apps - So this should work for both), my thinking was that i could load this plugin into the application however when i do so i get the following error:

Could not load file or assembly 'XIBrowser.dll' or one of its dependencies.  is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)"}
      System.BadImageFormatException: {"Could not load file or assembly 'XIBrowser.dll' or one of its dependencies.  is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)"}

It appears that i can't load the project without the main application being set to Target platform of x86 which means i loose all the benefits of running it on a x64 bit OS.
So ... Is there any way around this? I don't really want to maintain two versions of my application for x86 and x64.
Does anyone have any ideas of how to run CEFSharp but still keep my AnyCPU target?
Comment: No workaround. You cannot load 32-bit DLLs in 64-bit processes, nor vice-versa. The bitness of all your dependencies need to match that of your application. Just target 32-bit. It is exceedingly unlikely that your WinForms application requires more than 2 GB of RAM.
Comment: https://github.com/cefsharp/CefSharp/issues/1714
Comment: In the short term if memory is that important set the `largeaddressaware` flag on your executable and it will address `3gb` of memory. http://stackoverflow.com/questions/1346480/how-to-make-a-net-application-large-address-aware
Answer: Yes - You're all correct. No way around it.
I've now converted my Target Framework to x86 and i'm running the x86 version of CEFSharp. All working fine.
I wrapped an interface around it and dumped it into a new project, so if i ever need to run a x64 version then it'll be really easy to convert.
Thanks all.


Check primary keys values

Question: These are tables in SQLite: especie_similar
CREATE TABLE especie_similar (
    id_especie INTEGER NOT NULL,
    id_similar INTEGER NOT NULL,
    PRIMARY KEY (
        id_especie,
        id_similar
    ),
    FOREIGN KEY (
        id_especie
    )
    REFERENCES especie (id_especie) ON DELETE CASCADE,
    FOREIGN KEY (
        id_similar
    )
    REFERENCES especie (id_especie) ON DELETE CASCADE
);

And especie table:
CREATE TABLE especie (
    id_especie     INTEGER PRIMARY KEY AUTOINCREMENT
                           NOT NULL,
    nombre_especie VARCHAR NOT NULL,
    cient_especie  VARCHAR NOT NULL,
    desc_especie   TEXT,
    nidificacion   TEXT    NOT NULL,
    dimorfismo     INTEGER NOT NULL,
    genero_id      INTEGER NOT NULL,
    endemismo_id   INTEGER NOT NULL,
    abundancia_id  INTEGER NOT NULL,
    FOREIGN KEY (
        genero_id
    )
    REFERENCES genero (id_genero),
    FOREIGN KEY (
        endemismo_id
    )
    REFERENCES endemismo (id_endemismo),
    FOREIGN KEY (
        abundancia_id
    )
    REFERENCES abundancia (id_abundancia)
);

My situation: Table especie has multiple datas and I want to insert in especie_similar ids from table especie.

How can i code a trigger or sql statement checking if id_especie and id_similar are not equals?
How can i code to retrieve all especies distinct of target id
(ex: table especie_similar has id_especie=1 and id_similar=2
indicating that species id 1 is similar to another species id 2 but
cannot insert id_especie=2 and id_similar=1 due to previous
duplicate data)?

Thanks and sorry my english is not good.
Answer: For question #1 you can use a standard SQL constraint:
create table especie_similar (
  ...
  check (id_especie <> id_similar) -- your condition here
);

For question #2 you can use a standard "Recursive CTE". See SQLite WITH Clause. Example:
with recursive node as (
  select id from especie_similar
    where id_especie = 123 -- first node criteria here
  union all
  select s.id_especie
    from node n
    join especie_similar s on s.id_similar = n.id
)
select * from node;

Check primary keys values


Remover linhas repetidas em todos os aspectos no Oracle

Question: Em uma coluna CADASTRO eu possuo  duas linhas repetidas em todos os aspectos:
NOME   ID    EMAIL           SEXO
JOAO   1234  firstname.lastname@example.com  M
JOAO   1234  email@example.com  M

Como comparar essas duas linhas, conferir se todas as colunas estão idênticas e excluir uma delas a fim de resultar:
NOME   ID    EMAIL           SEXO
JOAO   1234  email@example.com  M

Comment: Você não tem nenhum identificador único pra sua tabela?
Comment: Se para a pergunta do George (acima) for não, você pode alterar a estrutura da tabela? Não sei quanto ao Oracle, mas, no SQL Server não tem como remover apenas uma delas - precisa de um identificador único para cada registro.
Comment: Estou votando para fechar esta pergunta como fora de escopo porque não está claro se AP pretende fazer isto num Select ou existem dados duplicados que ele quer excluir.
Answer: Entendendo que você quer eliminar do banco de dados os registros duplicados mas, mantendo um (1) deles, sugiro utilizar o rowid.
O ROWID é uma pseudo-coluna que retorna o endereço de um registro, estruturalmente você não o verá, mas, está lá.
Ele identifica exclusivamente uma linha dentro de uma tabela.
No script abaixo temos:

Uma sub-consulta buscando todos os menores rowid de cada agrupamento repetido;
Um comando delete em todos os registros que não estão no agrupamento mínimo feito na sub-consulta;

Script:
delete from cadastro
where rowid not in
     (select min(rowid)
      from cadastro
group by nome, id, email, sexo);

Com isso, serão eliminados os duplicados deixando pelo menos um de cada.
Obs: Você nunca deve armazenar um rowid em suas tabelas como um valor de chave (único).
Answer: Em sql server, o método abaixo funciona. Em oracle julgo que é semelhante:
select *
into #table
from(   select nome = 'JOAO', id=1234, email@example.com', sexo='m'
        union all
        select nome = 'JOAO', id=1234, email@example.com', sexo='m'
        union all
        select nome = 'manuel', id=1237, email@example.com', sexo='m') t

   ;WITH cte AS (
        SELECT  *,
                row_number() OVER(PARTITION BY nome,id,email,sexo ORDER BY nome,id,email,sexo) AS rn
        FROM #table
    )
    DELETE cte WHERE rn > 1

select *
from #table

drop table #table

Answer: Use um distinct.
Select Distinct * From Tabela;

Veja funcionando no SQL Fiddle.
Comment: O que eu entendi que ele quer remover do banco de dados essas linhas "a mais" - ou seja, unificar esses cadastros.
Comment: Mas ele precisa remover as linhas repetidas deixando apenas uma.
Comment: @Ismael Mas é isso que o distinct faz. Ou eu devo ter entendido errado (a pergunta e o seu comentário).
Comment: Sua teoria faz sentido, mas é pouco provável. Aí ele teria dois registros com o mesmo **ID**? Claro que é possível, mas não acredito que seja o caso.
Comment: Tem cada sistema doido por aí que não custa duvidar. Vamos aguardar mais detalhes.
Comment: Sim, você tem razão. Também vou esperar por mais detalhes.
Comment: Pra que este link? @Motta
Comment: @jbueno , post removido
Comment: @Motta Eu realmente não entendi, rs. Mas tudo bem.


Guitar tuning with digital tuner

Question: I am trying to tune my Washburn acoustic using a Stagg T-UC digital tuner, could use some help please
Manual for my tuner can be found here:
http://www.globalcube.net/clients/staggmusicv2/content/medias/download/SUPPORT/USERMANUELS/TunerMetronome/TUC.pdf
Q: the tuner gives me the option to set the Scale to Bb, Eb, C or F - what do these mean, and which one should I select for standard tuning?
Fyi, I have the tuner set to 440 Hz
Thanks!
Answer: Here's the key sentence:
This device allows a large variety of instruments to be tuned: woodwinds, brass, stringed instruments, etc.
That is, it allows instruments that are not concert pitch to be tuned in their native key. So, a trumpet would set it to Bb, a french horn to F, and an alto sax to Eb.
Guitar is a concert pitch instrument, so it should be set to C.

Guitar tuning with digital tuner


Email from "Drafts" being delivered blank

Question: We're having several problems when users send email from the "Drafts" in Outlook 2010.
For example: when an email is saved in the Drafts folder one day and sent on another day, the delivered email has a blank body. When they look in Sent Items, the message is blank there as well. This seems to happen randomly.  There are no errors generated.
I can see in the message tracking logs that the email was delivered successfully. It has a size of 12 KB, which means that email is not really empty. However, there is no text in body of email (email in sent items is empty, email in recipient inbox is empty). Microsoft Forefront Protection has not performed any actions in this time frame to explain this behavior. Does anyone have any ideas on what's wrong?
Answer: I would start with mailbox repair command, on the affected mailboxes:
New-MailboxRepairRequest -Mailbox "mailboxname" -CorruptionType ProvisionedFolder,SearchFolder,AggregateCounts,Folderview

Watch the logs to see if any corruptions have been fixed. The repair can be run while user is connected.
Comment: hi, sorry for delay. All of them have online mode.
Comment: Have you applied SP2 to Exchange and all the patches from windows update to the Outlook(office) on user's computer? Is that happens to one particular users or several?
Comment: we have SP2 RU3... yes, everything is up to date.
Several users are affected, but it occurs only rarely
Comment: Do you see any issues in the application event log on the server?
Comment: there is no error in the application log in that time. I checked both servers (mailbox and CAS+HUB)
Comment: Is there a chance to compare the outlook.exe version on the affected workstations, with the ones which are not experiencing issues?
Comment: Outlook is installed on terminal server. All users use the same version. On the other hand, I don't think that all users saved their emails to drafts. Anyway this problem occurs only rarely. I am not able to simulate this situation. That's a reason, why I am so frustrated.
Comment: thank you for tip. I did it, but no problem was found. I checked also the event logs. Do you have any other suggestion? Thank you in advance
Comment: What mode are your users are working at? Online? Offline?


Embed two blocks in a block

Question: I have three blocks A, B and C and I need to embed the blocks A and B into the template of a block C.  Is it possible?
Comment: I am just curious, why would you do this? So that you could move two other block around seamlessly by using one block as a container, or 'basket'?
Comment: My idea is that two blocks are in the same space that one block in the right column.  I thought in blocks embed.
Answer: Yes, when you create a block programatically you can add any content inclusive another blocks.
In your block function you can do something like:
<code>$blockA = module_invoke('block', 'block_view', 1);
$blockB = module_invoke('block', 'block_view', 2);
return $blockA['content'].$blockB['content'];
</code>
Comment: hello Gnuget - many thx for the great answer. This is convincing me. I love your solution! Greetings
Answer: Alternately, create a View that contains A, B, and C in some combination, and expose it as a block.
Answer: I believe you can embed several blocks within another mini-panel block, with the Panels module.

Embed two blocks in a block


What is the distribution of OR (odds ratio)?

Question: I have a bunch of articles presenting "OR" with a- 95% CI (confidence intervals).
I want to estimate from the articles the P value for the observed OR.  For that, I need an assumption regarding the OR distribution.  What distribution can I safely assume/use?
Answer: The estimators $\widehat{OR}$  have the asymptotic normal distribution
around $OR$. Unless $n$ is quite large, however, their distributions are highly
skewed. When $OR=1$, for instance, $\widehat{OR}$ cannot be much smaller than $OR$ (since $\widehat{OR}\ge0$), but it could be much larger with non-negligible probability. The log transform, having an additive rather than multiplicative structure, converges more rapidly to normality. An estimated Variance is:
$$
\text{Var}[\ln\widehat{OR}]=\left(\frac{1}{n_{11}}\right)+\left(\frac{1}{n_{12}}\right)+\left(\frac{1}{n_{21}}\right)+\left(\frac{1}{n_{22}}\right).
$$
The confidence interval for $\ln OR$:
$$
\ln(\hat{OR})\pm z_{\frac{\alpha}{2}}\sigma_{\ln(OR)}
$$
Exponentiating (taking antilogs) of its endpoints provides a confidence interval for $OR$.
Agresti, Alan. Categorical data analysis, page 70.
Comment: +1, Welcome to the site, @Marzieh. I took the liberty of sprucing up your $\LaTeX$ a little bit. Make sure you still like it.
Answer: The log odds ratio has a Normal asymptotic distribution :
$\log(\hat{OR}) \sim N(\log(OR), \sigma_{\log(OR)}^2)$
with $\sigma$ estimated from the contingency table.  See, for example, page 6 of the notes:

Asymptotic Theory for Parametric Models
Comment: I clicked on the link to see "Asymptotic theory for parametric models" and it was broken.
Comment: Link is dead :(
Comment: I had the feeling it would be something of this sort - many thanks!
Comment: Some correction should be made to formula above. It is var(log(OR)) not var(OR).
Answer: Generally, with a large sample size it is assumed as reasonable approximation that all estimators (or some opportune functions of them) have a normal distribution.  So, if you only need the p-value corresponding to the given confidence interval, you can simply proceed as follows:

transform $OR$ and the corresponding $(c_1,c_2)$ CI to $\ln(OR)$ and
$(\ln(c_1),\ln(c_2))$
[The $OR$ domain is $(0,+\infty)$ while $\ln(OR)$ domain is $(-\infty,+\infty)$]

since the length of every CI depends on its level alpha
and on estimator standard deviation, calculate
$$
d(OR)=\frac{\ln(c_2)-\ln(c_1)}{z_{\alpha/2}\times 2}
$$
$[\Pr(Z>z_{\alpha/2})=\alpha/2; z_{0.05/2}=1.96]$

calculate the p-value corresponding to the (standardized normal) test statistic $z=\frac{\ln(OR)}{sd(OR)}$
Comment: This site supports LateX commands, you just enclose them in dollar signs.  For example to get $(-\infty,\infty)$ write "(-\infty,\infty)" enclosed in $ signs. see [the wiki page](http://en.wikibooks.org/wiki/LaTeX/Mathematics) for syntax, but ignore the 'begin{math}' and 'end{math}' parts, just use dollar sign instead.
Answer: Since the odds ratio cannot be negative, it is restricted at the lower end, but not at the upper end, and so has a skew distribution.
Comment: Thank you for providing this comment!  But unless you can quantify the amount of skewness, that fact by itself is not very useful.  Plenty of distributional families are skewed but have practical normal approximations, such as the Chi-square (Gamma) and Poisson, and plenty more can be strongly skewed but rendered close to (or exactly) Normal through a simple re-expression of the variable, such as the Lognormal.  Could you perhaps amplify your answer to explain how the knowledge of the skewness could be used to estimate p-values from reported ORs?


cv.glmnet lambda stability

Question: Intro
I am running cv.glmnet from the glmnet package in R. I am running 10-fold cross validation 100 times on a dataset that has 25,000 observations and 150 variables. I am using the parallel = TRUE option, as that greatly speeds up results.
Problem Description

I notice that the minimum lambda value (lambda.min) and the lambda value within 1 standard error of the minimum (lambda.1se) are exactly the same in 99.9% of all 100 cross validation runs.
Each cross validation run leads to the calculation of exactly 25 lambdas - no more and no less (recall that the default is that the number of lambdas depends on whether the deviance changes sufficiently from one run to the next). I have left the default settings as they are, which allows for the calculation of 100 lambdas unless the deviance stops changing significantly.
The cross validation error varies minimally (average of 0.002).
If I run another few iterations of 100 10-fold cross validations on a different split into training and test populations, I get a slightly different minimum lambda and lambda within 1 standard error of the minimum from the other iterations. The above points hold, however, for the given iteration (i.e. same lambda, same exact number of lambdas calculated per cross validation run, minimal change in cross validation error).

Final Question
Why are all my cross validation results within a given iteration so similar (perhaps because all folds in the cross validation are always very similar)?
Answer: Folds should be different (if you don't fix seed) with every iteration.
I think there is nothing suprising here since you have a lot of observations (assuming your data is not sparse) and relatively few variables.
In this setting it is quite natural if you do 10-fold cross-validation that estimated relationships between your variables on 90% of your dataset will match the ones on full dataset quite closely and be similar to each other.
Low cross-validation error is not a problem. However when you fit the model you should check that you get similar error by making predictions on a test set (again assuming that data was split into test and train randomly).

cv.glmnet lambda stability


Como exibir foto da API em nova página?

Question: Consumo uma API que lista os dados de uma raça canina numa tabela. Ao clicar na raça sou direcionado a uma nova página recebendo a id e exibindo as informações do JSON.
Preciso exibir a imagem do cão da API.
Não consegui acessar o jpg contido na img: url em https://api.thedogapi.com/v1/breeds
meu objetivo: exibir a imagem no lugar da tag "p" do último código

function fazGet(url){
    let request = new XMLHttpRequest()
    request.open("GET",url,false)
    request.send()
    return request.responseText
    }
    fetch('https://api.thedogapi.com/v1/breeds').then(response => {
    return response.json()
    })

    function criaLinha(usuario){
    linha = document.createElement('tr')
    tdNome = document.createElement('td')
    tdNome.setAttribute('innerText', `https://api.thedogapi.com/v1/breeds/${usuario.id}`)
    tdLife = document.createElement('td')

    tdMais = document.createElement('a')
    tdMais.setAttribute('href',`detalhes.html?id=${usuario.id}`)

    tdNome.innerHTML = usuario.name;
    tdLife.innerHTML = usuario.life_span;
    tdMais.innerHTML = 'Info';

    linha.appendChild(tdNome)
    linha.appendChild(tdLife)

    linha.appendChild(tdMais)

    return linha
    }

    let cont = 0;
    function main(){
    let data = fazGet(`https://api.thedogapi.com/v1/breeds?limit=25&page=${cont}&order=ASC`)
    let usuarios = JSON.parse(data)

    let tabela = document.getElementById('tabela')
    usuarios.forEach(element => {
        let linha = criaLinha(element)
        tabela.appendChild(linha)
    })
    cont++
    }

    main()
table, th, td, tr{
    border: 1px solid black ;
    align-items: center;
}

nav{
    margin: 15px 15px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="main.css">
    <title>Document</title>

              »
              Exibir mais

const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');

function exec(){
    const data = fetch(`https://api.thedogapi.com/v1/breeds/${id}`)
    .then(e=>e.json())
    .then(param=>{
        const dados = param
        document.querySelector("#name").innerHTML = dados.name;
        document.querySelector("#weight").innerHTML = (`${dados.weight.metric} kg`);
        document.querySelector("#life_span").innerHTML = dados.life_span
        document.querySelector("#temperament").innerHTML = dados.temperament;
        document.querySelector("#origin").innerHTML = dados.origin;
        document.querySelector("#image").innerHTML = dados.reference_image_id;
        console.log(dados);
    })

}
exec()
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="main.css">
    <title>Document</title>

Raça

Peso

Tempo de Vida

Temperamento

Origem

    Retornar para lista

Answer: Voce pode criar uma nova pagina que busque as informacoes pelo ID.
Ao chamar sua nova pagina, voce devera passar o id como parametro na URL, pegar esse parametro da URL e enviar para a API novamente, para que ela lhe retorne os valores apenas desse animal
Vamos ao exemplo:
Se voce tem uma pagina chamada index.html, pode criar outra chamada detalhes.html
Onde voce colocou o
tdNome.setAttribute('href',`https://api.thedogapi.com/v1/breeds/${usuario.id}`)

voce pode substituir por :
tdNome.setAttribute('href',`detalhes.html?id=${usuario.id}`)

dentro dessa nova pagina, voce pode pegar o valor do ID com o seguinte codigo:
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');

E então, pode chamar a API para pegar as informações utilizando esse id:
fetch(`https://api.thedogapi.com/v1/breeds/${id}`).then(response => {
  const data = response.json()

  // considerando que você tem um elemento com o id "name"
  document.querySelector("#name").innerHTML = data.name;

  // altera o restante dos campos que quiser mostrar...
})

Buscando a imagem do cão:
Para isso, você precisará requisitar novamente a API, para que ela lhe retorne a URL. Pelo que li na documentação da API, eles têm essa rota para buscar informações de imagens (inclusive a URL):
https://api.thedogapi.com/v1/images/{image_id}

O image_id é o reference_image_id retornado na primeira requisição. Então basta fazer uma nova requisição para buscar os dados da imagem, dessa forma:
function getImage(imageId) {
  fetch(`https://api.thedogapi.com/v1/images/${imageId}`).then(response =>
  {
    const data = response.json()

    // lembre que você tem que ter um elemento
    //  dentro do HTML
    document.querySelector("#image").src = data.url;
  })
}

Então você deve chamar esse método dentro do método exec
No lugar do código
document.querySelector("#image").innerHTML = dados.reference_image_id

Você deve substituir por
getImage(dados.reference_image_id);

Comment: Atualizei a resposta com a busca da imagem. Espero ter ajudado
Comment: Vocês são demais! Única pendência é a imagem. Não consegui trazer da API, vou estar abrindo outra pergunta. Se puder dar uma olhada agradeço.
Comment: @Fhellipe: Se esta resposta resolveu o seu problema e não restou nenhuma dúvida, marque-a como correta/aceita ao clicar no "✅" que está ao lado dela, o que também marca a sua pergunta como resolvida. Se ainda te resta alguma dúvida ou gostaria de maiores esclarecimentos, fique à vontade para comentar. Se a resposta o agradou tanto considere votar na resposta que é [maneira correta de agradecer no Stack Overflow](https://pt.meta.stackoverflow.com/q/605/137387).
Comment: Allef Douglas, essa resposta não responde o problema do AP. Ele quer a foto do animal porém ele se recusa a ler a documentação da API que está usando, já tentei passar o link da documentação mostrando como usar ele ignorou e apenas replicou o que escrevi que é o que está na pergunta. Se realmente quer ajudar o usuário aqui está o [link de como trabalhar com fotos com The DOG API](https://docs.thedogapi.com/api-reference/images/)
Comment: Eu já tinha marcado, mas por algum motivo não aprovou. Quanto a eu ler a documentação, eu li mas não entendi mesmo. Tanto que meti um         document.querySelector("#image").innerHTML = dados.reference_image_id;
 e agora vi que não é a jpg. Sou iniciante mesmo e a minha falta de conhecimento pode ter passado má impressão.
Comment: Tem como dar like ou fazer alguma coisa a mais? Você é o mais brabo @AllefDouglas! Medalha de ouro!
Algum curso que possa me indicar pra dominar essa parte web mano? Js, React etc? Sucesso!
Comment: @Fhellipe, como assim *dar like ou fazer alguma coisa a mais*. Não foi você quem deu o votou positivo na resposta. A resposta teve 3 votos negativo, 1 voto positivo meu e a sua aceitação. O que pode fazer é votar positivamente como o foi orientado no link que anteriormente passei.

Como exibir foto da API em nova página?


Existe alguma diferença de performance entre escrever um arquivo como resposta e escrever em um arquivo por partes (buffer)?

Question: Eu tenho uma instância t2.micro na amazon onde eu utilizo IIS 10 como servidor e webforms na aplicação (C#).
Em uma determinada parte da aplicação, eu preciso pegar uma lista de arquivos de imagens de uma determinada pasta, zipar ela e responder como download para o usuário.
O problema é que em um determinado caso específico, quando o arquivo ZIP chegou a 1GB, o servidor simplesmente trava quando o usuário clica no botão para fazer o download desse arquivo ZIP.
Eu gostaria de tirar algumas dúvidas, não referente ao problema acima, mas uma dúvida técnica a respeito de como funcionam as respostas de download, quando você escreve ela através de um Stream ou algo do tipo.
Para o servidor, existe alguma diferença entre escrever uma resposta de um arquivo diretamente e escrever utilizando buffer (utilizando um while, por exemplo)?
Exemplo 1 - Diretamente:
// headers para download
readfile($filename);

Exemplo 2 - Por Buffer:
// headers para download

$handler = fopen($filename);

while(feof($handler) !== false) {
   echo fgets($handler, 4096);
}

Comment: Obrigado downvoter, gostaria de um feedback
Answer: Há diferenças sim.
No primeiro caso o arquivo será carregado inteiramente na memória do servidor antes de ser enviado para o cliente.
No segundo caso o arquivo será parcialmente carregado na memória e sendo enviado aos poucos para o cliente. Desta forma você compromete menos a memória do servidor, pois ele poderá atender múltiplas requisições consumindo pouca memória para cada uma delas.
Sobre o seu problema, provavelmente você está utilizando-se do primeiro caso (carregando o arquivo inteiro na memória), fazendo com que o servidor t2.micro (que curiosamente tem 1 GB de memória RAM) trave e pare de responder.
Em termos de performance, usando a técnica do segundo caso, o download não só economizará memória como também começará mais cedo a ser disponibilizado para o usuário, pois o tempo de carregar parte de um arquivo vs um arquivo inteiro na memória do servidor são bem diferentes.
Há uma implementação parcial feita em Java com Spring na qual é possível também reproduzir este comportamento, mostrando também as duas situações.


Alterar valor default de um boolean em um select ASP.NET

Question: Tenho um campo  no meu sistema que precisa informar se o produto está ou não disponível, no SQL está como bit( TRUE ou FALSE).
o EntityFramework gerou uma View com um SELECT True ou False.

    @Html.LabelFor(model => model.Alugada, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Alugada)
            @Html.ValidationMessageFor(model => model.ativa, "", new { @class = "text-danger" })

Como personalizo os campos True e False?
Comment: Você teria o acesso a criação desse form no front? Caso tenha você pode verificar a opção do select, vou postar uma resposta com o meu exemplo, porém o form é gerado por mim, não sei se é possivel
Answer: Eu criei um form e adicionei os mesmos campos para teste, espero que funcione.
Na hora que iniciar o form coloquei para que ele crie uma lista de string e adicione como dataSource da list.
    protected void Page_Load(object sender, EventArgs e)
    {
        List<string> situacao = new List<string>();
        situacao.Add("Ativo");
        situacao.Add("Inativo");
        lstSituacao.DataSource = situacao;
        lstSituacao.DataBind();
    }

Ai quando mandar para o banco você faz a validação e troca, que ficaria no button.

Caso tenha acesso ao BACK do form e FRONT eu conseguiria
  modifica-lo porém tem apenas um deles.


How to use `pipeline.start(execution_display_name)`

Question: I would like to control the "Name" field that appears in the SageMaker GUI and pass it custom values, determined upon SageMaker Pipeline execution.

Specifically I would like to use a time-stamp both for the "Name" field and for defining the pathing used to save SageMaker Pipeline artifacts to S3. That is, I would be able to look at the SageMaker list of executions and quickly be able to match it with the corresponding artifacts.
I have been able to change "Name" by going to run_pipeline.py and doing
execution = pipeline.start(execution_display_name='my-exec-name')

However, I have no idea where I should define a time-stamp such that it can be used here and in pipeline.py, eg.
import time
time_stamp = time.strftime("%Y-%m-%d--%H-%M-%S", time.gmtime())

such that time_stamp can be passed to both run_pipeline.py and pipeline.py
Answer: Got a solution I can live with. The following changes gave me the functionality I needed.
# run_pipeline.py
import time
time_stamp = time.strftime("%Y-%m-%d--%H-%M-%S", time.gmtime())
pipeline = get_pipeline_driver(time_stamp, args.module_name, args.kwargs)

# _utils.py
def get_pipeline_driver(time_stamp, module_name, passed_args=None):
    ...
    return _imports.get_pipeline(time_stamp, **kwargs)

# pipeline.py
def get_pipeline(
    time_stamp,
    ...
    ):