telegram api configuring project exception

Question: these days I'm trying to make an application using telegam api and source code. But when  I'm building project http://www.imgim.com/telegram2.png  error image is on this link. All off the Android Studio things are updated.
Android studio says:
org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':TMessagesProj'.
note: My sdk path's name don't have whitespace.
here is the all of output of build screen
org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':TMessagesProj'.
    at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:87)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:82)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:69)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.access$100(LifecycleProjectEvaluator.java:33)
    at org.gradle.configuration.project.LifecycleProjectEvaluator$ConfigureProject.run(LifecycleProjectEvaluator.java:103)
    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:197)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:49)
    at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:651)
    at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:133)
    at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
    at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:62)
    at org.gradle.execution.TaskSelector.getSelection(TaskSelector.java:100)
    at org.gradle.execution.TaskSelector.getSelection(TaskSelector.java:81)
    at org.gradle.execution.commandline.CommandLineTaskParser.parseTasks(CommandLineTaskParser.java:42)
    at org.gradle.execution.TaskNameResolvingBuildConfigurationAction.configure(TaskNameResolvingBuildConfigurationAction.java:44)
    at org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
    at org.gradle.execution.DefaultBuildConfigurationActionExecuter.access$000(DefaultBuildConfigurationActionExecuter.java:25)
    at org.gradle.execution.DefaultBuildConfigurationActionExecuter$1.proceed(DefaultBuildConfigurationActionExecuter.java:54)
    at org.gradle.execution.DefaultTasksBuildExecutionAction.configure(DefaultTasksBuildExecutionAction.java:44)
    at org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
    at org.gradle.execution.DefaultBuildConfigurationActionExecuter.access$000(DefaultBuildConfigurationActionExecuter.java:25)
    at org.gradle.execution.DefaultBuildConfigurationActionExecuter$1.proceed(DefaultBuildConfigurationActionExecuter.java:54)
    at org.gradle.execution.ExcludedTaskFilteringBuildConfigurationAction.configure(ExcludedTaskFilteringBuildConfigurationAction.java:47)
    at org.gradle.execution.DefaultBuildConfigurationActionExecuter.configure(DefaultBuildConfigurationActionExecuter.java:48)
    at org.gradle.execution.DefaultBuildConfigurationActionExecuter.select(DefaultBuildConfigurationActionExecuter.java:36)
    at org.gradle.initialization.DefaultGradleLauncher$CalculateTaskGraph.run(DefaultGradleLauncher.java:265)
    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:197)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
    at org.gradle.initialization.DefaultGradleLauncher.constructTaskGraph(DefaultGradleLauncher.java:173)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:128)
    at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:107)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
    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.run(GradleBuildController.java:75)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:53)
    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:197)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
    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:45)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:29)
    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:71)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:45)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:51)
    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:55)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:42)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:58)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:33)
    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:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    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:120)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    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:120)
    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:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
    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:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.api.GradleException: executing external native build for ndkBuild C:\wieapp\TMessagesProj\jni\Android.mk
    at com.android.build.gradle.internal.ExtraModelInfo.handleIssue(ExtraModelInfo.java:118)
    at com.android.builder.core.ErrorReporter.handleSyncError(ErrorReporter.java:77)
    at com.android.build.gradle.tasks.ExternalNativeJsonGenerator.build(ExternalNativeJsonGenerator.java:194)
    at com.android.build.gradle.BasePlugin.lambda$createAndroidTasks$6(BasePlugin.java:696)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
    at com.android.build.gradle.BasePlugin.createAndroidTasks(BasePlugin.java:684)
    at com.android.build.gradle.BasePlugin.lambda$null$3(BasePlugin.java:555)
    at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:81)
    at com.android.build.gradle.BasePlugin.lambda$createTasks$4(BasePlugin.java:551)
    at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:91)
    at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:80)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
    at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
    at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
    at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
    at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
    at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
    at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy26.afterEvaluate(Unknown Source)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:75)
    ... 98 more
Thank you for your interest
Answer: try this in the android studio terminal
<code>git submodule init
git submodule update
</code>
Comment: I Did'nt clone it , so <    C:\wieapp>git submodule init
fatal: Not a git repository (or any of the parent directories): .git     > is happening.  What can ı do now?


YARP proxy with Redisinsight

Question: has anyone managed to set up a YARP configuration for RedisInsight in Docker, which runs on localhost:8001? I would need to redirect myserver/app/redis to localhost:8001. When I tried it, I had a problem with loading JavaScript scripts, etc., because they are being searched for on myserver. Can anyone advise? Thanks in advance.
I tried setting RIPROXYPATH for RedisInsight but that doesn't work.
Comment: You have to change the default listening port for docker on server.  See https://github.com/dotnet/dotnet-docker/issues/3968
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: @Jaroslav Nerusil, can you please share the logs as well?
For RedisInsight v1, you'll have to set RIPROXYENABLE and set the path in RIPROXYPATH for RedisInsight to serve the application in a subpath.
While this is there, you don't need to forward the traffic to localhost:8001 on your web server because all the requests will always be made to the subpath and never to the root path. So, there is no need for any webserver configuration apart from serving the root application itself.
Here's a sample nginx setup - https://github.com/RedisInsight/RedisInsight-reverse-proxy/blob/main/nginx-subpath-proxy/nginx-subpath-proxy.conf.template

YARP proxy with Redisinsight


multiple network sockets python

Question: I'm creating a python script that listens on several ports (defined in the portslist) and when someone connects to any of these ports, a "hello" message will be sent to them. Currently, the code below creates sockets for all ports in the portlist but only sends message to communication on last port.
Thanks
servers = []
for port in portlist:
    datasocket = ("0.0.0.0", port)

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(datasocket)
    server.listen(5)

    servers.append(server)

while True:
ready_server = select.select(servers, [], [])

for s in ready_server:
        connection, address = server.accept()
        print str(address) + " has connected!\n"
        msg ="hello\n"
        connection.send(msg)
        connection.close()

Comment: for one, you have bad indentation under that `while` loop
Answer: When select.select returns, ready_server will be a list of lists like this:
[[<sockets ready to read from>], [], []]
So for s in ready_server will iterate over these lists, not over the sockets.
Also, server.accept() within that loop doesn't refer to any loop variable, but to the server from the previous loop.
Try this:
servers = []
for port in portlist:
    datasocket = ("0.0.0.0", port)

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(datasocket)
    server.listen(5)

    servers.append(server)

while True:
    # unpack the returned list
    ready_server, _, _ = select.select(servers, [], [])

    for s in ready_server:
        # use s.accept instead of server.accept
        connection, address = s.accept()
        print str(address) + " has connected!\n"
        msg ="hello\n"
        connection.send(msg)
        connection.close()

multiple network sockets python


Displaying multiple child-grandchild-relationships properly through Views

Question: I am using the most recent versions of Drupal (7.14), Views (3.3) and the Entity reference module (1.0 rc3).
I have three content types. The first of them (parent) contains a node reference field to the second (child), which has a node reference to the third (grandchild). Each of these reference fields have unlimited values.
I have set up a block view, with relationships for both node reference fields, and have defined a contextual filter for the parent node id.
This is what I want to display in the parent node, each with summaries and a few other fields from the referenced nodes:
Child 1
Grandchild 1
Grandchild 2
Grandchild 3

Child 2
Grandchild 4
Grandchild 5

With displaying an unformatted list of fields, I get the following result (aggregation doesn't help at all):
Child 1
Grandchild 1

Child 1
Grandchild 2

Child 1
Grandchild 3

Child 2
Grandchild 4

Child 2
Grandchild 5

Any suggestions for how I can get the display that I want?
Answer: So you've tried going into your 'Settings' for the unformatted list style and setting a 'Grouping field' already?
If not, try the following, and make sure to check the box I've checked here as well:
Comment: Thanks a million! I had tried to work with that before, but now I fiddled with it a little more, and got it to work. :)

Here's what I did in addition to your tip:
1. Excluded all child node type's fields from display
2. Grouped like you instructed by each field of the child node type
Comment: Glad it worked!


How to export/import a typedef in flutter

Question: With flowtype or typescript you can just import types where you need them.
If I make a typedef in flutter but need it in several files how can I do this?
As an example:
typedef VoidNoteOnClick = void Function(int index);

Answer: Just use import 'path/to/typedef.dart';


Time needed to decrypt a message $r=p\times q$, where $r$ is the message.

Question: If we can represent a secret message by a large prime
number $p$, we can transmit over the network the number $r = p · q$, where $ q > p$
is another large prime number that acts as the encryption key and $r$ can take 100 bits.
Question: What is the worst-case time complexity of the above algorithm?
Since the input to the algorithm is just one large number $r$, assume that the input size $n$ is the number of bytes needed to store $r$, that is, $n = \frac{\log_2{n}}{8}$, and that each division takes time $O(n)$. So we need $\frac{r}{p}$ divisions in order to get the encrypted message. Now the questions is how we can calculate the complexity of the algorithm where we need to guess each and every single possibility, thus I said we need $\frac{r}{p}$ divisions.
$$\frac{r}{p} = \frac{r}{2^{100}} ~~divisions$$
Problem: I assume the complexity in the question is referring to number of divisions or both divisions and space? So, the question is now, I am not sure why the complexity is $O(n \times 2^{4n})$?
Comment: Side comment: as an encryption scheme this doesn't quite make sense.  If you already have a shared secret key that's as large as the message, then just use it as a one-time pad :).  I guess it could be a feature that the message can be recovered with effort if the key is lost.
Comment: There is a detailed answer to your question on Wikipedia: [Integer factorization](https://en.wikipedia.org/wiki/Integer_factorization).
Comment: @Pin. Thank you. Pin, I am asking about complexity please not the concept.
Answer: Guessing each and every probability is not exactly an algorithm, since it doesn't specify what order we're guessing in.  Nevertheless, the most reasonable interpretation is that we're using trial division to find $p$, not $q$ which is the larger divisor of $r$.  The lengt of $p$ is at most half the number of bits of $r$, which is $4n$.  So $2^{4n}$ is the order of the maximum value of $p$.
Comment: @Avra $r$ has $n$ bytes, thus $8n$ bits.  Half of that is $4n$ so $p$ has up to $4n$ bits.  A number that's $4n$ bits long is proportional to $2^{4n}$.
Comment: @Avra Correct, assuming division can be done in $O(n)$ time as mentioned in the question.  I think this is a tiny bit smaller than the true cost, but it is true for very small divisors, and not that far from the truth.
Comment: Thank you! Got it. So again, if length of $p$ is at most half since $q>p$, then $p < \frac{\frac{log_2{n}}{8}}{2} = \frac{log_2{n}}{16} \frac{log_2{n}}{2^4}$. So I am not sure how you get $2^{4n}$ please?
Comment: Got it! Thanks. So since we have $2^{4n}$ possibilities and each take $n$ time to divide, so we have a total of $O(n\times 2^{4n})$?


Inhomogeneous linear transport equation Cauchy problem

Question: I am working through the first chapter of "Finite Difference Schemes and Partial Differential Equations" by Strikwerda and I am confused by this inhomogeneous problem (1.1.2):

Show that
$$
u_t +au_x = f(t,x)
$$
with $u(0,x) = 0$, $a>0$ a positive constant, and
$$
f(t,x) = \begin{cases}
        1, & \text{for } -1\leq x\leq 1\\
       0, & \text{otherwise.}
        \end{cases}
$$
has solution
$$
u(t,x) = \begin{cases}
\frac{1+x}{a}, & \text{if} & -1 \leq x \leq 1 &\text{and} & x-at\leq -1; \\
t, & \text{if} & -1 \leq x \leq 1 &\text{and} & -1 \leq x-at; \\
\frac{2}{a}, & \text{if} &  x \geq 1 &\text{and} & x-at\leq -1; \\
\frac{1-x+at}{a}, & \text{if} & x \geq 1 &\text{and} & -1 \leq x-at\leq1; \\
0, & \text{otherwise}
\end{cases}
$$

My initial approach was to use the formula derived for a general problem with $u(x,0) = u_0(x)$ given by $ u(t,x) = u_0(x-at) + \int_0^t f(s, x-a(s-t))\,ds$. For this particular problem, the formula would be $u(t,x) = \int_0^t f(s, x-a(s-t))\,ds$, but I am struggling on how to treat the integral given the source $f$ is limited to a region.
Is it possible to use this general formula by carefully considering the region in $u$-$t$ space to integrate? If so, any guidance on how? If not, any guidance as how to proceed? I have always had a difficult time with method of characteristics, so any help is appreciated.
Answer: The characteristic curves are the lines $x = x_0 + at$ along which $u = \int_0^t f(s, x_0 + a s) \, ds$, i.e.
$$
u(x,t) = \int_0^t f(s, x - a (t-s)) \, ds ,
$$
where we have used the initial condition $u(0,x)=0$. The change of variables $\xi = x - a (t-s)$ gives
\begin{aligned}
u(x,t) &= \frac1{a} \int_{x-at}^{x} f(t+(\xi-x)/a, \xi) \, d\xi \\
&= \frac1{a} \int_{\alpha}^{\beta} d\xi = \frac{\beta-\alpha}{a} ,
\end{aligned}
where we have restricted the domain of integration to its intersection $[\alpha,\beta]$ with the support of $f$ (i.e., the domain $\xi\in [-1,1]$ where $f$ is nonzero). Now, the restricted integration bounds $\alpha \geq x-at$ and $\beta \leq x$ have to be determined. This can be done simply by using set theory techniques, i.e. by writing the intersection as $$[\alpha,\beta] = [x-at,x] \cap [-1,1] .$$ Heuristically, we note that the integrand will be nonzero only for $-1\leq \alpha < \beta \leq 1$. Therefore, we find
\begin{aligned}
\alpha &= \min(\max(x-at,-1),1) ,\\
\beta &= \max(\min(x,1),-1) .
\end{aligned}
Now, if there is no mistake above, the correct result should have been obtained.
Comment: you are correct the $f(t,x)$ should be nonzero on $x\in[-1,1]$. I will make that change. For the limits of integration, could explain or point to a reference, how those are arrived at?
Comment: @Eilif Done, details added!


How do I execute an an anonymous method in the constructor declaration in C#?

Question: I have the following base class:
public class Baseclass
{
    public Baseclass(string anyparam)
    {
    }
}

I want to execute a lambda inside of the constructor of the child class:
public class Subclass : Baseclass
{
    public Subclass() : base(delegate()
    {
        string returnstring;
        // Do Something
        return returnstring;
    })
    {

    }
}

I don't want to waste any method on this, and I've not seen any example solving this without declaring the parameter type as func. How do I do this in C#?
Comment: This is a clear [XY-Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What are you *really* trying to achive, not how are you trying to achieve it.
Comment: What is wrong with a method? I like methods.
Comment: What is the actual question here?
Comment: "waste any method on this" -> For 'performance' reasons or conciseness reasons? If the latter; the readability more than makes up for the 'value' in saving keystrokes. If the former, do you have benchmarks? If for another reason, could you enlighten us?  What problem are you trying to solve?
Comment: See this: http://stackoverflow.com/questions/10763919/call-constructor-base-after-code-execution
Comment: Its just a simple *How do I do* to improve my knowledge of c#
Answer: You don't have to declare parameter as Func, you can create Func instance inline and call it:
public class Subclass : Baseclass
{
    public Subclass()
        : base((new Func<string>(() =>
                                 {
                                     const string returnstring = "a";

                                     // Do Something

                                     return returnstring;
                                 })()))
    {

    }
}

It it looks very ugly, can produce problems and I don't recommend it to you.
Comment: It's also not 'normal' C#.  Yes, it's possible, but it's not convention. I'd have to see the actual usecase the OP proposes to comment any more.  But to internet visitors coming from another language: This is not recommended in C#.
Comment: Yes, indeed. It is possible, but like I posted - I don't recommed that snippet. I strongly believe that the OP have badly designed classes if he/she is looking for such a solution.
Comment: Nothing about bad desing, it's just improving knowledge. I just recently used a statement lambda inside a collection.where() which I have found very useful
Comment: @LuckyLikey Don't do this in code bases with other developers; they'll likely ask "why did you do this?"
Comment: @GeorgeStocker there seems to be a missunderstanding, I only want to know how it may be done. I know doing this would produce many "WTF" from my colleagues  - **But anyway thank you for helping me**
Answer: I think the best you can do here is overload your base class constructor:
public class Baseclass
{
    public Baseclass(string anyparam)
    {

    }
    public Baseclass(Func<string> f):this(f())
    {

    }
}

public class Subclass : Baseclass
{
    public Subclass()
        : base(()=>
                {
                    string returnstring="foo";

                    // Do Something

                    return returnstring;
                })
    {

    }
}


Colimit of Disjoint Metric Spaces vs Topological Coproduct

Question: Let $\{X_i\}_{i=1}^{\infty}$ be a sequence of pairwise disjoint metric spaces.  Here we use the convention that a metric space can assume infinite distance.  Let Met be the category with metric spaces as objects and non-expansive maps as morphisms.  Let $F:Top\to Met$ be the forgetful functor, where Top is the category of topological spaces as objects with continuous maps as morphisms.
Then, unless I'm mistaken, the coproduct $\coprod_{i \in \mathbb{N}}^{Met} X_i$ in Met is the set-theoretic coproduct with metric given by
$$
d(f,g):=\begin{cases}
d_i(f,g): & f,g \in X_i\\
\infty :& else
\end{cases}
,
$$
where $d_i$ is the metric on $X_i$.  Let $\coprod_{i\in \mathbb{N}}^{Top} F(X_i)$ denote the coproduct in Top.  Is is the case that
$$
\coprod_{i \in \mathbb{N}}^{Top} F(X_i) \cong F\left(
\coprod_{i \in \mathbb{N}}^{Met} X_i
\right)
.
$$
Or have I made a mistake somewhere?
Answer: This is correct. You metric induces the topology of the disjoint union of topological spaces.
Comment: Thanks, I thought so, but I wanted to check I didn't make a silly overseight.


Increment variable in loop, unexpected result

Question: Code snippet:
int i=0;

for(int i=0;i<1;i++){
    i=--i-i--;
    System.out.println("for loop i= "+i);
}
System.out.println("i value outside for loop= "+i);

output:
for loop i= 0
i value outside for loop= 1

The value of i inside for loop is zero and outside for loop i is 1. Could you please help me understand it?
Comment: Note that you have two different `i` variables .
Comment: @Arnaud Not really. The correct thing to say is "this code won't compile". You can't have different variables with the same name within the same context, hence you cannot *have two different i variables*.
Comment: @BackSlash : You're right, then it would be better to have the actual code in the question.
Comment: Interestingly, the variable is block scoped to the for loop so in theory this code could be valid. If there is a Java compiler which accepts this code, then the loop is irrelevant. The i in the outer scope is never changed.
Answer: i=--i-i--; changes the value of i to -1 and then back to 0, because it assigns to it -1-(-1), which is 0. The reason for this result is that pre-decrement operator - --i - returns the decremented value -1 while post-decrement operator - i-- - returns the value prior to decrementing it (therefore it returns -1 instead of -2).
However, the loop's i++ clause increments i to 1, which causes the loop to terminate. Therefore the value of i is 1 after the loop.
Note that you have a typo in your question. You are declaring i twice in the same scope. In order for the code to pass compilation (and display the output you claim you got), you should change it to:
int i=0;

for (i = 0; i < 1; i++) {
    i = --i-i--;
    System.out.println("for loop i= "+i);
}
System.out.println("i value outside for loop= "+i);

Comment: And dropping the entire wonky `i=--i-i--;` will result in the exact same output, the 0 inside vs. 1 outside is just how `for` loops work.


how is cin and cout working in the below program?

Question: In the below program:
<code>#include <iostream>
using namespace std;

int main()
{
    char ch;
    while (cin >> ch){
        cout << ch;
    }
   return 0;
}
</code>
input : abcEnter
output : abc
Whatever I type on the keyboard gets printed only when I press Enter i.e. new line.
Why is not each character being printed simultaneously?
Which statement here takes the newline as an input and prints all the characters printed till now?
Comment: thats becuase cin is buffered - https://stackoverflow.com/questions/16732793/how-does-input-buffering-work-in-c
Comment: [Related, bordering on a duplicate](https://stackoverflow.com/q/421860/335858).
Answer: Your terminal doesn't send every new character as it's pressed; it waits for you to provide a whole line then sends it all in one go.
In the Linux world, this is called canonical mode.
If you want the result of your keystrokes to be immediately sent to whatever your terminal is connected to, turn off canonical mode.
I cannot tell you how to do that, however, as you did not say what your terminal is.
It is sometimes possible for the program itself to request that the terminal not use canonical mode (e.g. curses applications have to do this), but the manner in which this is achieved depends on your operating system — and, again, what your terminal is.


How do I make the ellipse move along my polynomial equation?

Question: My equation is located on the following url: https://www.desmos.com/calculator/7iewlnmfwv
Basically trying to make my ellipse move on my polynomial equation. Almost, like a roller coaster.
I'm aiming for the vertex of my ellipse to be on the line of my polynomial equation. As well as move along that line when the value is changed.
Answer: You have a long way to go on a long roller coaster ride ...First you have not defined the shape of your roller coaster path!
Second.. to describe rolling  on a straight path without slipping, go with an exercise on cycloid motion.
Thirdly, learn up what are  natural or intrinsic equations of curves.
Fourthly, find out connection between locus of ellipse focus and constant mean curvature curves or DeLaunay Unduloids.
Good Luck!
Comment: Oh I am sorry. I actually didn't want to create a literal roller coaster ride. But instead, have the vertex of my ellipse slide along the line of my polynomial function.


How to coach a player out of bad habits?

Question: The specific case I'm thinking of is throwing in quidditch (so think baseball, dodgeball, football, etc. mechanics). I'm hoping however to find a more general guiding principle if possible.
I coach a mix of players at different levels of athletic abilities, some come from other ball sports, some from others sports, some others had no prior sporting experience at all.
In the case of throwing mechanics, I try to teach with fairly simple methods, breaking down the movement in its components like in this answer. I have seen moderate progress with several players, but they seem to forget everything by the first couple of plays in a scrimmage or actual game.
Is there some recognized method or best practice for this sort of situation? Again, ideally a general approach would be great, but I'm happy with answers specific to throwing mechanics as well.
Answer: By using the principles outlined in "The Art of Learning" by Josh Waitzkin and "Body Mind Mastery" by Dan Millman, I have seen the greatest results from paying attention to Balance, movement minimization, and smoothness/rhythm.
These principles are at the foundation of T'ai Chi; finding their application to throwing is the mission of the learning process.
I suffered from the yips as a baseball player (had a mental block and couldn't throw the ball back to the pitcher as a catcher) and these principles helped me overcome the physical mistakes that accompanied the mental block.
Develop balance through every part of the throwing motion. You should be able to stop and remain perfectly still at any point of the throwing motion.
Use only the parts of your body relevant to throwing. My mistake with the yips was a very tense throwing arm (my bicep was fully flexed, which resulted in stopping my wrist mid-throw). I also had excess movement as a result of the tension and there was no rhythm.
Rhythm and smoothness comes from near effortless movement from the arm because your are balanced and not using any excess muscles.
Test balance regularly by pausing at different points of the motion. Try to slow the movement down to as slow as you can, maintaining balance, movement minimization, and smoothness. Once you can do so slowly, scale up to a more normal pace.


Fnished all the tasks in todo list

Question: I'm trying to make a to-do list program and  when the user finish a task it will a class named(finished) added to make a line through the task.. so I'm trying to make a button when all the tasks finished but the problem is I can't put class (finished) to all the task classes it's just added to one task class

let input = document.getElementById('input');
let addButtob = document.querySelector('.plus');
let noTasksMsg = document.querySelector('.no-tasks-mess');
let tasksContainer = document.querySelector('.tasks-content');
let count = document.querySelector('.count span');
let completed = document.querySelector('.tasks-completed span');
let empty = document.querySelector('.empty');
let deleteAll = document.querySelector('.delete-all');
let finishAll = document.querySelector('.finish-all');

window.input.focus();
addButtob.onclick = function () {
    if (input.value != '') {

        noTasksMsg.remove();
        let mainSpan = document.createElement('span');
        deleteSpan = document.createElement('span');

        let text = document.createTextNode(input.value);
        let deleteText = document.createTextNode('Delete');

        mainSpan.appendChild(text);
        mainSpan.className = 'tasks-box';
        deleteSpan.appendChild(deleteText);
        deleteSpan.className = 'delete';

        mainSpan.appendChild(deleteSpan);

        tasksContainer.appendChild(mainSpan);

        input.value = '';
        input.focus();
        count.textContent++;

    }

    else {
        empty.style.visibility = 'visible';
        input.focus();

    }

}

input.oninput = function () {

    empty.style.visibility = 'hidden';
}

document.addEventListener('click', function (e) {

    if (e.target.className == 'delete') {
        e.target.parentNode.remove();
        count.textContent--;
    }

    if (e.target.classList.contains('tasks-box')) {

        e.target.classList.toggle('finished');

        completed.textContent = document.querySelectorAll('.tasks-content .finished').length;
    }

    if (tasksContainer.children.length === 0) {

        tasksContainer.appendChild(noTasksMsg);
    }

});

deleteAll.onclick = function () {
    console.log(tasksContainer.innerHTML);

    tasksContainer.innerHTML = '';
    count.textContent = 0;
}

finishAll.onclick = function () {

    document.querySelector('.tasks-box').classList.add('finished');

}

*{
    box-sizing:border-box;
}

.todo-container {
    width:600px;
    margin: 30px auto 0;
    background: #8C4D70;
}

    .todo-container .add-task {
        background: #BF5E81;
        padding:15px;
        position:relative;
    }
        .todo-container .add-task input {
            width: calc(100% - 15px);
            padding: 9px 15px;
            display: inline-block;
            border: none;
            color: #fff;
            background: #F2C2CB;
            font-size:20px;
        }
            .todo-container .add-task input:focus {

                outline:none;
            }

        .todo-container .add-task .plus {
            position: absolute;
            width: 43px;
            height: 43px;
            background: #ffffff;
            color: #BF5E81;
            border-radius: 50%;
            text-align: center;
            line-height: 43px;
            font-size: 40px;
            font-weight:bold;
            right: 12px;
            cursor: pointer;
            transition: transform .2s;
        }

        .todo-container .add-task .plus:hover {

            transform:rotate(90deg);
        }

.tasks-content {

    padding:5px;
}
.no-tasks-mess {
    color: #F2C2CB;
}

.tasks-content > span {
    display: block;
    padding: 10px;
    background: #fff;
    margin: 10px;

}
.delete {
    float: right;
    background: #73435D;
    padding:3px 10px;
    border-radius: 4px;
    cursor:pointer;
    color:#fff;
    font-size:12px;
    font-weight:bold;
}
.tasks-status {
    width: 600px;
    padding: 8px 10px;
    margin-left: 30%;
    font-size: 12px;
}
    .tasks-status .count {
        float:left;
    }
    .tasks-status .tasks-completed {
        float:right;
    }

    .tasks-status .count span {
       background-color:#BF5E81;
       padding:1px 4px;
       border-radius:5px;

    }
    .tasks-status .tasks-completed span {
        background-color: #0460D9;
        padding: 1px 4px;
        border-radius: 5px;

    }

    .finished {
        text-decoration:line-through;
    }

.empty {
    position: absolute;
    color: red;
    text-decoration: overline;
    top:55px;
    font-size:15px;
    visibility:hidden;

}

button {
    background: #73435D;
    color: #fff;
    font-weight: bold;
    border: none;
    padding: 8px 10px;
    outline: none;
    font-size:12px;
    border-radius:5px;
    cursor:pointer;

}
.finish-all {

    float:right;
    margin-top:30px;
    margin-right:-85px;

}

.delete-all {
    float: left;
    margin-top: 30px;
    margin-left: -50px;
}

The Field is Empty!

            <input id="input"  type="text" />
            +

            NO TASKS TO SHOW

            Tasks
            0

            Complated
            0

        <button class="delete-all">Delete All</button>
        <button class="finish-all">Finished All</button>

... here is the code
Answer: Try this.
finishAll.onclick = function () {

    document.querySelectorAll('.tasks-box').forEach(e => {
        e.classList.add('finished');

    })

}

You used querySelector which takes only first of the class. If you use querySelectorAll you take a nodelist with doms which matches the selector you have.
Answer: Use this to change the class of every element:
document.querySelectorAll('.tasks-box').forEach( (node) => node.classList.add('finished') )

Fnished all the tasks in todo list


How do I change the site mail address?

Question: I want to change my site-wide email address. To do this, I changed the settings on admin/config/system/site-information. However, when I send an email from rules, it still uses the old email address.
How can I get the new email address to be picked up?
Comment: ok - under the Rules Settings, Advanced - try Recheck Integrity, and Rebuild Rules' Cache... if that doesn't change anything, try add a system message with the token and see what it gives
Comment: I deleted my old comments, just to clean this up - well, we're narrowing it down. Does it happen for both html mail and the core mail?  try adding the token to the body of the message
Comment: it is sounding like a bug in Rules, or at least the mail implementation in Rules. I would suggest creating an issue in the issue queue for Rules, but I am nearly out of ideas - the only other thing that comes to mind - are you using a template for the mail, and to check the template to make sure it is set up properly
Comment: @Geoff 1. I cleared cache and ran Cron. 2. I am using HTML Mail and regular email. 3. In Rules it says, "leave blank to use site-wide email address:, so I left it blank. However, I have also done experiment with the built in Rules token of: `[site:mail]` and creating my own token, but it's the same issue 4. Here is the URL of the rule export: http://pastebin.com/p3tRAW9K
Comment: @Geoff I am not using tokens for any of the email addresses in TO or FROM. The reason there are two addresses in TO is for debugging reasons, but it still uses the old site-wide address for FROM even when TO has only 1 address. For FROM I am not entering any email address, as if you leave it blank, it is supposed to use the default. However, it just uses the old default (even when I use a token, it still uses the old default).
Comment: @Geoff When I use `site:mail` in body text (on a node) it is correct. But in rules, it prints the old address.
Comment: @Geoff Thanks, I have rechecked Rules Integrity and Rebuilt Rules Cahce. The token works in the system message, but not in the email sender field.
Comment: @Geoff It happens for both core and HTML mail. If I put the token in the body, it prints fine, but for the "From" field it reverts to the old email address. If I hardcode (e.g. by typing it) the address, it works fine. However, I'd rather user a token, just incase it changes in the future.
Comment: @Geoff. No, I am not using any template. As it does seem to be a Rules bug, please could you post that as your answer and I can mark it as correct.
Answer: Based on the comments, and narrowing down the problem to the Rules module itself, or its integration with the mail system:

Tokens work elsewhere
Tokens within the body of the message work but not the from field
No templates are used
Core mail as well as third-party mail are affected
Clearing the cache, including the rules one, had no effect

It would appear to be a bug in the Rules module or the mail delivery part of it. I would suggest adding an issue to the Rules issue queue and see if they can further explore options for correcting the problem.

How do I change the site mail address?


Can a deep neural network approximate multiplication function?

Question: Let's say we want to do regression for simple f = x * y using standard fully-connected deep neural network. The network takes x and y as input, and should learn to output x * y.
I remember that there is research proving that NN with one hidden layer can approximate any function, but I have tried and was unable to approximate even this simple multiplication.
Only log-normalization of the data helped m = x*y => ln(m) = ln(x) + ln(y) because it turns multiplication into addition, but that looks like a cheat. Can NN do this without log-normalization?
The answer seems to be Yes, so the question is more what should the type/configuration/layout of such NN be?
Answer: NN with relu activation function can approximate multiplication when range of inputs is limited. Recall that relu(x) = max(x, 0).
It is enough if NN approximates a square function g(z) = z^2, because x*y = ((x-y)^2 - x^2 - y^2)/(-2). Right-hand side has just linear combinations and squares.
NN can approximate z^2 with a piecewise linear function. For example, on range [0, 2] a combination of x and relu(2(x-1)) is not that bad. Below figure visualises this. No idea if this is useful beyond theory :-)
Answer: A big multiplication function gradient forces the net probably almost immediately into some horrifying state where all its hidden nodes have a zero gradient (because of neural network implementation details and limitations). We can use two approaches:

Divide by a constant. We are just dividing everything before the learning and multiply after.

Use log-normalization. It makes multiplication into addition:
\begin{align}
m &= x \cdot y\\
&\Rightarrow  \\
\ln(m) &= \ln(x) + \ln(y)
\end{align}
Answer: I'm unable to comment due to being a newly active user on StackExchange.  But I think this is an important question because it's so friggin simple to understand yet difficult to explain.  With respect, I don't think the accepted answer is sufficient. If you think about the core operations of a standard feed-forward NN, with activations of the form s(W*x+b) for some nonlinear activation function s, it's actually not obvious how to "get" multiplication from this even in a composed (multi-layered) network.  Scaling (the first bullet in accepted answer) does not seem to address the question at all ... scale by what?
 The inputs x and y are presumably different for every sample.  And taking the log is fine as long as you know that's what you need to do, and take care of the sign issue in preprocessing (since obviously log isn't defined for negative inputs).  But this fundamentally doesn't jive with the notion that neural networks can just "learn" (it feels like a cheat as the OP said).  I don't think the question should be considered answered until it really is, by someone smarter than me!
Comment: The accepted answer indeed does not answer the question, but the answer by @JussiKujala does.
Answer: A similar question struck me earlier today, and I was surprised I couldn't find a quick answer. My question was that given NN's only have summation functions, how could they model multiplicative functions.
This kind of answered it, though it was lengthy explanation. My summary would be that NN's model the function surface rather than the function itself. Which is obvious, in retrospect…
Comment: "The surface" is properly called an "envelope."
Answer: Traditional neural network consists of linear maps and Lipschitiz activation function. As a composition of Lischitz continuous functions, neural network is also Lipschitz continuous, but multiplication is not Lipschitz continuous. This means that neural network cannot approximate multiplication when one of the x or y goes too large.
Comment: @alvitawa A complete understanding of Lipschitz continuity requires a rigorous training in elementary analysis, which is far beyond the scope of most machine learning materials.

Lipschitz continuity more or less means having bounded slope.  Let's make our life easier. Assume we want to approximate f(x) = x^2 with sigmoid as our activation function so that everything is differentiable. The composition of function of bounded slope is of bounded slope, which indicates that neutral network is of bounded slope. While for f(x) = x^2, you can see the slope becomes larger as x goes to infinity.
Comment: Something of bounded slope will always deviate something with unbounded slope when things go to infinity, i.e. neural network cannot even approximate f(x) = x^2.
Comment: Where can I learn more about Lipschitz continuity? So that I can understand why neural networks are and multiplication is not lipschitz continuous.
Answer: "one hidden layer" does not limit the number of neurons and kinds of activate function used, it still has a large representation space. One simple method to validate the existence of this problem: Train this regress problem with a real neuron network, record each weights and bias, use these parameters plot the predict curve, contrast it with the target function curve.
This essay may help.
Answer: Feed-forward REUL, will never be able to learn multiplication exactly or approximately with absolute bounded error, if numbers are unbounded.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Why $A_{t-1}$ in reinforcement learning history $H_t = O_1, R_1, A_1, ..., A_{t-1}, O_t, R_t$?

Question: I learn with David Silver's slides reinforcement learning. His definition of the history $H_t$ is:
$H_t = O_1, R_1, A_1, ..., A_{t-1}, O_t, R_t$
$O =$ observations
$R =$ rewards
$A =$ actions
Why do we have $A_{t-1}$ and not $A_t$?
Comment: Have you transcribed the start of $H_t$ correctly? I would expect to either see $O_0, A_0, R_1,$ at the start or $O_1, A_1, R_2$ - please could you reference the specific lecture and slide number, because your current link is to a page with many different lectures and many different slides for each lecture, and I don't want to search through them all to discover your reference
Comment: [Slide 18](https://www.davidsilver.uk/wp-content/uploads/2020/03/intro_RL.pdf). I transcribed the start of $H_t$ correctly. @NeilSlater
Answer: David Silver has chosen not to include the action taken at time $t$ because the history is being referenced so that the agent can choose $A_t$.
The observation $O_t$ is available because the agent has just arrived at time step $t$ and received the observation. It needs to make a decision on what to do next.
Histories at other stages of the process exist in principle. E.g. just after taking the action, but before receiving the immediate reward and next state is a valid point to construct a history of the trajectory so far. However, it is a less useful history when considering what inputs you have available for a policy function.
Comment: Okay, so it can be written also like this $H_t = O_1, R_1, A_1, ..., A_t, O_{t+1}, R_{t+1}$ if I understand you correctly?
Comment: @MaxHager Yes, but only if you wanted to consider the choice of action at $A_{t+1}$ - it would be more natural to consider action choice at time $t$ then write the history definition to match, than to decide to stop the trajectory at time $t+1$ just before action choice, so that there isn't an awkward-looking $t-1$ in the summary of the trajectory


Erro ao salvar dados de uma sessão no banco

Question: Estou desenvolvendo um sistema de vendas. Segue o link:
Salvar Pedido - ASP.NET MVC
Porém ao finalizar a compra e salvar os dados no banco, eu recebo o seguinte erro:

"An entity object cannot be referenced by multiple instances of IEntityChangeTracker"

Como posso resolver isso?
public ActionResult SalvarCarrinho()
{
    var carrinho = Session["Carrinho"] != null ? (Pedido)Session["Carrinho"] : new Pedido();

    contexto.Pedidos.Add(carrinho);
    contexto.SaveChanges();

    return RedirectToAction("Carrinho");
}

Dá erro nesta linha:
 contexto.Pedidos.Add(carrinho);

Código completo do Controller:
public ActionResult AdicionarCarrinho(int id)
{
    Pedido carrinho = Session["Carrinho"] != null ? (Pedido)Session["Carrinho"] : new Pedido();

    var produto= db.Produto.Find(id);

    if (produto != null)
    {
        var itemPedido = new ItemPedido();
        itemPedido.Produto = produto;
        itemPedido.Qtd = 1;

        if (carrinho.ItemPedido.FirstOrDefault(x => x.IdProduto == produto.IdProduto) != null)
        {
            carrinho.ItemPedido.FirstOrDefault(x => x.IdProduto == produto.IdProduto).Qtd += 1;
        }
        else
        {
            carrinho.ItemPedido.Add(itemPedido);
        }

        carrinho.ValorTotal = carrinho.ItemPedido.Select(i => i.Pedido).Sum(d => d.Preco);

        Session["Carrinho"] = carrinho;
    }

    return RedirectToAction("Carrinho");
}

public ActionResult Carrinho()
{
    Pedido carrinho = Session["Carrinho"] != null ? (Pedido)Session["Carrinho"] : new Pedido();

    return View(carrinho);
}

public ActionResult Remover(int id)
{
    var carrinho = Session["Carrinho"] != null ? (Pedido)Session["Carrinho"] : new Pedido();
    var itemExclusao = carrinho.ItemPedido.FirstOrDefault(i => i.IdItemPedido == id);
    carrinho.ItemPedido.Remove(itemExclusao);

    Session["Carrinho"] = carrinho;
    return RedirectToAction("Carrinho");
}

public ActionResult FinalizarCarrinho()
{
    var carrinho = Session["Carrinho"] != null ? (Pedido)Session["Carrinho"] : new Pedido();

    var id = Convert.ToInt32(Session["IdUsuario"]);
    var usuario = db.Usuario.FirstOrDefault(u => u.IdUsuario == id);
    carrinho.DtPedido = DateTime.Now;
    carrinho.Usuario = usuario;
    carrinho.StatusPedido = "esperando pagamento";
    carrinho.TipoPag = "boleto";
    db.Pedido.Add(carrinho);
    db.SaveChanges();

    return RedirectToAction("Carrinho");
}

Comment: Agora você coloca o código que está dando problema no corpo da pergunta, por favor.
Comment: Acredito que seja o fato de haver mais de um contexto em algum lugar. O código não é claro quanto a isso. Como está a declaração dos contextos?
Comment: ta ai o código.
Comment: você quer ver as classes pedido etc?
Comment: Não, eu quero o código do *Controller*.
Comment: Não utilizei a guid pois o IdItemPedido é gerado sozinho pelo banco de dados.
Comment: já atualizei com oque você pediu.
Answer: Não lembro se disse isso em outra resposta, mas possivelmente a causa do problema é isto:
var itemPedido = new ItemPedido();
itemPedido.Produto = design; // Aqui você definiu um Produto (e de forma errada)
itemPedido.Qtd = 1;
itemPedido.IdProduto = produto.IdProduto; // Então aqui vai dar problema

Considerando ainda que você tomou a decisão de utilizar Id como inteiro sequencial, a chance de confundir o Entity Framework é grande. Explico:
Ao definir uma Id desta forma:
itemPedido.IdProduto = produto.IdProduto;

Você está forçando num objeto não mapeado em contexto uma Id de um objeto mapeado em contexto. E aqui:
itemPedido.Produto = design;

Você está colocando um outro objeto (que eu não sei de onde veio, porque possivelmente é uma colagem de outra resposta que eu dei) que eu não sei se está mapeado no contexto ou não. Fazendo isto, você está basicamente criando um produto que não existe (ou pelo menos o contexto entende assim), porque é a Id de um objeto com o conteúdo de outro objeto.
Neste caso, preencher itemPedido.IdProduto é totalmente desnecessário, visto que você já está preenchendo itemPedido.Produto. Deve-se evitar preencher um Id de chave estrangeira diretamente, pois o Entity Framework pode entender que é um objeto novo (muito provável que seja este o seu problema) e inserir no banco de dados algo que não deve.
Mesma coisa pra este código:
carrinho.IdUsuario = Convert.ToInt32(Session["IdUsuario"]);

O correto é você selecionar o usuário e atribuir o objeto de Usuario ao carrinho, para que o Entity Framework entenda de onde esse usuário veio:
var usuarioId = Convert.ToInt32(Session["IdUsuario"]);
var usuario = db.Usuarios.FirstOrDefault(u => u.IdUsuario == usuarioId);
carrinho.Usuario = usuario;

EDIT
Baseado nos comentários, aparentemente os objetos que vão para a sessão estão guardando a referência de um contexto que não existe mais, então antes de inserir produtos no pedido, faça o seguinte:
var produto = db.Produto.Find(id);
db.Entry(produto).State = EntityState.Detached;

if (produto != null)
{
    var itemPedido = new ItemPedido();
    itemPedido.Produto = produto;
    itemPedido.Qtd = 1;

    ...

Isto garante que você estará trabalhando com objetos destacados de contexto.
Pra salvar, você precisa recolocar os objetos no contexto:
public ActionResult FinalizarCarrinho()
{
    var carrinho = Session["Carrinho"] != null ? (Pedido)Session["Carrinho"] : new Pedido();

    var id = Convert.ToInt32(Session["IdUsuario"]);
    var usuario = db.Usuario.FirstOrDefault(u => u.IdUsuario == id);

    foreach (var itemPedido in carrinho.ItemPedido) {
        db.Produtos.Attach(itemPedido.Produto);
    }

    carrinho.DtPedido = DateTime.Now;
    carrinho.Usuario = usuario;
    carrinho.StatusPedido = "esperando pagamento";
    carrinho.TipoPag = "boleto";
    db.Pedido.Add(carrinho);
    db.SaveChanges();

    return RedirectToAction("Carrinho");
}

Não testei essa solução, mas creio que deve funcionar.
Comment: Agora funcionou. Muito obrigado mesmo, salvou minha pele aqui.
Comment: Retirei as outras linhas, e deixei somente essa: itemPedido.Produto = produto mas continua dando o mesmo erro. Vou postar como está o codigo atualmente.
Comment: Atualizei da forma que você indicou, mas o erro continua.
Comment: Ainda tenho uma dúvida: onde fica e como você inicializa esse contexto? A impressão que dá é que ele está sendo inicializado N vezes, que é o que o erro diz.
Comment: Não sei se eu entendi muito bem. Mas eu chamo as classes do banco de dados através dessa linha que eu defini no inicio do controller: private Entidades db = new Entidades();
Comment: Acho que já sei o que é. Vou editar a resposta.
Comment: @GuilhermeVinicius Veja agora.
Comment: Esses "métodos" attach e dettach tem que fazer alteração nas classes, porque ele não tá reconhecendo e da erro nessa linha?
Comment: Verdade. Veja agora.
Comment: cara o attach ele achou mas o dettach não.
Comment: @GuilhermeVinicius Mudaram a sintaxe. Use `db.Entry(produto).State = EntityState.Detached;`.


What is it called when a music has two concurrent tempos

Question: I've recently watched a BBC documentary about the history of music and recall an episode where they talk about music that has two distinct tempos (and possibly time signatures) at the same time for different sets of instruments.
Still, I can't remember how this is called and who are the famous composers that composed that way (Stravinsky?).
Comment: @Mark: Polyrhythm and polymeter share either the same beat/pulse, or the same measure division. If it's truly different tempos, it sounds like neither. Steve Reich has used this technique, having similar or the same melodic figures, but with slightly different tempo playing against each other. These effects are not easily described by a ratio, which polyrhythms usually use.
Comment: "The Unanswered Question" is the only thing I can think of that uses the technique and it's not really a technique in this piece. It's more of a statement that the three different ideas are not synced up kind of like walking into a room and hearing different conversations about the same topic: https://www.youtube.com/watch?v=kkaOz48cq2g
Comment: @RockinCowboy I think your example could fall under the 'Polyrhythm' category; From what I understood, Op is looking for something like woodwinds at 100 and brass at 135
Comment: @Shevliaskovic most likely you are right.  But more clarification from OP might prevent others from going off track with future answers.
Comment: Related: http://music.stackexchange.com/questions/14410/the-harmony-of-clashing-tempos
Comment: Here are a couple of non-classical examples (from 1985 and 1989 respectively): [The Fall](https://www.youtube.com/watch?v=ijuJhyUfhDQ) and [Nine Inch Nails](https://www.youtube.com/watch?v=WAGAoy5WZWY).
Comment: Do you mean different sets of instruments are each being played at different tempos?  In other words, the woodwinds are perhaps playing at 100 Bpm and the brass is playing at 200 Bpm or something like that?
Answer: The answer here is deceptively simple: Polytempo.  There are other names, such as multi-tempo, polytemporal, and others, but they all describe the same phenomena.
Here is a link for further reading on Wikipedia.
For a list of composers that have used this technique, as well as the pieces in which this technique was used, check out this page and look under "Compositions".

I want to clarify for everyone that Polyrhythm and Polymetric are both incorrect here.  Polyrhythms are multiple, independent rhythmic lines (typically ostinatos) that can form a hemiola or hemiola-like effect in music.  Polymeters are ways of organizing the beat.  Tempo is the speed of the beat, not how it is organized, or the rhythms that it defines.
Here is a wonderful Q/A from this very website that addresses the difference: Polymeter vs Polyrhythm
Comment: @luserdroog Pick your poison, they all get you to the same place. English is wonderful for butchering other languages and cultures. :)
Comment: *multitempo* has a more consistent derivation (Italian), while *poly-* is a greek prefix. *Polychronic*?
Answer: This sort of thing has been explored pretty deeply by, among other people, Conlon Nancarrow. He used player pianos to perform pieces which would most likely have been too complex for anyone to perform organically. One way in which he complicated things was that he used what he called a tempo canon. As discussed here, one such piece was his Study for Player Piano 41a. It used multiple voices, each with its own tempo and the ratios were on a strict, but irrational ratio. If the ratio between tempos was rational, it would line up, or converge, so that two notes could fall at the same time. However, if the ratio was irrational, they would never converge and dance around each other until the piece ended.
This basic concept, although the effect can be jarring, is really not very different from polyrhythms and polymeters. It's just obfuscated by using complicated ratios. For example, if you have a bar and a main voice hit four evenly spaced beats, you have the standard quarter note pulse in 4/4. You can fit 3 notes evenly into that same bar in a second voice and the second voice will be playing half-note triplets. For every four notes in the main voice and every three notes in the second voice, the voices will play together. That's your bar. And that's a polyrhythm. That would be a 4:3 ratio. I'm not sure that's how it's typically notated, but the idea translates. You can imagine how this can be seen as two voices at different tempos. Say maybe one voice in 4/4 at 120 and another voice in 3/4 at 90. They would line up the same way.
Here's another example. If your main voice plays 8 eighth notes before repeating and your second voice plays 7 eighth notes before repeating, they will line up every 56 (7×8) eighth notes. In other words, after your main voice repeats seven times and your second voice repeats eight times. That's a polymeter. Now you can see how these concepts can get mixed up. As the ratios get more complicated (ie 128:73) or less rational (ie √2:φ), the tempos line up less and less and the individual tempos will get closer and/or less distinguishable. That is where you cross the line into tempo canon territory.

Note: I understand that 'irrational ratio' is a terrible oxymoron, but
  I can't think of better terminology. Also, this is just the one conceptualization of
  the multiple tempo idea. There is world music where this is done organically and many
  people have already mentioned other composers who have worked with the idea. But hopefully this helps.
Comment: It's not an oxymoron. sqrt(2) : sqrt(3), for example, is irrational and also a ratio.
Comment: I understand. I'm just referring to how the root word of rational is ratio. So etymologically, an irrational ratio might be a ratio which is not a ratio. At least that's how I see it. The ideas are still there regardless.
Comment: "Rational" refers to a ratio between two integers, so the concepts of being rational and being a ratio are sort of different. I see your point, though :)
Answer: There is both polymeter and polyrhythm.

Polymeter is sometimes referred to as "tactus-preserving polymeter." The measure size differs, the beat is the same. Since the beat is the same, the various meters eventually agree.

https://en.wikipedia.org/wiki/Meter_%28music%29#Polymeter
A good example of polymeter is the Tala which is an extream form of complex time.

Polyrhythm is the simultaneous use of two or more conflicting rhythms, that are not readily perceived as deriving from one another, or as simple manifestations of the same meter. The rhythmic conflict may be the basis of an entire piece of music (cross-rhythm), or a momentary disruption. Polyrhythms can be distinguished from irrational rhythms, which can occur within the context of a single part; polyrhythms require at least two rhythms to be played concurrently, one of which is typically an irrational rhythm.

https://en.wikipedia.org/wiki/Polyrhythm
Commonly used in modren Jazz.  See: Mongo Santamaria and Elvin Jones.
Comment: Polyrhythm is wrong as an answer here; the quote you provided states exactly what it is, which is not what OP asked. Polyrhythm is different rhythms, but same tempo
Answer: Neilsen's 5th symphony was an early example (1922). Towards the end of the first movement, the side drum part is in a different tempo and time signature from the rest of the orchestra. The first edition of the score instructed the drummer to "improvise as if at all costs he wants to stop the progress of the orchestra".
In a later edition that instruction was replaced by a written part which breaks off with the direction "cadenza ad lib".
Skip to about 14:45 here:

 (There is also an important side drum part in a more "conventional" rhythm earlier in the piece.


Can anyone help me to identify these piano notes

Question: Im having trouble figuring this out. What is it called, and how do you play it?
Thank you for all the help!
Answer: It's a series of upward arpeggios.  The implication is that you should play the notes in the lower staff with your left hand, the ones in the upper staff with your right hand.  Hence the need for extra clefs.
It's a Dm7 chord then a G chord. We're told to 'change' the pedal when the chord changes - lift it so that the Dm7 is no longer sustained, put it straight down again to start sustaining the G.
Here's another (not necessarily better) way to notate it.
Answer: They're 32nd notes with a gazillion ledger lines and left-hand clef changes. You can tell they're 32nd notes because they all have 3 horizontal-enough beams.
The ledger lines are for the top staff for all notes with stems pointing down and for the bottom staff for all notes with stems pointing up (which is only the bottommost note with a ledger line).
Even worse, there's a damper-pedal-up marking followed by a damper-pedal-down marking at the second clef change.
Comment: Damper ped. change is because there's a different chord.


TNS:could not resolve the connect identifier specified at OCI call OCIServerAttach

Question: I am working on OBIEE-12c. My db is also Oracle-12c. During repository creation i am getting following error.
[nQsError:17014] Could not connect to Oracle database.
[nQsError:17001] Oracle Error code: 12154, message: ORA-12154:
TNS:could not resolve the connect identifier specified
at OCI call OCIServerAttach.

Comment: 1. Is listener of DB you're connecting up and running? 2. Is TNS_ADMIN variable pointing to proper location of tnsnames.ora? 3. Does tnsnames.ora contain TNS entry for DB you're trying to connect?
Comment: Yes all of your points you are saying are done on my side moreover i have  made tnsping to my service and it is also working.
Comment: I have connected now through this string localhost:1521\pdborcl. make sure with slash if it is / or \.
Answer: Have you tried writing the full connection string, as it appears in the tnsnames.ora file, instead of just the name??
Instead of writing pdborcl write:
(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = pdborcl))
  )

Or whatever your connect string looks like.
I'm not sure why that happens but i couldn't make my work until I did that.
Comment: I have connected now through this string localhost:1521\pdborcl. make sure with slash if it is / or \.
Answer: to resolve the issue, try the following
(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = <what ever SID you specified>)))
log : anonymous
P/w : < the password you specified when creating the Database>

Comment: Exactly the same answer as given by @Lando, 4 months ago.


Ruby metaprogramming, how does RSpec's 'should' work?

Question: I was reading up on RSpec and I was trying to figure out how RSpec's "should" was implemented.
Could someone give a hand on how the meta nature of this function works?
The code is located here:
http://github.com/dchelimsky/rspec/blob/master/lib/spec/expectations/extensions/kernel.rb
TIA,
-daniel
Clarification:
target.should == 5

How did target's value get passed along to "should", which in turn was "=="'d against 5?
Answer: Take a look at class OperatorMatcher.
It all boils down to Ruby allowing you to leave out periods and parenthesis.  What you are really writing is:
target.should.send(:==, 5)

That is, send the message should to the object target, then send the message == to whatever should returns.
The method should is monkey patched into Kernel, so it can be received by any object.  The Matcher returned by should holds the actual which in this case is target.
The Matcher implements the method == which does the comparison with the expected which, in this case, is the number 5.  A cut down example that you can try yourself:
module Kernel
  def should
    Matcher.new(self)
  end
end

class Matcher
  def initialize(actual)
    @actual = actual
  end

  def == expected
    if @actual == expected
      puts "Hurrah!"
    else
      puts "Booo!"
    end
  end
end

target = 4
target.should == 5
=> Booo!

target = 5
target.should == 5
=> Hurrah!

Comment: Thanks fo a great little explanation that not only answers the question but is a nice summary of some mechanisms in Ruby. For people new to Ruby, be aware that the last expression in a function is implicitly the return value, so should above would in C++ be
Matcher* Kernel::should()
{
  return new Matcher(this);
}
Comment: First: Very good answer, thanks a lot! Two quick observations: instead  of defining "should" on the Kernel module, you could do it on the class Object. I find it safer, as it's less generic. The second thing is that you don't need metaprogramming to define the method ==. You can just define it as any other normal method, so that it's easier to read: def ==(expected)
Comment: Thanks @Nicholas, I have updated my answer with your suggestion.


Determining the "variability" of a benchmark

Question: I have a software benchmark which is quite noisy. I am trying to for the bugs which are causing the noise, and I need to be able to measure it somehow.
The benchmark is comprised of a number of subbenchmarks, for example:
"3d-cube": 31.56884765625,
"3d-morph": 21.89599609375,
"3d-raytrace": 51.802978515625,
"access-binary-trees": 15.09521484375,
"access-fannkuch": 45.578857421875,
"access-nbody": 8.651123046875,

The times are in milliseconds. The times typically vary between runs. For example, on my machine, the "3d-cube" benchmark tends to take around 35ms, but I've seen it go as high as 44ms, and 31ms (above) is uncharacteristically low.
My aim is to change the benchmark so that minor improvements to the run-time can be visible in a benchmark result. What I need is a number that tells me whether I have reduced the "variability" of the benchmark.
My own solution
I run it the benchmark 1000 times, the took the sum of the differences between each subbenchmark's mean and its actual run-times. In pseudo-code:
v = 0
for s in subbenchmarks:
  x = mean of all iterations of s
  for i in iteration
    v += absolute_value(results[s][i] - x)

I'm sure this isn't statistically valid (having asked someone), but what is a "correct" way of measuring this "variability" so that I can reduce it.
Comment: An amusing observation: all your benchmark times are multiples of 2^-12 (=1/4096).
Comment: @whuber: you're clearly spending too much time on stats.SE :P
Comment: @whuber: must be the maximum resolution - a quarter of a microsecond ain't bad! 22-bits resolution-ish?
Answer: As gd047 mentioned, the standard way of measuring variability is to use the variance. So your pseudo-code will be:
vnew = vector of length subbenchmarks
for s in subbenchmarks:
  vnew[i] = variance(s)

Now the problem is, even if  you don't change your code, vnew will be different for each run - there is noise. To determine if a change is significant, we need to perform a hypothesis test, i.e. can the change be explained as random variation or is likely that something has changed. A quick and dirty rule would be:
\begin{equation}
Y_i = \sqrt{n/2} \left(\frac{vnew_i}{vold_i} -1\right) \sim N(0,1)
\end{equation}
This means any values of $Y_i < -1.96$ (at a 5% significance level) can be considered significant, i.e. an improvement. However, I would probably increase this to -3 or -4. This would test for improvement in individual benchmarks.
If you want to combine all your benchmarks into a single test, then let
\begin{equation}
\bar Y = \frac{1}{n} \sum Y_i
\end{equation}
So
\begin{equation}
\sqrt{n} \bar Y \sim N(0, 1)
\end{equation}
Hence, an appropriate test would be to consider values of $\bar Y < 1.96$ to indicate an improvement.

Edit
If the benchmarks aren't Normal, then I would try working with log(benchmarks). It also depends on what you want to do. I read your question as "You would like a good rule of thumb". In this case, taking logs is probably OK.

Further details of the mathematical reasoning are found at Section 3.2 of this document.
I've made a approximation by assuming that v_old represents the true underlying variance.
Comment: I'm told that the results of the benchmarks (the times in ms) are not normally distributed. Will the variances be normally distributed? How does that affect the choice of 1.96?
Answer: I guess that your method is the one described here, and it's apparently valid. You could also have used the standard deviation as a measure of variability (which according to the article, it's not as robust as your absolute deviation)
Check out this, for other measures of statistical dispersion.
Comment: A strong case can be made for robust techniques that do the opposite of "punishing" outliers, because outliers in benchmarks often occur unavoidably due to other processes and external perturbations causing a process to wait from time to time.  This could be the reason the benchmarks do not appear to be normally distributed, too.  However, as cgillespie's answer points out, you can go a long way with the standard hypothesis testing machinery applied to SDs.  As a compromise, a lightly Winsorized version of the SD might be a good choice.  (http://en.wikipedia.org/wiki/Winsorising )
Comment: I would go with variance and/or standard deviation (sd is just the square root of the variance) instead of the absolute deviation, because variance and sd punish extreme outliers stronger. This seems desirable in your case.
Comment: When I go with standard deviation or variance, I come up with the problem of how to combine the results for the subbenchmarks into a whole. Absolute variance (assuming that's what I did) gives me a single number.
Comment: Note that I tried to combine my sub-variances using "the variance of the total is the mean of the variances of the subgroups + variance of the means of the subgroups", which I got from http://en.wikipedia.org/wiki/Variance.


PHP cli script for flushing drupal cache

Question: So I have created script that flushes drupal's cache and it's ran in CLI.
The problem is after first use, I can't use the script again, because some classes ('SelectQueryExtender' or 'DrupalDefaultEntityController') are missing. Clearing cache via drupal admin menu (admin_menu/flush-cache) fixes it and I can rerun.
Now the question is why clearing cache from via HTTP works and from CLI doesn't?
I'm running on Drupal 7 and code can be found below:
define('DRUPAL_ROOT', '/srv/www/'); // Drupal root folder.

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Clear cache.
drupal_flush_all_caches();

EDIT: when I clear cache via drupal_flush_all_caches and later make curl call for cache clearing through apc-status.php, then even website itself gives Fatal on above mentioned classes missing.
Comment: Your code has syntax errors, it won't run until you fix those
Comment: Thanks, but that's not the case as DRUPAL_ROOT part was only line that was not copied.
Comment: why are you not using drush ?
Comment: I don't see a necessity of having one big tool for such a minor thing and also I would like, actually need to know the logic behind this behaviour.
Comment: Okey, apperantly I had script starting on wrong folder thus breaking modules search. Basically for drupal_flush_all_caches() to work (or registry_rebuild to be more percise), script would need to be at same place where DRUPAL_ROOT is located or chdir(DRUPAL_ROOT); should be used after drupal_bootstrap.

Next time I will add more code as this wasn't informative enough.
Comment: @R.P If you'd be good enough to summarise what you did to make the fix in an answer that'd be great - this is a Q+A site after all :) Answering your own question is encouraged as it might help someone out with the same problem in the future, and comments are likely to be deleted without much notice
Answer: Install Drush. It's your friend. Then you can issue
drush cc all

To clear caches.
You can also rebuild registries if needed to if you have that module installed.


Editar status de vários registros com checkbox marcado?

Question: Preciso enviar um array com os id dos registros que tiverem o checkbox marcado, para editar de uma só vez o campo status.
Nota1: todos registros sofrerão a mesma alteração listada em um select.
Nota2: consigo editar cada registro individualmente através de um link com o seu id respectivo.
<form action="<?php echo current_url(); ?>" id="formExportacao" method="post" class="form-horizontal" >
  <?php echo form_hidden('idExportacao',$result->idExportacao) ?>

   Status*

       <select class="span3" name="status" id="status" value="">
       <option <?php if($result->status == 'Faturado'){echo 'selected';} ?> value="Faturado">Faturado</option>
       <option <?php if($result->status == 'Finalizado'){echo 'selected';} ?> value="Finalizado">Finalizado</option>
       <option <?php if($result->status == ''){echo 'selected';} ?> value="Não Faturado">Não faturado</option>
      </select>

   <button type="submit" class="btn btn-primary"> Alterar</button>
   <a href="<?php echo base_url()?>index.php/exportacao" id="btnAdicionar" class="btn"> Voltar

</form>

Controller: Exportacao.php
Essa função é adaptada da função "editar individualmente"
A função editarStatus será só para o status, e a outra caso haja algum dado inserido errado, podendo alterar todos seus campos, mas isso já tá resolvido.
function editarStatus() {

    $this->load->library('form_validation');
    $this->data['custom_error'] = '';

    if ($this->form_validation->run('exportacao') == false) {
        $this->data['custom_error'] = (validation_errors() ? '
' . validation_errors() . '
' : false);
    } else {
        $data = array(
            'status' => $this->input->post('status')
        );
        if ($this->fatexpo_model->editStatus('exportacao', $data, 'idExportacao', $this->input->post('idExportacao')) == TRUE) {
            $this->session->set_flashdata('success', 'Registro editado com sucesso!');
            redirect(base_url() . 'index.php/exportacao/editarStatus/'.$this->input->post('idExportacao'));
        } else {
            $this->data['custom_error'] = '

Ocorreu um erro.

';
        }
    }

    $this->data['result'] = $this->fatexpo_model->getById($this->uri->segment(3));
    $this->data['view'] = 'exportacao/editarExpoStatus';
    $this->load->view('tema/topo', $this->data);

}

Model: fatexpo_model.php
function editStatus($table,$data,$fieldID,$ID){
    $this->db->where($fieldID,$ID);
    $this->db->update($table, $data);

    if ($this->db->affected_rows() >= 0)
    {
        return TRUE;
    }

    return FALSE;
}

Na página da minha tabela, eu consigo exibir os ids marcados pelo checkbox dessa maneira:
<button onclick='pegaIDs()'>Pegar IDs</button>

Comment: Você tentou fazer um foreach() do $_POST pra editar os que estão marcados?
Comment: @AndréBaill poderia me dar um exemplo por gentileza?
Comment: @AndréBaill consegue ajudar amigo?
Comment: ***Faça da seguinte maneira: Crie um método chamado alterarCheckbox, e coloque o action do seu form para este, e ao receber, fará a atualização de acordo com os selecionados.** Como colocar o action para o form? O método alterarCheckbox é inserido em Controller? Alguém poderia me esclarecer, por favor? @Matheus Madalozzo, como vc fez?
Answer: Faça da seguinte maneira:
Crie um método chamado alterarCheckbox, e coloque o action do seu form para este, e ao receber, fará a atualização de acordo com os selecionados.
    // Excluir com checkbox
    public function alterarCheckbox(){

        $ids =  $this->input->post('status');
        $numRegs = count($ids);

        if($numRegs > 0){

            // atualiza status no banco de dados
            foreach($this->input->post('status') as $valor){
                $dados['status'] = 1;
                $this->db->where('idExportacao', $valor);
                if($this->db->update('exportacao', $dados)){
                    echo $valor." > Atualizado
";
                }
            }

        } else {
            echo "Nenhum item foi marcado.";
        }
    }

Comment: Perfeito, funcionou! Obrigado


Non-parametric alternative to two-way ANOVA using SPSS?

Question: I would like to test for the interaction effect of 2 independent categorical variables on 1 dependent continuous variable using SPSS. Unfortunately, I do not have equal sample sizes; the residuals are not normally distributed; Levene's test is significant too. What test can I use?
I have run an ANOVA and it shows very interesting results. Yet, I guess that with all those violations, I cannot consider them, right?
I have checked other (similar) questions, but surprisingly none of them could give me an answer. Could someone help me? Thanks a lot!
Answer: SPSS doesn't have a nonparametric analogue of a 2x2 ANOVA per se, but the GENLIN procedure for generalized linear models offers modeling for variables with other than normal distributions.


Error in Python 3.4 (Spyder) while plotting on Open Mandriva

Question: I was trying to plot an IR spectrum from csv file, like this :
import matplotlib.pyplot as plt

file=open('261.1_2014-12-10t16-33-55.csv')
for line in file :
    data.append(line)
    pointset=data[6:]
    for point in pointset:
        res=point.split(',')
        h=float(res[0])
        wn.append(h)
        y=float(res[1])
        Ads.append(y)
plt.plot(wn,Ads)
plt.show()

but instead of single line, i get huge lot of them.
variables Ads and wn have much more entries then point set and data.
What is wrong?
Comment: What is the shape of `wn` and `Ads`?  They should lists of floats which will get converted to `(N, )` shaped arrays.
Comment: Thank you for edit! They were lists of float. Now it works.
Answer: You are iterating over the lines in the file twice.  For each line in the file, you iterate over each point in pointset, but pointset is just the set of all lines read so far except the first six.
I think this is what you want:
from matplotlib import pyplot as plt

file = open('filename.csv')

for ii,line in enumerate(file):
    if ii>=6: #skip lines 0, 1,2,3,4,5
        fields = line.split(",")
        wn.append(float(fields[0]))
        Ads.append(float(fields[1]))
plt.plot(wn,Ads)
plt.show()


Get value from GridView when a button is clicked

Question: I have a GridView , and the GridView has an item template. Now I need to get the value of the first cell which contains the value I need but I have tried the following and does not work, it eturns a ""
 int id = Convert.ToInt32(GridView.Rows[index].Cells[0].Text);

Here is the code I have in the gridview
<Columns>
   <asp:TemplateField HeaderText="ID">
         <ItemTemplate>
             <asp:Label runat="server" ID="lblDepartmentID" Text='<%#DataBinder.Eval(Container.DataItem,"DepartmentID")%>' />
                                        </ItemTemplate>
                                        <HeaderStyle HorizontalAlign="Left" />
      </asp:TemplateField>

I have to emphazise that I do not want to use the GridView_RowCommand or other GridView events.. I need to pull this value upon clicking a button on the same page.
How can I do this?
Comment: where is this code under then? the int id line. Also, are you using the object type **Gridview** in the code?? is the GridView object named something else? Like GridView1 or something?
Comment: the line of code is in a btn_Click event. Now usinf the Gridview object, the Gridview is named GridView1
Answer: If you are trying to access the text value of Label then you have to first get the reference to Label control like this:
Label lbl = (Label)GridView.Rows[index].FindControl("lblDepartmentID");

and then use it's Text property to get the value required:
int id = Convert.ToInt32(lbl.Text);


How is  the joint distribution of random variables defined and determined?

Question: Suppose there are two random variables $X: \Omega \rightarrow U$ and $Y: \Omega \rightarrow V$ with probability space $(\Omega, \mathcal{F}, P)$, measurable spaces $(U, \mathcal{F}_u)$ and $(V, \mathcal{F}_v)$.

I was wondering how the joint distribution of $X$ and $Y$  is
defined? I just realized I am not clear about its definition.
If I am correct, the joint distribution is not the same as the
product measure of those on $(U, \mathcal{F}_u)$ and $(V,
    \mathcal{F}_v)$ induced by $X$ and $Y$ from $(\Omega, \mathcal{F},
    P)$ respectively. If they are the same, then $X$ and $Y$ are said to
be independent.
Is the joint distribution of $X$ and $Y$ defined on the
$\sigma$-algebra generated from $\mathcal{F}_u \times
    \mathcal{F}_v$?
For $S_u \in \mathcal{F}_u$ and $S_v \in \mathcal{F}_v$, is the
joint distribution determined by $P([X, Y] \in S_u \times S_v) =
    P(\{X \in S_u\} \cap \{Y \in S_v\})$?
How about the joint distribution probability of other sets that are
more general and may not be "rectangle"-like as $S_u \times S_v$?

Thanks and regards!
Answer: The joint distribution is a function assigning a probability to each measurable subset of $U\times V$, which is the probability that the pair $(X,Y)$ is in that subset.  It must of course be a probability measure on the sigma-algebra of measurable subsets of $U\times V$.
But which subsets are measurable?  That's your question #3, and the answer is yes.
I'm pretty sure the answer to #4 is yes, although I haven't thought this through in a while.  Certainly it's yes when $U = V = \mathbb{R}$ with the the measurable sets being the Borel sets.  For sets that are not "rectangle-like", the probabilities are determined by the probabilities for sets that are rectangle like, plus countable additivity, etc.
Comment: Re #4: The family of measurable rectangles is closed under finite intersections, and generates the product $\sigma$-algebra. By the Monotone Class Theorem, the measure is determined by its value on rectangles. That is, we have *uniqueness*.
Comment: ....and your point #2 is correct.


Colocar como pattern valores com duas casas decimais em input html5

Question: Tenho uma input numérica, e gostaria que nela só fosse válido pelo pattern, valores com .xx  (ponto mais duas casas decimais).
Meu código:

     Valor:
    <input type="number" pattern=" " id="valorTransf" />

Answer: O atributo pattern só funciona em types: text, search, tel, url, email, ou password. Não funciona em type="number". (Veja documentação MDN)
Para validar o campo usando regex, você poderá fazer via JavaScript usando match:

$("#valorTransf").blur(function(){

   var valor = $(this).val();

   if(valor.match(/^\.\d{2}\b/)){
      console.log("ok");
   }else{
      console.log("inválido");
   }
});

 Valor:
<input type="number" id="valorTransf" />

Onde a regex:
^\.\d{2}\b/

^\.    -> deverá iniciar com um ponto
\d{2}  -> deverá ter 2 dígitos após o ponto
\b     -> metacharacter que delimita o início (ou fim).
          Significa que não pode ter mais que 2 dígitos após o ponto


Chef Selenium: Strange error when I go to the hub ip:4444/wd/hub

Question: I get the following stacktrace:

{
    "status": 13,
    "value": {
        "class": "java.lang.NullPointerException",
        "stackTrace": [
            {
                "fileName": "ExternalSessionKey.java",
                "className": "org.openqa.grid.internal.ExternalSessionKey",
                "methodName": "fromWebDriverRequest",
                "lineNumber": 77
            },
            {
                "fileName": "WebDriverRequest.java",
                "className": "org.openqa.grid.web.servlet.handler.WebDriverRequest",
                "methodName": "extractSession",
                "lineNumber": 62
            },
            {
                "fileName": "RequestHandler.java",
                "className": "org.openqa.grid.web.servlet.handler.RequestHandler",
                "methodName": "getSession",
                "lineNumber": 237
            },
            {
                "fileName": "RequestHandler.java",
                "className": "org.openqa.grid.web.servlet.handler.RequestHandler",
                "methodName": "process",
                "lineNumber": 119
            },
            {
                "fileName": "DriverServlet.java",
                "className": "org.openqa.grid.web.servlet.DriverServlet",
                "methodName": "process",
                "lineNumber": 83
            },
            {
                "fileName": "DriverServlet.java",
                "className": "org.openqa.grid.web.servlet.DriverServlet",
                "methodName": "doGet",
                "lineNumber": 61
            },
            {
                "fileName": "HttpServlet.java",
                "className": "javax.servlet.http.HttpServlet",
                "methodName": "service",
                "lineNumber": 707
            },
            {
                "fileName": "HttpServlet.java",
                "className": "javax.servlet.http.HttpServlet",
                "methodName": "service",
                "lineNumber": 820
            },
            {
                "fileName": "ServletHolder.java",
                "className": "org.seleniumhq.jetty7.servlet.ServletHolder",
                "methodName": "handle",
                "lineNumber": 565
            },
            {
                "fileName": "ServletHandler.java",
                "className": "org.seleniumhq.jetty7.servlet.ServletHandler",
                "methodName": "doHandle",
                "lineNumber": 479
            },
            {
                "fileName": "SessionHandler.java",
                "className": "org.seleniumhq.jetty7.server.session.SessionHandler",
                "methodName": "doHandle",
                "lineNumber": 225
            },
            {
                "fileName": "ContextHandler.java",
                "className": "org.seleniumhq.jetty7.server.handler.ContextHandler",
                "methodName": "doHandle",
                "lineNumber": 1031
            },
            {
                "fileName": "ServletHandler.java",
                "className": "org.seleniumhq.jetty7.servlet.ServletHandler",
                "methodName": "doScope",
                "lineNumber": 406
            },
            {
                "fileName": "SessionHandler.java",
                "className": "org.seleniumhq.jetty7.server.session.SessionHandler",
                "methodName": "doScope",
                "lineNumber": 186
            },
            {
                "fileName": "ContextHandler.java",
                "className": "org.seleniumhq.jetty7.server.handler.ContextHandler",
                "methodName": "doScope",
                "lineNumber": 965
            },
            {
                "fileName": "ScopedHandler.java",
                "className": "org.seleniumhq.jetty7.server.handler.ScopedHandler",
                "methodName": "handle",
                "lineNumber": 117
            },
            {
                "fileName": "HandlerWrapper.java",
                "className": "org.seleniumhq.jetty7.server.handler.HandlerWrapper",
                "methodName": "handle",
                "lineNumber": 111
            },
            {
                "fileName": "Server.java",
                "className": "org.seleniumhq.jetty7.server.Server",
                "methodName": "handle",
                "lineNumber": 349
            },
            {
                "fileName": "AbstractHttpConnection.java",
                "className": "org.seleniumhq.jetty7.server.AbstractHttpConnection",
                "methodName": "handleRequest",
                "lineNumber": 452
            },
            {
                "fileName": "BlockingHttpConnection.java",
                "className": "org.seleniumhq.jetty7.server.BlockingHttpConnection",
                "methodName": "handleRequest",
                "lineNumber": 47
            },
            {
                "fileName": "AbstractHttpConnection.java",
                "className": "org.seleniumhq.jetty7.server.AbstractHttpConnection",
                "methodName": "headerComplete",
                "lineNumber": 884
            },
            {
                "fileName": "AbstractHttpConnection.java",
                "className": "org.seleniumhq.jetty7.server.AbstractHttpConnection$RequestHandler",
                "methodName": "headerComplete",
                "lineNumber": 938
            },
            {
                "fileName": "HttpParser.java",
                "className": "org.seleniumhq.jetty7.http.HttpParser",
                "methodName": "parseNext",
                "lineNumber": 634
            },
            {
                "fileName": "HttpParser.java",
                "className": "org.seleniumhq.jetty7.http.HttpParser",
                "methodName": "parseAvailable",
                "lineNumber": 230
            },
            {
                "fileName": "BlockingHttpConnection.java",
                "className": "org.seleniumhq.jetty7.server.BlockingHttpConnection",
                "methodName": "handle",
                "lineNumber": 66
            },
            {
                "fileName": "SocketConnector.java",
                "className": "org.seleniumhq.jetty7.server.bio.SocketConnector$ConnectorEndPoint",
                "methodName": "run",
                "lineNumber": 254
            },
            {
                "fileName": "QueuedThreadPool.java",
                "className": "org.seleniumhq.jetty7.util.thread.QueuedThreadPool",
                "methodName": "runJob",
                "lineNumber": 599
            },
            {
                "fileName": "QueuedThreadPool.java",
                "className": "org.seleniumhq.jetty7.util.thread.QueuedThreadPool$3",
                "methodName": "run",
                "lineNumber": 534
            },
            {
                "fileName": "Thread.java",
                "className": "java.lang.Thread",
                "methodName": "run",
                "lineNumber": 745
            }
        ]
    }
}

Have you seen such errors?
Do you have any idea how to solve this because there is nothing in the log files?
Answer: After doing some research, it seems like this is expected behavior and shouldn't impact testing:
https://github.com/nicegraham/selenium-grid2-api/blob/master/README.md#wdhub