text:
Q: What exactly is "ParameterErrors" of NonlinearModelFit? I am trying to get what I call a "$\chi^2$ fit". This means taking a function $f(x,p)$ of the variable $x$ with a parameter $p$ and finding the value of $p$ that minimizes the "distance" from a data set $\{x_i, d_i\}$, i.e. minimizes the quantity
$$\chi^2=\frac{\left(f(x_i,p) - d_i\right)^2}{d_i}$$
See this Yale course notes for a reference.
You can find the value of the parameter $p$ with NMinimize, of course, or use NonlinearModelFit. I figured out that to get the same result, i.e. perform the same minimization, you need to use
nlm = NonlinearModelFit[data, 1 + p x^2, {p}, x, Weights -> (1/#2 &)]

where I have taken f[x,p] = 1 + p*x^2 just to give an example
This procedure is supposed to give you the best estimate of the parameter $p$ and an error is associated to to this estimate. I thought that nlm["ParameterErrors"] would give this error, but I do not find any documentation for this.
Usually, for a one parameter estimation at 68% confidence level, the error comes from looking at the curve $\chi^2=1+\chi_\min^2$ where $\chi_\min^2$ is the value of the function $\chi^2$ for the parameter $p$ that minimizes $\chi^2$ (in other words the value at the best fit).
By direct computation and confronting with "ParameterErrors" it seems that "ParameterErrors" does not give this type of error estimate.
Now, is anybody aware of what exactly "ParameterErrors" does and how to instruct NonlinearModelFit to do what I need to do?

A: To fit a model and obtain a measure of precision for the parameter estimates one needs to consider the error structure in addition to matching the data with a function to be minimized or maximized.  And finding the value of a parameter that minimizes some function does not necessarily result in a "best fit."  Again, it depends on what is a reasonable error structure for generating similar data.
Usually the $\chi^2$ fit involves count data (as shown in all of the examples of the notes you reference) but you don't explicitly state that in your question.  Using your example of
$$f(x,p)=1+p x^2$$
suppose $d_i \sim Poisson(1+p x_i^2)$.  For the set of observed counts $d_i$ you want to calculate
$$\chi^2 = \sum_{i=1}^n {{(f(x_i,p)-d_i)^2}\over{d_i}}$$
But there are problems when $d_i=0$ and this isn't the definition in the referenced notes.  The definition in the notes is
$$\chi^2 = \sum_{i=1}^n {{(observed_i-expected_i)^2}\over{expected_i}}$$
which translates to
$$\chi^2 = \sum_{i=1}^n {{(d_i-f(x_i,p))^2}\over{f(x_i,p)}}$$
where $f(x_i,p)>0$.
The most straightforward way to estimate $p$ and obtain an appropriate measure of precision is to use maximum likelihood.  That can be done directly by constructing the likelihood function and maximizing it with respect to $p$ or using GeneralizedLinearModelFit.  Your use of NonlinearModelFit results in an estimator with nearly the same optimal properties of the maximum likelihood estimator.  (A Bayesian approach is also reasonable but I've left that out.)
To show the differences (and similarities) among the different estimation techniques first generate some data:
(* Generate some observed counts where p = 0.5 *)
n = 100;
x = Table[i/10, {i, n}];
e = 1 + p x^2;
SeedRandom[1234];
d = Flatten[Table[RandomVariate[PoissonDistribution[e[[i]] /. p -> 1/2], 1], {i, n}]];
data = Transpose[{x, d}];

Now estimate $p$ in a variety of ways:
(* Minimize sum of (observed-expected)^2/expected *)
pmin = p /. NMinimize[{Total[(d - e)^2/e], p > 0}, p, WorkingPrecision -> 100][[2]];
N[pmin, 20]
(* 0.52824973972704747790 *)

(* NonlinearModelFit with weights *)
pnlm = p /.
   NonlinearModelFit[data, 1 + p xx^2, {p}, xx, Weights -> (1/#1 &),
     WorkingPrecision -> 100]["BestFitParameters"];
N[pnlm, 20]
(* 0.50953435937653171258 *)

(* Maximum likelihood estimate *)
(* First get log of likelihood *)
logL = -Sum[1 + p x[[i]]^2, {i, n}] +
   Sum[o[[i]] Log[1 + p x[[i]]^2], {i, n}];
pmle = p /. NMaximize[{logL, p > 0}, p, WorkingPrecision -> 100][[2]];
N[pmle, 20]
(* 0.51267504624247847170 *)

(* GerneralizedLinearModelFit - logically the same as maximum likelihood estimate *)
glm = GeneralizedLinearModelFit[data, xx^2, xx,
   ExponentialFamily -> "Poisson", LinearOffsetFunction -> 1,
   IncludeConstantBasis -> False, LinkFunction -> "IdentityLink",
   WorkingPrecision -> 100];
N[glm["BestFitParameters"][[1]], 20]
(* 0.51267504624247847170 *)

An estimate of the standard error of the maximum likelihood estimator of $p$ is found with
N[glm["ParameterErrors"][[1]], 20]
(* 0.012605361614497436926 *)


text:
Q: CodeIgniter Cannot Locate Model When Using SSL I seem to be having an SSL issue with a site I am developing using CodeIgniter.  I am using a wildcard SSL certificate issued via Thawte that has been verified and properly installed.  However it seems I am having a problem with CodeIgniter locating models when I access it through the secure URL.
When I access the following URL via https, I get an error that CI cannot locate the model.
https://takeoff.specwise.com/index.php/admin/
I believe this is an SSL issue because if I access the same page via a regular insecure URL, the page loads as it should:
http://takeoff.specwise.com/index.php/admin/
I have been reading all the information I can regarding SSL & CodeIgniter, both here and on the CodeIgniter forums, but I can't seem to find a fix for my specific problem.
If anybody has any thoughts or ideas as to what is going wrong or how I can correct the issue, I would really appreciate it.
Thanks for your help.

A: First thing to check: you can access your main page (index.php) OK with https?
Are you using Apache? You might want to check that you don't have some settings (redirections, rewrites) in your apache conf that apply only to the http virtual site. I once had the apache settings for my site in a virtual name host:
<VirtualHost *:80>
    ServerName example.com
....
</VirtualHost>

Obviously, that does not apply to https, so in that case you'd need to change the 80 to a *, or define another virtual host for your https site.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert enum to char I'm working on a Hibernate project, here is an extract of my class:
@Entity
@Table(name = "T_JOB")
@SequenceGenerator(name = "seqJob", sequenceName = "SEQ_JOB", allocationSize = 1)
@Getter
@Setter
public class Job {

    @Convert(converter = HibernateBooleenVersCaractere.class)
    @Column(name = "STATUT_EXTRACTION")
    private boolean statutExtraction;
}

In my database STATUT_EXTRACTION is a CHAR type that's why I used a converter (HibernateBooleenVersCaractere implements AttributeConverter) and it worked perfectly.
The boolean statutExtraction was usefull until now because I had only two state (OK = true = 1 in DB, Error = false = 0 in DB). But now I would like to add a state. In order to do that I created a enum state and used enumerated type:
@Entity
@Table(name = "T_JOB")
@SequenceGenerator(name = "seqJob", sequenceName = "SEQ_JOB", allocationSize = 1)
@Getter
@Setter
public class Job {
    public enum Statut {
        ERROR, OK, LOAD
    }

    @Column(name = "STATUT_EXTRACTION")
    @Enumerated(EnumType.STRING)
    private Statut statutExtraction;
}

Here I got an error caused by EnumType different from STATUT_EXTRACTION type in database I guess.
I had a second idea: use a converter as I did for converting boolean to char:
public class HibernateEnumVersChar
        implements
        AttributeConverter<Statut, Character> {

    @Override
    public Character convertToDatabaseColumn(final Statut statut) {
        if (statut == Statut.OK) {
            return '1';
        } else if (statut == Statut.LOAD) {
            return '2';
        } else if (statut == Statut.ERROR) {
            return '0';
        } else {
            return null;
        }

    }

    @Override
    public Statut convertToEntityAttribute(final Character dbData) {
        if (dbData == '1') {
            return Statut.OK;
        } else if (dbData == '2') {
            return Statut.LOAD;
        } else if (dbData == '0') {
            return Statut.ERROR;
        } else {
            return null;
        }
    }

}

And changed my Job class to:
@Entity
@Table(name = "T_JOB")
@SequenceGenerator(name = "seqJob", sequenceName = "SEQ_JOB", allocationSize = 1)
@Getter
@Setter
public class Job {
    public enum Statut {
        ERROR, OK, LOAD
    }

    @Convert(converter = HibernateEnumVersChar.class)
    @Column(name = "STATUT_EXTRACTION")
    private Statut statutExtraction;
}

And here I have this error:

Error attempting to apply AttributeConverter

Sadly I can't change the database type (char) because I have a lot of data.
Has some one an idea where can my error be (or why not a different way to do what I need to do !) ?

A: What I suggest here is to use the @Enumerated annotation with the attribute EnumType.ORDINAL, ORDINAL here will get you a number 0, 1 or 2 giving the order the value was defined in the Enum.
So when you define:
public enum Statut {
    ERROR, OK, LOAD
}

So here we will have:
Statut.ERROR.ordinal()  ---> gives 0
Statut.OK.ordinal()  ---> gives 1
Statut.LOAD.ordinal()  ---> gives 2

Conculsion:
Change your column definition like this:
@Enumerated(EnumType.ORDINAL)
@Column(name = "STATUT_EXTRACTION")
private Statut statutExtraction;

Note:
The database column should be changed to NUMBER(1,0), or you can convert it to a Char inside your Enum definition, please read Hibernate & Enum handling article for further details.


text:
Q: Spock mock - set and get parameter I'm using atlassian's maven in my project and want to implement tests in spock framework. I have a problem with Mock classes from maven (for example class Issue - it has some private value like key or summary and there is not method like setKey and setSummary).
I want to Mock() Issue object, set there some value and then get it (there is getKey() and  getSummary()).
My code looks like:
class WriterSpec extends Specification {

    def returnValue() {
        given:
            Issue g = Mock(key: "exampleKey")
            String response = g.getKey()
        expect:
            response == "exampleKey"
    }
}

If I tried to run tests from IDE there is an error(there is no problem with Issue object in java classes, just in groovy):
Information:Groovyc: While compiling tests of exampleProject:java.lang.NoClassDefFoundError: Unable to load class com.atlassian.jira.issue.Issue due to missing dependency org/ofbiz/core/entity/GenericValue
    at org.codehaus.groovy.vmplugin.v5.Java5.configureClassNode(Java5.java:391)
    at org.codehaus.groovy.ast.ClassNode.lazyClassInit(ClassNode.java:265)
    at org.codehaus.groovy.ast.ClassNode.getDeclaredMethods(ClassNode.java:872)
    at org.codehaus.groovy.ast.ClassNode.getMethods(ClassNode.java:887)
    at org.spockframework.compiler.SpecialMethodCall.checkIsConditionBlock(SpecialMethodCall.java:194)
    at org.spockframework.compiler.SpecialMethodCall.parse(SpecialMethodCall.java:151)
    at org.spockframework.compiler.AbstractDeepBlockRewriter.visitMethodCallExpression(AbstractDeepBlockRewriter.java:110)
    at org.codehaus.groovy.ast.expr.MethodCallExpression.visit(MethodCallExpression.java:66)
    at org.codehaus.groovy.ast.CodeVisitorSupport.visitBinaryExpression(CodeVisitorSupport.java:146)
    at org.spockframework.compiler.AbstractDeepBlockRewriter.doVisitBinaryExpression(AbstractDeepBlockRewriter.java:150)
    at org.spockframework.compiler.AbstractDeepBlockRewriter.visitBinaryExpression(AbstractDeepBlockRewriter.java:98)
    at org.spockframework.compiler.DeepBlockRewriter.visitDeclarationExpression(DeepBlockRewriter.java:86)
    at org.codehaus.groovy.ast.expr.DeclarationExpression.visit(DeclarationExpression.java:89)
    at org.codehaus.groovy.ast.CodeVisitorSupport.visitExpressionStatement(CodeVisitorSupport.java:71)
    at org.codehaus.groovy.ast.ClassCodeVisitorSupport.visitExpressionStatement(ClassCodeVisitorSupport.java:196)
    at org.spockframework.compiler.AbstractDeepBlockRewriter.doVisitExpressionStatement(AbstractDeepBlockRewriter.java:146)
    at org.spockframework.compiler.DeepBlockRewriter.doVisitExpressionStatement(DeepBlockRewriter.java:61)
    at org.spockframework.compiler.AbstractDeepBlockRewriter.visitExpressionStatement(AbstractDeepBlockRewriter.java:87)
    at org.codehaus.groovy.ast.stmt.ExpressionStatement.visit(ExpressionStatement.java:42)
    at org.spockframework.compiler.StatementReplacingVisitorSupport.replace(StatementReplacingVisitorSupport.java:44)
    at org.spockframework.compiler.AbstractDeepBlockRewriter.visit(AbstractDeepBlockRewriter.java:71)
    at org.spockframework.compiler.DeepBlockRewriter.visit(DeepBlockRewriter.java:49)
    at org.spockframework.compiler.SpecRewriter.visitAnyBlock(SpecRewriter.java:311)
    at org.spockframework.compiler.model.SetupBlock.accept(SetupBlock.java:32)
    at org.spockframework.compiler.model.Method.accept(Method.java:70)
    at org.spockframework.compiler.model.Spec.accept(Spec.java:113)
    at org.spockframework.compiler.SpockTransform$Impl.processSpec(SpockTransform.java:77)
    at org.spockframework.compiler.SpockTransform$Impl.visit(SpockTransform.java:64)
    at org.spockframework.compiler.SpockTransform.visit(SpockTransform.java:47)
    at org.codehaus.groovy.transform.ASTTransformationVisitor$3.call(ASTTransformationVisitor.java:321)
    at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:931)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:593)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:569)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:546)
    at org.jetbrains.groovy.compiler.rt.GroovyCompilerWrapper.compile(GroovyCompilerWrapper.java:62)
    at org.jetbrains.groovy.compiler.rt.DependentGroovycRunner.runGroovyc(DependentGroovycRunner.java:115)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jetbrains.groovy.compiler.rt.GroovycRunner.intMain2(GroovycRunner.java:136)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jetbrains.jps.incremental.groovy.InProcessGroovyc.runGroovycInThisProcess(InProcessGroovyc.java:156)
    at org.jetbrains.jps.incremental.groovy.InProcessGroovyc.access$000(InProcessGroovyc.java:51)
    at org.jetbrains.jps.incremental.groovy.InProcessGroovyc$1.call(InProcessGroovyc.java:85)
    at org.jetbrains.jps.incremental.groovy.InProcessGroovyc$1.call(InProcessGroovyc.java:82)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

and if I tried to run tests from console (by using atlas-mvn clean test):
Running example.WriterSpec
wrz 28, 2017 10:51:35 AM org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap invoke
INFO: Configuring com.athaydes.spockframework.report.SpockReportExtension
wrz 28, 2017 10:51:35 AM org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap invoke
INFO: SpockReports config loaded: [com.athaydes.spockframework.report.template.TemplateReportCreator.reportFileExtension:md, com.athayde
s.spockframework.report.template.TemplateReportCreator.specTemplateFile:/templateReportCreator/spec-template.md, com.athaydes.spockframe
work.report.IReportCreator:com.athaydes.spockframework.report.internal.HtmlReportCreator, com.athaydes.spockframework.report.template.Te
mplateReportCreator.summaryTemplateFile:/templateReportCreator/summary-template.md, com.athaydes.spockframework.report.internal.HtmlRepo
rtCreator.summaryReportCss:spock-summary-report.css, com.athaydes.spockframework.report.template.TemplateReportCreator.summaryFileName:s
ummary.md, com.athaydes.spockframework.report.internal.HtmlReportCreator.featureReportCss:spock-feature-report.css, com.athaydes.spockfr
amework.report.hideEmptyBlocks:false, com.athaydes.spockframework.report.outputDir:build/spock-reports]
wrz 28, 2017 10:51:35 AM org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap invoke
INFO: Loading settings for reportCreator of type com.athaydes.spockframework.report.internal.HtmlReportCreator
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.718 sec <<< FAILURE!
returnValue(example.WriterSpec)  Time elapsed: 0.05 sec  <<< ERROR!
java.lang.NoClassDefFoundError: org/apache/lucene/search/FieldComparatorSource
        at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
        at java.lang.Class.privateGetPublicMethods(Class.java:2902)
        at java.lang.Class.privateGetPublicMethods(Class.java:2911)
        at java.lang.Class.getMethods(Class.java:1615)
        at org.codehaus.groovy.util.LazyReference.getLocked(LazyReference.java:49)
        at org.codehaus.groovy.util.LazyReference.get(LazyReference.java:36)
        at example.WriterSpec.returnValue(WriterSpec.groovy:13)
Caused by: java.lang.ClassNotFoundException: org.apache.lucene.search.FieldComparatorSource
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 7 more

I did a little bit of research but it didn't help. I have no idea what is a problem and why it doesn't work. What should I do to fix it?
@UPDATE dependency from pom file:
<dependencies>
        <dependency>
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-tests</artifactId>
            <version>7.2.1</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <artifactId>dom4j</artifactId>
                    <groupId>dom4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-api</artifactId>
            <version>${jira.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- spock-core -->
        <dependency>
            <groupId>org.spockframework</groupId>
            <artifactId>spock-core</artifactId>
            <version>1.0-groovy-2.4</version>
            <scope>test</scope>
        </dependency>
        <!-- Overrides the Groovy version specified by spock-core-->
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.4</version>
            <scope>test</scope>
        </dependency>
        <!-- Creates the test report -->
        <dependency>
            <groupId>com.athaydes</groupId>
            <artifactId>spock-reports</artifactId>
            <version>1.2.7</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

A: Here's how to test returnIssueKeyWithPrefix only:
import spock.lang.Specification

class LolSpec extends Specification {

    def 'whatever'() {
        given:
        def prefixer = new Prefixer()
        def issue = Mock(Issue) {
            getKey() >> '1234'
        }

        when:
        def withPrefix = prefixer.returnIssueKeyWithPrefix(issue)

        then:
        withPrefix == 'prefix1234'
    }
}

class Issue {
    String getKey() {
        throw new UnsupportedOperationException('No!')
    }
}

class Prefixer {
    String returnIssueKeyWithPrefix(Issue issue) {
        return "prefix${issue.key}"
    }
}


text:
Q: Access HttpServletResponse from GWT Client I have an upload form to upload a file. The uploading is through form.submit() and a Servlet. I got a feedback from the server as sesponse and I would like to print the response on GWT-Client to the user. In a servlet I can not use any GUI-Widget so how can I access the http servlet response from gwt client, which invoked the servlet?

A: The HttpServletResponse class is a server side class, you can't access it from the client side.
What you can do is add a FormPanel.SubmitCompleteHandler to the FormPanel, and in the onSubmitComplete() method you can access the result text of the form submission:
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
    public void onSubmitComplete(SubmitCompleteEvent event) {
        Window.alert(event.getResults());
    }
});

Complete runnable example program can be found in the javadoc of FileUpload.


text:
Q: eslint: no return assign So I'm having a problem with a no return assign but my script seems good can someone help me with it?
The script is:
(function() {
    'use strict';
    let root = document.querySelector(":root");
    root.style.setProperty("--tv-color-pane-background", "#000");

    setTimeout(() => document.querySelector("html.theme-dark .tv-floating-toolbar").style.backgroundColor = "black", 1000);
})();

on the settimeout line It's giving me this error:enter image description here


text:
Q: SetFrame of the UIWebView I'm loading an HTML string into a UIWebView. When the UIWebView finishes loading, I resize its height like this:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    float newSize = [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"] floatValue];
    [self.webViewContent setFrame:CGRectMake(self.webViewContent.bounds.origin.x,
         self.webViewContent.bounds.origin.y,
         self.webViewContent.frame.size.width,
         newSize)];

Everything works fine until a certain height. When the HTML string gets really long - 60 000px, for example - then I get a crash. Any ideas, how could I avoid the crash? I tried to find examples where a UIWebView is being tiled, but I couldn't find anything useful.

A: You're almost certainly running out of memory. I've determined through experimentation that UIWebView allocates memory based on the frame size. You can have a seemingly infinite contentSize and iOS will handle the memory for you as content scrolls in and out of the visible frame.
I had to give up on a design that tiled UIWebViews inside of a UIScrollView. BTW, this behavior changed somewhere around iOS 4.2. It used to be possible to tile UIWebViews with very large frame sizes and the memory was constrained by the frame size of the containing UIScrollView.


text:
Q: Search records with in an two dimensional array i am trying to do one thig ,but i am not getting the point.can anyone please suggests me ..
two dimensional array like below
$array = Array
([1] => Array
    ([1] => EST_ID
     [2] => EST_CODE
     [3] => EST_EXT
     [4] => EST_NAME
     [5] => INCROP_ADDRESS1
     [6] => INCROP_ADDRESS2
     [7] => INCROP_CITY
     [8] => INCROP_DIST
     [9] => INCROP_STATE
     [10] => INCROP_PIN
     )
 [2] => Array
    ([1] => HRKNL0006923000
     [2] => 6923
     [4] => VAIBHAV CARPETS
     [5] => BHUL-BHULIA CHOWK
     [6] => BODHWA RAM COLONY
     [7] => PANIPAT
     [8] => PANIPAT
     [10] => 132103)

 [3] => Array
    ([1] => HRKNL0004638000
     [2] => 4638
     [4] => GURU TEG BHADUR PUBLIC SCHOOL
     [5] => MODEL TOWN
     [6] => KARNAL
     [7] => KARNAL
     [8] => KARNAL
     [10] => 132001)
)

i have to search the array key of either 2 or 3 from $array

A: Not exactly sure which one you need as I didn't fully understand the question but one of these two functions will help array_key_exists() or in_array()

A: It sounds like you may be trying to do what I asked in Search a multi-dimensional array for certain values


text:
Q: Check if a text contains HTML-style tags First of all yes I am aware that it's not advisable to use regex to parse HTML, that's not the purpose of the question.
The thing is, I have some text which may contain HTML style tags like this:
<random>

Hi nice to see you!

Hi it's great to see you!

Hi how are you?

Hi! <set foo="bar">I can</set> really feel your smile today.

Hi! It's delightful <sr /> to see you.

</random>

What I want to do is to check if the given text contains (just contains) one of more of the tags. I have tried something like this but for the text above it keeps returning false.
String regex ="<(?:\"[^\"]*\"['\"]*|'[^']*'['\"]*|[^'\">])+>"; //http://stackoverflow.com/a/1736801
boolean p = Pattern.compile(categoryToUpdate.getTemplate()).matcher(regex).find();

Thanks in advance and sorry if it's a silly question :(.


text:
Q: Error using neo4j's gds.beta.pipeline.nodeClassification.train: Tensor of dimensions greater than 2 are not supported, got 2 dimensions I'm trying to do node classification with neo4j's graphdatascience (GDS).
There's some example here, but it is clear it is out of date:
https://neo4j.com/developer/graph-data-science/node-classification/
Here's some newer documentation that I'm also following:
https://neo4j.com/docs/graph-data-science/current/machine-learning/nodeclassification-pipelines/
So I have the Cora dataset of nodes which are "Papers" and edges which are between these Paper nodes. Each "Paper" node has feature x, a list of 0/1 entries that indicate whether specific words are present in the document. Also, a possible feature is "pr", the pagerank as computed by the algorithm. The label is denoted by "y" and represents the class of the Paper.
Goal is to train model on set of Paper nodes to classify (i.e. find the label y) then check this model on a testing data and generally be able to do predictions on y.
This is my code so far:
    # Client import
from graphdatascience import GraphDataScience

# Replace with the actual URI, username and password
AURA_CONNECTION_URI = "neo4j+s://xxx.databases.neo4j.io"
AURA_USERNAME = "neo4j"
AURA_PASSWORD = "password_here"

# Client instantiation
gds = GraphDataScience(
    AURA_CONNECTION_URI,
    auth=(AURA_USERNAME, AURA_PASSWORD),
    aura_ds=True
)

# Project a graph using the extended syntax
extended_form_graph_final, result = gds.graph.project(
    "Long_form_example_graph",
    {"Paper": {"label": "Paper", "properties": {"y":{"property":"y"}, "pr":{"property":"pr"}, "intX":{"property":"intX"}, "train":{"property":"train"}, "valid":{"property":"valid"}, "test":{"property":"test"}}}},
    "Citation"
)

gds.run_cypher(
    """
    CALL gds.beta.pipeline.nodeClassification.create('pipe')
    """)

gds.run_cypher(
"""
CALL gds.beta.pipeline.nodeClassification.addLogisticRegression('pipe', {penalty: 0.0625})
""")

gds.run_cypher(
"""
CALL gds.alpha.pipeline.nodeClassification.addRandomForest('pipe', {numberOfDecisionTrees: 5})
""")

gds.run_cypher(
"""
CALL gds.beta.pipeline.nodeClassification.train('Long_form_example_graph', {
  pipeline: 'pipe',
  nodeLabels: ['Paper'],
  modelName: 'hello',
  targetProperty: 'y',
  randomSeed: 1,
  metrics: ['F1_WEIGHTED']
})
""")

I'm using the jupyter lab so all of the code works, except for the last run_cypher where I'm calling gds.beta.pipeline.nodeClassification.train:
ClientError: {code: Neo.ClientError.Procedure.ProcedureCallFailed} {message: Failed to invoke procedure gds.beta.pipeline.nodeClassification.train: Caused by: java.lang.IllegalArgumentException: Tensor of dimensions greater than 2 are not supported, got 2 dimensions}
I've tried using only "pr" as a feature to guess the label y, thinking that maybe the problem was that intX is a list of integers as a feature. But that still gave me the same error :-(
Also, note that initially the feature list x was a "String", but then I used Neo4j Browser to transform the String into a list on int's which I called intX (code not shown, but I've verified this)


text:
Q: Get particular part(s) from String in C# I'm reading an email and performing a few operations.
In email it can't be in defined format as below,
Email formats:

Hi Team,
Please create 7025-45-365-14, 9851-98-524-12
      5741-55-452-45
Thanks

MailItem.Body = "Hi Team,\r\n\r\n \r\n\r\nPlease create 7025-45-365-14, 9851-98-524-12\r\n\r\n5741-55-452-45.\r\n\r\n    \r\n\r\nThanks\r\n"

My goal is to exact only the string parts into a loop one by one as below,
1st loop > 7025-45-365-14
2nd loop > 9851-98-524-12
3rd loop > 5741-55-452-45
I tried various logic but I can't extract as I need. Can someone help me?

A: To extract digits in that pattern (4-2-3-2)
foreach (var m in new Regex(@"\b(\d{4}-\d{2}-\d{3}-\d{2})\b").Matches(mail))
    Console.WriteLine(m.Value);


text:
Q: Setting Jumbo Frames Windows Server 2012 LBFO NIC Team I have created a LBFO team for use in storage and would like to enable Jumbo Frames. If I do, "Get-NetIPInterface" I get the result:
NlMtu(Bytes) 1500
If I execute, "Set-NetIPInterface -InterfaceAlias "Storage Team" -NlMtuBytes 9000 -AddressFamily "IPv4"" and do "Get-NetIPInterface" again, the MTU still reports as 1500.

*

*Do LBFO Teams support jumbo frames?

*If so, is this the correct method to set it? "Get-NetAdapterAdvancedProperty" doesn't seem to have a jumbo frame or MTU setting.

A: From what I can see the LBFO team inherits the MTU set on the interfaces. So if you use the Set-NetIPInterface -NlMtu on the interface prior to using the LBFO commands to create or add them to a team then you should end up with a team which can use jumbo frames.
Be warned though the MTU is set per address family and also probably requires you to change an advanced adapter setting in the Configure -> Advanced section of the interface properties and as far as I know these are not exposed to the PowerShell interface.

A: Just wanted to add something to this question - I came across the same issue:

*

*A LBFO team was created initially when all underlying adapters were at 1500 MTU

*There was a requirement to enable jumbo frames on this team

*After enabling jumbo frames on the underlying NICs, jumbo frames were still not enabled on the LBFO team interface

My fix was to simply restart the LBFO team adapter:
After restarting the LBFO interface with the PowerShell command Restart-NetAdapter, using the command Get-NetIPInterface now correctly showed the 9000 MTU, and jumbo frames tested with ping -f -l 8000 x.x.x.x worked correctly.
An alternative is to right click Disable & Enable on the LBFO team interface.
Each underlying NIC does not have to be restarted because they reset when you apply the jumbo frame setting. Since the LBFO adapter never understands it needs to reset to apply the MTU change, it must be done manually.


text:
Q: Como resolver problema de cálculo de margem no JavaScript? Galera tenho o seguintes inputs:
1º Custo, onde eu informo o valor de 6,23
2º Margem, onde eu informo o valor de 29,21
O JavaScript faz o cálculo automático e me retorna 8,05 no valor
Bom esta tudo correto. Porém quando faço ao contrário acontece o erro.
1º Custo, onde eu informo o valor de 6,23
2º Valor, onde eu informo o valor de 8,05
O JavaScript faz o calculo automático e me retorna 36.44 na margem, sendo que o correto seria 29,21
Alguém sabe o que pode ser?
Segue o código:

$(document).ready(function () {
    $(".valor").on("input", function () {
        // Margem
        var valor = $(this).val();
        var valorCorrigido = parseFloat(adicionarPontos(valor));

        var valorFloat = parseFloat(valorCorrigido) || 0.0;

        // Custo
        var valorCusto = $('#custo').val();
        var valorCustoCorrigido = parseFloat(removerPontos(valorCusto));
        var valorCustoFloat = parseFloat(valorCustoCorrigido) || 0.0;

        // Calculo
        var calculo = (parseFloat(valorFloat) - parseFloat(valorCustoFloat)) / parseFloat(valorCustoFloat) * 100;
        var inputMargem = $(this).attr("margem");

        $("#" + inputMargem).val(calculo.toFixed(2)).trigger('blur');
    });
    // Faz o calculo do valor com base na margem
    $(".margem").on("input", function () {
        // Margem
        var valorMargem = $(this).val();
        var valorMargemCorrigido = parseFloat(adicionarPontos(valorMargem));
        var valorMargemFloat = parseFloat(valorMargemCorrigido) || 0.0;

        // Custo
        var valorCusto = $('#custo').val();
        var valorCustoCorrigido = parseFloat(removerPontos(valorCusto));
        var valorCustoFloat = parseFloat(valorCustoCorrigido) || 0.0;

        // Cálculo
        var calculo = (parseFloat(valorCustoFloat) * parseFloat(valorMargemFloat) / 100) + parseFloat(valorCustoFloat);
        var inputValor = $(this).attr("valor");

        var resultadoMonetario = calculo.toFixed(2).toString();
        resultadoMonetario = resultadoMonetario.replace(".", ",");

        $("#" + inputValor).val(resultadoMonetario).trigger('blur');
    });

    function removerPontos(valor){
        valor = valor.replace(".","");
        valor = valor.replace(",",".");
        return valor;
    }

    function adicionarPontos(valor){
       if(valor.length == 1){
           return valor;
       }
       else{
       if(valor.length == 2){
           return valor;
       }
       else{
       valor = valor.replace(",","");
      var inteiro = valor.substring(0,valor.length - 2);

       console.log(inteiro);

       var decimal = valor.substr(2);

       console.log(inteiro + "." + decimal);
       return inteiro + "." + decimal;
       }
       }
    }
});

$('input').mask('00.000.000,00', {
    reverse: true
});

Custo:
<input type='text' id='custo' class='custo valores' name='custo'>

 Valor:
<input type='text' id='valor1' class='valor valores' name='valor1' margem='margem1'> Margem:
<input type='text' id='margem1' class='margem valores' name='margem1' valor="valor1">

 Valor:
<input type='text' id='valor2' class='valor valores' name='valor2' margem='margem2'> Margem:
<input type='text' id='margem2' class='margem valores' name='margem2' valor="valor2">

A: Tem um erro na função adicionarPontos:
O correto é:
 var inteiro = valor.substring(0,valor.length - 2);
 var decimal = valor.substring(valor.length - 2, valor.length);

Todos os trechos "console.log" podem ser removidos. São usados apenas para debugar.


text:
Q: Using Git Credentials with Azure - how does it work? I created a web app with azure, following this link

*

*Cloned a github project to my local PC

*Created a git deployment user using az webapp deployment user set --user-name <username> --password <password>.

*Created an Azure web app with az webapp create --name <app_name> --resource-group <group_name> --plan <plan_name> **--deployment-local-git**

*Add remote azure to the local repository and pushed the code to Azure.
git remote add azure
git push azure master

*Result: App is up and running

*Now I made some changes to the code locally and tried to commit with the Azure CLI.
git commit -am "Some comment"
This failed because of missing user and email configuration.

***** Please tell me who you are.

Run**

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

*It took me a while to understand I can supply any user and email here. I thought i need to supply a predefined credentials, which I didn't know what they are.  after defining any user and mail commit succeeded.

So I have few question about the process:

*

*How can push commits to Azure without supplying the credentials created is step 2 above? What are these for?

*How come I can set any user and email to perform the local commits, before pushing.

*As part of my tries I tried use the Git GUI application.
When I open the local repository I was prompt for user and password. I entered the user and password created in step 2 above. And indeed repository was opened.

*How many copies does the app have. 2 (local copy and one on Azure) or 3 (extra copy on git hub)

A: The credentials you specified in step #2 are Azure-specific. Per your link, "This deployment user is required for FTP and local Git deployment to a web app."
When you're setting up your machine to do local Git work, you should set local credentials. That way you won't get the error you show.
In your example, after cloning the Github repo to your local machine in step #1, Github is no longer involved. You could have done the clone anonymously, or you could have supplied credentials (required if you want to make actual changes to the Github repo). So to answer question #4, there are three copies, but the Github one is irrelevant at this point.
You can push from local Git to Azure, or you can push from Github to Azure (particularly useful for continuous deployment).


text:
Q: mapping state to props is returning undefined and does not update i am mapping my store state to my pagination component but it's returning undefined and only running one time when it's value is undefined not when it has value and i'm setting it to state and it's not updating the state too so i had to use store.subscribe method but this is not very good and how can i set the value to slicedPage outside the for loop so it won't run as many time as total_pages if i set outside the for loop it's empty and hope i explained it well
import React from "react";
import { connect } from "react-redux";
import store from "../../store";
import { all_Movies } from "../../actions";

My Pagination Class
export class Pagination extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      one: 0,
      last: 10,
      total_pages: this.props.pages,
      pageNumber: [],
      slicedPage: []
    };
    store.subscribe(() => {
      if (store.getState().all_Movies.total_pages) {
        console.log(store.getState().all_Movies.total_pages);
        this.setState(
          { total_pages: store.getState().all_Movies.total_pages },
          () => {
            for (let i = 1; i < this.state.total_pages; i++) {
              this.setState(
                prevState => ({ pageNumber: [...prevState.pageNumber, i] }),
                () => {
                  // page.push(this.state.pageNumber[i])
                  // console.log(page);

                  this.setState({
                    one:
                      this.state.pageNumber.slice(
                        this.state.one,
                        this.state.last
                      ).length -
                      this.state.pageNumber.slice(
                        this.state.one,
                        this.state.last
                      ).length
                  });
                  this.setState({
                    last: this.state.pageNumber.slice(
                      this.state.one,
                      this.state.last
                    ).length
                  });

I want to set this outside the for Loop
                  this.setState({
                    slicedPage: this.state.pageNumber.slice(
                      this.state.one,
                      this.state.last
                    )
                  });

----------^^^^^^
                 console.log(this.state.one, this.state.last);
                }
              );
            }
          }
        );
      }
    });
  }

  render() {
    return (

          {this.state.slicedPage.map(number => (

              <button
                onClick={() => {
                  this.loadPage(number);
                }}
              >
                {number}
              </button>

          ))}

    );
  }
}

Mapping state to props
const mapStateToProps = state => ({
  pages: state.all_Movies.total_pages,
  type: state.all_Movies.type
});

export default connect(
  mapStateToProps,
  { all_Movies }
)(Pagination);


text:
Q: Calculate tax value from gross and tax percentage I need to calculate the actual tax value when only the gross value and tax percentage is known.
The basic formula to calculate the gross amount:
$Gross = Net * (1+Vat)$
$Tax = Net * Vat$
Example:
Net = 152.75 USD
Vat = 0.07

Gross = 152.75 * (1+0.07) = 163.44 USD
Tax = 152.75 * 0.07 = 10.69 USD

Proof:
Gross - Tax = Net
163.44 USD - 10.69 USD = 152.75 USD

However, in my case I only have $Gross$ and $Vat$ and need to get the $Tax$ value in a single multiplication.
The current approach is the following:
$Tax = Gross - \frac{Gross}{(1 + Vat)}$
Example:
Tax = 163.44 USD - (163.44 USD / 1.07) = 10.69 USD

Question:
How can I get the $Tax$ value with a simple multiplication, without the need of a subtraction.

A: Using @Matti P. derived formular, one can assume that his function $f(x)=\frac{Vat*x}{1+Vat}$ is linear for a constant value of $Vat$. Hence, plotting the function with $Vat=0.07$ leads to:

The plot shows the y-intersect at $0$. Hence, one can simply use a first-order polynomial $y=mx+b$, where $m$ is unknown, $x$ is $Gross$ and $b=0$ and solve it for $m$ with any previously calculated value of $y=10.69$ and associated $x=163.44$. This leads to $m=\frac{10.69}{163.44}$.
To have a single coefficient to calculate the Tax value from using a single multiplication, one can simply use $f^*(x)=0.0654063*x$ for $Vat=0.07$.
$Tax = f^*(163.44)=0.0654063*163.44 = 10.690005672$


text:
Q: Why does blitted text on screen have a rectangle behind it in pygame? I am making a small game about chickens and I ran into something I could not find a solution for. The problem is that my text has a small rectangle behind it, as shown here: The number of coins and a rectangle behind it.
I have also figured out that the error is coming from reading a text file, the code is:

import pygame
from pygame import *

pygame.init()
surface = pygame.display.set_mode((800,600))
pg = pygame

coins = 0
eggs = 0
time_left = 12
chickens = 0
grain = 0

with open('stats.txt', 'r') as f:
    a = f.readlines()
    coins = a[0]
    eggs = a[1]
    time_left = a[2]
    chickens = a[3]
    grain = a[4]

font = pg.font.Font("freesansbold.ttf", 28)
text = font.render(coins,False,(255,255,255))

run = True
while run:
    surface.fill(0)
    for event in pg.event.get():
        if event.type == pg.QUIT:
            run = False
    surface.blit(text,(20,-2))
    pg.display.update()

The text file is:
0
0
12.0
0
0

I do not think I can change the way I am getting information from the file, but if you know a way of doing it and it works, you can let me know.

A: At the end of the text there is a character that cannot be displayed. The last character of the text is \n, because each line in the text file ends with a newline. So just remove the tailing newline from the text (see How do I remove a trailing newline?):
coins = a[0]
coins = a[0].rstrip()


text:
Q: Adjective capitalization of fictional species and nationalities There exist a fictional nation called Elf Nation. (not a creative name but this is for a grammar experiment)
The species which inhabit this nation are called elf(singular) and elves (plural).
Would the nationality of this nation be capitalized?
For example, in the real world, we would refer to a citizen of a nation as: American citizen or British citizen or Russian citizen and so on. We would capitalize the nationality and not the profession. More examples: Japanese writer, Chinese professor.
What if the adjective of our nation's citizens is the same as the species name. Would we capitalize the adjective then? Example from the real world: human astronaut, not Human astronaut
So, would we refer to a general of this fictional nation Elf Nation as: elf general or Elf general?
Also, would it be elf culture or Elf culture, seeing that we use human culture and not Human culture?
I know you could just make up a separate adjective in this case and a separate adjective already exists for this species. My question is mostly about if and when can you mix nationality and species if they are fundamentally the same.

A: When we talk about Earth as a planet (part of the Earth-Moon system), we capitalize it. When we talk about earth meaning soil, we don't. The same rules should hold for Elf/elf.
You have two different meanings of the word here. There are Elves who are citizens of Elf Nation and there is the race of elves. And for all you know, there may be dwarfs who are citizens of Elf Nation, and elves who are citizens of Ruritania, so these two concepts don't cover the same set of people.
I don't see why you shouldn't use use capitalization or not depending on whether you're using it for the nationality or the race. It will make sentences like "that dwarf is an Elf" much less confusing.
So if you say somebody is an Elf general, you mean that he is a general in the army of Elf Nation, not that he is an elf. (Of course, this ambiguity could be resolved by using elven for generals who are elves.)


text:
Q: I cannot find my test payments in sandbox [SOLVED - Sandbox bug?]
I'm trying to setup a paypal payment with IPN.
The IPN works well and gives me the right answer but:
-I cannot find the test transactions in my sandbox business account page list (only in the sandbox user account of the payer as pending)
-The transaction ID shown in receipt page when I pay is different from the one stored by the IPN script (for example  2P3936636X9979307 in receipt page and 36E923443V406174V in the IPN for the same transaction)
Where is the mistake?
Thanks
Tommaso


text:
Q: Plot a data frame I have a data frame like this:
ReviewDate_month,ProductId,Reviewer
01,185,185
02,155,155
03,130,130
04,111,111
05,110,110
06,98,98
07,101,92
08,71,71
09,73,73
10,76,76
11,105,105
12,189,189

I want to plot it, ReviewDate_Month in X, Product ID and Reviewer in Y ideally. But I will start with 1 line either Product ID or Reviewer.
so i tried:
df_no_monthlycount.plot.line

Got below error msg:
File "C:/Users/user/PycharmProjects/Assign2/Main.py", line 59, in <module>
01                      185       185
02                      155       155
03                      130       130
04                      111       111
05                      110       110
06                       98        98
07                      101        92
08                       71        71
09                       73        73
10                       76        76
    df_no_monthlycount.plot.line
AttributeError: 'function' object has no attribute 'line'
11                      105       105
12                      189       189

Process finished with exit code 1

I also tried this:
df_no_monthlycount.plot(x=df_helful_monthlymean['ReviewDate_month'],y=df_helful_monthlymean['ProductId'],style='o')

Error msg like this:
Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/Assign2/Main.py", line 52, in <module>
    df_no_monthlycount.plot(x=df_helful_monthlymean['ReviewDate_month'],y=df_helful_monthlymean['ProductId'],style='o')
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 1797, in __getitem__
    return self._getitem_column(key)
  File "C:\Python34\lib\site-packages\pandas\core\frame.py", line 1804, in _getitem_column
    return self._get_item_cache(key)
  File "C:\Python34\lib\site-packages\pandas\core\generic.py", line 1084, in _get_item_cache
    values = self._data.get(item)
  File "C:\Python34\lib\site-packages\pandas\core\internals.py", line 2851, in get
    loc = self.items.get_loc(item)
  File "C:\Python34\lib\site-packages\pandas\core\index.py", line 1572, in get_loc
    return self._engine.get_loc(_values_from_object(key))
  File "pandas\index.pyx", line 134, in pandas.index.IndexEngine.get_loc (pandas\index.c:3838)
  File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:3718)
  File "pandas\hashtable.pyx", line 686, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12294)
  File "pandas\hashtable.pyx", line 694, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12245)
KeyError: 'ReviewDate_month'

A: Call the plot as shown below:
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('data.csv')

print(df)

df.plot(x ='ReviewDate_month',y=['ProductId', 'Reviewer'] ,kind='line')
plt.show()

Will give you:

A: If you want to plot ReviewDate_Month in X, Product ID and Reviewer in Y, you can do it this way:
df_no_monthlycount.plot(x='ReviewDate_Month', y=['Product ID', 'Reviewer'])


text:
Q: Multiple data sets not working when using ChartJS I am using chart js to produce a line graph and I want to display multiple datasets showing different data. After looking online I found a solution below, but for some reason it is not working. In the console I get the following error: Uncaught ReferenceError: ctx is not defined at 1:80.
If anyone can see why the chart is not working, that would be great.
JS:
document.getElementById('productDetailGraph').getContext('2d');
    var productGraph = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['01, 10', '02, 10', '03, 10', '04, 10', '05, 10', '06, 10', '07, 10', '08, 10', '09, 10', '10, 10', ],
            datasets: [{
                data: ['123, 124, 125, 126, 128, 122, 127, 121, 125, 127'],
                label: 'Argos',
                backgroundColor: 'rgb(255, 255, 255)',
                fill: false,
                borderColor: 'rgb(128, 128, 128)',
            }, {
                data: ['121, 122, 124, 122, 129, 131, 134, 137, 138, 140'],
                label: 'Smyths',
                backgroundColor: 'rgb(255, 255, 255)',
                fill: false,
                borderColor: 'rgb(128, 128, 128)',
            }, {
                data: ['122, 129, 125, 134, 135, 138, 139, 142, 145, 154'],
                label: 'Entertainer',
                backgroundColor: 'rgb(255, 255, 255)',
                fill: false,
                borderColor: 'rgb(128, 128, 128)',
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:false
                    }
                }]
            }
        }
    });

A: You are using the variable ctx which is indeed not defined.
Change this line:
document.getElementById('productDetailGraph').getContext('2d');

To this:
var ctx = document.getElementById('productDetailGraph').getContext('2d');


text:
Q: How to disable FCM on spesific activity Android i want to ask about FCM. I have an FCM service that is running as it should this is my code
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "ch1")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(remoteMessage.getNotification().getBody())
            .setAutoCancel(true)
            .setContentIntent(pendingIntent);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
        NotificationChannel channel = new NotificationChannel("ch1",
                getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
        channel.enableLights(true);
        channel.enableVibration(true);
        mNotificationManager.createNotificationChannel(channel);
    }
    mNotificationManager.notify(0, notificationBuilder.build());

but i want to disable this notification on spesific activity, for example i have ChatActivity. where if i get notificatin on this activity, the fcm service is not showing a notification. I have tried implement this code but still not work
if(!(this.getApplicationContext() instanceof ChatActivity)){
   //build the notification
}

anyone have solution for my problem? thank you.

A: First of all keep a flag in your SharedPreferences for ChatActivity to know if it's open or not.
Now inside ChatActivity set this flag true in onResume() and false in onStop(). Like this:
@Override
protected void onResume() {
    super.onResume();
    AppPreferences.getInstance().setBoolean("IS_CHAT_ACTIVITY", true);
}

@Override
protected void onStop() {
    super.onStop();
    AppPreferences.getInstance().setBoolean("IS_CHAT_ACTIVITY", true);
}

If you don't know anything about SharedPreferences check This Tutorial.
Now in your FCM Service class, you have onMessageReceived() callback, which is triggered every time a notification comes.
Now Do this in your onMessageReceived() callback:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if(remoteMessage.getNotification() != null) {
        if (AppPreferences.getInstance().getBoolean("IS_CHAT_ACTIVITY", false)) {
            //Do Nothing, Ignore Notification
        } else {
            //Write code to show notification here
            //Show Notification
            generateNotification(remoteMessage.getNotification());
        }
    }
}

That's it, that's how you can prevent the notification while you're on ChatActivity.


text:
Q: Sharepoint 2013 custom search refiners there are some oob types of refiners like slider or slider with graph. I would like to customize a refiner to look like e.g. a treeview. Is there a way I can edit existing ones? Or maybe can I write my own from scratch? How?

A: This is what I had in mind...
http://blogs.msdn.com/b/murads/archive/2013/03/01/using-jquery-and-jqplot-in-your-display-template-to-show-a-piechart-refiner.aspx


text:
Q: Scaling font Glyph Directly c# I can't figure out my problem here. I am Scaling a Bool[] that represents a font glyph. Original size width = 6, height =14. The size I am using for my test size=4 (4 * original size). Simple multiply the height and width by 4. As a final result I am creating a Bool[] array representing the resized glyph.  But my resized array is a total of 1248. My calculation says it should be 1344. I am short 96 bits in my example. font is a custom struct.  I know there are libs that can do this but I am handling this directly. I really just want to understand what the issue with my loops are.
 private font ScaleFont(font fnt, int size )
        {
            List<bool> line = new();
            List<bool> Lineout = new();
            List <bool> fntOut = new();
            font outt = new();
            int lineJump = fnt.BbxWidth;
            int l;
            // get a line
            for (int x = 0; x < fnt.Char.Length; x++)
            {
                if ((x  <= lineJump) )
                    line.Add(fnt.Char[x]);
                else
                {
                    lineJump += fnt.BbxWidth;

                    Lineout.Clear();
                    foreach (bool b in line)
                    {
                        for (l = 1; l <= size; l++)
                        {

                            Lineout.Add(b);

                        }

                    }

                    for (l = 1; l <= size; l++)
                    {

                        fntOut.AddRange(Lineout);

                    }

                    line.Clear();
                    line.Add(fnt.Char[x]);

                }
            }
           outt.pixalOffsetWidth = fnt.pixalOffsetWidth * size;
            outt.pixalOffsetHeight = fnt.pixalOffsetHeight * size;
            outt.Char = fntOut.ToArray();
            outt.BbxWidth = fnt.BbxWidth * size;
            outt.BbxHeight = fnt.BbxHeight * size;

            return outt;

        }


text:
Q: Django - AttributeError when trying to access a field in a Form I have a form somewhere:
class FooForm(forms.Form):
    a_field = forms.CharField()
    not_a_field = 'hello world'

When instantiating this, and trying to access the field, I get a
>>> from baz.views import FooForm
>>> f = FooForm()
>>> f.not_a_field
'hello world'
>>> f.a_field
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'FooForm' object has no attribute 'a_field'

What is going on?

A: The way that Form is designed, the attributes are removed as attributes and added to the fields attribute.  This is done so that we can use declarative syntax to define our Form, but can loop through the fields when the time comes.
>>> f = FooForm()
>>> f.fields['a_field']
<django.forms.fields.CharField object at 0x1750350>

You can find the logic for this in two places.  django/forms/forms.py contains the class DeclarativeFieldsMetaclass and the method get_declared_fields.  These two bits contain the logic to move everything into the fields list.

A: Form fields are accessable through the 'fields' property.
From shell:
>>> f = FooForm()
>>> f.fields['a_field']

will return:
<django.forms.fields.CharField object at [memory location]>

You won't be able to access the field using f.a_field unless it has a value.

A: that's because a_field isn't initialized
ex:
>>> f.a_field = 'hi'
>>> print f.a_field
'hi'

you have to add data and perform your save() there


text:
Q: Restreaming video containing two languages live with ffmpeg I have a project where i need to restream a live stream which has two languages setup on the audio.
Spanish on left and English on right
The stream mapping is:
Stream #0:0: Video: h264 ([7][0][0][0] / 0x0007), yuv420p, 512x288 [SAR 1:1 DAR 16:9], q=2-31, 1k tbn, 1k tbc
Stream #0:1: Audio: mp3 ([2][0][0][0] / 0x0002), 44100 Hz, stereo, s16, 18 kb/s

I need to restream this back live with just the English from the right side or just spanish from the left side, I tried looking everywhere but did not find any type of solution .
Since this needs to be done live, I can't be using other programs to separate video and audio to get it done.
This needs to be done through ffmpeg and I wonder if it even capable of doing so with original built or it would need some custom modification.

A: You can use the -map_channel option or the pan filter. Unfortunately you didn't specify if you want a stereo or mono output. If stereo you can simply mute a channel or duplicate a channel into both left and right channels of the output. Here are some examples assuming you want to keep a stereo output.
To copy the right channel of the input to the left and right channels of the output:
ffmpeg -i input -map_channel 0.1.1 -map_channel 0.1.1 output

To mute the left channel:
ffmpeg -i input -map_channel -1 -map_channel 0.1.1 output

To mute the left channel using pan:
ffmpeg -i input -filter:a pan="stereo:c1=c1" output

FFmpeg usage questions are better suited for superuser.com since stackoverflow is programming specific.


text:
Q: How can I efficiently model the sum of Bernoulli random variables? I am modeling a random variable ($Y$) which is the sum of some ~15-40k independent Bernoulli random variables ($X_i$), each with a different success probability ($p_i$). Formally, $Y=\sum X_i$ where $\Pr(X_i=1)=p_i$ and $\Pr(X_i=0)=1-p_i$.
I am interested in quickly answering queries such as $\Pr(Y<=k)$ (where $k$ is given).
Currently, I use random simulations to answer such queries. I randomly draw each $X_i$ according to its $p_i$, then sum all $X_i$ values to get $Y'$. I repeat this process a few thousand times and return the fraction of times $\Pr(Y'\leq k)$.
Obviously, this is not totally accurate (although accuracy greatly increases as the number of simulations increases). Also, it seems I have enough data about the distribution to avoid the use simulations. Can you think of a reasonable way to get the exact probability $\Pr(Y\leq k)$?
p.s.
I use Perl & R.
EDIT
Following the responses I thought some clarifications might be needed. I will shortly describe the setting of my problem. Given is a circular genome with  circumference c and a set of n ranges mapped to it. For example, c=3*10^9 and ranges={[100,200],[50,1000],[3*10^9-1,1000],...}. Note all ranges are closed (both ends are inclusive). Also note that we only deal with integers (whole units).
I am looking for regions on the circle that are undercovered by the given n mapped ranges. So to test whether a given a range of length x on the circle is undercovered, I test the hypothesis that the n ranges are mapped randomly. The probability a mapped range of length q>x will fully cover the given range of length x is (q-x)/c. This probability becomes quite small when c is large and/or q is small. What I'm interested is the number of ranges (out of n) which cover x. This is how Y is formed.
I test my null hypothesis vs. one sided alternative (undercoverage). Also note I am testing multiple hypothesis (different x lengths), and sure to correct for this.

A: @onestop provides good references.  The Wikipedia article on the Poisson binomial distribution gives a recursive formula for computing the exact probability distribution; it requires $O(n^2)$ effort.  Unfortunately, it's an alternating sum, so it will be numerically unstable: it's hopeless to do this computation with floating point arithmetic.  Fortunately, when the $p_i$ are small, you only need to compute a small number of probabilities, so the effort is really proportional to $O(n \log(\sum_i{p_i}))$.  The precision necessary to carry out the calculation with rational arithmetic (i.e., exactly, so that the numerical instability is not a problem) grows slowly enough that the overall timing may still be approximately $O(n^2)$.  That's feasible.
As a test, I created an array of probabilities $p_i = 1/(i+1)$ for various values of $n$ up to $n = 2^{16}$, which is the size of this problem.  For small values of $n$ (up to $n = 2^{12}$) the timing for the exact calculation of probabilities was in seconds and scaled quadratically, so I ventured a calculation for $n = 2^{16}$ out to three SDs above the mean (probabilities for 0, 1, ..., 22 successes).  It took 80 minutes (with Mathematica 8), in line with the predicted time.  (The resulting probabilities are fractions whose numerators and denominators have about 75,000 digits apiece!)  This shows the calculation can be done.
An alternative is to run a long simulation (a million trials ought to do).  It only has to be done once, because the $p_i$ don't change.

A: With different $p_i$ your best bet I think is normal approximation. Let $B_n=\sum_{i=1}^np_i(1-p_i)$. Then
\begin{align*}
B_n^{-1/2}\left(\sum_{i=1}^nX_i-\sum_{i=1}^np_i\right)\to N(0,1),
\end{align*}
as $n\to\infty$, provided that for each $\varepsilon>0$
\begin{align*}
B_n^{-1}\sum_{i=1}^nE\left((X_i-p_i)^2\mathbf{1}\{|X_i-p_i|>\varepsilon B_n^{1/2}\}\right)\to 0,
\end{align*}
as $n\to\infty$, which for Bernoulli variables will hold if $B_n\to\infty$. This is the so-called Lindeberg condition, which is sufficient and necessary for convergence to the standard normal.
Update:
The approximation error can be calculated from the following inequality:
\begin{align*}
\sup_x|F_n(x)-\Phi(x)|\le AL_n,
\end{align*}
where
\begin{align*}
L_n=B_n^{-3/2}\sum_{i=1}^nE|X_i-p_i|^3
\end{align*}
and $F_n$ is the cdf of the scaled and centered sum of $X_i$.
As whuber pointed out, the convergence can be slow for badly behaved $p_i$. For $p_i=\frac{1}{1+i}$ we have $B_n\approx \ln n$ and $L_n\approx (\ln n)^{-1/2}$. Then taking $n=2^{16}$ we get that the maximum deviation from the standard normal cdf is a whopping 0.3.

A: Well, based on your description and the discussion in the comments it is clear that $Y$ has mean $\sum_i p_i$ and variance $\sum_i p_{i}(1-p_{i})$.  The shape of $Y$'s distribution will ultimately depend on the behavior of $p_i$.  For suitably "nice" $p_i$ (in the sense that not too many of them are really close to zero), the distribution of $Y$ will be approximately normal (centered right at $\sum p_i$).  But as  $\sum_i p_i$ starts heading toward zero the distribution will be shifted to the left and when it crowds up against the $y$-axis it will start looking a lot less normal and a lot more Poisson, as @whuber and @onestop have mentioned.
From your comment "the distribution looks Poisson" I suspect that this latter case is what's happening, but can't really be sure without some sort of visual display or summary statistics about the $p$'s.  Note however, as @whuber did, that with sufficiently pathological behavior of the $p$'s you can have all sorts of spooky things happen, like limits that are mixture distributions.  I doubt that is the case here, but again, it really depends on what your $p$'s are doing.
As to the original question of "how to efficiently model", I was going to suggest a hierarchical model for you but it isn't really appropriate if the $p$'s are fixed constants.  In short, take a look at a histogram of the $p$'s and make a first guess based on what you see.  I would recommend the answer by @mpiktas (and by extension @csgillespie) if your $p$'s aren't too crowded to the left, and I would recommend the answer by @onestop if they are crowded left-ly.
By the way, here is the R code I used while playing around with this problem: the code isn't really appropriate if your $p$'s are too small, but it should be easy to plug in different models for $p$ (including spooky-crazy ones) to see what happens to the ultimate distribution of $Y$.
set.seed(1)
M <- 5000
N <- 15000
p <- rbeta(N, shape1 = 1, shape2 = 10)
Y <- replicate(M, sum(rbinom(N, size = 1, prob = p)))

Now take a look at the results.
hist(Y)
mean(Y)
sum(p)
var(Y)
sum(p*(1 - p))

Have fun; I sure did.

A: I would suggest applying Poisson approximation. It is well known (see A. D. Barbour, L. Holst and S. Janson: Poisson Approximation) that the total variation distance between $Y$ and a r.v. $Z$ having Poisson distribution with the parameter $\sum_i p_i$ is small:
$$ \sup_A |{\bf P}(Y\in A) -  {\bf P}(Z\in A)|
\le \min \left\{ 1, \frac{1}{\sum_i p_i} \right\} \sum_i p_i^2.
$$
There are also bounds in terms of information divergence (the Kullback-Leibler distance, you may see P. Harremoёs: Convergence to the Poisson Distribution in Information Divergence. Preprint no. 2, Feb. 2003, Mathematical Department, University of Copenhagen. http://www.harremoes.dk/Peter/poisprep.pdf and other publications of P.Harremoёs), chi-squared distance (see Borisov and Vorozheikin https://link.springer.com/article/10.1007%2Fs11202-008-0002-3) and some other distances.
For the accuracy of approximation
$|{\bf E}f(Y) - {\bf E}f(Z)|$ for unbounded functions $f$ you may see Borisov and Ruzankin https://projecteuclid.org/euclid.aop/1039548369 .
Besides, that paper contains a simple bound for probabilities: for all $A$, we have
$${\bf P}(Y\in A) \le \frac{1}{(1-\max_i p_i)^2} {\bf P}(Z\in A).$$

A: If it often resembles a Poisson, have you tried approximating it by a Poisson with parameter $\lambda = \sum p_i$ ?
EDIT: I've found a theoretical result to justify this, as well as a name for the distribution of $Y$: it's called the Poisson binomial distribution. Le Cam's inequality tells you how closely its distribution is approximated by the distribution of a Poisson with parameter $\lambda = \sum p_i$. It tells you the quality of this approx is governed by the sum of the squares of the $p_i$s, to paraphrase Steele (1994). So if all your $p_i$s are reasonably small, as it now appears they are, it should be a pretty good approximation.
EDIT 2: How small is 'reasonably small'? Well, that depends how good you need the approximation to be! The Wikipedia article on Le Cam's theorem gives the precise form of the result I referred to above: the sum of the absolute differences between the probability mass function (pmf) of $Y$ and the pmf of the above Poisson distribution is no more than twice the sum of the squares of the $p_i$s. Another result from Le Cam (1960) may be easier to use: this sum is also no more than 18 times the largest $p_i$. There are quite a few more such results... see Serfling (1978) for one review.

A: I think other answers are great, but I didn't see any Bayesian ways of estimating your probability. The answer doesn't have an explicit form, but the probability can be simulated using R.
Here is the attempt:
$$ X_i | p_i \sim Ber(p_i)$$
$$ p_i \sim Beta(\alpha, \beta) $$
Using wikipedia we can get estimates of $\hat{\alpha}$ and $\hat{\beta}$ (see parameter estimation section).
Now you can generate draws for the $i^{th}$ step, generate $p_i$ from $Beta(\hat{\alpha},\hat{\beta})$ and then generate $ X_i$ from $Ber(p_i)$. After you have done this $N$ times you can get $Y = \sum X_i$. This is a single cycle for generation of Y, do this $M$(large) number of times and the histogram for $M$ Ys will be the estimate of density of Y.
$$Prob[Y \leq y] = \frac {\#Y \leq y} {M}$$
This analysis is valid only when $p_i$ are not fixed. This is not the case here. But I will leave it here, in case someone has a similar question.

A: As has been mentioned in other answers, the probability distribution you describe is the Poisson Binomial distribution. An efficient method for computing the CDF is given in Hong, Yili. On computing the distribution function for the Poisson binomial distribution.
The approach is to efficiently compute the DFT (discrete Fourier transform) of the characteristic function.
The characteristic function of the Poisson binomial distribution is give by
$\phi(t) = \prod_j^n [(1-p_j)+p_je^{it}]$ ($i=\sqrt{-1}$).
The algorithm is:

*

*Let $z_j(k) = 1-p_j+p_j \text{cos}(\omega k)+ i p_j \text{sin}(\omega k)$, for $\omega=\frac{2\pi}{n+1}$.

*Define $x_k=\text{exp}\{\sum_j^n log(z_j(k))\}$, define $x_0=1$.

*Compute $x_k$ for $k=1,\dots,[n/2]$. Use symmetry $\bar{x}_k=x_{n+1-k}$ to get the rest.

*Apply FFT to the vector $\frac{1}{n+1}<x_0,x_1,\dots,x_n>$.

*Take the cumulative sum of result to get the CDF.

The algorithm is available in the poibin R package.
This approach gives much better results than the recursive formulations as they tend to lack numerical stability.

A: I came across your question while searching for a solution to this very problem. I wasn't terrifically satisfied with the answers here, but I think there's a pretty simple solution that gives you the exact distribution, and is pretty tractable.
The distribution of the sum of two discrete random variables is the convolution of their densities. So if you have $Z = X + Y$ where you know $P(X)$ and $P(Y)$ then you can compute:
$$P(Z=z) = \sum_{k=-\infty}^{\infty} P(X=k) \; P(Y=z-k)$$
(Of course for Bernoulli random variables you don't need to go quite to infinity.)
You can use this to find the exact distribution of the sum of your RVs. First sum two of the RVs together by convolving their PDFs (e.g. [0.3, 0.7] * [0.6, 0.4] = [0.18, 0.54, 0.28]). Then convolve that new distribution with your next Bernoulli PDF (e.g. [0.18, 0.54, 0.28] * [0.5, 0.5] = [0.09, 0.36, 0.41, 0.14]). Keep repeating this until all RVs have been added. And voila, the resulting vector is the exact PDF of the sum of all your variables.
I've verified with simulation that this produces the correct results. It doesn't rely on any asymptotic assumptions, and has no requirements that the Bernoulli probs are small.
There may also be some way to do this more efficiently than repeated convolution, but I haven't thought about it very deeply. I hope this is helpful to somebody!

A: (Because this is approach is independent of the other solutions posted, including one that I have posted, I'm offering it as a separate response).
You can compute the exact distribution in seconds (or less) provided the sum of the p's is small.
We have already seen suggestions that the distribution might approximately be Gaussian (under some scenarios) or Poisson (under other scenarios).  Either way, we know its mean $\mu$ is the sum of the $p_i$ and its variance $\sigma^2$ is the sum of $p_i(1-p_i)$.  Therefore the distribution will be concentrated within a few standard deviations of its mean, say $z$ SDs with $z$ between 4 and 6 or thereabouts.  Therefore we need only compute the probability that the sum $X$ equals (an integer) $k$ for $k = \mu - z \sigma$ through $k = \mu + z \sigma$.  When most of the $p_i$ are small, $\sigma^2$ is approximately equal to (but slightly less than) $\mu$, so to be conservative we can do the computation for $k$ in the interval $[\mu - z \sqrt{\mu}, \mu + z \sqrt{\mu}]$.  For example, when the sum of the $p_i$ equals $9$ and choosing $z = 6$ in order to cover the tails well, we would need the computation to cover $k$ in $[9 - 6 \sqrt{9}, 9 + 6 \sqrt{9}]$ = $[0, 27]$, which is just 28 values.
The distribution is computed recursively.  Let $f_i$ be the distribution of the sum of the first $i$ of these Bernoulli variables.  For any $j$ from $0$ through $i+1$, the sum of the first $i+1$ variables can equal $j$ in two mutually exclusive ways: the sum of the first $i$ variables equals $j$ and the $i+1^\text{st}$ is $0$ or else the sum of the first $i$ variables equals $j-1$ and the $i+1^\text{st}$ is $1$.  Therefore
$$f_{i+1}(j) = f_i(j)(1 - p_{i+1}) + f_i(j-1) p_{i+1}.$$
We only need to carry out this computation for integral $j$ in the interval from $\max(0, \mu - z \sqrt{\mu})$ to $\mu + z \sqrt{\mu}.$
When most of the $p_i$ are tiny (but the $1 - p_i$ are still distinguishable from $1$ with reasonable precision), this approach is not plagued with the huge accumulation of floating point roundoff errors used in the solution I previously posted.  Therefore, extended-precision computation is not required.  For example, a double-precision calculation for an array of $2^{16}$ probabilities $p_i = 1/(i+1)$ ($\mu = 10.6676$, requiring calculations for probabilities of sums between $0$ and $31$) took 0.1 seconds with Mathematica 8 and 1-2 seconds with Excel 2002 (both obtained the same answers).  Repeating it with quadruple precision (in Mathematica) took about 2 seconds but did not change any answer by more than $3 \times 10^{-15}$.  Terminating the distribution at $z = 6$ SDs into the upper tail lost only $3.6 \times 10^{-8}$ of the total probability.
Another calculation for an array of 40,000 double precision random values between 0 and 0.001 ($\mu = 19.9093$) took 0.08 seconds with Mathematica.
This algorithm is parallelizable. Just break the set of $p_i$ into disjoint subsets of approximately equal size, one per processor.  Compute the distribution for each subset, then convolve the results (using FFT if you like, although this speedup is probably unnecessary) to obtain the full answer.  This makes it practical to use even when $\mu$ gets large, when you need to look far out into the tails ($z$ large), and/or $n$ is large.
The timing for an array of $n$ variables with $m$ processors scales as $O(n(\mu + z \sqrt{\mu})/m)$.  Mathematica's speed is on the order of a million per second.  For example, with $m = 1$ processor, $n = 20000$ variates, a total probability of $\mu = 100$, and going out to $z = 6$ standard deviations into the upper tail, $n(\mu + z \sqrt{\mu})/m = 3.2$ million: figure a couple seconds of computing time.  If you compile this you might speed up the performance two orders of magnitude.
Incidentally, in these test cases, graphs of the distribution clearly showed some positive skewness: they aren't normal.
For the record, here is a Mathematica solution:
pb[p_, z_] := Module[
  {\[Mu] = Total[p]},
  Fold[#1 - #2 Differences[Prepend[#1, 0]] &,
   Prepend[ConstantArray[0, Ceiling[\[Mu] + Sqrt[\[Mu]] z]], 1], p]
  ]

(NB The color coding applied by this site is meaningless for Mathematica code.  In particular, the gray stuff is not comments: it's where all the work is done!)
An example of its use is
pb[RandomReal[{0, 0.001}, 40000], 8]

Edit
An R solution is ten times slower than Mathematica in this test case--perhaps I have not coded it optimally--but it still executes quickly (about one second):
pb <- function(p, z) {
  mu <- sum(p)
  x <- c(1, rep(0, ceiling(mu + sqrt(mu) * z)))
  f <- function(v) {x <<- x - v * diff(c(0, x));}
  sapply(p, f); x
}
y <- pb(runif(40000, 0, 0.001), 8)
plot(y)


text:
Q: How to return selected value of Combobx from a bind function using Python ListA, ListB and ListC which are actually combobxes and inter-related; such that ListB depends on value of ListA and List C depends on value of ListC.
I want to concatenate the selected values of each comboboxes and then use them later in my code. It will something similar to
Concatenate = Value from ListA + Value Value from ListB + Value from ListC
But I dont know how to return values to main code. I would love to hear from you. Here is my code.
# Binder Functions
def bind_mkmodel(e):
    if mkmodel.get()=="3051CD":
        modclass.configure(state=tkinter.NORMAL)
        modclass.config(values=list_class1)
        modclass.current(0)
    elif mkmodel.get()=="3051SCD":
        modclass.configure(state=tkinter.NORMAL)
        modclass.config(values=list_class2)
        modclass.current(0)
    elif mkmodel.get()=="3051SMV--1or 2":
        modclass.configure(state=tkinter.NORMAL)
        modclass.config(values=list_class3)
        modclass.current(0)
    elif mkmodel.get() == "3051SMV--3 or 4":
        modclass.configure(state=tkinter.NORMAL)
        modclass.config(values=list_class4)
        modclass.current(0)
    else:
        modclass.config(values=[""])
        modclass.current(0)
        modclass.configure(state=tkinter.DISABLED)

    modclass.event_generate("<<ComboboxSelected>>")

def bind_modclass(e):
    if modclass.get()=="Std":
        dp.configure(state=tkinter.NORMAL)
        dp.config(values=list_dp1)
        dp.current(0)
    elif modclass.get()=="S_Ultra" or modclass.get() == "S_Classic":
        dp.configure(state=tkinter.NORMAL)
        dp.config(values=list_dp2)
        dp.current(0)
    elif modclass.get() == "S_Ultra for Flow":
        dp.configure(state=tkinter.NORMAL)
        dp.config(values=list_dp3)
        dp.current(0)
    elif modclass.get() == "SMV12_Classic" or modclass.get() == "SMV34_Ultra" or modclass.get() == "SMV34_Classic":
        dp.configure(state=tkinter.NORMAL)
        dp.config(values=list_dp4)
        dp.current(0)
    elif modclass.get() == "SMV12_Ultra for Flow":
        dp.configure(state=tkinter.NORMAL)
        dp.config(values=list_dp5)
        dp.current(0)
    elif modclass.get() == "SMV34_Ultra for Flow":
        dp.configure(state=tkinter.NORMAL)
        dp.config(values=list_dp6)
        dp.current(0)
    else:
        dp.config(values=[""])
        dp.current(0)
        dp.configure(state=tkinter.DISABLED)

# region Frames definition
frame_0 = Frame(root_tk,background="white")
frame_0.place(x=0,y=0,height=1100,width=150)
frame_6 = customtkinter.CTkFrame(master=root_tk, corner_radius=15,fg_color="white")
frame_6.place(x=10,y=10)
# endregion
# --------- FRAME 6 COMPONENTS ---------
# Labels Creation
lab_heading6 = Label(frame_6, text="  Dropdowns",anchor=W,width=35,font='Arial 10 bold',bg=hdcolor,fg="white")
lab_mkmodel = Label(frame_6, text="  List A",anchor=W,width=23,bg="#2E2E2E",pady=2,background="white",fg=nlcolor)
lab_modclass = Label(frame_6, text="  List B",anchor=W,width=23,bg="#2E2E2E",pady=2,background="white",fg=nlcolor)
lab_dp = Label(frame_6, text="  List C",anchor=W,width=23,bg="#2E2E2E",pady=2,background="white",fg=nlcolor)
# Labels positioning
lab_heading6.grid(row=0, column=0,pady=10,columnspan=2)
lab_mkmodel.grid(row=1, column=0)
lab_modclass.grid(row=2, column=0)
lab_dp.grid(row=3, column=0)
# Creating List A dropdown
list_mkmodel = ["3051CD", "3051SCD", "3051SMV--1or 2","3051SMV--3 or 4","Custom"]
mkmodel = ttk.Combobox(frame_6,values=list_mkmodel,width=13,style="TCombobox")
mkmodel.grid(row=1, column=1, ipadx="11")
mkmodel.bind("<<ComboboxSelected>>",bind_mkmodel)
# Creating List B dropdown
list_class1 = ["Std"]
list_class2 = ["S_Ultra", "S_Classic","S_Ultra for Flow"]
list_class3 = ["SMV12_Classic", "SMV12_Ultra for Flow"]
list_class4 = ["SMV34_Ultra","SMV34_Classic", "SMV34_Ultra for Flow"]
modclass = ttk.Combobox(frame_6,values=[""],width=13,style="TCombobox")
modclass.grid(row=2, column=1, ipadx="11")
modclass.bind("<<ComboboxSelected>>",bind_modclass)
# Creating List C dropdown
list_dp1 = ["1","2","3","4","5"]
list_dp2 = ["1A","2A","3A","4A","5A"]
list_dp3 = ["2A","3A"]
list_dp4 = ["1","2","2 SP=5","3","3 SP=5","4","5"]
list_dp5 = ["2","2 SP=5","3","3 SP=5","4"]
list_dp6 = ["2","2 SP=5","3","3 SP=5"]
dp = ttk.Combobox(frame_6,values=[""],width=13,style="TCombobox")
dp.grid(row=3, column=1, ipadx="11")

root_tk.mainloop()


text:
Q: CGContext pdf page aspect fit I am displaying a pdf page on the CGContext using the code
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
    CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0);
    CGContextFillRect(ctx, layer.bounds);
    CGContextTranslateCTM(ctx, 0.0, layer.bounds.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    CGContextConcatCTM(ctx, CGPDFPageGetDrawingTransform(myPageRef, kCGPDFBleedBox, layer.bounds, 0, true));
    CGContextDrawPDFPage(ctx, myPageRef);
}

The problem is that the pdf page is getting drawn on the center of the page leaving border on all four sides. Is there any way to make the page fit to screen.

A: The CGPDFPageGetDrawingTransform just will not return scale-up transformation if the PDF page rectangle is smaller than the rect parameter.

A: To expand on Tia's answer; the built-in method CGPDFPageGetDrawingTransform will scale down but not up. If you want to scale up then you need to work out your own transform by comparing the results of CGPDFGetBoxRect to your content area. Typing extemporaneously:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
    CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0);
    CGContextFillRect(ctx, layer.bounds);
    CGContextTranslateCTM(ctx, 0.0, layer.bounds.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);

    CGRect cropBox = CGPDFGetBoxRect(myPageRef, kCGPDFCropBox);
    CGRect targetRect = layer.bounds;
    CGFloat xScale = targetRect.size.width / cropBox.size.width;
    CGFloat yScale = targetRect.size.height / cropBox.size.height;
    CGFloat scaleToApply = xScale < yScale ? xScale : yScale;
    CGContextConcatCTM(ctx, CGAffineTransformMakeScale(scaleToApply, scaleToApply));

    CGContextDrawPDFPage(ctx, myPageRef);
}

So: work out how much you'd have to scale the document by for it to occupy the entire width of the view, how much to occupy the entire height and then actually scale by the lesser of those two values.

A: Cursory reading of your code suggests the use of kCGPDFBleedBox should be replaced by another setting, perhaps kCGPDFMediaBox. See here for more information.

A: The other answers are correct that CGPDFPageGetDrawingTransform will not scale up, however you can scale the rectangle down to capture just the chosen box.  Use CGPDFPageGetBoxRect() and calculate the scale as Tommy suggested in the accepted answer, then use that to scale down the capture rectangle passed into CGPDFPageGetDrawingTransform().
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
    CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0);
    CGContextFillRect(ctx, layer.bounds);
    CGContextTranslateCTM(ctx, 0.0, layer.bounds.size.height);

    CGRect box = CGPDFGetBoxRect(myPageRef, kCGPDFBleedBox);
    CGFloat xScale = layer.bounds.size.width / cropBox.size.width;
    CGFloat yScale = layer.bounds.size.height / cropBox.size.height;
    CGFloat scaleToApply = xScale < yScale ? xScale : yScale;

    CGRect captureRect = CGRectMake(0, 0,
                                    layer.bounds.size.width/scaleToApply,
                                    layer.bounds.size.height/scaleToApply);

    CGAffineTransform drawXfm = CGPDFPageGetDrawingTransform(myPageRef,
                                                             kCGPDFBleedBox,
                                                             captureRect,
                                                             0,
                                                             true);

    CGContextScaleCTM(ctx, scaleToApply, -scaleToApply);
    CGContextConcatCTM(ctx, drawXfm);
    CGContextDrawPDFPage(ctx, myPageRef);
}

Then it's easily extended to handle landscape too:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
    CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0);
    CGContextFillRect(ctx, layer.bounds);
    CGContextTranslateCTM(ctx, 0.0, layer.bounds.size.height);

    CGRect box = CGPDFGetBoxRect(myPageRef, kCGPDFBleedBox);
    int rotate;
    CGFloat xScale, yScale;
    if (box.size.width > box.size.height) {
        // landscape
        rotate = 270;
        xScale = layer.bounds.size.height / cropBox.size.width;
        yScale = layer.bounds.size.width / cropBox.size.height;
    } else {
        // portrait
        rotate = 0;
        xScale = layer.bounds.size.width / cropBox.size.width;
        yScale = layer.bounds.size.height / cropBox.size.height;
    }
    CGFloat scaleToApply = xScale < yScale ? xScale : yScale;

    CGRect captureRect = CGRectMake(0, 0,
                                    layer.bounds.size.width/scaleToApply,
                                    layer.bounds.size.height/scaleToApply);

    CGAffineTransform drawXfm = CGPDFPageGetDrawingTransform(myPageRef,
                                               kCGPDFBleedBox,
                                               captureRect,
                                               rotate,
                                               true);

    CGContextScaleCTM(ctx, scaleToApply, -scaleToApply);
    CGContextConcatCTM(ctx, drawXfm);
    CGContextDrawPDFPage(ctx, myPageRef);
}

A: Here is my solution, which also handles rotation. Might by useful.
// Create transformation
int rotation = CGPDFPageGetRotationAngle(pdfPage);
CGRect rect = CGPDFPageGetBoxRect(pdfPage, kCGPDFCropBox);
CGRect rotatedRect = rect;
CGRectApplyAffineTransform(rotatedRect, CGAffineTransformMakeRotation(M_PI * rotation / 180.0));

CGFloat scale = MIN(self.bounds.size.width / rotatedRect.size.width, self.bounds.size.height / rotatedRect.size.height);
// Scale
CGContextConcatCTM(context, CGAffineTransformMakeScale(scale, scale));
// Move left bottom cornet to 0, 0
CGContextConcatCTM(context, CGAffineTransformMakeTranslation(rotatedRect.size.width * 0.5, rotatedRect.size.height * 0.5));
// Rotate
CGContextConcatCTM(context, CGAffineTransformMakeRotation(-M_PI * rotation / 180.0));
// Move center into 0, 0
CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-rect.origin.x - rect.size.width * 0.5, -rect.origin.y - rect.size.height * 0.5));

CGContextDrawPDFPage(context, pdfPage);


text:
Q: PHP inserting blanks into MySQL database I have an HTML form which submits values to the following PHP file, which inserts them into a MySQL database:
<?php
  $con = mysql_connect("*","*","*");
  if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }

  mysql_select_db("*", $con);

  $sql="INSERT INTO scores (hometeam, awayteam, result)
  VALUES
  ('" . mysql_real_escape_string($_POST['hometeam']) . "',
   '" . mysql_real_escape_string($_POST['awayteam']) . "',
   '" . mysql_real_escape_string($_POST['result']) . "')";

  if (!mysql_query($sql,$con))
    {
    die('Error: ' . mysql_error());
    }
  echo "1 record added";

  mysql_close($con);
?>

Sometimes an input field in the HTML form will be left empty and in this case I do not want anything inserted into the database. I want the value to remain NULL. At the moment when I fill in my form like this:
Home team: Blue team
Away team: [empty]
Result: Won
The following is inserted into my database:
Home team: Blue team
Away team: ' '
Result: Won
What I want to be inserted/not inserted is:
Home team: Blue team
Away team: NULL
Result: Won
I've hunted hours for a solution. Can anyone help? Thank you.

A: Don't quote them inside your query. Instead, build variables first, and append quotes to the escaped string values outside the query, giving you the ability to insert NULL keywords if your strings are empty:
// If any is not set or empty in the POST, assign the string "NULL" unquoted to a variable
// which will be passed to MySQL as the unquoted NULL keyword.
// Otherwise escape the value from $_POST and surround the escaped value in single quotes
$ateam = !empty($_POST['awayteam']) ? "'" . mysql_real_escape_string($_POST['awayteam']) . "'" : "NULL";
$hteam = !empty($_POST['hometeam']) ? "'" . mysql_real_escape_string($_POST['hometeam']) . "'" : "NULL";
$result = !empty($_POST['result']) ? "'" . mysql_real_escape_string($_POST['result']) . "'" : "NULL";

// Then pass the three variables (already quoted if necessary) directly to the query.
$sql="INSERT INTO scores (hometeam, awayteam, result) VALUES ($hteam, $ateam, $result);

In the long run, it is recommended to begin using a MySQL API which supports prepared statements, like PDO or MySQLi. They offer better security, can handle input NULLs more elegantly, and the old mysql_*() functions are soon to be deprecated.

A: In your code, replace:
$sql="INSERT INTO scores (hometeam, awayteam, result)
  VALUES
  ('" . mysql_real_escape_string($_POST['hometeam']) . "',
   '" . mysql_real_escape_string($_POST['awayteam']) . "',
   '" . mysql_real_escape_string($_POST['result']) . "')";

With:
if($_POST['awayteam'] == '')
 $awayteam = 'NULL';
else
 $awaytem = "'" . mysql_real_escape_string($_POST['awayteam']) "'";
$sql="INSERT INTO scores (hometeam, awayteam, result)
  VALUES
  ('" . mysql_real_escape_string($_POST['hometeam']) . "',
   " . $awayteam . ",
   '" . mysql_real_escape_string($_POST['result']) . "')";

A: You can use the NULLIF function from mysql database. What it does is, it takes 2 parameters and return null if they are same. So basically you can change your code to be like following:
  $sql="INSERT INTO scores (hometeam, awayteam, result)
  VALUES
  (NULLIF('" . mysql_real_escape_string($_POST['hometeam']) . "', ''),
   NULLIF('" . mysql_real_escape_string($_POST['awayteam']) . "', ''),
   NULLIF('" . mysql_real_escape_string($_POST['result']) . "', ''))";

It will basically check if the entered value is ''(empty string), and if that's the case, it would instead save NULL in the database. You can even trim leading or trailing spaces from your variables before passing onto NULLIF, so if someone only enters spaces in your input boxes, it still saved NULL.
Also, as Michael said, it would be safer and better if you move on to PDO or mysqli extension. Hope my answer helps.

A: Or if you have access to db alter the columns( that are optional) and set them as NULL by default.
i.e. if nothing is inserted in that column NULL will be displayed by default.

A: Why not replace ' ' and other invalid forms of data with 'null'?
OR
Check if $_POST['data'] is equal to ' ' or '' and if true, set them to 'null'.
Also,
Instead of mysql_real_escape_string, use the PHP function 'addslashes'.


text:
Q: ZK How to update ListBox ListModel using selected item I'm making a web file browser using ZK Components and find a block. Is there any way to update the ListBox model using the selected item of the listbox?
The use case is when traversing the files and folder, the user click the folder, and the list is refreshed with the content of the selected folder. The selection event is triggered and for regular file, it handle well, but not the folder.
My Code:
myfilesvm.zul
<zk>
    <window apply="org.zkoss.bind.BindComposer"
        viewModel="@id('vm') @init('com.my.zk.mvvm.MyFilesViewModel')">
        <hlayout>
            <listbox vflex="true" hflex="1" model="@load(vm.files)"
                id="fileBrowser" selectedItem="@bind(vm.selectedFile)">
                <auxhead>
                    <auxheader colspan="3">File List</auxheader>
                    <auxheader colspan="3">
                        <hlayout>
                            <!-- breadcrumb, implemented later -->
                        </hlayout>
                    </auxheader>
                </auxhead>
                <listhead>
                    <listheader label="Name" />
                    <listheader label="Size" />
                    <listheader label="Modified" />
                </listhead>
                <template name="model" var="file">
                    <listitem>
                        <listcell label="@load(file.name)" />
                        <listcell label="@load(file.length())" />
                        <listcell label="@load(file.lastModified())" />
                    </listitem>
                </template>
            </listbox>
        </hlayout>
        <separator />
    </window>
</zk>

MyFilesViewModel.java
package com.my.zk.mvvm;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;

import com.my.zk.FileCrumbManager;

public class MyFilesViewModel  {

    private static Logger log = LoggerFactory.getLogger(MyFilesViewModel.class);
//  AuthenticationService authService = new AuthenticationServiceImpl();
//  UserCredential cre = authService.getUserCredential();
    String homeFolder = "D:\\path\\home";

    ListModel<File> files = new ListModelList<File>(Arrays.asList(FileCrumbManager.populateList(new File(homeFolder))));
    File selectedFile;

    @Init
    public void init() { // Initialize

    }

    public ListModel<File> getFiles() {
        return files;
    }

    @NotifyChange({ "selectedFile" })
    public void setFiles(ListModel<File> files) {
        this.files = files;
    }

    public File getSelectedFile() {
        return selectedFile;
    }

    public void pilihFile() {
        if (getSelectedFile().isDirectory()) {
            log.info("File is a directory");
            this.files = new ListModelList<File>(
                    Arrays.asList(FileCrumbManager.populateList(new File(getSelectedFile().getAbsolutePath()))));
        } else {
            try {
                Filedownload.save(getSelectedFile(), null);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                log.error(e.getMessage());
            }
        }
    }

    public void setSelectedFile(File selectedFile) {
        this.selectedFile = selectedFile;
        pilihFile();
    }

}

Appreciate for any help. Thank you.

A: The correct way to refresh ListModelList in pilihFile() is:
this.files.clear();
this.files.addAll(Arrays.asList(FileCrumbManager.populateList(new File(getSelectedFile().getAbsolutePath()))));

Because Listbox is model-driven rendering, you should control the rendering by manipulating the model object. When you call methods of ListModelList, it will notify Listbox to render into a browser. If you replace this.files with a new object, ZK doesn't know it. That's why your browser doesn't have the update.


text:
Q: Detecting Server Crash With RMI I'm new to Java and RMI, but I'm trying to write my app in such a way that there are many clients connecting to a single server.  So far, so good....
But when I close the server (simulating a crash or communication issue) my clients remain unaware until I make my next call to the server.  It is a requirement that my clients continue to work without the server in an 'offline mode' and the sooner I know that I'm offline the better the user-experience will be.
Is there an active connection that remains open that the client can detect a problem with or something similar - or will I simply have to wait until the next call fails?  I figured I could have a 'health-check' ping the server but it seemed like it might not be the best approach.
Thanks for any help

A: actually i'm just trying to learn more about RMI and CORBA but i'm not that far as you are. all i know is that those systems are also built to be less expensive, and as far as i know an active conneciton is an expensive thing.
i would suggest you use a multicast address to which your server sends somehow "i'm still here" but without using TCP connections, UDP should be enough for that purpose and more efficient.

A: I looked into this a bit when I was writing an RMI app (uni assignment) but I didn't come across any inbuilt functionality for testing whether a remote system is alive. I would just use a UDP heartbeat mechanism for this.

A: (Untested).  Having a separate RMI call repeatedly into the server, which just does a "wait X seconds" and then return, should be told that the execution has failed when the server is brought down.


text:
Q: Binding events to device context objects in wxpython I am new to wxpython and am running into a problem. What I'd like to do is bind events to device context objects. For example, in one window I would draw a number of different device context objects (i.e. lines, rectangles, etc). First, I would like to be able to select a specific object within the window, for the purposes of linking it to a text box that names it. Second, I'd like to be able to drag the object anywhere within the window, preferably with mouse-down, mouse-move events. I know that this is possible in Tkinter's canvasses, but I can't find any equivalent method in wxpython. Any help would be appreciated.
Thanks,
David

A: The wxPython demo has an example of selecting objects and dragging them around. There's also the Whyteboard program that has similar functionality and it's written in wxPython too. I would check that out: https://launchpad.net/whyteboard