Libgdx project fails to compile with 'Cannot change strategy of configuration ':android:natives''

Question: The issue is very easy to recreate using either IDEA or Android studio.
Using latest libgdx project creator (gdx-setup.jar) create android project (no other platforms).
add following to the root gradle file under build script/dependencies
classpath 'com.google.gms:google-services:4.0.0'

Then add following to the gradle file or android module
apply plugin: 'com.google.gms.google-services'

When sync and compile follwoing error is thrown.
Cannot change strategy of configuration ':android:natives' after it has been resolved.

If I comment out apply plugin: 'com.google.gms.google-services' I can compile and run but this causes issues with fire base.
How do I get around this?
The detailed error as follows
org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':android'.
    at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:94)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:66)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.access$100(LifecycleProjectEvaluator.java:34)
    at org.gradle.configuration.project.LifecycleProjectEvaluator$ConfigureProject.run(LifecycleProjectEvaluator.java:110)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:50)
    at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:667)
    at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:136)
    at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
    at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:62)
    at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:38)
    at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuild.run(DefaultGradleLauncher.java:261)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.initialization.DefaultGradleLauncher.configureBuild(DefaultGradleLauncher.java:173)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:132)
    at org.gradle.initialization.DefaultGradleLauncher.getConfiguredBuild(DefaultGradleLauncher.java:110)
    at org.gradle.internal.invocation.GradleBuildController$2.call(GradleBuildController.java:87)
    at org.gradle.internal.invocation.GradleBuildController$2.call(GradleBuildController.java:84)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
    at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
    at org.gradle.internal.invocation.GradleBuildController.configure(GradleBuildController.java:84)
    at org.gradle.tooling.internal.provider.runner.ClientProvidedBuildActionRunner.run(ClientProvidedBuildActionRunner.java:64)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
    at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:49)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:32)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:57)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:45)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.gradle.api.GradleScriptException: A problem occurred evaluating project ':android'.
    at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:92)
    at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl$2.run(DefaultScriptPluginFactory.java:204)
    at org.gradle.configuration.ProjectScriptTarget.addConfiguration(ProjectScriptTarget.java:77)
    at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:209)
    at org.gradle.configuration.BuildOperationScriptPlugin$1.run(BuildOperationScriptPlugin.java:61)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.configuration.BuildOperationScriptPlugin.apply(BuildOperationScriptPlugin.java:58)
    at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:41)
    at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:26)
    at org.gradle.configuration.project.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:34)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:64)
    ... 84 more
Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin [id 'com.google.gms.google-services']
    at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:150)
    at org.gradle.api.internal.plugins.DefaultPluginManager.apply(DefaultPluginManager.java:125)
    at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyType(DefaultObjectConfigurationAction.java:120)
    at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.access$200(DefaultObjectConfigurationAction.java:38)
    at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction$3.run(DefaultObjectConfigurationAction.java:86)
    at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.execute(DefaultObjectConfigurationAction.java:143)
    at org.gradle.api.internal.project.AbstractPluginAware.apply(AbstractPluginAware.java:46)
    at org.gradle.api.internal.project.ProjectScript.apply(ProjectScript.java:34)
    at org.gradle.api.Script$apply.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:166)
    at build_8em97xhqkzbnq5e74cbtx6jkv.run(testIDEA\android\build.gradle:137)
    at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:90)
    ... 97 more
Caused by: org.gradle.api.InvalidUserDataException: Cannot change strategy of configuration ':android:natives' after it has been resolved.

Comment: downgrade to `com.google.gms:google-services:3.1.0`, resolve issue :)
Comment: thanks for the reply. I want to use firebase. Do you know what version of firebase I should use with 3.1.0. In order to work with 4.0.0, where can I get help?
Comment: Which libraries of Firebase, you're using ?
Comment: firebaseCore = "16.0.0"
firebaseAuth = "16.0.1"
firebaseFirestore = "17.0.1"
 implementation "com.google.firebase:firebase-core:$firebaseCore"
 implementation "com.google.firebase:firebase-auth:$firebaseAuth"
 implementation "com.google.firebase:firebase-firestore:$firebaseFirestore"
 implementation 'com.google.firebase:firebase-storage:16.0.1'
Comment: Are you using all of the above libraries of firebase. Is your app is firebase centric ??
Comment: no its a libgdx game, however adding new functionality to it using latest firebase database capabilities.
Comment: @Aryan it works, you should add it as an answer
Comment: @Curio Added as an answer
Comment: libGDX project check this : https://stackoverflow.com/a/61377080/5733853
Answer:
Caused by: org.gradle.api.InvalidUserDataException: Cannot change
strategy of configuration ':android:natives' after it has been
resolved.

Issue will be resolved by downgrading Google Services Gradle Plugin version to 3.1.0
classpath 'com.google.gms:google-services:3.1.0'

I found the same issue on LibGDX issue tracker, according to them issue will be resolved when we disable configure on demand in our project. I tried but not succeed on my old LibGDX project.
Disable configuration on demand

Disable configuration on demand in your gradle.properties file as shown below :
org.gradle.configureondemand=false

To disable configuration on demand in the Android Studio settings, choose File > Settings (Android Studio > Preferences on Mac), select the Compiler category in the left pane, and clear the Configure on demand checkbox.
Comment: org.gradle.configureondemand=false didn't work for me neither.
Comment: Also you've to disable `configuration on demand` in the Android Studio settings
Comment: I'm not using Android Studio, but IntelliJ Idea.
Comment: same option is available in IntelliJ Idea, Have you tried to downgrade version of `Google Services Gradle Plugin` to `3.1.0`
Comment: Thanks, I'll check that option then. I can't downgrade the plugin because I have other dependencies that rely on a newer version.


Closed-form expression for infinite series related to a Gaussian

Question: Consider the following infinite series, where $x$ is indeterminate and $r$ is held constant:
$\displaystyle 1 + \frac{x}{r} + \frac{x^2}{r^2} + \frac{x^3}{r^3} + ...$
It is relatively easy to see that the above, for $\frac{x}{r} < 1$, converges to
$\displaystyle \frac{1}{1-\frac{x}{r}}$
Now suppose we modify the above to this:
$\displaystyle 1 + \frac{x}{r} + \frac{x^2}{r^{2^2}} + \frac{x^3}{r^{3^2}} + ...$
which we can rewrite as
$\displaystyle 1 + \frac{x}{r} + \frac{x^2}{r^4} + \frac{x^3}{r^9} + ...$
Does there then exist a well-known, closed-form expression for this series?
If not for general $r$, then perhaps for certain special values of $r$? For example, if we set $r=e$ above, then we get
$\displaystyle 1 + \frac{x}{e} + \frac{x^2}{e^4} + \frac{x^3}{e^9} + ...$
which we can rewrite as
$\displaystyle 1 + xe^{-1^2} + x^2e^{-2^2} + x^3e^{-3^2} + ...$
So that we can see that for x=1, this becomes a series of evenly spaced points on a Gaussian function.
Does there exist a closed-form expression for any of these?
Answer: Interestingly, if we change the definition slightly, we get something related to the Jacobi theta function.
If we start with this series:
$\displaystyle 1 + \frac{x}{r} + \frac{x^2}{r^4} + \frac{x^3}{r^9} + ...$
We can make the following substitutions:
$q = \frac{1}{r}$
$x = \exp(2\pi i z)$
to obtain
$\displaystyle 1 + q\exp(2\pi i z) + q^4\exp(4\pi i z) + q^9\exp(6\pi i z) + ...$
$ = \sum_0^\infty q^{n^2} \exp(2\pi i n z)$
If we simply change the bottom bound from $0$ to $\infty$, we get
$\theta_3(z;q) = \sum_{-\infty}^\infty q^{n^2} \exp(2\pi i n z)$
So it is easy to write the Jacobi theta function in terms of the function I described; it is probably possible to write it the other way as well.
Answer: Your original series is
$f(x, r)
=\sum_{n=0}^{\infty} \dfrac{x^n}{r^{(n^n)}}
$.
This is not the same as
$g(x, r)
=\sum_{n=0}^{\infty} \dfrac{x^n}{(r^n)^n}
=\sum_{n=0}^{\infty} \dfrac{x^n}{r^{n^2}}
$.
Also,
you went from
$\displaystyle 1 + \frac{x}{e} + \frac{x^2}{e^4} + \frac{x^3}{e^9} + ...
$
to
$\displaystyle 1 + x \cdot e^{-1^2} + x \cdot e^{-2^2} + x \cdot e^{-3^2} + ...
$,
somehow losing the
exponent of $x$.
Comment: Thanks, edited the typos


Which is a better way of handling virtual destructor?

Question: I have a few classes (around 10 in my project) that needs a virtual destructor while also requiring support for std:move and std::copy calls. To keep both copy and move semantics in these classes, I added another class to serve as a base class for these classes:
/*
This class should be inherited by any class that:
- needs a virtual destructor,
- doesn't require explicit definitions of destructor, copy/move constructor/assignment
- needs to support copy and move semantics.

Such classes can inherit from the class defined below to make their destructor virtual,
and keeping copy and move semantics intact.

INFO: This class won't be able to serve it's purpose if any of the 5 mentioned member
functions are explicitly defined in the derived class.
*/

class VirtualDtor
{
protected:
   virtual ~VirtualDtor() = default;
};

This class drew some concerns such as - A derived class may (by mistake or design) explicitly define one or few of the 5 member functions, even after inheriting from VirtualDtor. That would lead to the removal of copy/move semantics defeating the purpose of VirtualDtor. To avoid such scenarios, maintaining rule of 5 by declaring the 5 functions as default in each class individually could bring some clarity about what to expect.
But inheriting from this class will make the code more readable and if we understand it's requirements and usage before inheriting, it will not cause any unexpected behavior.
So I would like to know which is a better way of handling virtual destructors and the rule of 5.
Note: I could have added copy and move member functions too in the VirtualDtor class like it's suggested here.
I didn't keep them to avoid the mistaken impression that any class that derives from VirtualDtor will inherit copy and move-semantics which it won't. It will only make the destructor in derived classes virtual. So I skipped the rule of 5 in VirtualDtor.
Comment: Honestly, i don't think inherting from a base class like VirtualDtor is more readable than just implementing a virtual destructor in the classes that need one.
Comment: You may wish to consider following - and requiring derived classes to follow - the rule of zero rather than rule of five.    The default is then easy - derived classes don't need to implement any of the five and, if a developer chooses to implement any of the five, the onus is on them to justify a claim that their class works as intended.    I personally would not bother with having a base class with the only purpose of providing a virtual destructor - a base class should provide some facilities (e.g. interface) that are needed by the derived classes.
Answer: Adding a base class such as VirtualDtor can't enforce anything on the derived classes.
The best way to enforce rule of 5 is through a style checker such as clang-tidy, which has an option for this sort of thing: https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-special-member-functions.html
Comment: Thanks for the `clang-tidy` insight, it's quite helpful. I am guessing that you're suggesting to use it to flag classes that don't follow rule of 5, so that we add missing member functions inside the class. Let me know if I am wrong.

My motivation to `VirtualDtor` is to use Rule of 0 (less error-prone) while having a virtual destructor. [Here](https://godbolt.org/z/pHWBK5), I have intentionally skipped on adding the virtual destructor (common mistake), creates warning.
[Here](https://godbolt.org/z/SvgmQk), I have added `VirtualDtor`. I've checked if rule of 5 is enforced. It works alright.
Comment: Yes, I was suggesting that you use clang-tidy to flag classes that don't follow the rule of 5. Your `meets_rule_of_5` check doesn't actually check that, it just checks that the type can be moved and copied, not that they do something sensible. If you provide a copy constructor or just a copy assignment operator, then your type will still pass the check. https://godbolt.org/z/wAD247


How to compute mathematical expression using string in Android?

Question: Hi I have create mathematical expression as string format
<code>    String strFormula = "((2*(" + a + "+(2*" + st + "))+2*(" + b + "+(2*" + st + ")))*" + l + "/1000000)*" + amount;
    strFormula = CommonFunctions.FormatFormulaWithGermanStandard(strFormula);
</code>
I want to evaluate this mathematical expression .
Please suggest me usable link or sample code.
Answer: there are 2 ways you can execute this.

use SQL lite (inbuilt) db to execute a select statement with the expression
use google, make a google request with the expression and it will return a response.
Answer: There are three ways to solve an expression which are by prefix, postfix or infix you can implement or can check java code for one of these methods to solve your expression like here is link below of code for solving an expression using postfix method
http://resume.technoplaza.net/java/postfix-calc.php
by googling you can find more useful links
Answer: If you don't want to roll your own, JEXL should be able to handle that kind of expression, and it's relatively lightweight.


Solving a complex equation including $\Im (z)$

Question: Solve the following complex equation:
$$
e^{z+5} + e^{\overline z} + i\operatorname{Im}(z)
= 6 + i\tfrac{π}{3}
$$
I tried using the cartesian form of a complex number $z$ meaning $z=x+iy$ where $x$ and $y$ are the real and the imaginary part of $z$, respectfully.
Doing some basic calculations (algebra), I conclude that the following system of equations must be valid:
$$
\left\{
\begin{aligned}
e^x \cos y &= \frac{6}{e^5+1} \\[2pt]
e^x \sin y &= \frac{\frac{π}{3}-y}{e^5-1}
\end{aligned}
\right.
$$
I do not know how to solve this system. I tried to divide the $2$ equations but then there is a tany to the LHS and a $y$ to the RHS. I also tried to write $i\operatorname{Im}z$ as $e^{\operatorname{Log}(\operatorname{Im}z)}$ where $\operatorname{Log}$ is the principal branch of complex logarithmic function.
Comment: Very mysteriously, I find graphically very many solutions which seem to have the same $x$ coordinate and are periodic in $y$. But that doesn't make sense… but how can we expect to find the solutions to:  $$\tan(y)=\frac{\frac{\pi}{3}-y}{6}\cdot\frac{e^5+1}{e^5-1}$$Which is one of those impossible equations? Where did you get this problem? This seems achievable only numerically
Comment: @FShrike. Almost the same $x$ effectively. One more time for approximation. Cheers :-)
Comment: @FShrike it's from a set of excercises for Complex Analysis,given to a Greek University. I think that the professor had something else in his mind.....
Answer: Using @FShrike's comment and cross multiplying we need to find the zeros of function
$$f(y)=(\pi -3 y) \cos (y)-k \sin(y) \qquad \qquad k=18\,\frac{ e^5-1}{e^5+1}$$ which, for $y \in (0,2\pi)$ shows three roots.
Working the small root, using series
$$f(y)=\sum_{n=0}^\infty \frac{\pi  \cos \left(\frac{\pi  n}{2}\right)-(k+3 n) \sin
   \left(\frac{\pi  n}{2}\right)}{n!}\,y^n$$ Truncating to some order and using power series reversion
$$y=\frac{\pi }{k+3}-\frac{\pi ^3}{2 (k+3)^3}+\frac{\pi ^3 \left((k^2+12k+3) \left(9+\pi ^2\right)\right)}{6
   (k+3)^5}+\cdots$$
Using only the above terms, the estimate is
$y=\color{red}{0.1503}873$ while Newton method leads to
$y=0.1503578$ which is not bad.
Using twice more terms, this would give
$y=\color{red}{0.150357}603$
while Newton method leads to
$y=0.150357827$.
We could do the same around $y=\pi$ and $y=2\pi$ for the same accuracy.
When $y$ is known, just compute $x$.


Describe how to obtain a sphere in $\mathbb R^3$ as a quotient of a closed disk in $\mathbb R^2$

Question: Let $Y$ be a closed interval in $\mathbb R$ and let $X=\{(x,y):x^2+y^2=1\}$ be the unit circle in the plane. Describe as precisely as possible how to obtain a space homeomorphic to $Y$ as an identification space of $X$. Assume that all spaces are endowed with the relative topologies induced by the metric topology of $\mathbb R^n$
I know that $X$ is a closed disk, if I glue every equivalent point on $X$ together I will have a basket ball ( a sphere), but I don't think it's a very precise description and I don't know how to explain formally.
Comment: $X$ isn't a disk,  it's a circle.
Answer: You can go both ways with quotients here: $X$ (the unit circle) can be seen as a quotient image of $Y$ (a closed interval), by identifying end points. I suppose you covered this already.
You can also go the other way: restrict the projection onto the x-axis to $X$, and then the image is $[-1,1]$. This is a quotient map because the projection is continuous and the domain $X$ is compact.
Another way to see this, is to define an equivalence relation $R$ on $X$ by declaring all pairs $(x,y)$ and $(x, -y)$ to be equivalent, and no others. Then $X/R \simeq Y$. This is essentially the same idea.
To expand on this last idea: we have defined an equivalence relation by specifying all classes (all of them doubletons, except that $(-1,0)$ and $(1,0)$ are in a class by themselves (as $-0 = 0$). The set of all these classes is called $X/R$ (so it is a set of sets).
There is a standard map $q$ from $X$ to $X/R$, defined by sending a point $x$ to its class $[x]$ under $R$. E.g. $q((0,1)) = \{(0,1), (0,-1)\}$ (this is a point in $X/R$, recall!), $q((1,0)) = \{(1,0)\}$. The topology on $X/R$ (the quotient topology) is defined by $O \subset X/R$ is open iff $q^{-1}[O]$ is open in $X$. As $X$ already has a topology (inherited from being a subset of the plane), this defines a topology on $X/R$ (needs a small proof, but I assume this is in your text). By definition $q$ is then also a continuous map, so this makes $X/R$ a continuous image of $X$.
This also has the nice property that to see that a function $f: X/R \rightarrow Y$ for some space $Y$ is continuous for this topology, it suffices to check that $f \circ q$ is continuous between $X$ and $Y$: if $O$ is open in $Y$, $f^{-1}[O]$ should be open in $X/R$, but this just means by definition that $q^{-1}[f^{-1}[O]]$ is open in $X$, but the latter is exactly $(f \circ q)^{-1}[O]$, so if $f \circ q$ is continuous, we know that $f^{-1}[O]$ is indeed open.
Now we define a function f on $X/R$ to $[-1,1]$ as follows: for a class $[(x,y)]$ define $f([(x,y)]) = x$ (so we take the projection onto the first coordinate, really). We check first this is actually well defined: if a class in $X/R$ has more than one element, it in fact has two , and they are of the form $(x,y)$ and $(x,-y)$ (this is how we defined $R$). Whichever one we choose as the representative for the class (as $[(x,y)] = \{(x,y), (x,-y)\} = [(x,-y)]$), the $x$-coordinate is the same, so we get the same value in $[-1,1]$ in either case.
And the function $f \circ q$ is just the normal function $(x,y) \rightarrow x$, which we know to be continuous, so $f$ is continuous by the previous.
Also, $f$ is 1-1: if $f([(x,y)]) = f([(x',y')]$ this means that $x = x'$. And two points on the unit circle with the same $x$-coordinate can only differ in sign on the $y$-coordinate (as $y = \pm \sqrt{1-x^2}$), and so these points are in the same class, hence are really the same class in $X/R$ (!).
And a 1-1 continuous function from a compact (as $X/R$ is the continuous image of the compact $X$) space to a Hausdorff space ($[-1,1]$) is a homeomorphism so $X/R$ is homeomorphic to $[-1,1]$ under $f$.
Comment: Can you explain a little bit more about the last paragraph, this is what my book keep talking about , but I don't really understand it, and I'm independent study so I have no one to ask, except you guys
Comment: @DianeVanderwaif what book are you using?
Comment: it's called Elementary Topology by Michael C.Gemigani. However, I don't find it very elementary.
Comment: I'm sorry for keep asking. So paragraph #5 and #6(from the top)  you are trying to prove that $f o g : X-> Y$ are continuous, right? and the second paragraph from the bottom, you were showing that the map from $X$ to $Y$ is bijective? I don't see where you show that the inverse function from $X->Y$ is continuous. We need 3 of them to conclude that it's is homeomorphism.
Comment: Well, this follows from the compactness argument. We have a closed map, because if $C$ is closed in $X/R$, it is compact, so $f[C]$ is compact in $[-1,1]$, and thus closed. And $f$ being a closed map is the same as the inverse being continuous, for $f$ a bijection.
Comment: oh, I'm in chapter 6, and compactness is at the end of chapter 7, so I don't know I'm allowed to use it.
Comment: In that case, try showing directly that $f$ is open. But that's a bit more complicated.


Views Global: PHP can't get variable

Question: I need to get field_ip_serwera from node in table views using global PHP. For now it doesn't work :-(
if(function_exists('fsockopen')){
$language = array(
    'serveronline' => '.',
    'serveroffline' => '.',
);
$timeout = 1;

$adres = $row->field_ip_serwera;
$pport = "27015";

$server = array(
    'check' => true,
    'ip' => "$adres",
    'port' => "$pport",
);

$output = "";

if ($server['check']) {
    if ($fp = @fsockopen($server['ip'], $server['port'], $errno, $errstr, $timeout)) {
        fclose($fp);
        $serveronline = true;
        $output .= "
\n";
        $output .= "  ".$language['serveronline']."\n";
        $output .= "
\n";
    } else {
        $serveronline = false;
        $output .= "
\n";
        $output .= "  ".$language['serveroffline']."\n";
        $output .= "
\n";
    }
}
return $output;
}
else { echo'Funkcja fsockopen nie jest dostępna na Twoim serwerze...'; }

My english is poor, examples plx
Answer: You can use var_dump to check the content inside the variable $row
But maybe you can use this variable to get what you need:
$row->_field_data['nid']['entity']->field_ip_serwera['und'][0]['value'];

As long as that field belongs to the node you're using in that View

Views Global: PHP can't get variable


Pulling data across multiple servers

Question: The company i am working for is implementing Share-point with reporting servers that runs on an SQL back end. The information that we need lives on two different servers. The first server being the Manufacturing server that collects data from PLCs and inputs that information into a SQL database, the other server is our erp server which has data for payroll and hours worked on specific projects. The i have is to create a view on a separate database and then from there i can pull the information from both servers. I am having a little bit of trouble with the syntax for connecting the two servers to run the View. We are running ms SQL. If you need any more information or clarification please let me know.
Comment: What have u tried till now ? post your sql query
Answer: Please read this about Linked Servers.
Alternatively you can make a Data Warehouse - which would be a reporting data base.  You can feed this by either making procs with linked servers or use SSIS packages if they're not linked.
Answer: It all depends on a project size and complexity, but in many cases it is difficult to aggregate data from multiple sources with Views. The reason is that the source data structure is modeled for the source application and not optimized for reporting.
In that case, I would suggest going with an ETL process, where you would create a set of Extract, Transform and Load jobs to get data from multiple sources (databases) into a target database where data will be stored in the format optimized for reporting.
Ralph Kimball has many great books on the subject, for example:
1) The Data Warehouse ETL Toolkit
2) The Data Warehouse Toolkit
They are truly worth the read if you are dealing with data

Pulling data across multiple servers


two-sample Kolmogorov-Smirnov test p-value in R confusion

Question: I'm confused about the appropriate interpretation of p-values returned by the two-sample Kolmogorov-Smirnov test (ks.test) in R.
In slide 23 of this presentation about non-parametric two-sample tests, the author states that when analyzing the ks.test results:
ks.test(male, female)
Two-sample Kolmogorov-Smirnov test
data: male and female
D = 0.8333, p-value = 0.02597

the p-value

needs to be multiplied by 2 for a 2-tail test. Thus, P = 0.05194

Is that true?
If we used the original p = 0.02597, we would reject the hypothesis that the distributions similar, because p < 0.05, correct? Whereas if we multiply it by 2, the p would suggest that there is no difference between distributions, since p > 0.05?
What am I missing?
Comment: `alternative="two-sided"` is the *default*, which is why nothing changed.  Try the other alternatives.  I won't speculate on what the author of that presentation might have been thinking.
Comment: The other alternatives are `less` and `greater` which is not what I need. My goal is to simply check if two distributions have "similar shape" so I'll take the p-vale produced by the ks.test at, well, face-_value_.
Comment: The manual page for `ks.test` documents an optional parameter `alternative` that specifies the kind of test. Why don't you use it and see what the answer is?  (Or you could just trust the account of the test in the "Details" section of that page.)
Comment: I looked the example in the ks.test() help file. Whether I used the option 'alternative="two-sided"' or not, the resulting p-value was the same. Which means no multiplication is needed, correct? Why did the author of slides claim it was, then?
Answer: No, it's wrong. The default Kolmogorov-Smirnov in R is already two sided (i.e. already tests $F_X\neq F_Y$ rather than $F_X<F_Y$ or $F_X>F_Y$ (in all three cases, we should add "somewhere").
If you had done a one-tailed test but intended to do a two tail test (and if the sample turned out to have a difference in the direction you tested for), it's usually reasonably-near-to-correct to double the p-value for a two-tailed test, but strictly speaking, still wrong.
While in the case of the t-test the events of rejecting in each tail are mutually exclusive - so you can just add their probabilities, and symmetric so adding is doubling - for the Kolmogorov-Smirnov they're not mutually exclusive -- each of the one-tailed Kolmogorov-Smirnov tests can reject on the same sample. However, under the null it's relatively rare to be able to reject both directions and so it's generally not a bad approximation to double.
It's just unnecessary, since the ks.test function will happily calculate two-tailed p-values for us without doing a thing -- in fact we have to explicitly ask for a one-tailed one.


While loop is endless because the break point doesn't work

Question: I'm trying out the code below but I'm getting a endless loop. The break point doesn't seem to help at all.
import java.util.Scanner;

public class Question2 {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter ID Number: ");
        int studentSn = keyboard.nextInt();

        System.out.print("Enter your Marks: ");
        int Score = keyboard.nextInt();

        Scanner scan = new Scanner(System.in);
        boolean stop = false;

        String answer = "";
        String Grade = "";
        String msg = "";
        int counter = 0;

        while (!stop) {

            if (Score < 50) {
                Grade = "F";
            } else if (Score <= 64) {
                Grade = "P";
            } else if (Score <= 74) {
                Grade = "C";
            } else if (Score <= 84) {
                Grade = "D";
            } else if (Score <= 100) {
                Grade = "HD";
            } else {
                msg = "Invalid Input";

            }

            if (Grade != null) {
                System.out.println("Student Serial Number: " + studentSn);
                System.out.println("Your Grade is: " + Grade);
                System.out.println("Do you want to continue (yes/no): " + answer);
            } else {
                System.out.println("Student Serial Number: " + studentSn);
                System.out.println(msg);
                System.out.println("Do you want to continue (yes/no): " + answer);
            }

            while (answer.equalsIgnoreCase("YES"));
            {
                counter++;

                if (answer.equalsIgnoreCase("NO")) {
                    break;
                }
            }
        }
    }
}

Comment: Where is `stop`? You set it to `false` to start the loop, but then you never change it to `true` so how do you expect the loop to stop?
Comment: Please remove the breakpoint tag; that refers to the concept of a breakpoint in a debugger, not the `break` in your loop.
Answer: There are multiple infinite loops in this scenario. With
while (!stop) {
   // ...
}

you never set "stop" to true, meaning that the loop would end. The break statement in
while (answer.equalsIgnoreCase("YES"));
{
    counter++;

    if (answer.equalsIgnoreCase("NO")) {
        break;
    }
}

would only break out of that loop, not the !stop loop. If you wanted to break out of both loops, you'd need to do
MY_LABEL: while (!stop) {
    // ...
    while (answer.equalsIgnoreCase("YES"));
    {
        counter++;

        if (answer.equalsIgnoreCase("NO")) {
            break MY_LABEL;
    }
}

or otherwise write stop = true; at some point. However, that is not the only endless loop in your code. In
while (answer.equalsIgnoreCase("YES"));
{
     // loop body                     ^ problem here
}

your loop statement is followed by a semicolon! This should be
while (answer.equalsIgnoreCase("YES"))
{
     // loop body
}

since your code right now is the same as writing
while (answer.equalsIgnoreCase("YES"))
    ; // do nothing
// loop body

because of how Java's syntax works. Your current code compiles because you can have a block without any loops or if statements
// do some stuff
{ // begin new scope
    int x = 10;
} // end scope
int y = x; // error because x is not in scope!

but this is clearly not what you intended.
Beyond that, you never read anything into answer meaning it always equals ""-- it never equals "YES" or "NO" at all! At least somewhere you should be saying
answer = scan.nextLine();

to read input.
The entire program is a bit wonky though. Here's how I would lay it out:
// Instead of using "stop", we can just break out of the loop when we're done
while(true) {
    // ...

    // Prompt for input. I use "print" instead of "println" so that the user's answer will be on the same line as the question, e.g.
    // Do you want to continue (yes/no): YES
    // instead of
    // Do you want to continue (yes/no):
    // YES
    // and so forth
    System.out.print("Do you want to continue (yes/no): ");
    // This is how we actually read input.
    String answer = scan.nextLine();

    // If the user doesn't say "YES" (this could be "NO" or "q" or "asdf" or anything else), break out of the loop
    if(!answer.equalsIgnoreCase("YES"))
        break;
}

I think you're a bit confused about how loops and input work. Just because you write System.out.println("my question: " + answer) doesn't mean that Java will read the rest of the line into answer. It'll actually write whatever is already in answer, for example
answer = "abc"
System.out.println("Question? " + answer);
// "Question? abc" will be printed, and no input will be read
// answer still equals "abc"

and additionally, if you want to ask a question repeatedly, you have to put all of that questioning into the loop. Java will not read anything new into answer until you readLine() again, so I think that's where the confusion about the while loop comes from. In your answer.equalsIgnoreCase("YES") loop, nothing new will be read unless you put answer = scan.readLine() in it.
Comment: Hi James, appreciate your time replying to my queries. I'm still pretty confuse since I'm really new to Java :( Do you think you can show me a example on how it's suppose to be done?
Comment: @HowardD I've edited my answer with an example, and added a bit of explanation based on what I think you might be confused about. If you need further clarification, I can try to explain further. If you understand it now, consider accepting my answer.
Answer: You have two while loops going on, your attempt to break has not been executed correctly, is only exiting the inner loop.
Let strip your loop logic back to only describing the variables and logic that will affect the loop itself: I have replaced your other code with method calls to simplify the demo, assume that you already implemented these methods and that they do what the names infer.

This is a good technique for transitioning form pseudo code to actual code but just as useful for evaluating loop constructs that aren't going the way you planned

int studentSn = ReadInt("Enter ID Number: ");
int Score = ReadInt("Enter your Marks: ");
string answer = "";
boolean stop = false;
while(!stop) { // this is never ending, nothing ever sets stop to true
    Grade = DetermineGrade(score);
    if (Grade != null) {
        ShowGrade(studentSn, Grade);
        answer = ReadContinuePrompt();
    } else {
        ShowError(studentSn, "Invalid Input");
        answer = ReadContinuePrompt();
    }

    while (answer.equalsIgnoreCase("YES"));
    {
        counter++;

        if (answer.equalsIgnoreCase("NO")) {
            break;
        }
        // If this user's input was not NO, then this loop is infinite and should run into a stack overflow error when the value of counter exceeds the max value of int
    }
}

Your outer loop is based on a stop variable:
while (!stop)

So inside your loop logic, instead of using a break statement, all you need to do is set the value of stop to true. A carefully placed break statement could also do this, but coding a deliberate stop parameter the way you have is a good design that makes the intent very clear.
Now your inner loop is just wrong, I don't want to over analyse it, because you ask for the user input outside of the loop, there is no way to change the answer. So lets replace the inner loop with a simple conditional statement
    if(answer.equalsIgnoreCase("NO"))
        stop = true; // or break;
    else
        counter++;

Now we need to go back to how you have coded your outer loop. Again, because the main input is outside of the loop, there is no amount of times with this code where we can say "YES" that will give a different answer, we need to ask the score input inside the loop so the result can be changed
That now gives us this logic:
int studentSn = ReadInt("Enter ID Number: ");
string answer = "";
boolean stop = false;
while(!stop) {
    // read the score inside the loop.
    int Score = ReadInt("Enter your Marks: ");
    Grade = DetermineGrade(score);
    if (Grade != null) {
        ShowGrade(studentSn, Grade);
        answer = ReadContinuePrompt();
    } else {
        ShowError(studentSn, "Invalid Input");
        answer = ReadContinuePrompt();
    }

    if(answer.equalsIgnoreCase("NO"))
        stop = true; // or break;
    else
        counter++;
}


Is this an allowable question topic on this site?

Question: I'm asking here in meta because it does not seem that chat is getting much attention here.
For the first time in my life I am in need of sending money abroad, through currencies and oceans.
Would it be appropriate if I ask here what options are available, what scams to look out for, and how to determine if a provider is trustworthy?
I am not looking to ask what's the "best" solution, I understand that's going to be my deliberation, I am asking for guidelines on how to determine if a service is trustworthy/good/won't be a waste of time and money.
Answer: Generally we prefer very precise questions for a specific situation. It sounds like you may be asking for opinions (although the scam warning shouldn't be that) on different options. Nothing wrong with that. But that's very likely to get close votes here. You could try Finance, but I think they too very much prefer precise questions.
Comment: I feel I am not looking for opinions, but for options. I understand that it is on my to make sure that the point gets across. I will think about it and see if I can formulate the question in an acceptable manner. thank you


return a primitive's name

Question: For my program I have a large number of Public static int, it's mainly a readability thing so I can do something like SkillsArray[Archery] = 25 to see at a glance that the "archery skill" has a value/level/rank of 25 instead of trying to figure out what SkillsArray[7] = 25 is supposed to mean.
It's basically naming the unique Id to be used in a relational database structure but if I want to print those names I nave to build a function that takes a int argument that reads a huge if/else tree to spit out a string with the name "Archery" or "cooking" or whatever.
I'd like to replace all those functions with something simple like
String printStaticName() {
    return this.getClass().getName();
}

which can read the primitive attached to it and get its name but Eclipse tells me I can't do those kind of operations on a primitive type. Ideas?
A example of how I currently use the system i have.
//races
public static final int Chosen = 0;
public static final int Native = 1;
public static final int High_Elf = 2;
public static final int Wood_Elf = 3;
public static final int Gremlin = 4;
public static final int Goblin = 5;
public static final int Hobgoblin = 6;
    ....

String getRaceNameString(int r){
    String temp = "No Race Set";
    if (r == Chosen){temp = "Chosen";};
    if (r == Native){temp = "Native";};
    if (r == High_Elf){temp = "High Elf";};
    if (r == Wood_Elf){temp = "Wood Elf";};
    if (r == Gremlin){temp = "Gremlin";};
    if (r == Goblin){temp = "Goblin";};
    if (r == Hobgoblin){temp = "Hobgoblin";};
    return temp;
}//close getRaceNameString

int getRaceIDFromString(String r){
    int result = 0;
    if (r == "Chosen"){result = Chosen;};
    if (r == "Native"){result = Native;};
    if (r == "High Elf"){result = High_Elf;};
    if (r == "Wood Elf"){result = Wood_Elf;};
    if (r == "Gremlin"){result = Gremlin;};
    if (r == "Goblin"){result = Goblin;};
    if (r == "Hobgoblin"){result = Hobgoblin;};
    return result;
}//close getraceIDFromString()

    class Race extends WoSCharacter {
private int raceID = Chosen;
private double purity = 1;
private String active_headshot = "headshot.jpg";
private String active_fullbody = "TemplateforPortrait.png";
private String Description;
private double minHeight;
private double maxHeight;
private int AttributeMods[] = new int[9];
private double lifespan;
private boolean isModRace = false;

void setRace(int RName, long pure, int gender){
    purity = pure;
    raceID = RName;
    switch (raceID){
    //region case
    case Chosen:
        AttributeMods[STR] = 5;
        AttributeMods[DEX] = 5;
        AttributeMods[CON] = 5;
        AttributeMods[CHA] = 5;
        AttributeMods[PER] = 5;
        AttributeMods[WIL] = 5;
        AttributeMods[INT] = 5;
        AttributeMods[INS] = 5;
        AttributeMods[WIS] = 5;
        active_headshot = "headshot.jpg";
        Description = "The race of man are the sole survivors of the Mage Wars that took destroyed magic and everything but the animal races and humanity. Now they are facing their own extinction as the Black Plague washes over the world, crossing continents and destroying entire family lines. Some of mankind have developed an immunity, being christened 'the chosen' but this this comes at cost as they are further divorced from the just now returning powers of magic.";
        minHeight = 150;
        maxHeight = 170;
        lifespan = 50;
        if (gender == MALE){
            active_headshot = "male_headshot.jpg";
            active_fullbody = "TemplateforPortrait.png";
            minHeight = 162;
            maxHeight = 190;
            lifespan = 49;
        }else if (gender == FEMALE){
            active_headshot = "Fem_headshot.jpg";
            active_fullbody = "Fantasy_Landscape_01.jpg";
            minHeight = 150;
            maxHeight = 170;
            lifespan = 43;
        }//gender headshot switch
        break;
        //endregion case
    case Native:
        AttributeMods[STR] = 5;
        AttributeMods[DEX] = 5;
        AttributeMods[CON] = 5;
        AttributeMods[CHA] = 5;
        AttributeMods[PER] = 5;
        AttributeMods[WIL] = 5;
        AttributeMods[INT] = 5;
        AttributeMods[INS] = 5;
        AttributeMods[WIS] = 5;
        active_headshot = "headshot.jpg";
        Description = "The race of man are the sole survivors of the Mage Wars that took destroyed magic and everything but the animal races and humanity. Now they are facing their own extinction as the Black Plague washes over the world, crossing continents and destroying entire family lines. Some of mankind have developed an immunity, being christened 'the chosen' but this this comes at cost as they are further divorced from the just now returning powers of magic.";
        minHeight = 150;
        maxHeight = 170;
        lifespan = 49;
        if (gender == MALE){
            active_headshot = "male_headshot.jpg";
            active_fullbody = "TemplateforPortrait.png";
            minHeight = 162;
            maxHeight = 190;
            lifespan = 49;
        }else if (gender == FEMALE){
            active_headshot = "Fem_headshot.jpg";
            active_fullbody = "TemplateforPortrait.png";
            minHeight = 150;
            maxHeight = 170;
            lifespan = 43;
        }//gender headshot switch
        break;
      }

    }

Comment: First, write your question using moderate language, this is not a forum but a question and answer site for **professionals**. Second, you can't do what you want in an array (and Eclipse is telling you), instead use a `Map`.
Comment: Rather than the giant if else structure why dont you just have an array of strings called names and just put names [archery]="archery" then you can get the name with ease (doesnt solve your full problem but its an improvement
Answer: Use an enum instead (provided your skill set is fixed):
public enum Skill
{
    ARCHERY,
    ETC
}

And in order to build a skill "array", use an EnumMap. You could do, in the enum for instance:
public enum Skill
{
    ARCHERY,
    ETC;

    public static Map<Skill, Integer> newSkillMap()
    {
        final Map<Skill, Integer> ret = new EnumMap(Skill.class);
        for (final Skill skill: values())
            ret.put(skill, 0);
        return ret;
    }
}

Usage:
final Map<Skill, Integer> skillMap = Skill.newSkillMap();
map.get(Skill.ARCHERY); // skill for archery
map.put(Skill.ARCHERY, 30); // change value

You can even improve your enum so as to have default values, etc; enums can do a lot of things in Java. Sample:
public enum Skill
{
    ARCHERY(10, "archery"),
    ETC(0, "etc");

    private final int defaultValue;
    private final String description;

    Skill(final int defaultValue, final String description)
    {
        this.defaultValue = defaultValue;
        this.description = description;
    }

    public static Map<Skill, Integer> newSkillMap()
    {
        final Map<Skill, Integer> ret = new EnumMap(Skill.class);
        for (final Skill skill: values())
            ret.put(skill, skill.defaultValue);
        return ret;
    }

    @Override
    public String toString()
    {
        return description;
    }
}

Comment: The only downside here is that you if you want to add more skills you must recompile the application (or this jar). If OP's following a good design, the skills would be loaded separately from a file or another data source.
Comment: Yes, that is true. But I suppose the skill set is fixed ;)
Comment: It would be better to suppose nothing or providing a comment explaining what you're supposing.
Answer: You can use an enum for your purpose:
public enum Skill {
  SWORD(0, "Sword"),
  ARCHERY(1, "Archery")
  ;

  public final String name;
  public final int index;

  Skill(int index, String name) {
    this.name = name;
    this.index = index;
  }
}

skillsArray[ARCHERY.index] = 25;
System.out.println(ARCHERY.name+" is +"skillsArchery[ARCHERY.index]);

Mind that you can use ARCHERY.ordinal() if you prefer the builtin index assigned to your enum value. That will be safer but less flexible (since it will depend on position imposed in enum declaration).
Comment: i tried using enums before but could never get the results i want.
A bit problem i have is i use the int for readability in naming catagories like Race names, class names, skills, then have a class that uses....hold on let me just modify the OP to illistrate

return a primitive's name


Is this result correct? Limits don't depend on norm.

Question: Let $\|\cdot\|: \mathbb R \to \mathbb R$ be some norm on $\mathbb R$ which is not the standard absolute value $|\cdot|$ we all know and love. $f: \mathbb R \to \mathbb R, L \in \mathbb R.$
Suppose that $\lim_{t \to 0} f(t) = L$ with respect to $\| \cdot \|$
This means that $\forall \epsilon > 0 \exists \delta >0: \|t\| \leq \delta \implies\|f(t)-L\| \leq \epsilon$
I would like to show that this is also true with respect to $|\cdot |$. The limit does not depend on with respect to which norm does $t$ approach zero.
What I did:
Fix $\epsilon >0 $ and choose a $\delta$ such that $\|t\| \leq \delta \implies\|f(t)-f(0)\| \leq \epsilon$.
All norms are equivalent, so there is $c >0$ such that $c|t| \leq \|t\| \leq \delta$ and $c|f(t)-L| \leq \|f(t)-L\| \leq \epsilon$
So $|t| \leq \frac{\delta}{c} = \delta'$ and $|f(t)-L| \leq \frac{\epsilon}{c} = \epsilon'$
Finally, $|t| \leq \delta ' \implies\frac{\|t\|}{c} \leq\frac{\delta}{c} \implies \|t\| \leq \delta$
That implies by our initial assumption that $\|f(t)-L\| \leq \epsilon$, but then $|f(t)-L| \leq \frac{\epsilon}{c} = \epsilon'$.
Since our $\epsilon$ is as small as we would like, so is $\epsilon'$, and that concludes the proof.
Is this proof correct?
Question number 2
The differential of a function activated on unit vector $h$ is defined to be $D_f(a)h = \lim_{t \to 0} \frac{f(a+th)-f(a)}{t}$.
Suppose my proof is correct and it does not matter with respect to which norm does $t$ approach zero here. Does it matter with respect to which norm is $h$ a unit vector?
In other words- Does the differential of a function at all depend on the choice of the norms and inner products we work with? If so - why? if not - why not?
Comment: @gimusi apologies! I just saw it now. I actually managed to solve that question on my own so I moved ahead and forgot to tend to that page. Thank you, good answer. Liked the use of the binomial theorem and little "o" notation.
Answer: The argument you gave contains the main idea to prove what you want to show.
But there is one point that should be revised. You say "Finally, $|t|\le\delta'\Longrightarrow \frac{\|t\|}c\le\frac\delta c$". Probably this is true in this case, but it is not obviously derived from the equations and inequalities you have. You should improve the arguments in order to prove the implication.
Spoiler: better using the existence of $c$ such that $\|t\|\le c|t|$.
For the second question: first, note that your definition does not depend on $h$ being a unit vector. Then, try to prove the following (a generalization of your first question):
Let $f:\mathbb{R}\to\mathbb{R}^n$ and let $\|\cdot\|_1$ and $\|\cdot\|_2$ be two (equivalent) norms in $\mathbb{R}^n$. Then $\|f(t)\|_1\to0$ as $t\to0$ if and only if $\|f(t)\|_2\to0$ as $t\to0$.
Notation. $\|f(t)\|\to0$ as $t\to0$ means
$$
\lim_{t\to0}\|f(t)\|=0.
$$
(one last commentary: $t\to0$ if and only if $|t|\to0$, so if and only if $\|t\|\to0$, where $\|\cdot\|$ is any norm in $\mathbb{R}$.)


Hosting Cacti install from NginX

Question: I have having an issue with hosting a Cacti installation from NginX.
I have cacti installed under /usr/share/cacti and the below block in my default NginX config file.
location / {
    root /var/www;
    index index.html index.htm
}

location /cacti {
    root /usr/share/cacti;
    index index.php index.html index.htm;
    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$request_filename;
    }
}

The problem as I can see is that the NginX error log is full of errors that "/usr/share/cacti/cacti/index.php" doesn't exist.
For now I have simply added the extra directory to cacti, but I can't figure how to get NginX to 'drop' the '/cacti/' prefix from the URI when processing the page requests (and passing them on to PHP5-FPM)
Any help would be appreciated.
Comment: try just changing location line from "location /cacti {" to "location / {"
Comment: The "location /" already has a root of /var/www - Updated post to add this
Comment: might be worth noting that you are missing a semi-colon after `index.html index.htm`
Answer: The root directive still results in the URL path being appended, so if the root is /usr/share/cacti and the path is /cacti the directory is /usr/share/cacti/cacti. You can do one of two things:

Since your URL path matches the directory, set the root one level higher:
location /cacti {
    root /usr/share;
    ...
}

Use the alias directive, which doesn't append the URL path. This approach will require modifying the SCRIPT_FILENAME parameter passed to PHP however.
location /cacti {
    alias /usr/share/cacti;
    ...
    fastcgi_param SCRIPT_FILENAME /usr/share$request_filename;
}

Comment: When I use the alias directive, the pages fail to load and my NginX log shows that PHP-FPM is still looking for the scripts in /usr/share/cacti/cacti/...
Comment: @TimJones See my edit. I'd go with the first option.

Hosting Cacti install from NginX


How can I most performantly display musical chord sheets in HTML5?

Question: I am currently working on my final year project for my degree in Software Engineering. I have decided that my project will be to develop a web application using HTML5 that will display chord sheets in a web browser (specifically Google Chrome). The idea is that each member of a band might have some sort of device in front of them (iPad, laptop etc.) which can access the application where they can log in, view the chords for the songs as the progress through a set and add annotations which are stored in the database and then shown to the user each time the song is displayed on their screem.
However, I am having a problem with how best to display all this in a browser window. I want it to have a similar appearance to that of a PDF document displayed in a browser window in that the user is able to scroll horizontally and vertically and zoom in and out as if they were viewing a PDF document. Is using SVG graphics the best way to achieve this? Or is there another way?
Rendering speed is going to be important as the idea is that this will be a system that could potentially be used in live situation, and I need to make sure I keep page loading/rendering times as low as possible.
I would greatly appreciate any thoughts you have!
Answer: Check out Vexflow! It's an open-source web-based music notation rendering API, written completely in JavaScript, and runs right in the browser. VexFlow supports HTML5 canvas and SVG.
Here's a demo and here's a tutorial.
Comment: Thanks, that does look good and may prove to be quite useful at some point, although I'm wanting to display lyrics/chords rather than music notation in this case.


How do I convert the following data serialization format into POJO or JSON?

Question: I was expecting a JSON string while testing an API using Postman, but instead got this:
{city=Shanghai, work=112-454-7895, fax=788-899-7899}
Obviously I cannot put that into Google and ask what format is it, hence I am asking it here. Postman also says it is a 'bad string'.
I have never seen the above data serialization format. If someone can point the format out to me I would be able to find and use a converter. Additional suggestion with converting it to POJO or JSON are welcome as well.
Answer: I figured out that the above format is a stringified version of a HashMap<String, String>, and that there is no direct way to convert it into JSON/POJO. Converting it into json string requires additional work but is fairly straightforward.


How to set up a singleton class as a delegate?

Question: I have a class that is a singleton. This singleton is instantiated using GCD (via macro that uses a block), and is accessed by other objects via a class method. The problem is I need this singleton to be a delegate of other object.
Where(when) can I set this, I have no access to init, but I need to set this up soon, when the singleton instance is created.
Comment: As far as I understand your question, you want to set this singleton to be the delegate of _another object_, so it doesn't really matter when the singleton is created, it matters when _that other object_ is created and that's where you would typically set its delegate.
Comment: I don't understand how this is different from setting any other delegate – just set the `delegate` property of your other object to be the singleton after you create it...
Comment: I do not create the singleton object..it is created by GrandCentralDispatch when it doesn't exist and when it is accessed by some other objects. More than one object has access to that singleton, and I do not know when. I mean, it is impossible to tell for sure that this or that will be the first one. Furthermore, I don't think its a good idea to set this singleton to be the delegate over and over, every time some object accesses it. Are you sure you understand the question at all?
Comment: I tried it the way you describe and it of course works :) Thanks.
Answer: The normal behavior for a singleton is that, if it needs an internal instance, it creates one the first time it is referenced.  (I think that's what you're saying but it's not explicit.)  If that's the case, then it seems that the object that needs to have it as a delegate should simply assign it whenever that object is created.  So part of the init of the other object's creation would be:
self.delegate = [MySingleton sharedInstance];
I'm not sure it matters but is there a reason for making it a delegate instead of just using it whenever the object needs to, via something like:  [[MySingleton sharedInstance] doSomething];?
Comment: It's not possible. The delegator here is a built-in Cocoa touch framework class from Apple. I also have never seen such a practice, so far I have always seen the delegate setting itself to be the delegate. In other words, the initiative to be the delegate always came from the delegate.
Comment: If it's not possible in this case, that's fine but there are various other patterns in use, for example, an object making a 2nd object the delegate of a 3rd.  One reason that you seldom see an object set its own delegate is what I said in my second paragraph: if the object can find it on its own (like a singleton), the whole delegation idea loses its purpose.
Answer:
you create a class implements delegate
then in callback method
[[NSNotificationCenter defaultCenter] postNotification:your-notification];

then in real
implements viewController [center addObserver:self selector:@selector(your-delegate-mothed:) name:your-name object:nil];

finally:
-(void)your-delegate-mothed:xx
 {
  //by NSNodificationCenter as gloal delegate ,dispatch callback
 }


SMS 2003 and WSUS on the Same Server?

Question: I'm dealing with a SMS 2003 SP3 server that is also running WSUS 3 and we're experiencing suspect behavior between the two.  Neither seems to be giving us the details we think we should be getting.  Has anyone heard of any issues or had any experience where the two have not played nice with each other?  Our plan is to seperate them moving each to a new server.  Thoughts?
Answer: A quick Google search reveals SEVERAL folks out there having problems with SMS 2003 SP3 and WSUS 3 on the same machine.
I'd say if you can separate the two reasonably quickly and test it will potentially save you A LOT of time in the long run.
To word it another way... there are enough examples out there of other people having the same (or similar) problems as you to justify separating the two to see if that fixes the problem.
Good luck! :-)
Comment: Yes, thank you.  Seperating the two seems to be the smart way to go.

SMS 2003 and WSUS on the Same Server?


Increase tmpfs size more than available RAM Is that a good option?

Question: Is it advisable to increase the size of tmpfs /dev/shm more than available RAM. Will it crash the machine?
The reason for the excercise is to optimize the perfromance of the SAP application.
Assume:Current RAM is 64GB.
By default /tmpfs is 50% of RAM - 32GB

Current Requirment of /tmpfs - 150 GB

Comment: How will this optimize performance?  The /tmpfs will be swapping out memory to disk constantly, this would serve no benefit to performance.  The benefit of performance from /tmpfs comes from the use of RAM.  If you have a /tmpfs larger than your RAM size, there will no longer be a benefit.  It will probably decrease performance due to overhead.
Comment: Who told you to do this?
Comment: if you write more then available, i think you know, your server will have same problem
Comment: @c4f4t0r Thanks for the quick response. Is there a recommended ratio between RAM size and /tmpfs other than the default 50%?
Comment: i don't see any recommend.
Comment: @Devon Sorry for the late reaction. Tmpfs won't "swap constantly", it will only swap if the data on it is actually used. Using the example scenario in my answer, if you have an 1GB machine, with a 16GB used tmpfs space. If there is a process what uses only, for example, 100MB on this space (for example, an actively updated database table), then only this 100MB will be in ram, the remainder will be in disk (in your swap partition), and your system won't swap.
Answer: You can give so many data into your tmpfs, as you wish. There is no difference between tmpfs instances in their maximal usage limits. You can even change this easily by a simple remount.
What in the case of the tmpfs counts, it is actual usage.
Tmpfs, against ramfs, is capable to swap out its content. Thus, the statement, that "you can't have a tmpfs much bigger as your physical ram", is simply false. For example, you can have as big tmpfs as you wish - if you have enough free swap space. You can have a 16GB tmpfs with a single GB of ram - although it can cause your system to a little bit of overload, similarly as if you would run a process with 16GB ram on an 1GB machine.
In the daily practice I never meet a single case, as a big tmpfs had been required. In this cases I used always normal filesystem space (mostly below /tmp). But the possibility exists and you can use it if would be needed.


Is co-variance safe here?

Question: class Food{}

class Meat extends Food{}

class Animal{
    void feed(Food f){}
}

class Lion extends Animal{
    void feed(Meat m){}
}

void foo(Animal a){
   Food f = new Food();
   a.feed(f);
}

What will happen if we send to foo(new Lion()) ?
I know that it will get error but I need the explanation please
Comment: Why do you think you will get an error here? Lion's feed method doesn't overrides Animal's feed method, so animal's feed method will call in foo. Overriding will occur if you try to use subclass in return type, but not in paarmeters list
Comment: Actually you won't get an error.  The Lion will eat the food, but the method in `Animal` will get called, not the more specific but non-matching method in `Lion`
Answer: Your Lion can eat Meat, but it can also eat any kind of food (like Spinach).
If your Lion could not eat any kind of Food, then it could not be considered an implementation of Animal.
This is critical to understand when deciding to use sub-classing and class inheritance as a means of constructing programs: you don't make your subclasses more specific than your interface or super classes.
For sub-classing to work in ways that solve problems (instead of create problems), you need to abide by this guideline: All subclasses must be functionally equivalent to the super-class (Liskov Substitution Principle)  This means that three classes which provide database access to three different databases is a good candidate for being subclasses from a common class (or perhaps sharing a common interface), because the "functionality" is "offer database access".
Where your Lion example falls short is that according to your definition of Animal a real world, Lions are not an Animals because real world Lions don't eat any kind of Food.  Real world Lions are more specific in their food eating ability than the general definition of an unknown animal.  And it is this functional difference which makes modeling real world Lions as subclasses of this specific definition of Animal a bad fit.
You could easily fix this by having the Animal "eat food" method throw an IncompatibleFoodException, which changes the definition of an Animal from something that "eats food" to something that "eats or rejects food".
Comment: This is where the `@Override` annotation comes in handy, because it would show that `Lion.feed(Meat)` doesn't override anything.
Answer: This violates the Liskov substitution principle, so it should likely be avoided (as Edwin says, it's really not an Animal if it can't eat Food).
Perhaps against first thought, this will actually not result in an error, but rather will call Animal::feed instead of Lion::feed as expected.
Just reread the title, and to answer the question specifically: No, covariance is not safe here (in terms of behaviour.  In terms of syntax it is.).
Quick copy and paste of the question into an example:
class Food{}

class Meat extends Food{}

class Animal{
    void feed(Food f){
        System.out.println("om nom nom");
    }
}

class Lion extends Animal{
    void feed(Meat m)
    {
        System.out.println("OM NOM NOM");
    }
}

public class test
{

    public static void main(String[] args)
    {
        foo(new Lion());
    }

    static void foo(Animal a){
       Food f = new Food();
       a.feed(f);
    }

}

Outputs "om nom nom"

Is co-variance safe here?


Liberação de memória em dicionários do python

Question: Eu estou tentando desenvolver um programa que armazena temporariamente uma quantidade significativa de variáveis. Essas variáveis estão armazenadas na memória RAM, dentro de dicionários.
Mas estou com dificuldade de compreender como o "coletor de lixo" do python funciona em dicionários dentro de dicionários. Não consigo liberar a memória dos dicionários filhos deletados. Usei gc.collect() e .clear(), mas não resolve.
.clear() no dicionário pai faz a liberação da memória, mas isso não resolve meu problema, preciso fazer a liberação da memória nos dicionários filhos.
Usando Debian 32-bit no virtual box os valores do dicionário ficam assim.
#TESTE DE LIBERAÇÃO DE MEMORIA

from sys import getsizeof

d = dict()

for key in range(100):
    d["TESTE-"+str(key)] = {}

#resultado depois de adicionar dicionários
print(getsizeof(d))
#SAIDA -> 2612

for key in list(d):
    del d[key]

#resultado depois de deletar dicionários filho
print(getsizeof(d))
#SAIDA -> 2612

Indiferente se usar d[key].clear() antes de del d[key], ou gc.collect() não limpa a memória.
Há alguma maneira de limpar a memória dos dicionários filhos?
Essa maneira de armazenar dados temporários está errada? Se sim, como devo trabalhar?
Comment: Talvez [essa resposta](https://stackoverflow.com/questions/32167386/force-garbage-collection-in-python-to-free-memory) (em inglês) seja útil pra você.
Answer: A liberação de memória em objetos como dicionários e listas não é automática -
depois que uma estrutura de dados cresce - ela não diminui de tamanho - mas mantém o tamanho interno para poder crescer até o tamanho máximo que teve.
Em outras palavras: se eu crio uma lista, e adiciono 100.000 elementos, o Python tem uma heurística que já deixa a lista com espaço para uns 120.000 elementos (por exemplo).
Agora - isso é o tamanho da lista  - o tamanho dos objetos que estão dentro da lista, não é contabilizado no tamanho dela  - e  o "getsizeof" engana. (Você viu que ele não é extensamente documentado? é por que é mais uma função de debugging do que de uso para programas finais). Ou seja, o getsizof retorna o tamanho em bytes de um objeto, mas não de objetos referênciados ou "contidos" nele. No caso de lista ou dicionários, cada objeto "dentro" deles ocupa só 8 bytes (um ponteiro para o objeto real) - mesmo que esse outro objeto tenha vários megabytes.
Então: você está medindo o valor errado. Há receitas na internet para usar o getsizeof de maneira recursiva e te dar o tamanho total de um objeto - mas mesmo se você fizer isso, não resolve o seu problema: se você remover objetos grandes de dentro de um dicionário "A" o tamanho total do dicionário "A" vai ser menor - por que o outro dicionário não está mais dentro de "A" - mas pode haver algum vazamento se esses objetos tiverem outras referências (em outras estruturas de dados, tais como caches, variáveis nonlocal esquecidas, etc). Então a forma de monitorar se não há vazamento de memória é monitorar a memória do processo inteiro do Python com uma ferramenta externa.
E ainda tem que lembrar que  o Python repete um pouco para o interpretador a receita que ele usa pra listas: se o processo precisou de 20MB - ao precisar de menos, ele não devolve de imediato esses 20MB para o S.O., já que tem uma chance grande de logo precisar desses 20MB de volta.  Para testar você tem que monitorar de fora, criar estruturas de dados de alguns MB (poucos bytes ou KB, como chaves de dicionário com strings nao adiantam). Ver o tamanho máximo. Apagar os objetos grandes. Criar outros objetos de tamanho equivalente - e aí ver se aquele tamanho máximo prévio se mantém (se ao criar outra geração de objetos grandes, o seu processo passar de 20MB para 40MB - sinal de que a primeira geração ainda está por lá em algum lugar)
Isso é dificil, porque vai ser um teste "de integração" - que é mais uma coisa do ambiente final de execução mesmo, do que algo para se preocupar no desenvolvimento.
Em geral em Python você realmente não tem que se preocupar com gerenciamento de memória - se você criar dicionários gigantes que entram como values dentro de outro dicionário, ao apagar aquela chave, a memória do objeto é liberada imediatamente. (mas pode ficar alocada para o processo Python, para o próximo objeto do mesmo tamanho).
Exercício
Criei um código aqui que cria e descria sub-dicionários grandes,
e pega a própria memória no sistema operacional (estou no
Linux e usei o comando pmap) - veja o programa e a saída abaixo:
import os, sys
import random

def get_process_memory():
    """Return total memory used by current PID, **including** memory in shared libraries
    """
    raw = os.popen(f"pmap {os.getpid()}").read()
    # The last line of pmap output gives the total memory like
    # " total            40140K"
    memory_mb = int(raw.split("\n")[-2].split()[-1].strip("K")) // 1024
    return memory_mb

def create_mass(size=50):
    return chr(random.randint(32, 127)) * size * 1024 * 1024

def main():
    container = {}
    print(f"memory at start: {get_process_memory()}MB")
    container["mass1"] = {i: create_mass() for i in range(10)}
    print(f"memory after creating first mass: {get_process_memory()}MB")
    container["mass2"] = {i: create_mass() for i in range(10)}
    print(f"memory after creating second mass: {get_process_memory()}MB")
    del container["mass1"], container["mass2"]
    print(f"memory after deleting first second masses: {get_process_memory()}MB")
    container["mass3"] = {i: create_mass() for i in range(10)}
    container["mass4"] = {i: create_mass() for i in range(10)}
    print(f"memory after creating 3rd an 4th masses: {get_process_memory()}MB")
    del container["mass3"]
    print(f"memory after deleting 3rd mass: {get_process_memory()}MB")
    del container["mass4"]
    print(f"memory after deleting 4th mass: {get_process_memory()}MB")
    container.clear()
    print(f"memory after clearing container: {get_process_memory()}MB")

if __name__ == "__main__":
    main()

Saída num ubuntu, com 8GB, core i7, Python 3.8.0:
jsbueno ~/tmp01$ time python memory_exercize.py
memory at start: 45MB
memory after creating first mass: 545MB
memory after creating second mass: 1045MB
memory after deleting first second masses: 45MB
memory after creating 3rd an 4th masses: 1045MB
memory after deleting 3rd mass: 545MB
memory after deleting 4th mass: 45MB
memory after clearing container: 45MB

real    0m1,522s
user    0m0,582s
sys     0m0,823s

Acima, eu afirmei que o Python nem sempre devolve a memória para o sistema operacional, podendo já deixar "reservada" a memória para um eventual uso.
Nesse exemplo, em que aloquei 50MB em cada objeto, isso não fica visível: em todos esses casos, o Python liberou a memória imediatamente.
Para valores bem mais modestos, o efeito pode ser observado. Reduzi a unidade de alocação de 50MB para 256K (ou seja, 200 vezes menor) - e aí podemos ver, entre a terceira e quarta desalocação que o Python "segura" 3MB lá com ele:
memory at start: 45MB
memory after creating first mass: 47MB
memory after creating second mass: 50MB
memory after deleting first second masses: 45MB
memory after creating 3rd an 4th masses: 50MB
memory after deleting 3rd mass: 50MB
memory after deleting 4th mass: 45MB
memory after clearing container: 45MB


Recursive deletion of files (bash)

Question: I'm familiar with how I would tackle this with PHP, however I'd like to get some more practice with bash scripting.
The task is to delete all files in a folder, which itself contains subfolders (with files).  The files would typically be .pdf (or some variant: PDF, Pdf, pDf, ect), however there may occasionally be other file types including extensions unknown to me at this time.
Here's what I have so far.  It echoes the filename, but if I issue rm $i, the system returns file not found on each file.
for i in `ls -bRC1 /foo/temp_folders/* ` ; do echo $i ; rm $i ; done

How would I force the absolute path when issuing rm $i?
Comment: Is there some reason why you wouldn't just use [find](http://linux.die.net/man/1/find)?
Answer: Per Zoredache... why not:
find /foo/temp_folders/ -type f -iname * -exec rm {} +
Edit: changed the trailing \; to + for performance as noted here
Comment: I wouldnt go with -exec rm {} + but rather simply with -delete -> it's much faster than constantly calling Linux's exec. The other day I had to delete tons of files and tried both, -delete option came out as absolute winner
Comment: I'd uprate you, but I don't have the mojo just yet - thanks for the response.
Comment: Nifty, I didn't realize find even had a -delete option... I'll have to remember that one.
Answer: find -exec would be slow on large number of files. I would suggest:
find /foo/temp_folders -type f -print0 | xargs -0 rm

Comment: I'd uprate you, but I don't have the mojo just yet - thanks for the response.
Comment: Actually, this is a good point, and not one I usually have to consider.  I found an interesting article that compares "-exec {} \;" to "-exec {} +" to "| xargs" here: http://fahdshariff.blogspot.com/2009/05/find-exec-vs-xargs.html

Recursive deletion of files (bash)


How to convert sport odds into percentage?

Question: I am wondering how to convert sport odds to the percentage format.
There's this example:
Odds for the home team victory: 2.50
Odds for the draw:`3.25
Odds for the away team victory: 3.00

To convert these odds into percentages, I can do this:
1/2.50 = 0.40 => 40% that the home team wins
1/3.25 = 0.31 => 31% for draw
1/3.00 = 0.33 => 33% that the away team wins

But if the percentages are added, then:
40% + 31% + 33% = 104%

What am I doing wrong that the sum is not equal to 100%? Is the procedure I follow wrong?
Comment: It is the bookie's edge. If it is under 100% it is a "sure bet" for the gambler, and there is a web site for this where they combine the websites of all bookies to check if there is a surebet possibility by betting on WinHome on betting site A, Draw on betting site B, WinAway on betting site C. If it is more than 100% then it means bookie is making money on overall population of gamblers. They are also mitigating their risk (on average they win but there is volatility) of loss on a single event by modifying the odds based on the bets they have received so far as time gets nearer to the event.
Answer: The odds you have are in decimal format, which the bookmaker calculates as:
$$
d_E = \frac{1}{p_E + o_E}
$$
where $d_E$ is the decimal odds for event $E$, $p_E$ is the bookmakers estimated probability of event $E$, and $o_E$ is the over-round which the bookmaker adds to the decimal odds for event $E$. The over-round effectively reduces the odds, making them unfair for the bettor.
In your example, with events $H$ (home win), $D$ (draw), and $A$ (away win), you have:
$$
\frac{1}{d_H} + \frac{1}{d_D} + \frac{1}{d_A} = (p_H + p_D + p_A) + (o_H + o_D + o_A) = 1.04
$$
of course, $p_H + p_D + p_A = 1$. One option is assuming $o_H = o_D = o_A = o$ so you have $1 + 3o = 1.04$ and so $o = 0.04/3$, which you can use to uncover the bookmaker's underlying probabilities, $p_H$, $p_D$, and $p_A$. In practice however, there is no way of knowing how the bookmaker adds over-round onto betting events, it is likely they add more over-round to events which are more likely to be bet, for example a UK bookmaker's odds on England to win the World Cup.
Answer: If the odds describe real events, you most likely got them from some betting site.
You are searching for overround. If your implied probabilities do not add up to 1 but are greater 1, then the bookmaker makes a sure profit of all above 1.
A simple way to work is to re-normalize, i.e. divide every inverse odd again by the sum, 1.04 in your example.
Answer: If you just want to estimate the probabilities, it seems indeed reasonable to just devide each percentage by 1.04.
However, if you want to find out more about the true percentages that the bookkeeper uses, you can do something more.
Let's assume that the bookkeeper does not want to accept a negative expected value for any of his bets
Now we can conclude the following:
40, 31 and 33 are upper bounds for the underlying true percentages.
40-4, 31-4 and 33-4 are lower bounds for the underlying true percentages (otherwise one of the other two odds would give him a negative expected value)
40+31-4, 31+33-4 and 40+33-4 are lower bounds for the underlying true percentages of a pair of possible outcomes (otherwise the other odd would give him a negative expected value)

Sidenote: I expect a bookkeeper to especially pad bets with a high risk factor, so if it would be 60% vs 40% vs 4%, it would be safe to say that the 4% contains relatively much padding.
Answer: I think they are odds against. i.e.
2.5 = (Prob(away team wins) + Prob(draw)) / Prob (Home team wins)
You can compute P(Away team wins) + Prob(draw) by taking 1/(2.5+1).
If you do that for all 3, you can P(W) = 0.285, P(D) = 0.235, P(L) = 0.25.
They do not sum up to 1, probably because the odds are rigged. But you can easily normalise them
i.e. P*(W) = P(W) / P(W) + P(D) + P(L) = 0.37
Comment: is this method reversible? If I know the probabilities and the target margin, how to I calculate the odds (2.5, 3.25, 3.00)
Answer: There is a major issue with the odds that are offered in this scenario.  Where did they come from?
Suppose I bet \$1 on the home team.  With odds of 2.5, I would win \$2.50 and get my \$1 back, for a collection of \$3.50.  So, let's look at the chart below:
Winner - Odds - Payback on $1
Home   - 2.5  - $3.5
Draw   - 3.25 - $4.25
Away   - 3.00 - $3.00

Therefore, I can bet \$3 (\$1 on each), and have a positive return.  Therefore, there is no way this is odds from a bookmaker, which is why I wonder where the odds come from?
Comment: The odds are decimal, so if you bet £1 at odds of 2.5, you get £1.50 profit and your £1 stake back.


how to list all function of man page 9

Question: I did "man copy_to_user" - It shows some kernel help text. It belongs to section 9. Now I would like to know ,whether is there way to display all function belongs to this section 9.
Comment: All functions that belongs to all software on section 9?..
Comment: Yes,list all functions that belongs to section 9. I'm interested in functions.I can see them under /usr/share/man/man9 . But would like to know anyother better way to list them.
Answer: whatis -s 9 -w "*" will list the name and descriptions of all the manpages it knows about (uses the mandb database) in section 9.  Be sure to quote the * character.
Comment: It says unknown option. `[laks@space ~]$ whatis --version
whatis from man-1.6f
[laks@space ~]$ whatis -s  9 -w "*"
whatis: -s: unknown option`
Comment: I've got `whatis 2.5.7` which is in debian stable's man-db 2.5.7-8 package.  Even oldstable has 2.5.2.  Check `man whatis` and see if your version has some other way of specifying section and wildcard matches.

how to list all function of man page 9


Password - Binary Modular Crypt Format

Question: Encontro-me neste momento a reduzir o tamanho de uma base de dados e várias são as técnicas utilizadas. No entanto estou com uma dúvida na decisão a tomar num ponto e gostaria que alguém me conseguisse ajudar.
No modelo em questão e na tabela de utilizadores é utilizado uma password BCRYPT esta tem definido um tamanho de máximo de 60 bytes na base de dados. Sei que utilizando técnicas
BMCF (Binary Modular Crypt Format ) posso conseguir reduções para 40 bytes... em detrimento do MCF que é o standard.
No entanto esta técnica adiciona mais um "layer" que no caso de passwords acho que vale a pena, não no sentido da segurança mas no trabalho de redução da base de dados.
Para um algoritmo em PHP estarei certo? Ou seja mais um "layer" sobre servidores de alta disponibilidade irá colocar alguma latência, mas se mantiver o atual MCF e tendo em conta que a password não é um campo de "INDEX" da base de dados será que vale mesmo a pena?
Conhecem  outras técnicas alternativas?
PS: Sei que existem outros além do BCRYPT mas isso eu não posso mudar.
Answer: Por não ter obtido qualquer resposta à minha questão venho colocar qual a minha decisão esperando que a mesma seja útil para alguém.
O meu ponto de partida era reduzir o tamanho da base de dados que é repartida por vários SHARDS e que mesmo assim e pelo diagnóstico dentro em breve irá rebentar pelas costuras. Antes de colocar novo servidor e dividir os vários SHARDS pelos servidores, o meu esforço era o de reduzir o que fosse possível.
Muitos foram os aspectos considerados e após a minha análise, consegui em muitas tabelas uma redução perto de 33%... ou seja em tabelas de quase 1TB reduzir apenas com optimizações de campos e algumas alterações de código PHP inclusivé foi motivo para já ganhar um medalha... heheheh (desculpem o aparte)
No entanto faltava a tabela de utilizadores e aí após a luta deparei-me com o campo da PASSWORD. E foi então que na dúvida coloquei aqui a questão.
Reduzir um campo de 60 bytes de uma senha BCRYPT para 40 na realidade pode ser feito e o ganho numa análise simplista é de executar e nem olhar para trás.
No entanto este processo trazia alguns pontos negativos:

adiciona mais um layer ao sistema para a gravação e leitura
a gravação tem de acontecer num campo BINARY
O conteúdo deixa de ser um STANDARD

Ora, no caso o campo de PASSWORD não é um campo de index e quem lida com MYSQL sabe de alguns problemas que se obtem ao gravar campos em BINARY. Tendo já conseguido reduzir o tamanho do registo optei por apenas alterar um campo VARCHAR(60) para CHAR(60) BINARY e assim manter o standard tendo em conta que o BCRYPT...

é um processo já muito seguro e que o hash resultante é muito mais que um hash
a avaliação para saber se a senha precisa do re-hash é imediato após leitura sem
precisar de mais um "layer"
o mesmo do ponto 2 mas para a obtenção do "salt"
a alteração de VARCHAR para CHAR parece-me óbvia e a TAG BINARY é apenas para que não seja considerada _bin de forma a não acontecer qualquer tradução de caracteres.

Espero ajudar outros quando confrontados com uma situação semelhante.
Conclusão mantive o tamanho!

Password - Binary Modular Crypt Format


Prove that $V_{m}:=\sum_{j=0}^{m}a_{j}T^{j}.\rightarrow f\left( T\right) $ in $B\left(X\right)$

Question: Let $f\left( z\right) =\sum_{n=0}^{\infty }a_{n}z^{n}$ be a
power series with complex coefficients and convergent on the open disk $%
D\left( 0,R\right) \subset \mathbb{C}$, $R>0.$

If $T\in B\left(X\right)$ (i.e. $T$ is a bounded operator on a Banach space $X$)
  with $\left\Vert T\right\Vert <R$. Why $V_{m}:=\sum_{j=0}^{m}a_{j}T^{j}.\rightarrow f\left(
T\right) $ in $B\left(X\right)$ ?
If $X$ is just a normed space not complete, is the above result remains true?
Answer: We have that
$$||V_n-V_m||\leqslant \sum_{j=m+1}^n |a_j| ||T||^j$$
The RHS can be made arbitrary small, because $||T||$ is inside the radius of convergence of $f$. The completeness of $B(X)$ will guarentee that $(V_n)$ is convergent. But if $X$ is not Banach, then nothing will guarentee the completeness of $B(X)$.


Taylor's Polynomial with Lagrange's form of remainder.

Question: Suppose our function be written as
$$f(x)=P_n(x)+R_n(x)$$ where $P_n(x)$ is n-th Taylor's Polynomial about $x_0$ and $R_n(x)$ is associated remainder/error term both of which are given as
$$P_n(x)= \sum _ { k = 0 } ^ { n } \frac { f ^ { ( k ) } \left( x _ { 0 } \right) } { k ! } \left( x - x _ { 0 } \right) ^ { k }$$
$$R _ { n } ( x ) = \frac { f ^ { ( n + 1 ) } ( \xi ( x ) ) } { ( n + 1 ) ! } \left( x - x _ { 0 } \right) ^ { n + 1 }\quad \text{for }  \xi(x)\in [x,x_0]$$
Suppose $\lim\limits_{n\to\infty}R_n(x)=0$ or in other words  $\lim\limits_{n\to\infty}P_n(x)=f(x)$
Define  $$g(n)=\sup |R_n(x)| = \sup |f(x)-P_n(x)|$$
Can it be proven that $g(n)=\sup |R_n(x)|$ is decreasing function of $n$
Comment: For one $x$ or every $x?$ What are you taking the $\sup$ over? Where is $f$ defined?
Comment: @zhw. For any general function. We are talking for all those x at which  taylor's polynomial converges to the function.
Comment: Let $f(x)= e^x.$ Then $\sup_{x\in \mathbb R} |e^x-P_n(x)| = \infty$ for any $n.$
Answer: Consider $f(x) = 1/(1-x)$ on $[-2,0]$. Expand it at $x =0$, then
$$
f^{(n)}(0) = n!(1-x)^{-(n+1)}|_{x=0} = n!,
$$
and the Taylor formula is
$$
f(x) = \sum_0^n x^j + (1- \xi)^{-(n+2)} x^{n+1}.
$$
Now
$$
\sup |R_n(x)| = \sup\left| \frac 1{1-x}- \sum_0^n x^j\right| = \sup\left|\frac {1-(1-x^{n+1})}{1-x}\right| = \sup \left|\frac{x^{n+1}} {1-x}\right| =\sup \frac {(-x)^{n+1}} {1-x} \geqslant \frac {2^{n+1}} {1+2} \nearrow +\infty,
$$
so the sequence $g(n)$ cannot be decreasing.
UPDATE
Inspired by @zhw., if the interval is $(-1,1)$ instead, then
$$
g(n) \geqslant \frac {(1-1/n)^{n+1}}{1 - 1+1/n} \xrightarrow{n\to \infty} +\infty,
$$
and $g(n)$ still cannot be decreasing.
Comment: Can we claim that $g(n)$ will be decreasing with $n$ only for those functions whose Taylor's polynomial will converge to the function.
Comment: On $[-2,0]?$ i would think the natural domain here is $(-1,1).$ Why did you take the absolute values off at the end there? Actually the $\sup = \infty$ for every $n.$
Comment: That is before the OP added the restriction $R_n(x)\to 0$.


Is this true that, $u \in \bigcap_{ \alpha<1} C^{0, \alpha}$ implies $u \in C^{0,1}$

Question: Is there a holder continuous function with any order less than 1, but not Lipschitz. Or does $u \in \bigcap_{\alpha<1} C^{0, \alpha}$ imply $u \in C^{0,1}$.
Answer: No, a log-Lipschitz function, i.e. one that satisfies
$$ |u(x) - u(y)| \le C|x-y| |\log|x-y||$$
 is $C^{0,\alpha}$ for any $\alpha<1$, but not Lipschitz. See this MSE post. An example of such a function is
$$|x||\log|x||$$
Comment: What is in your brain???