text:
Q: How to solve fxml loading exceptions in compiled JavaFX project using GluonHQ client, Native Image and GraalVM? This is a follow up question to this question.
I am attempting to compile a JavaFX project into a Native Image so that it will run natively without the user needing Java installed. The problems with JavaFX and reflection have been solved with the GluonHQ client plugin, so that compilation is now a success.
I have managed to get a simple JavaFX project (the example generated by IntelliJ upon creating a JavaFX project) to compile using the Gluon client maven plugin. However, when running the native image at the command line, it gives a JavaFX fxml loading exception:
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
        at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
        at java.lang.Thread.run(Thread.java:834)
        at com.oracle.svm.core.thread.JavaThreads.threadStartRoutine(JavaThreads.java:518)
        at com.oracle.svm.core.posix.thread.PosixJavaThreads.pthreadStartRoutine(PosixJavaThreads.java:192)
Caused by: javafx.fxml.LoadException:
sample.fxml:8

        at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2629)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2607)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2470)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3241)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3198)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3167)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3140)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3117)
        at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3110)
        at sample.Main.start(Main.java:13)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
        at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
        at com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
        at java.security.AccessController.doPrivileged(AccessController.java:101)
        at com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
        at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
        at com.oracle.svm.jni.JNIJavaCallWrappers.jniInvoke_VA_LIST:Ljava_lang_Runnable_2_0002erun_00028_00029V(JNIJavaCallWrappers.java:0)
        at com.sun.glass.ui.gtk.GtkApplication._runLoop(GtkApplication.java)
        at com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(GtkApplication.java:277)
        ... 3 more
Caused by: com.sun.javafx.fxml.PropertyNotFoundException: Property "alignment" does not exist or is read-only.
        at javafx.fxml.FXMLLoader$Element.processValue(FXMLLoader.java:355)
        at javafx.fxml.FXMLLoader$Element.processPropertyAttribute(FXMLLoader.java:332)
        at javafx.fxml.FXMLLoader$Element.processInstancePropertyAttributes(FXMLLoader.java:242)
        at javafx.fxml.FXMLLoader$ValueElement.processEndElement(FXMLLoader.java:775)
        at javafx.fxml.FXMLLoader.processEndElement(FXMLLoader.java:2842)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2561)
        ... 20 more

It to was only possible to get the native image to work by changing the sample.fxml from this:
<?import javafx.scene.layout.GridPane?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<GridPane fx:controller="sample.Controller"
          xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
</GridPane>

to this (removing the alignment, hgap and vgap attributes):
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<GridPane fx:controller="sample.Controller"
          xmlns:fx="http://javafx.com/fxml">
</GridPane>

and then recompiling. The compiled binary then runs as expected.
Reflection has been configured as follows for the Gluon plugin in the POM.xml:
<plugin>
    <groupId>com.gluonhq</groupId>
    <artifactId>client-maven-plugin</artifactId>
    <version>0.1.30</version>
    <configuration>
        <mainClass>sample.NewMain</mainClass>
        <reflectionList>
            <list>sample.Main</list>
            <list>sample.NewMain</list>
            <list>sample.Controller</list>
            <list>javafx.fxml.FXMLLoader</list>
        </reflectionList>
    </configuration>
</plugin>

These FXML loading exceptions are the same once a larger project JavaFX project is compiled with reflection configured. Exceptions always say Caused by: com.sun.javafx.fxml.PropertyNotFoundException: Property [X] does not exist or is read-only. Both projects run fine on the JVM, with no exceptions being thrown. My IDE can detect no errors with the code.

A: I will expand a little bit more @mipa's answer.
As you may know, FXML is all about reflection: we have an (f)xml file, and a parser (FXMLLoader), that finds classes (GridPane), and properties names (alignment) that are resolved to method names (setAlignment(Pos) and getAlignment()) while parsing that file.
By default, the Client plugin provides for you a reflectionConfig.json file with most of the JavaFX classes and methods that you might use in your FXML files.
As you can read here, this file is generated when you run mvn client:compile (or mvn client:link), and can be found under target/client/$arch-$os/gvm/reflectionconfig-$arch-$os.json (with your target architecture and OS name).
As is now, it contains around 290 classes (Java and JavaFX), with fields and methods.
If you inspect it, you will see, for that given GridPane class:
,
  {
    "name" : "javafx.scene.layout.GridPane",
    "methods":[
      {"name":"<init>","parameterTypes":[] },
      {"name":"setRowIndex","parameterTypes":["javafx.scene.Node","java.lang.Integer"] },
      {"name":"getRowIndex","parameterTypes":["javafx.scene.Node"] },
      {"name":"setColumnIndex","parameterTypes":["javafx.scene.Node","java.lang.Integer"] },
      {"name":"getColumnIndex","parameterTypes":["javafx.scene.Node"] },
      {"name":"setColumnSpan","parameterTypes":["javafx.scene.Node","java.lang.Integer"] },
      {"name":"getColumnSpan","parameterTypes":["javafx.scene.Node"] },
      {"name":"setRowSpan","parameterTypes":["javafx.scene.Node","java.lang.Integer"] },
      {"name":"getRowSpan","parameterTypes":["javafx.scene.Node"] },
      {"name":"getRowConstraints","parameterTypes":[] },
      {"name":"getColumnConstraints","parameterTypes":[] },
      {"name":"setHgrow","parameterTypes":["javafx.scene.Node","javafx.scene.layout.Priority"] },
      {"name":"getHgrow","parameterTypes":["javafx.scene.Node"] },
      {"name":"setVgrow","parameterTypes":["javafx.scene.Node","javafx.scene.layout.Priority"] },
      {"name":"getVgrow","parameterTypes":["javafx.scene.Node"] },
      {"name":"setMargin","parameterTypes":["javafx.scene.Node","javafx.geometry.Insets"] },
      {"name":"getMargin","parameterTypes":["javafx.scene.Node"] }
    ]
  }
,

As you can notice, it contains the constructor and all the static methods in GridPane, so this works with the Client plugin:
<GridPane>
    <Label text="a label" GridPane.columnIndex="0" GridPane.rowIndex="0"/>
</GridPane>

however, the alignment methods are not included, and that's why your fxml fails.
There are two possible solutions:
1. Config files
Following the Config files section, you can add your own file to your project and add the missing methods:

*

*Create the file reflectionconfig.json under src/main/resources/META-INF/substrate/config/

*Add the missing methods:
[
  {
    "name" : "javafx.scene.layout.GridPane",
    "methods":[
      {"name":"setAlignment","parameterTypes":["javafx.geometry.Pos"] },
      {"name":"getAlignment","parameterTypes":[] },
      {"name":"setHgap","parameterTypes":["double"] },
      {"name":"getHgap","parameterTypes":[] },
      {"name":"setVgap","parameterTypes":["double"] },
      {"name":"getVgap","parameterTypes":[] }
    ]
  }
]

*

*Run again mvn client:build client:run, this time it should work.

If you inspect again the target/client/$arch-$os/gvm/reflectionconfig-$arch-$os.json file, you will see that the content of your json file has been included at the end, and now all the used GridPane methods are available for reflection.
2. Reflection List
Alternatively, you could simple add the whole class to the reflectionList:
<reflectionList>
    <list>javafx.scene.layout.GridPane</list>
</reflectionList>

After you run it, inspecting the json file you will see:
  {
    "name" : "javafx.scene.layout.GridPane",
    "allDeclaredConstructors" : true,
    "allPublicConstructors" : true,
    "allDeclaredFields" : true,
    "allPublicFields" : true,
    "allDeclaredMethods" : true,
    "allPublicMethods" : true
  }

The difference with the option 1 is now that you are telling GraalVM to add all the declared and public constructors, fields and methods of that class to its reflection list, whether they are used or no, which might have a (small) impact in compilation time and memory footprint. Ideally, the option 1 above is better than option 2.
Providing only the required classes/methods will be best, but as @mipa points out, this will require some tooling that could discover which are those. In the meantime, you will have to run some iterations to find out if all the classes/methods used in your FXML files are included or not by the default json file, and add the missing ones to your reflection file (or simply the classes name to the reflection list).

A: You have to add more of the classes, which are loaded via FXML, to the reflexion list. E.g. I also had to add javafx.geometry.HPos and javafx.geometry.VPos. This is complicated by the fact that this is not consistent. Some classes are already included by default - others are not. You will need some experimentation here. Sometimes I even had to specify the parent of a class if a property is defined there already. For my own purposes I have written a little tool to make this easier: https://github.com/mipastgt/JFXToolsAndDemos#fxml-checker

A: I'd just like to add one more specific case to José's answer and maybe he can also clarify that.
Another annoying problem is that sometimes it is not sufficient to just put the class you want to load into the reflection list. E.g., if you want to load a ProgressBar and have put this class into the reflection list, you will still get the following error: ProgressBar Property "progress" does not exist or is read-only. The reason is that the property "progress" is defined in the super-class of ProgressBar and so you have to add ProgressIndicator to the list as well.
Why is this so and can it be prevented somehow?

A: This is so frustrating, but finally I get everything right, Here is some advice.
If you have fxml file and the the file is loaded in Controller, just add the Controller in the reflectionList is fine.
The resourceReflection.json does not contains all properties for javafx class, check if all properties is added in json, if not just add the fx class in the reflectionList, so add
javafx.scene.layout.GridPane
 will add all properties of GridPane.
Check your import class in fxml, some of them may not get added in json file, add to reflectionList whenever you find it, for example if you have RadioButton, ComboBox in fxml file, you won't find them in generated json file.
So 1. Copy and add generated resourceReflection.json in META-INF.substrate.config directory.
2. Add all YOUR class to reflectionList, the View which used to load fxml file don't need to be added.
3. Add e.printStackTrace() to your fxml loader to check what happen in exception.
4. mvn clean client:build client:run.
Happy Coding! Good Job Gluon team.


text:
Q: how to make a plot of an integral function? I made an integral as follow :
fun = @(t)((2/sqrt(pi)) * (exp(1).^((-t).^(2))));

it works fine to calculate it :
q = integral(fun, 0, 2);

But I'd like to plot the result from 0 to different max (0 to 1, 0 to 2, etc...)
I tried
plot(A,fun, '-b');

and I cannot find another way to make it work. What would be the right way, and why isn't it working?

A: Because you want to compute the integral at each maximum value, there's no way you can vectorize this because of the natural way you're calling integral.  As such, you have to put this into a for loop.
At each iteration in the loop, you'd compute the integral, put this into an array then plot the array.  Perhaps do something like this:
vals = 1:3; %// For different maxima - Change to suit your tastes

%// To store the integral results
q = zeros(1,numel(vals));

%// Your code
fun = @(t)((2/sqrt(pi)) * (exp(1).^((-t).^(2))));

%// For each value
for ii = 1 : numel(vals)
    q(ii) = integral(fun, 0, vals(ii)); %// Find integral of each value
end

%// Plot the max value and integral pairs
plot(vals, q);

I get this:

A: integral can only handle numeric values for the integration limits. To have a generic integration limit, you can define that limit to be a symbolic variable and carry out the integration symbolically, for which you use int. That gives you the integral as a symbolic function of the upper limit. Finally, particularize values for the upper limit and plot.
fun = @(t)((2/sqrt(pi)) * (exp(1).^((-t).^(2))));
syms y; %// variable that defines upper integration limit
q = int(fun, 0, y); %// symbolic function of upper integration limit
yValues = linspace(0,2,100); %// define actual values for integration limit
qValues = subs(q, y, yValues); %// particularize q for those values
plot(yValues, qValues) %// plot values

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unexpected Token but not sure as to why I'm not sure why I am getting an Unexpected Token error. I can't seem to see the error. Unless
Line 41 is: }.bind(this), right after this.setState
ERROR in ./app/views/components/navbar.js
Module build failed: SyntaxError: /Users/bli1/Development/projects/cherngloong/cherngloong/app/views/components/navbar.js: Unexpected token (41:4)
                console.log(response);
                this.setState({logoPath: response});
            }.bind(this),
            error: (xhr, status, err) => {
                console.error(this.props.url, status, err.toString());
            }.bind(this),
    at Parser.pp.raise (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:1378:13)
    at Parser.pp.unexpected (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:2817:8)
    at Parser.pp.expect (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:2811:33)
    at Parser.pp.parseObj (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:937:12)
    at Parser.pp.parseExprAtom (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:718:19)
    at Parser.parseExprAtom (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:4305:22)
    at Parser.pp.parseExprSubscripts (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:504:19)
    at Parser.pp.parseMaybeUnary (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:484:19)
    at Parser.pp.parseExprOps (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:415:19)
    at Parser.pp.parseMaybeConditional (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:397:19)
    at Parser.pp.parseMaybeAssign (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:360:19)
    at Parser.pp.parseExprListItem (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:1206:16)
    at Parser.parseExprListItem (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:3692:24)
    at Parser.pp.parseCallExpressionArguments (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:580:20)
    at Parser.pp.parseSubscripts (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:543:29)
    at Parser.pp.parseExprSubscripts (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:514:15)
    at Parser.pp.parseMaybeUnary (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:484:19)
    at Parser.pp.parseExprOps (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:415:19)
    at Parser.pp.parseMaybeConditional (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:397:19)
    at Parser.pp.parseMaybeAssign (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:360:19)
    at Parser.pp.parseExpression (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:324:19)
    at Parser.pp.parseStatement (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:1874:19)
    at Parser.parseStatement (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:3507:22)
    at Parser.pp.parseBlockBody (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:2208:21)
    at Parser.pp.parseBlock (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:2189:8)
    at Parser.pp.parseFunctionBody (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:1125:22)
    at Parser.parseFunctionBody (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:3494:20)
    at Parser.pp.parseMethod (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:1094:8)
    at Parser.parseClassMethod (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:3735:12)
    at Parser.pp.parseClassBody (/Users/bli1/Development/projects/cherngloong/cherngloong/node_modules/babylon/index.js:2456:10)
 @ ./app/views/components/layout.js 17:14-36

Reactjs Component
class Logo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    componentDidMount() {
        $.ajax({
            url: this.props.url,
            dataType: 'json',
            method: 'GET',
            success: (response) => {
                console.log(response);
                this.setState({logoPath: response});
            }.bind(this),
            error: (xhr, status, err) => {
                console.error(this.props.url, status, err.toString());
            }.bind(this),
            data: {
                location: this.props.location
            }
        });
    }

    render() {
        return (

        )
    }
}

A: I'm surprised by the error, though I notice that ArrowFunction is an AssignmentExpression whereas FunctionExpression is a PrimaryExpression (spec), so arrow function expressions aren't direct drop-ins for function function expressions. Still surprised.
Two options for you:

*

*You don't need those .bind(this) calls. Arrow functions close over the this in the context where they're created (just like closing over a variable). So you can solve the error simply by removing those bind calls.
Example:

var foo = {
  name: "foo",
  doSomething() {
    setTimeout(() => {
      log("this.name = " + this.name);
    }, 0);
  }
};
foo.doSomething();

function log(msg) {
  var p = document.createElement('p');
  p.appendChild(document.createTextNode(msg));
  document.body.appendChild(p);
}

*Alternately, if you needed bind (perhaps to curry arguments; the this part will be ignored), put parens around the arrow function:
$.ajax({
    success: ((response) => {
// ----------^
    }).bind(null, arg0, arg1/*...*/)
// --^      ^^^^-- will be ignored, arrow functions inherit `this`
});

Example:

var foo = {
  name: "foo",
  doSomething() {
    setTimeout(((arg) => {
  // ----------^
      log("this.name = " + this.name + ", arg = " + arg);
    }).bind(null, "bar"), 0);
  // ^      ^^^^-- ignored, could be anything
  }
};
foo.doSomething();

function log(msg) {
  var p = document.createElement('p');
  p.appendChild(document.createTextNode(msg));
  document.body.appendChild(p);
}


text:
Q: npm ERR! ERESOLVE unable to resolve dependency tree when installing @nest/microservices I'm trying to install new dependency to my service,
@nest/microservices: ^7.0.3 and got this error:
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: vb-service-ads@0.0.1
npm ERR! Found: @nestjs/common@8.4.7
npm ERR! node_modules/@nestjs/common
npm ERR!   @nestjs/common@"^8.4.7" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @nestjs/common@"^7.0.0" from @nestjs/microservices@7.6.18
npm ERR! node_modules/@nestjs/microservices
npm ERR!   @nestjs/microservices@"^7.0.3" from the root project
npm ERR!

so versions of packages with problem are:
"@nestjs/common": "^8.4.7",
"@nestjs/core": "^7.6.15"

I tried to upgrade versions of core and microservices dependencies to ^8.0.0, and got more dependencies broken and also tried to downgrade common to ^7.6.15 and got same effect.
Tried to use yarn instead of npm, it resolved my problem, but i need all packages to be installed by npm

A: you can see the solution here, or at least this is what worked for me here. https://www.angularjswiki.com/angular/unable-to-resolve-dependency-tree-error-in-angular-while-installing-npm-packages/
I leave you the part where it worked for me

To fix Unable to resolve dependency tree error in Angular while
installing npm packages follow the below steps.

*

*Run npm install --save --legacy-peer-deps instead of npm install command. Another way is delete the node_modules folder and
package_lock.json file and then

*Run npm cache clean --force after npm i --force command.

A: So, I resolved this problem, with deleting node_modules, package-lock.json and removing dependencies and devDependencies in package.json
After i've installed all dependencies manually one by one


text:
Q: Comparing the derivatives of smooth maps $f, g : M\to N$ at $p \in M$ with $f(p) \ne g(p)$ We consider smooth maps $f : (M,p) \to (N,q)$ mapping a fixed point $p \in M$ to a fixed point $q \in N$. The derivative at $p$ is a linear map $df_p : T_pM \to T_qN$. We can therefore compare the derivatives of smooth maps $f, g : (M,p) \to (N,q)$. We can also do that without using tangent spaces  by choosing charts $\phi : U \to U'$ on $M$ around $p$ and $\psi : V \to V'$ on $N$ around $q$. Then we get "localized derivatives"
$d_{(\phi,\psi)} f_p  = d(\psi \circ f \circ \phi^{-1})_{\phi(p)}$ and $d_{(\phi,\psi)} g_p  = d(\psi \circ g \circ \phi^{-1})_{\phi(p)}$ in the usual sense of multivariable calculus. Clearly $df_p = dg_p$ iff $d_{(\phi,\psi)} f_p = d_{(\phi,\psi)} g_p$. Note that the last equation does not depend on the choice of $\phi, \psi$.
If $N = \mathbb R^n$ we can compare the derivatives at $p$ of any two smooth maps $f, g$ (without assuming that $f(p) = g(p)$) by taking the identity on $\mathbb R^n$ as a chart around both $f(p)$ and $g(p)$. This was used e.g. in Hitchin's definition of tangent space and tangent vectors to define the cotangent space $T^*_pM$.
I try to understand whether such a comparison is possible for more general $N$. So let us consider the case $f(p) \ne g(p)$ for a general $N$.
Naively one could use charts $\psi_f$ and $\psi_g$ around $f(p)$ and $g(p)$ and form the corresponding localized derivatives. But obviously this does not make sense because these charts can be chosen independently which prevents a comparison of the localized derivatives. It would be the same as choosing in case $f(p) = g(p)$ two charts depending on $f,g$. Also using the same chart for $f(p)$ and $g(p)$ if these points lie in a common chart region $V$ does not seem to helpful since for some choice $\psi : V \to V'$ we may have $d_{(\phi,\psi)} f_p = d_{(\phi,\psi)} g_p$ and for some other choice $d_{(\phi,\psi)} f_p \ne d_{(\phi,\psi)} g_p$. Even if the chart region $V$ is diffeomorphic to $\mathbb R^n$ (which can always be achieved if $f(p), g(p)$ lie in the same component of $N$) we have this problem.
In case $N = \mathbb R^m$ (or more generally  $N \subset \mathbb R^n$ open) we can circumvent the "chart choice problem" because we have the identity as a canonical chart. It does not seem that canonical charts are available on general $N$, thus this approach does not work.
But thinking again in terms of tangent spaces we see that the derivatives at $p$ of any two smooth maps $f, g : M \to \mathbb R^n$ can be compared because we have a canonical identification $T_q\mathbb R^n = \mathbb R^n$ for all $q \in \mathbb R^n$. That is, the tangent bundle $T\mathbb R^n$ has a canonical trivialization. It is not expedient to allow arbitrary trivalizations of $T\mathbb R^n$ because this would essentially reproduce the above chart choice problem.
The existence of a canonical trivialization of $TN$ is not a unique feature of $\mathbb R^n$. Each Lie group $N$ with neutral element $e$ has a canonical isomorphism $TN \approx N \times T_eN$. This should enable us to compare $df_p$ and $dg_p$ for any two smooth $f, g : M \to N$.
Another approach could be to consider manifolds with a flat connection. This gives canonical isomorphisms between any two tangent spaces. A connection is of course an additional ingredient, but I think in some cases we have a canonical one. Flat connections exist on more manifolds than on those having a trivial tangent bundle, so this is more general approach.
Do these two approaches make sense? Do they occur in the literature?
A possible problem seems to be that such a concept is not invariant under submanifold inclusion. As an example consider $S^1 \subset \mathbb R^2$. The maps $f : \mathbb R \to S^1, f(t) = e^{it}$, and $g : \mathbb R \to S^1, g(t) = -e^{it}$, are smooth. Their derivatives at any $t \in \mathbb R$ are equal if we use the canonical (Lie group) based identifications $d\tau_q : T_qS^1 \to T_1S^1$, where $\tau_q(z) = q^{-1}z$. But the maps $if, ig$ with inclusion $i : S^1 \to \mathbb R^2$ do not have the same derivatives at $t$.


text:
Q: How to retrive data from mysql to wysiwyg editor using php I am creating a job website in which I am using WYSIWYG editor to post details of a job into HTML format using WYSIWYG editor.
I am successful in posting job but when I retrieve the same data to update in WYSIWYG editor it does not display in the proper format? How can I do this please help me I am in trouble.

A: try html_entity_decode($content) if it's not working can you post me the content format loaded when load update window or did you check how the content was saved in DB? I think the content was saved with html_encoded for the security if that's is the case you have to do html_decode using above function.


text:
Q: How to transfer data between the content scripts of two different tabs? In my extension I need to transfer some data from one tab's content script to another tab's content script. How can I choose certain tab using chrome.tabs, if I know a part of that tab object's name or url in it? How can two tabs' scripts communicate?
UPDATE:
Apparently I don't have method sendMessage in chrome.extension. When I run the following from content script:
chrome.extension.sendMessage("message");

I get in console:

Uncaught TypeError: Object # has no method 'sendMessage'

A: First, note that messages passed within an extension are JSON-serialized. Non-serializable types, such as functions, are not included in the message.
Within a content script, you have to pass the message to the background page, because there is no method to directly access other tabs.
// Example: Send a string. Often, you send an object, which includes
//  additional information, eg {method:'userdefined', data:'thevalue'}
chrome.extension.sendMessage(' ... message ... ');

In the background page, use the chrome.tabs.query method to get the ID of a tab. For the simplicity of the example, I've hardcoded the patterns and urls. It might be a good idea to include the query values from the previous message, in this way: {query:{...}, data:...}.
// background script:
chrome.extension.onMessage.addListener(function(details) {
    chrome.tabs.query({
        title: "title pattern",
        url: "http://domain/*urlpattern*"
    }, function(result) {
        // result is an array of tab.Tabs
        if (result.length === 1) { // There's exactely one tab matching the query.
            var tab = result[0];
            // details.message holds the original message
            chrome.tabs.sendMessage(tab.id, details.message);
        }
    });
});

chrome.tabs.sendMessage was used to pass the original data to a different tab.
Remark: In the example, I only passed the message when the query resulted in one unique tab. When uniqueness is not a prerequisite, just loop through all resulting tabs, using result.forEach or:
for (var i=0, tab; i<result.length; i++) {
    tab = results[i];
    ...
}

A: From a content script you only can communicate with the background process.
You may communicate between two content scripts in differents tabs using the backgound as intermediate.
Also the DOM provide other way to communicate between DOM windows, but with the same origin policy...
To get a tab's url, you may execute a content script on it.  The content script can get the url using window.location.href


text:
Q: How can I generate Query in elastic search for multiple boolean queries I want to generate query for multiple boolean operation dynamically in elasticsearch with spring framework.
my data in elasticsearch is like
{
   "masterID" : "<id>"
   "processedData": [
                {
                    "string_value": "22",
                    "key": "a"
                },
                {
                    "string_value": "abc",
                    "key": "s"
                },
                {
                    "string_value": "xyz",
                    "key": "n"
                }
            ]
}

I want to execute query for this boolean operation ((n=xyz) && (s=abc))

A: To be able to query Array inner object you should map your processedData as a Nested type, arrays of objects do not work as you would expect because you cannot query each object independently of the other objects in the array. If you need to be able to do this then you should use the nested data type instead of the object data type. After changing your mapping you can make a nested query with a bool query like this:
{
  "query": {
    "nested": {
      "path": "processedData",
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "key": "n"
              }
            },
            {
              "match": {
                "string_value": "xyz"
              }
            }
          ]
        }
      }
    }
  }
}

For more information you can check here: https://www.elastic.co/guide/en/elasticsearch/reference/master/array.html


text:
Q: Backbone.js: add product twice to cart with new attributes. Correct MV architecture? I'm building an app that gets a collection of products from a JSON file and stores these as models in a collection.  The user can:

*

*select multiple instances of a product

*customise them - change colours, change materials, etc.

I don't have these attributes on the product model at the moment.
How would I go about setting this up?  Would I add all the possible customisation attributes to the original model?  I'm assuming I'd probably need a Cart Collection?  Would I need a separate Cart Item Model that is cloned from the original Product Model?  and would the best place to set all this up be in the main App View?
Any help would be greatly appreciated as I've just started with backbone and have a lot to learn!
many thanks

A: You can use nested model to wrapper Product Model as a attribute of Cart Item Model.
And when customise product by set deferent colours or size, if the API RETURN DEFERENT ID for deferent size or colour, you may be create new instance for each of them.


text:
Q: Using UserControls and Sockets in C# WinForms I'm quite new to Sockets and would appreciate if someone could give an advice.
In my Windows Forms application several users can add user controls to the same form and manage them. I am not sure if I've taken the right approach.
My first two functions are drawing and adding a UserControl. For drawing I simply send the  coordinates of Mouse_Move event to all clients:
private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (canDraw)
        {
            string coords= e.X.ToString() + "|" + e.Y.ToString();
            Sender(coords);
        }
    }

 void Sender(string msg)
 {
        byte[] bytes = new byte[1024];
        bytes = Encoding.UTF8.GetBytes(msg);
        client.Send(bytes);
 }

When I receive the bytes, I draw them:
 client.Receive(bytes);

 string data = Encoding.UTF8.GetString(bytes);
 //the received data in format "X|Y"
 string[] split_data = data.Split(new Char[] { '|' });
 Draw(Convert.ToInt32(split_data[0]),
     Convert.ToInt32(split_data[1]));

Draw method:
void Draw(int x, int y)
{
        Graphics graphics = CreateGraphics();
        graphics.FillEllipse(new SolidBrush(Color.Black), x, y, 5, 5);
}

Everything works fine at this point. Now I try to add UserControl to the form and send it to all clients. I simply send some sign when the control needs to be added, and create new userControl:
 private void AddRectButton_Click(object sender, EventArgs e)
 {
    Sender("RectControl|");
 }

And when I receive:
 client.Receive(bytes);
 if (bytes.Length != 0)
 {
   string data = Encoding.UTF8.GetString(bytes);
   string[] split_data = data.Split(new Char[] { '|' });

   if (split_data[0] == "RectControl")
   {
       this.Invoke(new MethodInvoker(delegate
       {
          RectControl control = new RectControl();
          this.Controls.Add(control);
       }));
   }
  else
  {
     Draw(Convert.ToInt32(split_data[0]),
     Convert.ToInt32(split_data[1]));
  }

I am not sure if i'm doing right, maybe there is another way of implementing this?
Also, when one client performs some changes on userControl (such as move, manipulation of control content, etc.) I will have to keep track of every change and send it to all the clients. How can I know exactly which control has been changed to apply these changes for the rest ones?

A: PLED gives good advice. I would add:
It is unclear what transport protocol you are using. If UDP, you might drop packets, so some clients might see new controls or moved controls that other clients do not.
I am guessing you use TCP for guaranteed delivery and congestion control. Keep in mind TCP is a streaming protocol. That means when you send a 50-byte message, you might receive that message all at once in one Receive call, or as many as 50 different Receive calls 1 byte at a time.
Also, you might receive multiple messages in a single Receive call.
Look up "TCP Framing". On each Receive, make sure you read in all full messages, hold onto any extra bytes that are part of the next message, and then make your next Receive call. One way to simplify framing is to use a length-prefix of 4 bytes before each message, so that you know when you are done reading a full message.
I would also recommend looking up protobuf-net (or another implementation of google protocol buffers), which will handle the serialization for you, and allow you to deal with simple types, where each field of your message is a property of the type. That would avoid the need to parse up the string. protobuf-net is extensible, so if you decide to add new fields to the message later, it's easier and won't break existing deployed builds.


text:
Q: Formatting Java String I have a simple question, but it's rather difficult to google. I have an input field for a number, and I need to make this number into a currency. So, if a user inputs 120, I need to format that into $1.20. Then, if they add another digit, say the number becomes 1204, I need to format this as $12.04. I'm using a Double.ParseDouble, but for say 120, this yields $120.00. So, I guess I need something like ParseDouble that will turn a value like 120 into $1.20 instead of $120.00. How do I do this?

A: use Double.parseDouble(double number);, but easily multiply with 0.01 :)
Then you have your currency and everything is fine ;)
Devlen

A: You can do it without even parsing in a numeric.
Use a StringBuilder object to do so:
    String input = "120";
    String output = new StringBuilder(input).insert(input.length() - 2,".")
                                            .insert(0, "$").toString();
    System.out.println(output); // Prints $1.20

A: public String getNumberCurrency(double number){

 NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.getDefault());
 String moneyString = formatter.format(number/100);
 return moneyString;

}


text:
Q: CFT - cloud foundation toolkit error I have been having a problem running CFT on Google Cloud shell or any other linux server. After installing all the pre-requisites upon running cft, I get the same error everywhere:
Steps
cloned Cloud foundation toolkit fro Github

cd dm
sudo make cft-prerequisites
make build
sudo make install

XXXXXXX:~/cloud-foundation-toolkit/dm$ cft
/usr/bin/python: No module named cloud_foundation_toolkit
XXXXX~/cloud-foundation-toolkit/dm$

A: After following your same steps I've managed to reproduce your issue.
In order to solve it I've followed the CFT Developer Guide and I got the cft command working.
The steps differ in that the guide creates and uses a virtual environment to execute the command. The steps are:
sudo make cft-prerequisites
make cft-venv
source venv/bin/activate
source src/cftenv

Please read the documentation in order to know the details of each command and how to exit the environment.


text:
Q: Chef: How I get file content to a variable ,but file do not exist yet I need to get a file content in a file that I will create.
My code:
     execute "foo" do
         command "echo "Hello World > /tmp/foo"
         action :run
end

variable = shell_out!("cat /tmp/foo").stdout

Erro
ERROR: Expected process to exit with [0], but received '1'
---- Begin output of cat /tmp/foo ----
STDOUT:
STDERR: cat: /tmp/foo: No such file or directory
---- End output of cat /tmp/foo ----
Ran cat /tmp/data.uuid returned 1

A: The issue is Chef's two-pass model, which I detail in https://coderanger.net/two-pass/. Unfortunately you do not give enough detail here to advise on a specific solution but roughly you need to move the shell_out!() call in to somewhere not evaluated at compile time.


text:
Q: Creating a class that executes python in c# I have a python code. I need to execute the python script from my c# program. After searching a bit about this, I came to know that there is mainly two ways of executing a python script from c#.
One by using 'Process' command and
the other by using Iron Python.
My question might seem dumb, is there any other way through which I can execute a python script? To be more specific, can I create a class , lets say 'Python' in c#  and a member function 'execute_script' which doesn't use any api like iron python or doesn't create a process for executing the script, so that if call 'execute_scipt(mypythonprogram.py)' , my script gets executed. Sorry if this seems dumb. If this is possible, please do help me. Thanks in advance.

A: You can embed python into your application. View the python documentation section Extending and Embedding > Embedding Python in Another Application.
edit: this requires C++, but it should not be too difficult to build a C++ wrapper that you can use from C# (see this MSDN article).

A: Can you create a C# class that calls a Python script without using Iron Python and without using any external API? No. That is not possible. You have a few other choices:

*

*Integrate the Python runtime into your program.

Smead already described one way to do this. It will work, and it does avoid creating another process, but it will be a lot of work to get it running, and it is still technically using an API. I do not recommend this for a single Python script where you don't need to pass data back and forth, but it's good to know that option exists if your other options don't pan out.

*Use the Process module.

This is probably what I would do. Process has security concerns when a malicious user can cause you to execute bogus shell commands, or if the malicious user can replace the contents of the Python script. It is quite safe when you can lock down those two things.
The speed is unlikely to be a concern. It will literally only take a few minutes to set up a C# program with a process call, so if your mentor is concerned about speed, just write it and measure the speed to see if it's actually a problem.

*Consider rewriting the script in C#

C# is a very expressive language with a very strong standard library, so assuming your script is not thousands of lines long, and does not use any obscure Python libraries, this might actually not be much work. If you really must not use Process, this would be the next solution I would consider.


text:
Q: Amcharts grouping / creating series by property I am using Amchart v4 and have the folowing data.
[
  {
    "date": 1583419378000,
    "id": "A",
    "value": "76"
  },
  {
    "date": 1583419378000,
    "id": "B",
    "value": "72"
  },
  {
    "date": 1583419378000,
    "id": "C",
    "value": "908"
  },
  {
    "date": 1583419379000,
    "id": "A",
    "value": "44"
  },
  {
    "date": 1583419379000,
    "id": "B",
    "value": "704"
  },
  {
    "date": 1583419379000,
    "id": "C",
    "value": "918"
  },
]

The x-axis is the date (timestamp) and the y-axis is the value. I want to create 3 lines on my line chart using the id.
Is there a way to group by id to get 3 lines? I only have one 'series' at the moment and it produces one line with all the data?
let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.minGridDistance = 60;

 chart.yAxes.push(new am4charts.ValueAxis());

// Create series
let series = chart.series.push(new am4charts.LineSeries());
series.dataFields.valueY = "value";
series.name = "id";
series.dataFields.dateX = "date";
series.dataFields.category = "id";
series.tooltipText = "{value}"
series.tooltip.pointerOrientation = "vertical";

chart.cursor = new am4charts.XYCursor();
chart.cursor.snapToSeries = series;
chart.cursor.xAxis = dateAxis;

I have tried series.dataFields.category = "id";

A: You need to create separate series for each line you want to display. There isn't a way for the chart to automatically create grouped series for you.
As for handling the data, you have two options:
1) Manually group your data by date but make separate value fields for each id:
chart.data =[
  {
    "date": 1583419378000,
    "valueA": "76",
    "valueB": "72",
    "valueC": "908"
  },
  // ... etc
];

//create each series and point to each individual value:

seriesA = chart.series.push(new am4charts.LineSeries());
seriesA.dataFields.valueY = "valueA";
series.dataFields.dateX = "date";
seriesA.name = "A"; // Note you have to specify the name directly. You can't map by a property.
// ... repeat

2) Manually create separate data arrays based on ID and assign the arrays directly to the series instead of the chart:
// assumes your data is in a variable called "data"
seriesA = chart.series.push(new am4charts.LineSeries());
seriesA.dataFields.valueY = "value";
seriesA.dataFields.dateX = "date";
seriesA.name = "A";
seriesA.data = data.filter(item => item.id == 'A');
// repeat for each id


text:
Q: 14.04 update: kernel crypto interface not available A few days ago, after a sytem update to kernel 3.19.0-56, I can not open anymore a tcrypt volume with cryptsetup. I get the following error:
sudo cryptsetup open --type tcrypt /dev/sda tcryptDisk
Enter passphrase:
Required kernel crypto interface not available.
Ensure you have algif_skcipher kernel module loaded.

Trying to load the mentioned module does not resolve the issue:
sudo modprobe algif_skcipher

Any pointer greatly appreciated!
Seb

A: I just ran into the same issue after a kernel update to 3.13.0-83-generic.  It appears to be bug with that kernel version reported on 3/16/16:
cryptsetup tcryptOpen doesn't work anymore
My temporary fix was to revert back to the previously installed kernel version.
Confirm current version:
$ uname -r
3.13.0-83-generic

Remove 3.13.0-83 version:
$ sudo apt-get purge linux-image-3.13.0-83-generic

Reboot your machine and confirm version:
$ uname -r
3.13.0-79-generic

Kernel 3.13.0-79-generic works for me and no longer get any error messages with cryptsetup.
Since you appear to be on a much newer version 3.19.0-56 you may need to somehow get to 3.19.0-51 which one of the commentators in the bug indicates it was still working "fine".
Instead of downgrading, you may try booting into that specific version via grub and setting it as your default.


text:
Q: TypeScript: How to set a const variable in a try block? I want to declare a const variable, initialize it inside a try block, and then use it outside of that try block. For example:
const result;

try {
    result = getResult();
} catch (error) {
    report(error);
    return;
}

use(result);

Or asynchronously:
const result;

try {
    result = await fetchResult();
} catch (error) {
    report(error);
    return;
}

use(result);

What I don't want:

*

*Use let because that allows overwriting the result later on.

*Move this to a separate function because I only want this logic to be accessible inside the given scope.

I'm seeing this pattern a lot in my code, so is there any way to do this using a modular TypeScript solution?
The following questions are similar, but don't provide a reusable type-safe solution:

*

*how use const in try catch block

*Javascript set const variable inside of a try block

A: Synchronous solution
Use the following type-safe utility function:
function tryGet<T>(getter: () => T): {
    success: true;
    value: T;
} | {
    success: false;
    error: Error;
} {
    try {
        return {
            success: true,
            value: getter(),
        };
    } catch (error) {
        return {
            success: false,
            error: error as Error,
        };
    }
}

Usage:
import { report, use } from './imagination';

const result = tryGet(getValue);

if (!result.success) {
    report(result.error);
    return;
}

use(result.value);

Asynchronous solution
export default async function tryGetAsync<T>(
    getter: () => Promise<T>
): Promise<{
    success: true;
    result: T;
} | {
    success: false;
    error: Error;
}> {
    try {
        return {
            success: true,
            result: await getter(),
        };
    } catch (error) {
        return {
            success: false,
            error: error as Error,
        };
    }
}

Usage:
import { report, use } from './imagination';

const result = await tryGetAsync(fetchValue);

if (!result.success) {
    report(result.error);
    return;
}

use(result.value);


text:
Q: How to merge audio and video in JW Player? We have some .mp4 videos which has no audio. Now i want to add a audio track to that videos. I have implemented all player functionality in JW Player. Is it possible to play both the .mp4 and .mp3 files at the same time? if yes please guide me how to do.
My current code is like below.
<script type='text/javascript'>
jwplayer('player').setup({
        width: '60%',
        height: '60%',
        primary: "flash",
        playlist: [{
            image: "15.png",
            sources: [{
              file: "anim_card_flip.mp4"
            }],
            title: "RK Movie Trailer",
            tracks: [{  // i want to specify audio file like this
              file: "ringtone.mp3"
            }]
        }]
});

A: I totally agree with @Ethan and @MisterNeutron that Player is just a player, Player will only process the video or audio, it won`t merge. it doesn't do anything with the media fed into it, other than play it back.
I think You should look for some other solution which helps you to merge the video and audio into one in mp4 format and then play it with jwplayer
while searching for solution I found about recordRTC (other link )and ffmpeg, using ffmpeg you can merge video, you need to explore more about this and how it works.

Once you have downloaded both video and audio files
  ('videoplayback.mp4' and 'videoplayback.m4a' respectively), here's how
  you can merge them into a single file:
 - Download and install ffmpeg. Open a Command Prompt window in your
   downloads folder and run the following command

 -  ffmpeg -i videoplayback.mp4 -i videoplayback.m4a -c:v copy -c:a copy output.mp4

 - Wait until ffmpeg finishes merging audio and video into a single file
   named "output.mp4".

Some more helpful links

*

*how to merge mp4 and m4a files (ffmpeg method)

*how to mix in audio to html5 video? ( This solution is same as suggested by @Ethan and @MisterNeutron, to create two instance of player and use one for audio and other for video)

I hope this helps :)


text:
Q: Flutter problemas con el Login de Google Buen día comunidad necesito de su apoyo, estoy desarrollando una App con flutter en lo cual estoy usando la autenticación con google y Firebase, estoy siguiendo una documentación en el siguiente link Flutter: Implementación de inicio de sesión de Google
en lo cual la documentación hace un énfasis lineas abajo sobre una excepción PlatformException y su solución, y bueno seguí la documentación detalladamente pero a pesar de eso recibo la excepción, agrego la excepción que recibo.

archivo pubspec.yaml
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  google_sign_in: ^4.0.4
  firebase_auth: ^0.11.1+8
  firebase_core: ^0.4.0+8
  http: ^0.12.0+2

archivo android/build.gradle
dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-core:17.0.0'
}

apply plugin: 'com.google.gms.google-services'

archivo android/app/build.gradle
buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath 'com.google.gms:google-services:4.2.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

archivo login.dart
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();

Future<String> signInWithGoogle() async {
  final GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
  final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;

  final AuthCredential credential = GoogleAuthProvider.getCredential(
    accessToken: googleSignInAuthentication.accessToken,
    idToken: googleSignInAuthentication.idToken
  );

  final FirebaseUser user = await _auth.signInWithCredential(credential);

  assert(!user.isAnonymous);
  assert(await user.getIdToken() != null);

  final FirebaseUser currentUser = await _auth.currentUser();
  assert(user.uid == currentUser.uid);

  return 'signInWithGoogle succeeded: $user';

}

void signOutGoogle() async {
  await _googleSignIn.signOut();
  print("USER SIGN OUT");
}

Vista de la localización del archivo google-services.json

Vista de las creedenciales:

Vista de console.google agregando los dominios

Recalcar que también habilite la autenticación en el proyecto de firebase y también habilite los métodos de sesión de google, correo electrónico y opcional(Google Play).
Agrego la descripción de la aplicación Android de Firebase

Es un error que hasta ahora no encuentro alguna solución espero de su gran ayuda, amigos.

A: Os lo pongo por si ayuda, ya que yo me volví loco hasta que lo encontré.
Lo que está claro es que el error 10, se refiere a una mala configuración de credenciales.

*

*Primero, consigue tus claves SHA-1 para el modo debug:
Click en Gradle (En el panel derecho)
Click en Tasks
Click en Android
Doble Click en signingReport (En la parte inferior verás las claves.)

*Añadir los credenciales a la API también
Ve a https://console.developers.google.com/apis/credentials
Crea nuevo OAuth Client ID
Name : Cliente Android pruebas
Signing-certificate fingerprint : Copiar y pegar tu clave SHA-1
Poner el nombre del paquete

*Añadir la clave al proyecto de Firebase :
Ir a la configuración del proyecto y añadir el certificado SHA
Volver a descargar el archivo google-services.json y cargarlo en el proyecto Android en la carpeta app.
Aquí hay un hilo en inglés que lo describe muy bien:
https://stackoverflow.com/questions/47437678/why-do-i-get-com-google-android-gms-common-api-apiexception-10

A: Te sugiero que uses un bloque try catch para capturar de mejor manera el error y saber por qué esta fallando, te pongo un ejemplo:
Future<FirebaseUser> signInGoogle() async {
  try {
    final GoogleSignInAccount googleSignInAccount = await _gSignIn.signIn();
    final GoogleSignInAuthentication authentication =
      await googleSignInAccount.authentication;
    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: authentication.accessToken,
      idToken: authentication.idToken);

    FirebaseUser user = await _fAuth.signInWithCredential(credential);
    new User(name: user.displayName, photoUrl: user.photoUrl, uid: user.uid);
    return user;
    } catch (err) {
        print(err);
        return null;
    }
 }

A: Buenas pude solucionar mi problema partiendo de un error garrafal mío, como se podrá notar en la primera imagen de mi pregunta, me muestra la siguiente Excepción: com.google.android.gms.common.api.apiexception: 10 esta excepción se basa con Firebase y las huellas digitales SHA, en base a ese problema llegue a un tutorial que generaba automaticamente un KEY, a la vez seguía un articulo y un video tutorial, pero mas me inclinaba en la explicación del video tutorial.
Imagen de mi key generada

El problema era que a través de tener problema tras problema no tenia conciencia lo que realmente tenia que solucionar, este era el problema ya que en este Articulo que coloque en la pregunta flutter-implementing-google-sign-in me decia que que tenia que generar mi SHA a través de esta ruta user.android\debug.keystore, y desde ahi puedo obtener SHA1. y luego agregarlo a mi proyecto en Firebase, desde mi funciona todo correctamente.


text:
Q: Select named element dynamically I have this code
$('#addPhone').click(function() {
    phoneCount = $("#phoneTabs").tabs("length") + 1;
    $('#phoneTabs').show();
    $('#phoneTabs').append('
<form id="phoneForm' + phoneCount + '" novalidate="novalidate" action="" method="post">

Phone Number ' + phoneCount + '

Phone number	<input type="text" class="required digits" maxlength="10" minlength="10"  name="phone_number' + phoneCount + '" />

Comment	<textarea rows="5" cols="25" name="phone_comment' + phoneCount + '"></textarea>

<button id="addPhone' + phoneCount + '">Add</button></form>
');

    $("#phoneForm" + phoneCount).validate({
        submitHandler: function() {
            return false;
        }
    });
    $('#addPhone' + phoneCount).button();
    $('#addPhone' + phoneCount).click(function() {
        $(this).button({
            disabled: true
        });
        $('#phoneForm' + phoneCount + ' input').attr('disabled', true);
    });

    $("#phoneTabs").tabs("add", "#phoneTabs" + phoneCount, phoneCount);
    $('#phoneTabs').tabs("select", phoneCount - 1);
    phoneCount++;
});

Why when i click on addPhone button only the button get disabled, why the other input elements that are child of #phoneForm'+ phoneCount are not disabled?
What i am doing wrong?

A: This is a closure issue, phoneCount value changes before it is applied in the click handler, to remove the closure try this
$('#addPhone' + phoneCount).click((function(selector){ return function() {
    $(this).button({
        disabled: true
    });
    $(selector).attr('disabled', true);
}})('#phoneForm' + phoneCount + ' input'));

EDIT
If you want to use the value of phoneCount in the function then pass only that to the IIFE
$('#addPhone' + phoneCount).click((function(phoneCount){ return function() {
    if (phoneCount operator operand){
        code
    }
    $(this).button({
        disabled: true
    });
    $('#phoneForm' + phoneCount + ' input, other selectors').prop('disabled', true);
}})(phoneCount));

A: It could be disabling the inputs on the LAST tab, if you change the line
$(this).button({disabled : true});
$('#phoneForm'+ phoneCount+ ' input').attr('disabled',true);

to be
$(this).button({disabled : true});
$(this).closest("form[id^='phoneForm'])".filter('input').attr('disabled',true);

should hopefully get the form that is active.


text:
Q: The "path" argument must be of type string or an instance of Buffer or URL. Received an instance of Object I'm trying to send an image file (converted into Uint8Array) to the server using post request.
How do I read this image file on the server side and convert it into 'base64' string at server side.
My code snippet is below
    let image = null
     document.getElementById('img').addEventListener('change', (event) => {
       const img = event.target.files[0]
      try {
        let file = new FileReader()
        file.readAsArrayBuffer(img)
        file.addEventListener("load", () => {
          this.image = new Uint8Array(file.result)
        })
      } catch (error) {
          console.log(error)
      }
    })

    var data = {image: this.image}

    axios.post('http:localhost:8080/post/upload', data, {headers: {'Content-type': 'application/json'}})
    .then((response) => {
       if(response) {
         console.log(response.data)
       }
    }).catch((err) => {
         console.log(err)
    })

My backend code snippet is below:
    private_router.post('/post/upload', async(req: express.Request, res:
    express.Response) => {
      let img = null
      fs.readFile(req.body.image, (err, data) => {
        if(err) console.log(err)
        else img = data
      })
      if(img != null) {
        console.log(img)
        return res.status(200).json({message: 'posted'})
      }
       res.status(200).json({message: 'posted'})

      })

When I make a post request using above code I get following error:
  (node:22468) UnhandledPromiseRejectionWarning:
TypeError [ERR_INVALID_ARG_TYPE]:
The "path" argument must be of type string or an instance of Buffer or URL. Received an instance of Object

I'm using Node.js as my backend.


text:
Q: Check whether object is in QuerySet of related objects I am building an application having to do with game achievements, and I want to display for each game, a page that lists the related achievements. That is done.
However, I also want each user to be able to see in that list which achievements they have completed.
My model is like this:
class Achievement(models.Model):
    game = models.ForeignKey(Game)
    ...

class Game(models.Model):
    ...

class GameProfile(models.Model):
    achievements = models.ManyToManyField(Achievement, through='Achieved')
    ...

class Achieved(models.Model):
    profile = models.ForeignKey(GameProfile)
    achievement = models.ForeignKey(Achievement)
    curr_count = models.PositiveSmallIntegerField()

In the game template page, I get all the achievements for the current game through the relationship with the Achievement model (ie achievements = game.achievement_set.all). Then I do a {% for ach in achievements %} on them and output a <li> for each.
If a user is logged in, I also want to display the curr_count associated with the achievement. So I need a list of Achieved objects for the specific GameProfile (think of it as the current user).
The problem is that I cannot do {% if ach in achieved %} (where ach is an Achievement instance and achieved an Achieved QuerySet), obviously.
I also thought I could get a QuerySet with the Achievements the user has achieved, but that lacks the curr_count, which I want to display.
I think what I want is some kind of list or dictionary with the Achievements of the user against which I can test if a specific Achievement is a member, but which will also carry the curr_count variable. Another solution might be to somehow add curr_count as a field to a QuerySet of Achievement objects (which will be the ones the user has achieved).
Can you suggest how to accomplish this in django?

A: If your GameProfile model has a link to (auth.)User then you can generate the following queryset and send it to the template.
def achievements_by_user(request, *args, **kwargs):
    user = request.user
    queryset = Achieved.objects.filter(profile__user = user)
    return render_to_response(...)

This queryset will filter all rows from Achieved based on the currently logged in user. If you also want to filter based on game (i.e. return all achievements for the currently logged in user for a specific game) then you can add another filter condition.
    queryset = Achieved.objects.filter(profile__user = user,
            achievement__game = <a game>)

Update
Apparently I misunderstood the question. Here is another stab at it.
@register.filter
def achievement_in(achieved, achievement):
    count = achieved.filter(achievement = achievement).count()
    return count > 0

# In template
{% for ach in achievements %}
    {% if achieved|achievement_in:ach %}
        ...
    {% else %}
        ...
    {% endif %}
{% endfor %}


text:
Q: unautomated subscription plugin I need to send some data to my subscribed visitors periodically.
Is there any plugin that just let users subscribe (enter their email) in my site that don't send anything automatically and I be able to use it manually?
I need a plugin that collect user emails (Using a subscription form) and let me send mass mails to them manually and nothing more!.
thanks

A: in case you don't afraid of some php, making a simple form that receives email address and insert it into wordpress database, is quite simple. this method allows you afterwards to generate mailing lists versatile as you like (divided to group of 50s, comma/tab seperated, etc.)
to do so the only plugin you'll need will be php-code-widget .


text:
Q: Refreshing browser not loading page but works while navigating through menu links (Angular) The site works fine on local server, but after deploying to a remote server the page reload not loading component.
It works only when clicked to nav links.
The site is https://astrohimalaya.com/. Components created only for home and about. I can not refresh from about page.
Help needed

A: You need to configure URL Rewrites on your hosting. Basically anything that hits your domain needs to point back to the index.html and the frontend router will take care of the state/page to display.

https://firebase.google.com/docs/hosting/full-config#rewrites


text:
Q: How to test EJB with TomEE? I'm using TomEE with Intellij to test my EJB/JPA beans. I saw on this answer that I should use a embedded container to test. I discovered Arquillian on this other answer(from the same question) but as stated on comments, it's difficult to set it up and not user friendly, things beginners like me search for.
Unfortunately I'm not using glassfish-embedded-all dependency as answered, but tomee-embedded. I saw on this official tutorial it should use JTA as well as answered above. But why?
Doing as last link, I was getting this error:
No EJBContainer provider available: no provider names had been found.

Then using a piece of code from @BeforeClass method from this answer. My test is shown below:
    Properties properties = new Properties();
    properties.setProperty(EJBContainer.PROVIDER, "tomee-embedded");
    EJBContainer container = EJBContainer.createEJBContainer(properties);
    AccountDao dao = (AccountDao) container.getContext().lookup("java:global/Test/AccountDao");

Where Test is my application name and AccountDao is my Stateless Bean that I want tested. But now I'm getting this error:
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: PG_CLASS

Although I'm not using HSQLDB, I'm having this error. How can I correctly add some postgresql properties to correctly instantiate my Hibernate entityManager? Here's my persistence.xml:
<persistence-unit name="unitName">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <class>entity.PersistentEntity.Account</class>
    <properties>
        <property name="tomee.jpa.factory.lazy" value="true"/>
        <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
        <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost/click10"/>
        <property name="javax.persistence.jdbc.user" value="postgres"/>
        <property name="javax.persistence.jdbc.password" value="postgres"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect"/>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.format_sql" value="true"/>
        <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
</persistence-unit>

A: I have had success with using the TomEE embedded container for unit tests. As with any external JUnit resource it can be managed using a @Rule so I have two classes, the Rule class and a wrapper for the Embedded TomEE.
The wrapper class for the TomEE Container class. Configures an embedded derby datasource, and a user so we can test Basic authentication.
/**
 * class for starting an Embedded TomEE server which will scan the classpath and start the application.
 * The configuration configures an InMemory derby database, and tells JPA to create tables based on the Entity annotations
 *
 */
public class EmbeddedTomEE {

    public static final String USERNAME = "aUser";
    public static final String PASSWORD = "aPassword";
    private Container container;

    public void start() {
        Configuration configuration = new Configuration();
        Properties properties = new Properties();
        properties.setProperty("jdbc/UdDB", "new://Resource?type=DataSource");
        properties.setProperty("jdbc/UdDB.jdbcDriver", "org.apache.derby.jdbc.EmbeddedDriver");
        properties.setProperty("jdbc/UdDB.jdbcUrl", "jdbc:derby:memory:udb;create=true");
        properties.setProperty("jdbc/UdDB.username", "SA");
        properties.setProperty("jdbc/UdDB.password", "");
        properties.setProperty("jdbc/UdDB.jtaManaged", "true");
        properties.setProperty("persistence_unit.javax.persistence.schema-generation.database.action", "create");
        properties.setProperty("persistence_unit.javax.persistence.sql-load-script-source", "META-INF/testdata.sql");
        properties.setProperty("rest-persistence_unit.eclipselink.logging.level", "FINE");  //use 'FINE' for JPA logging

        configuration.setProperties(properties);
        // use a random port so we can have TomEE running parallel with tests
        configuration.randomHttpPort();
        configuration.setWebXml("src/main/webapp/WEB-INF/web.xml");

        HashMap<String, String> users = new HashMap<>();
        users.put(USERNAME, PASSWORD);
        configuration.setUsers(users);
        HashMap<String, String> roles = new HashMap<>();
        roles.put("aUser", "user");
        configuration.setRoles(roles);
        container = new Container(configuration).deployClasspathAsWebApp();
    }

    public int getPort() {
        return container.getConfiguration().getHttpPort();
    }

    public void stop() {
        container.close();
    }
}

The JUnit Rule which takes care of starting the embedded TomEE before each test is executed. We also have some logic to avoid the cost of starting and stopping the container with every test. The class also creates a JAX-RS webClient that can be used to make calls to the applications REST services.
/**
 * JUnit rule for running an EmbeddedTomEE in memory. The rule has static state, this is to avoid starting and stopping the embedded container
 * with every test. Every time no test are running we start a timer, which is canceled if another test is started. This way the rule works well for a
 * single test run inside an IDE, and running multiple tests from Maven.
 *
 */
public class EmbeddedTomEERule extends ExternalResource {

    private static EmbeddedTomEE tomEE;
    private static final AtomicInteger count = new AtomicInteger();
    private static Timer timer;

    @Override
    protected void before() throws Throwable {
        startIfNeeded();
        if (timer != null) {
            timer.cancel();
        }
        count.incrementAndGet();
    }

    @Synchronized
    private void startIfNeeded() {
        if (tomEE == null) {
            tomEE = new EmbeddedTomEE();
            tomEE.start();
            Runtime.getRuntime().removeShutdownHook(new Thread(() -> tomEE.stop()));
        }
    }

    @Override
    protected void after() {
        int runningTests = count.decrementAndGet();
        if (runningTests == 0) {
            // stop after some time if no new test are started
            timer = new Timer();
            timer.schedule(new StopEmbeddedContainer(), 10000);
        }
    }

    public int getPort() {
        return tomEE.getPort();
    }

    /**
     * creates a new WebClient that can request data from the specified path
     */
    public WebClient getWebClient(String path, MediaType mediatype) {
        WebClient client = WebClient.create("http://localhost:" + tomEE.getPort() + "/", Collections.singletonList(new JohnzonProvider()),
                EmbeddedTomEE.USERNAME, EmbeddedTomEE.PASSWORD, null)

                .path(path).accept(mediatype);
        return client;
    }

    private static class StopEmbeddedContainer extends TimerTask {
        @Override
        public void run() {
            tomEE.stop();
        }
    }
}

Here is an example of how a Test would look
public class ExampleTest {

    @Rule
    public EmbeddedTomEERule rule = new EmbeddedTomEERule();

    @Test
    public void doTest() {

        WebClient client = rule.getWebClient("some-endpoint", MediaType.APPLICATION_JSON_TYPE);
        Output dto = client.get(Input.class);
    }
}

This type of test allows you to test your application at the HTTP layer, and it allows you to place breakpoints in both test and the server code. Technically it may be a stretch to call this a Unit test, but I prefer this type of test when testing more that one component. Since you need a fully functional TomEE you will need to provide a number of external dependencies, in my case it looked like this:
<dependency>
    <groupId>org.apache.derby</groupId>
    <artifactId>derby</artifactId>
    <version>${derby.db.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.apache.tomee</groupId>
    <artifactId>openejb-core</artifactId>
    <version>${openejb-core.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.apache.tomee</groupId>
    <artifactId>openejb-cxf-rs</artifactId>
    <version>${openejb-core.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.apache.tomee</groupId>
    <artifactId>openejb-server</artifactId>
    <version>${openejb-core.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.apache.tomee</groupId>
    <artifactId>openejb-rest</artifactId>
    <version>${openejb-core.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.apache.tomee</groupId>
    <artifactId>tomee-embedded</artifactId>
    <version>${openejb-core.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>el-impl</artifactId>
    <version>2.2</version>
    <scope>test</scope>
</dependency>


text:
Q: Generic List View raises Attribute Error: "'function' object has no attribute '_clone' An odd error here, perhaps someone can help track down source as it's attempting to extend the Django CMS project & attempts to use uses some logic written as part of that project which I'm not fully clear on. In short, using:
urls.py
======================
from django.conf.urls.defaults import *
from cmsplugin_flat_news.models import News

'''RETURNING _CLONE ERROR WHEN IMPLEMENTED
def get_news():
    return News.published.all()

news_dict = {
    'queryset': get_news,
}

news_list_dic = {
    'queryset': get_news,
    'paginate_by': 50,
}
'''
# NEXT SECTION FUNCTIONS BUT NEEDS SERVER RESTART TO SEE NEW POSTS.
#CHANGING TO JUST News.published.all RAISES SAME ISSUE AS USING WRAPPER
#SOLUTION ABOVE. SEE: http://docs.djangoproject.com/en/dev/topics/db/queries/#caching-and-querysets
#& EXAMPLE HERE: http://docs.djangoproject.com/en/dev/topics/generic-views/#adding-extra-context

news_dict = {
    'queryset': News.published.all(),
}

news_list_dic = {
    'queryset': News.published.all(),#SAME ISSUE
    'paginate_by': 50,
}

urlpatterns = patterns('django.views.generic.list_detail',
    (r'^$', 'object_list', news_list_dic),
    (r'^(?P<page>[0-9]+)/$', 'object_list', dict(news_list_dic)),
    url(r'^(?P<slug>[-\w]+)/$', 'object_detail', news_dict, name='news_view'),
)

models.py
======================
class PublishedNewsManager(models.Manager):
    #Filters out all unpublished news and news with a publication date in the future
    def get_query_set(self):
        return super(PublishedNewsManager, self).get_query_set() \
                    .filter(is_published=True) \
                    .filter(pub_date__lte=datetime.datetime.now())

class News(models.Model):
    title           = models.CharField(_('Title'), max_length=255)
    slug            = models.SlugField(_('Slug'), unique_for_date='pub_date')
    author          = models.ForeignKey(User)
    description     = models.TextField(_('Description'), blank=True)
    image           = generic.GenericRelation('NewsImage', blank=True, null=True)
    content         = models.TextField(_('Content'), blank=True)
    tags            = TagField()
    is_published    = models.BooleanField(_('Published'), default=False)
    pub_date        = models.DateTimeField(_('Publication date'), default=datetime.datetime.now())
    created         = models.DateTimeField(auto_now_add=True, editable=False)
    updated         = models.DateTimeField(auto_now=True, editable=False)
    published       = PublishedNewsManager()
    objects         = models.Manager()

See issue in comments: basically, error raised by implementing the 'correct' solution to add extra context to the views. Error is Attribute Error: "'function' object has no attribute '_clone'"
Trying: News.published.all instead of News.published.all() raises the error whether used as part of a wrapper function or directly in the queryset part of the urlpattern.
Must be missing something obvious? Think it is to do with the PublishedNewsManager not returning objects as a dictionary, or tweaking the code to correctly return the objects to the view.

A: The _clone errors are a red herring caused by you passing a function as an argument to a generic view where a QuerySet is expected. The version of your code which passes News.published.all() to the generic views is correct, as generic views will try to clone the QuerySet they are given, to avoid caching the first lot of data they query for (hence the error when you pass in a function).
Your problem seems to be that your custom get_query_set method is returning a QuerySet filtered based on the current date and time when the method was called.
I can't see anything in the documentation about filter arguments being callable, but I did find this ticket which suggests that filter can take callable arguments, so try changing your manager to pass in the function to be called to get the current date/time, rather than calling it immediately:
class PublishedNewsManager(models.Manager):
    def get_query_set(self):
        return super(PublishedNewsManager, self).get_query_set() \
                    .filter(is_published=True) \
                    .filter(pub_date__lte=datetime.datetime.now)

A: Well, I ain't exactly in the same use case as the OP, but I was trying to pass a RawQuerySet to the generic views and getting the _clone error, which I fixed with an ugly hack to the RawQuerySet instance.
It seems the only thing the generic view wants to do is to clone the queryset (for caching purposes?), so I had the object return a copy of itself which satisfied the call to _clone.
error:
'RawQuerySet' object has no attribute '_clone'
code:
from django.views.generic.list_detail import object_list

....

li_file = File.objects.raw("SELECT * FROM file_file WHERE fn like %s", [search])

#adding this fixed the _clone missing error
def clone(self):
    #return self  - this works as well.
    return copy.copy(self)

li_file.__class__._clone = clone
#end of addition

return object_list(request,
               queryset = li_file,
               template_name = "file/found.html",
               )


text:
Q: Creating a custom page for admin to add products Can we make a simple form in magento for admin to add products and other required details rather than using the default menu which is for the admin after login ??

A: use below function in controller to add new product
public function addNewProduct(Varien_Object $object){

        $product = Mage::getModel('catalog/product');

        $product->setSku('pro12');
        $product->setAttributeSetId(9);
        $product->setTypeId('simple');
        $product->setName('Product title');
        $product->setCategoryIds(array(7));
        $product->setWebsiteIDs(array(1));
        $product->setDescription('Product Full description');
        $product->setShortDescription('Product Short description');
        $product->setPrice(250.00);
        $product->setWeight(30.00);
        $product->setVisibility(4);
        $product->setStatus(1);
        $product->setTaxClassId(0);
        $product->setStockData(array(
           'is_in_stock' => 1,
            'qty' => 20
        ));
        $product->setCreatedAt(strtotime('now'));

        try {
            $product->save();
        }
        catch (Exception $e) {
            Mage::log($e->getMessage()); //check your var/log/system.log for error
        }

        echo "saved";
        die();
    }

Also to design form use this link to take necessary input from admin and you can add your product with simple form.


text:
Q: Only show first 4 results from query I only want to show the first 4 results from the SQL query. I have tried working with 'break;' but without success. I know I have to place a number variable somewhere (I think) like $x == 4; and $x++; but I'm not sure where. Should it be an outside loop? Any help would be greatly appreciated.
        <?php

    $q_news = "SELECT * FROM news ORDER BY date DESC";
    $raw_results = mysqli_query($conn, $q_news);

    if(mysqli_num_rows($raw_results) > 0) {

      while ($results = mysqli_fetch_array($raw_results)) {

    ?>

            <img class="newsbox-img" src="<?php echo $results['image']; ?>" alt="<?php echo $results['alt']; ?>">

<?php echo $results['title']; ?>

<?php

                  $str = $results['description_01'];

                  $str_12 = implode(' ', array_slice(str_word_count($str, 2), 0, 12));

                  echo $str_12 . "...";

              ?>

              <?php

              $orgDate = $results['date'];
              $newDate = date("j-F-Y", strtotime($orgDate));

              echo $newDate;

              ?>

            <a id="id" href="news-release.connect.php?id=<?php echo $results['newsID']; ?>" class="btn btn-info btn-sm">Read More

    <?php
      }
    }

    ?>


text:
Q: Given two rates of change at two coordinates, can an exponential function be derived to fit? I have an original exponential function:
$1000 \cdot 2^{0.1x}$
At the point $\big( 18+6 \frac {\log5} {\log2} (\approx 31.93) , 9146 \big)$, I'm looking to know if it is possible to derive an exponential function which continues on from the original exponential function, from only the following information:

*

*At $18+6 \frac {\log5} {\log2}$, the rate of change of the new exponential function is:
$(2^{0.1})^{\big(18+6 \frac {\log5} {\log2}\big)} \cdot \ln(2^{0.1}) \approx 633.959$.

(This is actually the intercept point between $x=18+6 \frac {\log5} {\log2}$ and the $\frac {\Bbb d} {\Bbb dx} (1000 \cdot 2^{0.1x})$.)

*

*The new function plateaus by $28+6 \frac {\log5} {\log2}$ (i.e., reaches its horizontal asymptote $-1$ by $x=28+6 \frac {\log5} {\log2}$).


text:
Q: Recurrence relation for the number of partitions of an integer $n$ with distinct summands Let $Q(n)$ give the number of ways of writing the integer $n$ as a sum of positive integers without regard to order with the constraint that all integers in a given partition are distinct. Equation $(11)$ on this page mentions (without proof) a recurrence relation for $Q(n)$,
$$Q(n) = s(n) + 2\sum_{i=1}^\sqrt{n}(-1)^{k+1}Q(n-k^2)$$
where
$$s(n) = \begin{cases}
    (-1)^j,& \text{if } n= j(3j \pm 1)/2\\
    0,              & \text{otherwise}
\end{cases}$$
What is the proof of this fact?


text:
Q: Can I add factory class to custom extension point Creating the extension point:

Attach to extension point class:

Can I add factory class to the custom extension point, which returns a different class depending on some rule?

A: To make your class a factory it can implement the IExecutableExtensionFactory class, The Eclipse extension manager will call the
public Object create() throws CoreException

method to ask your factory to create the extension class.
Many factory classes also implement IExecutableExtension which has the single method:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException

The extension manager will call setInitializationData before calling create. It gives you the entire configuration element from the plugin.xml so you can look at any attributes you want.


text:
Q: draw a movable canvas on Jpanel i want to draw a canvas that will be movable on a Jpanel. That is when the user clicks on the canvas and drags it it must move to a new positon. i have implemented the MouseMotionListener but i have no idea of what to include inside to make the canvas move as per requierements. here is the DisplayCanvas class:
class DisplayCanvas extends Canvas
{
    public DisplayCanvas()
    {
        setBounds(20, 40, 300, 300);
        setBackground(Color.white);
    }
}
class shape extends JFrame  implements MouseMotionListener{

static JPanel panel;
static Container contentpane;
static DisplayCanvas canvas;
shape()
{
    canvas=new DisplayCanvas();
    canvas.addMouseMotionListener(this);
    panel= new JPanel();
    panel.setBounds(20,20,250,140);
    panel.setLayout(null);
    contentpane = getContentPane();
    contentpane.add(canvas);
    contentpane.add(panel);
}
@Override
public void mouseDragged(MouseEvent e) {}
@Override
public void mouseMoved(MouseEvent arg0) {}
}

this is how i test it.
public class display
{
    static JFrame frame;
    public static void main(String[] args)
    {
        frame=new shape();
        frame.setBounds(380, 200, 500, 400);
        frame.setTitle("SHAPE AND COLOR");
        frame.setVisible(true);
    }
}

NB: please do not suggest that i use the JPanel am required to use the canvas.

A: The fact you don't want to extend JPanel seems quite weird but it is not unfeasible. Yet you will likely encounter issues at some point because you are mixing lightweight and heavyweight components. You will probably have visual glitches and other display issues.
However I would draw your attention to several important mistakes you made in your current code:

*

*Don't extends classes if not needed (no need to extend JFrame nor Canvas)

*Don't make variables static unless absolutely necessary

*Follow Java naming conventions: class names always start with an Upper-case letter

*Don't use a null LayoutManager.

Here is a snippet illustrating very basic way you can make this work (code needs to be refactored to separate aspects properly)
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager2;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestHeavyweightLightweight {

    public class MyLayoutManager implements LayoutManager2 {

        private Map<Component, Rectangle> constraints = new LinkedHashMap<Component, Rectangle>();

        @Override
        public void addLayoutComponent(String name, Component comp) {
            constraints.put(comp, comp.getBounds());
        }

        @Override
        public void removeLayoutComponent(Component comp) {
            constraints.remove(comp);
        }

        @Override
        public Dimension preferredLayoutSize(Container parent) {
            Rectangle rect = new Rectangle();
            for (Rectangle r : constraints.values()) {
                rect = rect.union(r);
            }
            return rect.getSize();
        }

        @Override
        public Dimension minimumLayoutSize(Container parent) {
            return preferredLayoutSize(parent);
        }

        @Override
        public void layoutContainer(Container parent) {
            for (Map.Entry<Component, Rectangle> e : constraints.entrySet()) {
                e.getKey().setBounds(e.getValue());
            }
        }

        @Override
        public void addLayoutComponent(Component comp, Object constraints) {
            if (constraints instanceof Rectangle) {
                this.constraints.put(comp, (Rectangle) constraints);
            } else {
                addLayoutComponent((String) null, comp);
            }
        }

        @Override
        public Dimension maximumLayoutSize(Container target) {
            return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
        }

        @Override
        public float getLayoutAlignmentX(Container target) {
            return 0;
        }

        @Override
        public float getLayoutAlignmentY(Container target) {
            return 0;
        }

        @Override
        public void invalidateLayout(Container target) {

        }

        public void setConstraints(Component component, Rectangle rect) {
            constraints.put(component, rect);
        }

        public class MouseDragger extends MouseAdapter {
            private Point lastLocation;
            private Component draggedComponent;

            @Override
            public void mousePressed(MouseEvent e) {
                draggedComponent = e.getComponent();
                lastLocation = SwingUtilities.convertPoint(draggedComponent, e.getPoint(), draggedComponent.getParent());
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                Point location = SwingUtilities.convertPoint(draggedComponent, e.getPoint(), draggedComponent.getParent());
                if (draggedComponent.getParent().getBounds().contains(location)) {
                    Point newLocation = draggedComponent.getLocation();
                    newLocation.translate(location.x - lastLocation.x, location.y - lastLocation.y);
                    newLocation.x = Math.max(newLocation.x, 0);
                    newLocation.x = Math.min(newLocation.x, draggedComponent.getParent().getWidth() - draggedComponent.getWidth());
                    newLocation.y = Math.max(newLocation.y, 0);
                    newLocation.y = Math.min(newLocation.y, draggedComponent.getParent().getHeight() - draggedComponent.getHeight());
                    setConstraints(draggedComponent, new Rectangle(newLocation, draggedComponent.getSize()));
                    if (draggedComponent.getParent() instanceof JComponent) {
                        ((JComponent) draggedComponent.getParent()).revalidate();
                    } else {
                        draggedComponent.getParent().invalidate();
                        draggedComponent.getParent().validate();
                    }
                    lastLocation = location;
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                lastLocation = null;
                draggedComponent = null;
            }

            public void makeDraggable(Component component) {
                component.addMouseListener(this);
                component.addMouseMotionListener(this);
            }

        }

    }

    private Canvas canvas;
    private JPanel panel;

    protected void createAndShowGUI() {
        JFrame frame = new JFrame(TestHeavyweightLightweight.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        canvas = new Canvas();
        canvas.setBackground(Color.WHITE);
        panel = new JPanel();
        MyLayoutManager mgr = new MyLayoutManager();
        panel.setLayout(mgr);
        panel.add(canvas, new Rectangle(20, 40, 300, 300));
        MyLayoutManager.MouseDragger mouseDragger = mgr.new MouseDragger();
        mouseDragger.makeDraggable(canvas);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestHeavyweightLightweight().createAndShowGUI();
            }
        });
    }

}


text:
Q: can't get 2> to work on g++ command line on Ubuntu update On a remote server that was updated with a newer version of Ubuntu, when I try to redirect stderr it won't work.  Using putty from windows, but I've done it on the old server all the time.
g++ filename 2> whatever.txt
just says

g++: error: 2: No such file or directory

When I click the up arrow to bring it back it shows the command with a space between 2 and > as:
g++ filename 2 > whatever.txt
What the heck is going on here?  Any ideas?

A: The problem was the shell was csh which doesn't support that.
To find if you're using it use:
echo $0


text:
Q: Is there a way to create an enum in jsonschema based on a same level property? Description
I have a JSON Object with two properties (among others), that are category and subcategory,I have a function to get the list of categories and another one to get the subcategories for a given category.
So my schema looks something like this:
{
  "type": "array",
  "items": {
    "type": "obect",
    "properties": {
      "category": {
        "type": "string",
        "enum": getCategories()
      },
      "subcategory": {
        "type": "string",
        "enum": getSubcategories(category)
      }
  }
}

Note: One subcategory is in only one main category

Problem
The list of categories is large and I want to check with json schema that the category and subcategory are valid, so I wonder if there is a way of doing so.

Using npm package for node js

Example:
Let's assume i have the categories A and B with [A1,A2] and [B1,B2] , if the json to validate has the category A I want to check that the subcategory is in [A1,A2] not in [A1,A2,B1,B2]
What I've tried
Tried if-else statements from this other post but as I mentioned the list is large and doesn't look like a good practice at all

A: At the moment, if/then constructs would be needed to specify the subcategory values based on category:
{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "category": {
        "type": "string",
        "enum": [ ... ]
      },
      "subcategory": {
        "type": "string",
      },
    },
    "allOf": [
      {
        "if": {
          "properties": {
            "category": { "const": "option1" },
          }
        },
        "then": {
          "properties": {
            "subcategory": {
              "enum": [ ... ]
            }
          }
        }
      },
      {
        "if": {
          "properties": {
            "category": { "const": "option2" },
          }
        },
        "then": {
          "properties": {
            "subcategory": {
              "enum": [ ... ]
            }
          }
        }
      },
      { ... }
    ]
  }
}

However, there is a proposal to add a new keyword for the next draft specification which would shorten the syntax considerably: https://github.com/json-schema-org/json-schema-spec/issues/1082


text:
Q: Angular Material Contact Chips validation ng-minlength/maxlength/required I've been trying to trigger a validation error on <md-contact-chips> for ng-minlength/maxlength/required but haven't been able to implement this effectively.
Is there a straight forward way to implement this myself? -- it seems for some reason that the contact chips directive in Angular Material does not support these validations.
See codepen here:
http://codepen.io/anon/pen/YqdRNw
<form name='myForm'>

  <md-content class="md-padding autocomplete" layout="column">
    <md-contact-chips ng-model="ctrl.contacts" ng-minlength='1' ng-required='true' ng-maxlenght='3' name='contacts' md-contacts="ctrl.querySearch($query)" md-contact-name="name" md-contact-image="image" md-contact-email="email" md-require-match="true" md-highlight-flags="i" filter-selected="ctrl.filterSelected" placeholder="To" >
    </md-contact-chips>

You did not enter a contact

Your contact list is too short

Your contact list is too long

  </md-content>

</form>

A: You cannot use this attribute directly. you have to use custom validation for it.
<md-contact-chips ng-model="ctrl.contacts" md-transform-chip="customvalidation($chip)"> </md-contact-chips>

 Required

    <p ng-show="ctrl.contacts.length < 3 && ctrl.contacts.$touched"> Minimum 2 Contacts are required

 5 && ctrl.contacts.$touched"> Maximum 5 Contacts can be added

Inside controller you can define customvalidation function and add extra condition if you want.
function customvalidation(chip){
 if(satisifedCondition(chip)){
    return null //It will add chip
 } else { return undefined } // It will not add chip
}

A: For the time being, you will need to write your own validation. Currently, md-chips only supports md-max-chips validation. Other forms of validation are currently pending. md-chips api
You can use the chips length property to get the number of chips in the array. With this you can use ng-show on your error messages to perform the necessary validation checks.
Ex: ng-show="myForm.contacts.length == 0"
Additionally,  you can use md-on-add or md-on-remove to write your own validation.

A: Thats the how can I handle required validation with md-chips and md-contact-chips
I don't test code completely but I wrote that for give you an idea. I hope it helps you !

angular.module('MyApp', ['ngMaterial'])
.controller("ContactChipDemoCtrl", ['$scope', function ContactChipDemoCtrl($scope) {
  $scope.formRequiredError = {};

  $scope.sendButton = function(form) {
    $scope.formRequiredError = {
      "required": $scope.contacts.length <= 0;
    };
  };
}]);

<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/angular_material/0.8.3/angular-material.min.css">

  <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/angular_material/0.8.3/angular-material.min.css">

  <form name='myForm'>

      <md-content class="md-padding autocomplete" layout="column">
        <md-contact-chips ng-model="ctrl.contacts" ng-minlength='1' ng-required='true' ng-maxlenght='3' name='contacts' md-contacts="ctrl.querySearch($query)" md-contact-name="name" md-contact-image="image" md-contact-email="email" md-require-match="true" md-highlight-flags="i"
        filter-selected="ctrl.filterSelected" placeholder="To">
        </md-contact-chips>

Your contact list is too short

Your contact list is too long

      </md-content>

    <div class="custom-error" ng-if="ctrl.contacts.length <= 0">

  </form>

A: Simple workaround:
<md-contact-chips
  ng-class="{'myError': object.fieldName !== undefined && object.fieldName.length == 0}"
  ng-model="object.fieldName"
  otherStuff></md-contact-chips>

In CSS
.myError input::placeholder {
    color: rgb(221,44,0) !important;
}


text:
Q: Long time of inserting HTML to content controller I'm currently developing Microsoft Office add-in on Word Online. I have large amount of content controllers (more than 100), and I have to replace in every content controller one stylled text to another in one action. For example "Document blabla nr 1"  to "Document blabla nr 2"
Only numbers changes in this oparation. So my problem is that I'm using function contentController.insertHTML(styled html text) to achieve this result, but it takes a very long time for such large number of content controllers. For 100 content controller it takes about 1 min to change it all! Has anybody got idea how can I do it much faster? Thank You for reply :)

A: I also have had performance problems updating values in large tables.  See my post:  Office.js Word Add-In: Performance Issue with Updating Values in Large Tables.  There may be some helpful ideas there.  The easiest may be to reduce screen updating impact by scrolling to top or part of document so your content controls are not visible.


text:
Q: Rsync exclude file that are having same name but different extension Is there any option to send files via rsync that ae having same name but other extension ? For ex filename.ts and filename.mp4 ??

A: I`m havin for example filename.ts on destination and filename.mp4 on source. I dont want to send filename .mp to destination becase basename is the same.


text:
Q: Python pip doesn't work when I ask its version I have download python 3.10.5 with pip, but when I do this: python -m pip --version, I have this errors:
https://i.stack.imgur.com/8GKcK.png

A: Do pip --version, not python -m pip --version.

A: try:
python3 -m pip --version

I assume python does not call python 3 but python 2 for which you probably have not installed pip.
Verify this with
python --version
python3 --version