What is the best way to move 20+ databases to a new database server? SQL 2005

Question: Current database server: SQL Server 2005 - Windows Server 2003
New destination database server: SQL Server 2005 - Windows Server 2003 Enterprise - VM Ware image
Current database server has 20+ databases on it, some application databases...others infastructure type databases (Citrix). We want to move all these databases to a new freshly built box that is virtualized.
So in further summary - yes, this is physical to virtual.
- 20+ databases transfered to this new virtual SQL 2005 box.
- applications on this box require minimal downtime.
A few approaches I can think of (all would be tested):
1. Third party physical to virtual converters - then shut down the old box.
- concerns = SID associations, Windows or SQL Server not liking this.

Move over all databases at once to the new server - Shut down the old server, change hostname on the new virtual box to the old hostname.
Move over all at once but use a different hostname for the new box - this allows parallel running in case something breaks - challenge = must change hostname within each application - could have problems.
Move over each databases in stages - this woudl mean a new hostname as well and a longer more drawn out project.

Anybody else have a similar scenario?
Answer: We moved from a single SQL server to a new SQL cluster (all new hardware). About 70 databases. The way we did it was to detach the databases, copy the files, and then attach the databases to the new SQL nodes.
We were forced to update the hostnames but I would take the old one offline and use the same hostname. You can always switch right back that way.
Comment: +1 for moving manually. I would do one at a time, which would result in just the one application being offline whilst you move the DB. Once verified it works on the new server, move onto the next.
Comment: Also remember to run sp_updatestats on all databases after a migration. To quickly run it against all the databases try this:

exec sp_msforeachdb @command1 = 'exec sp_updatestats'
Comment: I'd test with a few in different network zones if you have them, to make sure connections to the vm box work beforehand.
Answer: One way to minimize downtime is to use log shipping from one server to the other.  This requires repointing the app configs, but it has the benefit of having less downtime.  In general, the process is as follows:

Create the new server and move jobs/logins/SSIS, etc.
Set up source database for log shipping and start shipping.
Stop application(s) and set the DB to read-only.
Back-up the last tran log for the database.
Restore the last tran log on new server, set to no-recovery.
Set the new DB to back into read/write.
Bring repointed application back online.

A couple notes:

DB Mirroring is a similar solution.
SAN level replication is also similar, but it requires special SANs (like HP EVAs).

Pros:

Minimal downtime.
Log shipping is pretty easy to set up.
Rollback plan fairly easy.

Cons:

More manual steps.
Have to check the app to make sure it is properly repointed (more sys admin/DBA work).

So, there's a trade-off, but this method works and it is a common enough technique.
Eric
 -
Comment: +1:I have used this approach on a number of occasions. You can script out the majority of the steps required, for both the source and target servers, so that when the actual switch over needs to be made it's almost a matter of a few simple clicks.
Answer: Running in parallel risks data changing between when you made the copy & updating the copy accordingly.  Updating applications to point to a new hostname can cause grief as well.
I would recommend using a parallel setup for testing each application, but once satisfied with testing I would probably use Detach/Attach: How to move SQL Server databases to a new location by using Detach and Attach functions in SQL Server
Answer: From my experience p2v is an excellent & fast option, but not ideal if you want to minimize down time.  I'd use it only when existing servers are not a mess & virtualizing is only for hardware rationalization. (i.e. your not renaming the box, putting it in a new AD ect.)
SQL Server  & Windows will be ok if you p2v but you'll need to stop SQL Server services before you start the p2v. Windows SID's ect will all remain unchanged, what windows wont like is the physical & the virtual servers being connected to the same network.
If you go for the attach/detach method then make sure you also copy:

sql server logins
sql server agent jobs (including backup jobs)
linked servers
extended stored procedures

setting up new infrastructure & doing a cut-over means less down-time but requires more work.  As discussed, logshipping for a server 'cut-over' is the quickest way to do this, especially if you have big databases.
Answer: If you have a few dollars to spend, like 300.00 or so, check out idera admin toolset. An excellent piece of software. I used it on a recent project. It moved the databases and any relating objects, including users. It was worth it. In 3 clicks I moved all my databases. I still use it to move databases back and forth. I believe they have a trial version. Also you get many other tools, like moving users or objects across databases etc.


Alteryx REGEX upper first letter of every sentence and lower case for the rest

Question: I'm trying to transform strings in Alteryx using one regex tool as follows
Original:
lorem ipsum. DOLOR SIT AMET.

Looking for:
Lorem ipsum. Dolor sit amet.

Now, I did manage to match this pattern with the following REGEX
(^\w)|\.\s(\w)

But I'm not sure how to replace it in Alteryx.
Any ideas? I expected \U$1\U$2 and copy unmatched to work.
Answer: Could you please try following, written with your shown samples. This is creating 4th capturing groups, where 1st capturing will have like: D, 2nd capturing group contains OLOR, 3rd capturing group contains SIT and 4th capturing group contains AMET in shown samples.
^.*?\.\s+(.)(.*?)\s+(.*?)\s+([^.]*)\.$

Online demo for above regex
So you could try following command: $1 \U$2 \U$3 \U$4


New Guitar Setup at Time of Purchase

Question: Looking at buying a new guitar in the near future. The guitar will likely be an acoustic Martin or Taylor in the 1500-2000 price range. Should I explicitly ask for the shop to make sure it is setup properly (at no cost) before I take it home?
This is a large local shop - not a franchise.
Also, would I typically be buying the one on display or do they have more that they stock in the back? I kind of want one that hasn't been handled and bumped around by people shopping.
Comment: A good local shop should due an initial setup to your taste when buying a new guitar from them.
Answer: You can ask for it to be set up to your preference. Personally I've always preferred to do the setting up myself simply because I'm very specific! Truthfully it all boils down to how you like it at stock.
You will likely get a new guitar from the back unless it's an ex-display and in that case it should always be noted that it's ex-display.
Edit: Oh, keep in mind that a lot of guitar shops may charge a small fee for setting up the guitar and general maintenance costs. The most I've paid for this service is in the region of £10-30 depending on how much work needs done.
Comment: I do it myself as well for adjustable saddles, but for a fixed saddle he might be better off getting it done by a pro.
Comment: As long as you ask, they'll be more than happy to check it over for you. Be sure to play it first and find what you'd like altered, if anything at all.
Comment: That is very true. I'd imagine it would likely be a fixed saddle and they can be tricky and in that instance it would be the better option.
Comment: Sounds good. I haven't been playing long and only my beginner guitar at that. So I haven't really developed a preference. But it sounds like I can assume that a good shop will check that it meets factory setup specs before I take it home?
Comment: After calling a couple of shops, it sounds like standard procedure is to check them over and tweak if necessary to assure they are in spec with what the factory recommends.

New Guitar Setup at Time of Purchase


Sessions / Cookies not working for user login, registration or shopping cart

Question: The Problem
One of our sites has recently broken. Users can't login or register, and the shopping cart isn't working either.
Drupal does not display any errors. Upon clicking the submit button for the forms, it simply refreshes the page as if nothing had happened.
It's just as if sessions have stopped working altogether, which is a little strange, no?
The rest of the site works perfectly well.
No Drupal updates have been performed and no new modules have been installed.
I've been reassured that this isn't a server problem, but I'm still (really) not sure about that. Since I don't have SSH access to the server, I'd like to be sure beforehand.
I'm just looking for possible causes/fixes, and if anyone has had experience with this before, great. Ultimately I will end up checking out the server, but is there any chance it could be caused by Drupal?
Things I've Tried:
I've checked /sites/default/settings.php for the $base_url and $cookiedomain variables, but they are set properly.
This is not a .htaccess problem, either. Regardless of whether I use clean urls or not (site/user or site/index.php?q=/user) it just doesn't work at all.
Comment: I have the same problem on two of my local drupal installation(with commerce related modules). what I found out is:
drupal tries to login user when correct password is entered but it fails somehow to change 'uid' column of 'session' table.
did you find anything new?
Comment: do the error logs (drupal and server) say anything?  do you have a temp folder, is it assigned and does the folder have the correct permissions
Comment: I haven't found anything new, but thanks for your comment. I haven't gone through the PHP code line-by-line just yet.

Was hoping I'd be able to avoid it, but this doesn't seem to be a well-understood problem. Since the site was working before, I really don't know what to think. Just that I'll have to narrow down the list of causes somehow.
Comment: Did you end up finding a solution for this problem?
Answer: This is a very old question, but I stumbled on it while having the same issue.
In my case, the "rewrite" Apache module was turned off. I re-enabled it with:
<code>a2enmod rewrite
</code>
I could access /user, but could not login (it would loop back, with no error message). I assumed that since I could access /user, my rewrites and htaccess were OK. I could login with "drush uli", but no form would work. Even weirder: in some pages that had query parameters (GET, ex: foo?test=1), the GET parameters would not be passed to PHP. I was searching all over the place, and the solution was pretty trivial :)
Comment: or uncomment LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so


linker can't file the implementation file in c

Question: i am working with eclipse ARM ds-5 on an arria v development kit board and i configured the environment like they show on their website : https://developer.arm.com/products/software-development-tools/ds-5-development-studio/resources/tutorials/getting-started-with-ds-5-development-studio.
i am trying to use alt_sdmmc.h file. The program found the file but when i am trying to use any of the file function it doesn't auto complete the function or finds it.
when i try to build the program executes with status code 1 and with an undefined reference to 'sd_mmc_init'(for example).
can you halp me solve this problem ?
I tried to put the alt_sdmmc.c file in the project workspace it helped with other stuff but it only makes it worth because it couldn't compile it as well. the file is located in C:\altera\15.0\embedded\ip\hps\altera_hps\hwlib\include\alt_sdmmc.h.
the hwlib also have \src\hwrmgr\ "... .c" instead of \include\
i believe the the problem is that the linker doesn't recognize this folder
i've read alot of answers from stackoverflow about this problem (undefined reference) and most of the cases it was typing error which is not the case in here
Answer: Go to Projcet->Properties->C/C++ Build -> Tool Settings -> C Linker
Then add

"C:\altera\15.0\embedded\ip\hps\altera_hps\hwlib"

to the library search path (-L)
Comment: hi thanks for the help, i fixed the problem. eventually this wasn't the issue. my project is compiled with g++ and the file they provided there was extern "c" missing. after that i needed to compile with gcc instead of g++ because their code was not supported. by the way the -L didn't work because it is not a library;


Android Studio: what does the green dot mean in the "Run" button?

Question: What does the green dot that sometimes appear inside the Run button mean, exactly?
Answer: Android Studio is based on Intellij IDEA.
Quote from Intellij IDEA:

Now every run configuration has a small green indicator that tells you
  if it's running.

This green circle indicates that the selected run configuration is now running. Try stopping it, and see the green circle disappear.
IntelliJ IDEA 15 EAP Adds Indication for Running Configurations
Answer: Run with Green dot icon was replaced by another one
 ->
But the idea is the same - app is running and when you press it, the previous app will be exited and new app will be created


Using java how to add in-code generated jpg images to a word document without saving the file first

Question: Using java how can I add in-code generated jpg images to a word document without saving the file first.
The word document needs to be created from scratch in Java (poi does not seem to do the images).
Comment: With docx4j you can easily create docx from scratch in Java.
Comment: Please clarify the question. Do you have an in-memory representation of the Word document in Java, or is the word doc existing on the filesystem? Is it a binary .doc, or a docx (if the latter, docx4j will help)
Comment: The word document needs to be created from scratch in Java (poi does not seem to do the images)
Answer: Per the comments on my question from plutext and trying this out. The docx4j is working really good.


Prove that $a\equiv 0 $ $(mod$ $p)$ given $\sum^{p-1}_{k=1} \frac{1}{k^2} = \frac{a}{b}$ where $p$ is prime and $gcd(a,b)=1$

Question: That is prove that the numerator of $\sum^{p-1}_{k=1} \frac{1}{k^2}$ expressed in lowest terms is divisible by $p$ where $p$ is prime.
I have tried to express the numerator but am not having much luck reducing it and I cannot find much online that is helpful here. Any hints/help is greatly appreciated, thanks in advance.
Comment: GCD $ (a,b)=0?$
Comment: @Labbhattacharjee fixed, thanks
Answer: Hint:
$$\sum_{k=1}^{p-1}\dfrac1{k^2}\equiv\sum_{r=1}^{p-1}r^2\pmod p$$
as $(k,p)=1$ for $1\le k<p,$ there exists a unique $r,1\le r<p$ such that $kr\equiv1\pmod p$
See also: Multiplicative Inverse of Modulo n is UNIQUE
Comment: Because each element has a unique inverse mod p? I think I will be able to get it now, thanks!
Comment: @Rick, Thanks for the rectification


Capture the mouse right click event of a web browser control

Question: I would like to select all when a user right clicks on my web browser control.
I am developing a win forms app, and use web browsers to display my information, because i can use html to style the words.
The right click context menu is not working for me. The options on it are all irrelevant to my app.
But the context menu after a select has been made i want to keep, the copy, cut, paste options.
I can already select all:
getCurrentBrowser().Document.ExecCommand("SelectAll", true, null);

I would just like to do it in the right click event of the web browser?
Comment: possible duplicate of [Jquery/JS prevent right click menu in browsers](http://stackoverflow.com/questions/4920221/jquery-js-prevent-right-click-menu-in-browsers)
Comment: @Piskvor This is a win form app and done in C# sharp, there is no Jquery/JS involved nor do i want to prevent the right click menu, So this is not a possible duplicate!!
Comment: So, now you're saying there is no webbrowser control? Interesting...
Comment: @Piskvor i did not say there is no web browser control, i said its a win form app.
Answer: Handle MouseDown event:
webBrowser.Document.MouseDown += new HtmlElementEventHandler(Document_MouseDown);

and make sure user pressed Right button, then select all:
void Document_MouseDown(object sender, HtmlElementEventArgs e)
{
    if(e.MouseButtonsPressed == MouseButtons.Right)
    {
        webBrowser.Document.ExecCommand("SelectAll", true, null);
    }
}

Comment: +1 Thanks think this is the right way to do it and answers the Question asked.
Answer: This article shows how you can replace the context menu of the Web Browser with your own.
Alternatively, if you execute the following Javascript from within the Web Browser, it will disable the default right-click context menu:
    document.oncontextmenu=new Function("return false")

If you are using WinForms rather than WPF, you can set the IsWebBrowserContextMenuEnabled to false to prevent the IE context menu, in which case it will use the ContextMenu you supply on the WebBrowser control.
WPF doesn't have the same property exposed on the Web Browser, so it may not be so easy. In this case you may have to use WindowsFormsHost to host the WinForms Web Browser in WPF.
Comment: + 1 .Thanks for the answer :), i did manage to find an awesome work around :)
Answer: This works :)
When the context menu shows select all is running pushing out the contextmenu i want, with the copy, paste, cut and so on.
private void webCompareSQL_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webCompareSQL.Document != null)
            {
                webCompareSQL.Document.ContextMenuShowing += DocMouseClick;
            }
        }
        void DocMouseClick(object sender, HtmlElementEventArgs e)
        {
            webCompareSQL.Document.ExecCommand("SelectAll", true, null);
        }

Comment: It does not exactly capture the right click event, but the contextMenuShowing will always display when the web browser is clicked. so its a good work around.
Comment: what if Document is null??
for PDF webbrowser Document always null .then how you will create click event ?
Answer: You need to be sure, that the WebBrowser.Document property is already loaded. Then you can register the Mouse event.

`browser.DocumentCompleted += (s, e) => {
                             browser.Document.MouseMove += (sM, eM) +=> {
                                                          Debug.WriteLine(eM.ClientMousePosition.X);
                                                                        };
                                       };
`


AutoFac - WebApi cannot Register reflected types

Question: I'm having problems with the line "builder.RegisterInstance(Activator.CreateInstance(repoClass));".  Basically I want to reflect into a separate assembly to register my WebApiController and Types...for a plug in play architecture.  I'm new to AutoFac.  The RegisterInstance cannot resolve repoInterface in repoClass, I get a compile error. "Argument type 'object' is not assignable to parameter type repoClass."  I understand the error.  How else can I accomplish this so it works?
Thanks
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.EnableSystemDiagnosticsTracing();

        ContainerBuilder builder = new ContainerBuilder();

        string WebApisPath = ConfigurationManager.AppSettings["AutoFac_WebApiControllerAssembliesPath"];
        string titleLoanAsm = ConfigurationManager.AppSettings["WebApi_TitleLoanAssembly"];
        Assembly asm = Assembly.LoadFile(AssemblyDirectory.Replace("\\bin", "") + WebApisPath + titleLoanAsm);

        builder.RegisterApiControllers(asm);

        List<Type> exportedTypes = new List<Type>(asm.GetExportedTypes());

        Type repoClass = exportedTypes.FirstOrDefault(x => x.IsClass && x.Name.Contains("LGF"));

        if (repoClass == null)
            throw new ObjectNotFoundException(string.Format("No repositories found for controller"));

        Type repoInterface = repoClass.GetInterfaces().FirstOrDefault(x => x.IsInterface && x.Name.Contains("LGF"));

        if (repoInterface == null)
            throw new ObjectNotFoundException(string.Format("Interface not found for class {0}. Ensure class has and interface implemented with a name that contains LGF", repoClass.Name));

        builder.RegisterInstance<repoInterface>(Activator.CreateInstance(repoClass));

        IContainer container = builder.Build();

        AutofacWebApiDependencyResolver resolver = new AutofacWebApiDependencyResolver(container);

        config.DependencyResolver = resolver;
    }

Answer: Autofac has a way to register types and have instances created by reflection.
builder.RegisterType(repoClass).As(repoInterface);

Updated to address comments
I think the confusion here might be that in your initial question your specifically asked about the error you were getting for the RegisterInstance call for repoClass. My answer was addressing that. The issue of MVC controllers not being found is a different issue, not really an autofac problem, but an MVC routing problem. To solve that you will need to tell the routing system where to find those other controllers. To fix that you will need to do something like this:
routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" },
    new[] { "ExternalAssembly.Controllers" }
);

To find the value(s) to replace "ExternalAssembly.Controllers" with you will need to reflect into your external assembly similar to how your code already does and discover those namespaces.
Comment: What does a 404 have to do with Autofac registration?
Comment: 404 Not Found...look it up [link](http://en.wikipedia.org/wiki/HTTP_404).  Which means it's not registering correctly.  If I move the controller and types into the same assm. as the WebApi my unit test pass, if I move them out into a separate assm. and reflect the types, its not working.  As I said, I'm new to AutoFac. Maybe you could elaborate more, please?
Comment: Thanks again Nathan.  I did go the long route on this by building a dynamic runtime class.  Works great.  This at least proves my concept, now I need to genericize it.  Below is my RuntimeContainerBuilder, Answer.
Comment: I also don't think routes.MapRoute is available for WepApi.  It's config.Routes.MapHttpRoute.  A little different.  Thanks though!
Answer: So in my original post I was getting a compile error on the line "builder.RegisterInstance(Activator.CreateInstance(repoClass));"  This was because repoClass could not look in to repoInterface during design time.  So I created a dynamic runtime class that gets the actual types from repoClass and repoInterface at runtime, it then compiles and executes the class on the fly to return the ContainerBuilder from my Assembly.LoadFile.
public class RuntimeContainerBuilder
{
    public static object Evaluate(ContainerBuilder builder, Type controller, Type repoInterface, Type repoClass, Assembly assembly)
    {

        CSharpCodeProvider c = new CSharpCodeProvider();
        ICodeCompiler icc = c.CreateCompiler();
        CompilerParameters cp = new CompilerParameters();

        cp.ReferencedAssemblies.Add("system.dll");
        cp.ReferencedAssemblies.Add(AssemblyDirectory + "\\System.Web.Http.dll");
        cp.ReferencedAssemblies.Add(AssemblyDirectory + "\\Autofac.dll");
        cp.ReferencedAssemblies.Add(AssemblyDirectory + "\\Autofac.Integration.WebApi.dll");

        cp.ReferencedAssemblies.Add(@"E:\MainTrunk2\LeadGenFramework\trunk\LeadGenFramework.Web.Api\LeadGenFramework.Web.Api.Controller.TitleLoan\bin\LeadGenFramework.Web.Api.TitleLoan.dll");

        cp.CompilerOptions = "/t:library";
        cp.GenerateInMemory = true;

        StringBuilder sb = new StringBuilder("");
        sb.Append("using System;\n");
        sb.Append("using Autofac;\n");
        sb.Append("using System.Web.Http;\n");
        sb.Append("using System.Web.Http.Controllers;\n");
        sb.Append("using Autofac.Integration.WebApi;\n");
        sb.Append(string.Format("using {0};\n", assembly.ManifestModule.Name.Replace(".dll","")));

        sb.Append("namespace LeadGenFramework.Web.Api{ \n");
        sb.Append("public class DynamicBuild{ \n");
        sb.Append("public ContainerBuilder Build(ContainerBuilder obj){\n");
        sb.Append(string.Format("obj.RegisterApiControllers(typeof({0}).Assembly).PropertiesAutowired();\n",controller.Name));
        sb.Append(string.Format("obj.RegisterInstance<{0}>(new {1}());\n", repoInterface.Name, repoClass.Name));
        sb.Append("return obj; \n");
        sb.Append("} \n");
        sb.Append("} \n");
        sb.Append("}\n");

        string s1 = sb.ToString();
        CompilerResults cr = icc.CompileAssemblyFromSource(cp, s1);
        if (cr.Errors.Count > 0)
        {
            //Factory.LogManager.MainProcessLogger.Info(string.Format("DynamicFormatScriptEngine:Evaluate(): Error: {0}, Code: {1}", cr.Errors[0], s1));
            return null;
        }

        Assembly a = cr.CompiledAssembly;
        object o = a.CreateInstance("LeadGenFramework.Web.Api.DynamicBuild");

        Type t = o.GetType();
        MethodInfo mi = t.GetMethod("Build");

        object s = mi.Invoke(o,new object[]{builder});

        return s;
    }

Now my WebApiConfig is like so...see the line "RuntimeContainerBuilder.Evaluate(builder, controller, repoInterface, repoClass, asm)"
   public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.EnableSystemDiagnosticsTracing();

        ContainerBuilder builder = new ContainerBuilder();

        //string WebApisPath = ConfigurationManager.AppSettings["AutoFac_WebApiControllerAssembliesPath"];
        string titleLoanAsm = ConfigurationManager.AppSettings["WebApi_TitleLoanAssembly"];
        //Assembly asm = Assembly.LoadFile(AssemblyDirectory.Replace("\\bin", "") + WebApisPath + titleLoanAsm);

        Assembly asm = Assembly.LoadFile(AssemblyDirectory + "\\" + titleLoanAsm);

        List<Type> exportedTypes = new List<Type>(asm.GetExportedTypes());

        Type controller = exportedTypes.FirstOrDefault(t => !t.IsAbstract && typeof(ApiController).IsAssignableFrom(t));

        if (controller == null)
            throw new ObjectNotFoundException(string.Format("Contoller not found in assembly {0}.", asm.FullName));

        Type repoClass = exportedTypes.FirstOrDefault(x => x.IsClass && x.Name.Contains("LGF"));

        if (repoClass == null)
            throw new ObjectNotFoundException(string.Format("No repositories found for controller"));

        Type repoInterface = repoClass.GetInterfaces().FirstOrDefault(x => x.IsInterface && x.Name.Contains("LGF"));

        if (repoInterface == null)
            throw new ObjectNotFoundException(string.Format("Interface not found for class {0}. Ensure class has and interface implemented with a name that contains LGF", repoClass.Name));

        RuntimeContainerBuilder.Evaluate(builder, controller, repoInterface, repoClass, asm);

        IContainer container = builder.Build();

        AutofacWebApiDependencyResolver resolver = new AutofacWebApiDependencyResolver(container);
        config.DependencyResolver = resolver;
    }

The next step is to make it more generic to load assemblies into an array and setup the RuntimeContainerBuilder for each one...then builder.Build should resolve and activate everything correctly.  My end goal for this prototype is to drag and drop assemblies and have the WebApi pick them up dynamically.


If $(a_{2n+1})$ and $(a_{2n})$ converge to $a$ then $(a_n)$ converges to $a$.

Question:
If $(a_{2n+1})$ and $(a_{2n})$ converge to $a$ then $(a_n)$ converges to $a$.

So far I realize that if $(a_{2n+1})$ and $(a_{2n})$ converge then for each $\epsilon>0$, there exists $N$ such that for all $n>N$, $|a_{2n+1}|, |a_{2n}| < \epsilon$. As eventually even and odd values of $n$ converge (which is to say that eventually for all natural numbers $n>N$) $a_n$ converges.
I just don't know how to prove it. Perhaps I could show that the set of all odd and even numbers is the set of Natural numbers but I'm struggling to prove it properly.
P.S. Sorry for the simplicity of the question, I'm not used to proving such things.
Comment: Consider $|a_n-l|\leq\max(|a_{2E(n/2)}-l|,|a_{2E(n/2)+1}-l|)$ were l is the shared limit of $a_{2n}$ and $a_{2n+1}$
Comment: The statement in your first sentence is only true for $a=0$.
Answer: By assumption, for $\epsilon>0$ there exists $N_o$ such that $n>N_o$ implies $|a_{2n+1}-a|<\epsilon$ and there exists $N_e$ such that $n>N_e$ implies $|a_{2n}-a|<\epsilon$.
I claim that for $N:=\max\{2N_o+1,2N_e\}$ we have $|a_n-a|<\epsilon$ for all $n>N$.
Indeed, assume $n>N$. Then either $n$ is even or $n$ is odd. In the first case $n=2m$ for some $m$ and $m=\frac n2 > \frac N2\ge \frac{2N_e}2=N_e$, hence $|a_n-a|=|a_{2m}-a|<\epsilon$. In the other case $n=2m+1$ for some $m$ and $m=\frac{n-1}2>\frac{N-1}2\ge\frac{(2N_o+1)-1}2=N_o$, hence $|a_n-a|=|a_{2m+1}-a|<\epsilon$.
Comment: Something makes me think there should be another way, without division and such.
Answer: Here's a simpler way to do it. Note that
$$
\limsup a_n \leq \max \{\limsup a_{2n},\limsup a_{2n+1}\} = a,
$$
$$
\liminf a_n \geq \min \{\liminf a_{2n}, \liminf a_{2n+1}\} = a
$$
since any subsequence must take infinitely many odds or infinitely many evens
and so it follows that $\limsup a_n = \liminf a_n = \lim a_n = a$.
Answer: If $a_n$ does not converge to $a$ then there is a $a_1$ and a
subsequence of $a_{k_n}$ such that $a_{k_n} \rightarrow a_1 \ne a$. Possible $a_1 =\pm \infty$
Let
\begin{align}
A_0 =\{  n | k_n \equiv 0 \mod 2\}\\
A_1 =\{  n | k_n \equiv 1 \mod 2\}
\end{align}
Pigeonhole theorem suggests $A_0$ or $A_1$ is infinite.
But this leads to a contradiction because
of the fact that in a convergent sequence all of its subsequences converge to the same number.
Answer: Let $(p_j)$ and $(q_k)$ be strictly increasing sequences of integers such that
$\{p_j:j\in \Bbb N\}\cup\{q_k:k\in\Bbb N\}=\Bbb N$.
Suppose that $(a_{p_j})$ and $(a_{q_k})$ converge to $a$.
Let $N$ be a neighborhood of $a$.
Then for some $J,K\in\Bbb N$, $j\ge J\implies a_{p_j}\in N$ and $k\ge K\implies a_{q_k}\in N$.
Let $m=\max\{p_J,q_K\}$.
If $n\ge m$, then either $n=p_j$ for some $j$ or $n=q_k$ for some $k$.
Assume without loss of generality that $n=p_j$ for some $j$.
Since $n\ge m$, $p_j=n\ge p_J$ by the definition of $m$.
Since $(p_j)$ is strictly increasing, $j\ge J$, so $a_n=a_{p_j}\in N$.
So we see that $n\ge m\implies n\in N$.

This argument can easily be extended to any finite number of sequences, and I believe also to transfinite sequences. The "strictly increasing" criterion can almost certainly be weakened to an "eventually succeeeds each natural" one. I don't see a really natural extension to nets, but that is likely a failure of my imagination.


Make $3$ piles of $120$ from $241$ coins

Question: Starting with $241$ coins with positive integer values, you can make $3$ piles so that each of them has value exactly $120$. Coins together have value of $360$. Prove this is true for all values of coins.
I tried sorting the coins. Then picking three with largest values. Then somehow I need to fit all the remaining coins so that they fill the piles. How can this be done?
Minimum number of coins with value $1$ is $122$.
Comment: Make a pile of 120 value 1 coins and see what is left. Then see if you can divide up the rest.
Answer: HINT:
What is the minimum number of coins with value $1$? And what is therefore the maximum value of the sum of all coins with a value of 2 or more?
Answer
It is easy to see that there need to be at least $122$ coins with a value of $1$, and thus the total value of all the coins with a value of $2$ or more is at most $238$.
It is also easy to see that no individual coin can have a value of more than $120$
So, if there are at least two coins with a value between $60$ and $120$, then put each coin in a separate pile. Since the total value of the coins with a value of $2$ or more is at most $238$, and since the first two coins have a sum value of at least $120$, that means that the sum value of the rest of the coins with a value of $2$ or more is below $120$, and so they can all be put into a third pile, and now the three piles can be filled up with the coins of value $1$
If there is one coin with a value between $60$ and $120$, then put that one by itself, and now create a second pile of coins with a value of $2$ or more, adding at a time, until you either are out of those coins, or until that pile reaches a sum value of $60$ or more; as you are adding one coin at a time, it is impossible to go from a sum value from below $60$ to a sum value of above $120$, so if the sum value of the remaining coins with a value of $2$ or more is more than $60$, then you are guaranteed to get a second pile of such coins with a sum value of between $60$ and $120$. And, once you have that, you can once again put all the other coins with a value of $2$ or more into a third pile without going over $120$, by the same reasoning as before. And then you can fill up the three piles with the coins with a value of $1$
Finally, if there are no coins with a value of over $60$ at all, then by the above reasoning you can create two piles with coins with a value of $2$ or more, each with a sum value of between $60$ and $120$ (unless you can create only such pile, but then it is even more trivial to fill up the piles), and then once again you can put all the rest of those coins with a value of $2$ or more in a third pile, and then fill up the three piles with coins of value $1$
Comment: Edited question with this fact.
Comment: @IvanAgarsky OK, but can you go back to the drawing board yourself and see if *you* can now solve the problem given this fact?
Comment: I still can't solve this, so I put a bounty now.


Save gzip compressed data to cache storage from service worker

Question: We are trying to store some api responses in cache storage for a PWA app.We are intercepting the fetch request in service worker and are storing the responses to cache.But our uncompressed apis size is little large and we want to keep the compressed(gzip) version in the cache and uncompress it when needed.
Is there any way we can prevent the browser from automatically uncompressing the responses from server
Answer: I'm not aware of any way to do this automatically. Most servers will only compress their response bodies on the fly if the incoming request indicates that the browser supports compression, and in that case, the browser will automatically decompress the body before you have access to the compressed bytes.
You may have better luck either explicitly compressing the files on the server and downloading and storing that compressed version (i.e. fetch('asset.json.gz')), or alternatively, using a CompressionStream (which isn't widely supported outside of Chromium-based browsers) to compress your data client-side prior to storing it.
Comment: Thanks Jeff.Indeed we are going for the manual compression and decompression from server and client side.


Dúvida react-native

Question: Gostaria de saber se um aplicativo que atualize, por exemplo, uma pequena lista de informações automaticamente, ao sofrerem alterações no banco de dados (essas alterações não feitas no app vem outro lugar ) sem precisar pressionar qualquer botão, é simples de fazer e se tem algum problema de performance ou boa prática.
Comment: Ate onde eu sei atualizações em tempo real dependem de um "HOSPEDEIRO  PARA CONSTRUIR APLICATIVOS EM TEMPO REAL" que eu creio que seja isso que você procura, existe um chamado "Pusher" la você pode fazer uma integração com sua API e lá tem várias linguagens provavelmente tem alguma forma de integrar com o react-native e fazer sua lista atualizar em tempo real, sem precisar clicar no botão.
Comment: *"é simples de fazer"* Isso depende do seu nível de habilidade ;)
Comment: No caso eu tenho fire base, estou procurando alguns exemplos para usar como base. Grato pela atenção.
Answer: Caso você utilize da tecnologia para fins de exibição (FrontEnd), é possível sim. Não que não seja possível executar eventos, programar tratamento de dados e etc. Mas pela "Facilidade", dá sim.
Com React-Native você pode criar a interface, já que, a tecnologia ReactJS é um framework para UI, "...building user interfaces...".
Isso você pode programar um evento ou uma função no ciclo de vida dos componentes(Conceito chave do React) para sempre que você abrir aquela "Lista", ele fazer uma requisição para um Servidor Web(WebService) e exibir essa lista.
Não precisaria de Botão. Bastava abrir o aplicativo e ele atualizaria o conteúdo toda vez que abrisse aquela tela.
Fazendo uso da função Fetch, juntamente com as chamadas do ComponentDidMount() dá para conseguir atingir seu objetivo sem muita dificuldade.
O nível de dificuldade varia de acordo com seus conhecimentos sobre Javascript e a tecnologia React.
Espero ter ajudado, bom desenvolvimento!
Comment: Caso queira em tempo real a atualização, existem tecnologias que podem fazer a atualização automática. Não é difícil, é complexo. Coisas diferentes. Minha sugestão é: Coisas simples, soluções simples. Já que o servidor atualiza os dados, delegar a responsabilidade para consultar alterações do servidor ao dispositivo e não ao servidor. Deixe o dispositivo requerer uma tag, versão, quantidade de registros, numero de last patch, caso dê mismatch, puxe novamente os dados. Simples assim.

Dúvida react-native


Logstash input log stream via port

Question: Is there any way to read logstash raw input data that is forwarded via certain port?
input settings are as below
input {
    tcp {
          port => 1234
          type => "test"
   }
}

and from output config...
output {
  stdout { codec => rubydebug }
}

we can only see the logstash output but not the original input data..
any idea how can i read the input log?
Answer: You can copy things in a filter block:
filter {
  mutate {
    add_field => { "raw_input": "%{message}" }
  }
}

Which will give you the raw input in a raw_input field.

Logstash input log stream via port


Admin Menu is messed up - Drupal 6 (Not cache related)

Question: Here is a screenshot of the menu on our dev server, everything looks fine:

View it bigger here:https://i.stack.imgur.com/uVtpo.png
Here is a screenshot of the menu on production, not fine:

View it bigger here: https://i.stack.imgur.com/PZqGh.png
I cleared the cache a couple of times, not sure why it all of a sudden started happening.
This site has also had issues where the main nav menu disappears from time to time. Clearing the cache restores it and it may not be related to this issue at all, but thought I would mention it.
Admin Menu module 6.x-1.5
Comment: Have you got ads or other external Javascript on the live site? Often such problems are caused by scripts injecting broken HTML into the page.
Answer: Under admin/settings/admin_menu there is a feature to Wipe and Rebuild. That fixed the issue for me.
Very weird problem.


Can we create a C-array of Python objects in Cython?

Question: Can we create a C-array of Python objects in Cython?
Let's consider the following code:
class C:
    pass

cdef object f():
    return C()

cdef void g(unsigned n):
    cdef object obj0 = f()
    cdef object obj1 = f()
    cdef object obj2 = f()
    cdef object obj3 = f()

Is there a way to store the various objects in an array instead of using several variables? Something along the lines of:
cdef void g(unsigned n):
    cdef object[N_MAX] obj
    for i in range(n)
       obj[i] = f()

Comment: This is very very close to a duplicate of https://stackoverflow.com/questions/33851333/cython-how-do-you-create-an-array-of-cdef-class/33853634#33853634. You want a `list`.
Comment: Thanks, David. I saw the discussion at https://groups.google.com/g/cython-users/c/G8zLWrA-lU0 -- but I missed your previous answer. I look at that now.
Comment: The answer is more to do with an array of *specific* object type (which is why it isn't quite a duplicate) so some of the suggestions don't apply. But a list (or maybe a tuple, if you don't need to reassign) is probably the best solution - internally it's surprisingly close to a plain array of object pointers.
Comment: Yes. I didn't have the time to try that this evening -- but I will surely use a list. Maybe using directly [PyList_New](https://docs.python.org/3/c-api/list.html#c.PyList_New) to avoid the burden of creating the list incrementally by calling `append`.
Comment: Hi, @DavidW. I made several tests, and in the end, the simplest is certainly the better. I will use a list comprehension to store the array of objects. I posted my solution as an answer: https://stackoverflow.com/a/75998181/2363712
Answer: It is not really possible to create an array of object. One caveat is, if it would, we should manually manage the lifetime of the objects using Py_INCREf/Py_DECREF.
The simplest and safest move is probably to maintain the list of objects at the Python layer. Following the example given in the original question, we could, for example, use a list comprehension:
cdef void g(unsigned n):
    cdef list l = [f() for _ in range(n)]

    #...

This is compiled into something along the lines of:
  __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 10, __pyx_L1_error)
  __Pyx_GOTREF(__pyx_t_1);
  __pyx_t_2 = __pyx_v_n;
  for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) {
    __pyx_v__ = __pyx_t_3;
    __pyx_t_4 = __pyx_f_1a_f(); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 10, __pyx_L1_error)
    __Pyx_GOTREF(__pyx_t_4);
    if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_4))) __PYX_ERR(0, 10, __pyx_L1_error)
    __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
  }
  __pyx_v_l = ((PyObject*)__pyx_t_1);
  __pyx_t_1 = 0;

I was tempted to manually manage the list using PyList_New and PyList_SET_ITEM to avoid the successive calls to __Pyx_ListComp_Append:
from cpython cimport PyList_New, PyList_SET_ITEM, Py_INCREF
cdef void h(unsigned n):
    cdef list l = PyList_New(n)
    cdef unsigned i
    for i in range(n):
        o = f()
        Py_INCREF(o)
        PyList_SET_ITEM(l, i, o)

    #...

In practice, that makes the code much less readable (and more error-prone), for very little benefits.


How to connect stochastic volatility in SDEs with its empirical version?

Question: The standard definition of stochastic volatility model is:
$dS_t = \mu S_tdt + \sqrt{v_t}S_tdW_t$
$dv_t = \alpha_{v,t}dt + \beta_{v,t}dB_t$
$\langle d W_t, d B_t \rangle  = \rho$
(From wikipedia: https://en.wikipedia.org/wiki/Stochastic_volatility)
However, in Kim's paper (http://finance.martinsewell.com/stylized-facts/volatility/KimShephardChib1998.pdf), they define an empirical version:
$y_t = \beta \exp(h_t/2)\epsilon_t$
$h_{t+1} = \mu + \phi(h_t - \mu) + \sigma_t \eta_t$
$h_t \sim N(\mu, \frac{\sigma^2}{1-\phi^2})$
I have trouble in understanding how to get the empirical version from the SDE. Does it mean that other stochastic volatility models, i.e., SABR, have an empirical version?
Comment: I'm voting to close this question as off-topic because it belongs to https://quant.stackexchange.com/
Answer: "Empirical" just means they discretized it.
The original Hull-White (1987) paper has $\alpha_{v,t} = \mu v_t$, but  I'm not sure that is correct, because the log-variance doesn't have mean-reverting behavior.
If you let $Y_t = \log S_t$ (log price) and $h_t = \log( V_t)$ (log-volatility), $\alpha_{v,t} = (\theta - \alpha \log v_t)v_t$ ($\alpha > 0$), $\beta_{v,t} = \sigma v_t$ and apply Ito's lemma, you get
\begin{align*}
dY_t &= \left(\mu - \frac{v_t}{2}\right)dt + \sqrt{v_t} dB_{1t}\\
dh_t &= \left(\theta - \alpha\log v_t - \sigma^2/2\right)dt + \sigma dB_{2,t}\\
&= \alpha\left(\tilde{\mu} - h_t \right)dt + \sigma dB_{2t}.
\end{align*}
According to this, this was a model investigated by a guy named Wiggins. The log-variance follows an Ornstein-Uhlenbeck process, which is like a continuous time version of an AR(1). If you use the Euler-Maruyama method to discretize this, setting $\Delta t = 1$, you should see this
\begin{align*}
h_{t+1} &= \alpha \tilde{\mu} + h_t(1-\alpha) + \sigma \eta_t \\
&= \tilde{\mu}(1 - \phi) + \phi h_t + \sigma \eta_t \\
&= \tilde{\mu} + \phi(h_t - \tilde{\mu}) + \sigma \eta_t
\end{align*}
letting $\phi = 1-\alpha$. Note that $\tilde{\mu} \neq \mu$.
As far as the observation process goes:
\begin{align*}
y_{t+1} = Y_{t+1} - Y_t &= (\mu - \frac{v_t}{2}) + \sqrt{v_t}\epsilon_{t+1} \\
&= \left(\mu - \frac{\exp h_t}{2} \right) + \exp[ \log \sqrt{v_t}] \epsilon_{t+1} \\
&= \left(\mu - \frac{\exp h_t}{2}\right) + \exp\left[ \frac{h_t}{2}\right] \epsilon_{t+1}
\end{align*}

I can't quite get the drift term to cancel out. The mean of these returns should be $0$. Maybe because that's  because of some arbitrage argument I'm not privy to, or maybe it has to do with how the errors are correlated in the SDE.

NB: In the discrete time observation equation you wrote, you should set $\beta = 1$, otherwise the model isn't identifiable (because we have a non-zero mean for the log-variance process). This is mentioned in the paper you linked to, but it is also discussed on a thread on this site here.
Answer: If you read carefully both Kim's paper and Hull (1987) to which they refer, you'd notice that in Hull (1987) the volatility process is defined differently than in what you called "standard" model: they use log vol process, not levels like in yours. Here's equation (2) from their paper:
$$dV=\mu V dt +\xi V dz$$
where $V=\sigma^2$ is the variance.
Next, notice how Kim et al say that y in their Eq.1 is the mean corrected return on asset, and $h_t$ is the log vol. Using these two observations it's rather straightforward to see how the discrete (empirical) version connects to the continuous time version.
Comment: I have something different for the variance process. Also, what is the exact definition of mean-corrected?
Comment: @Taylor, see p.18, it's just shifted by mean: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.197.8017&rep=rep1&type=pdf


How many method to evaluate the integral $\int_{0}^{1} \frac{\ln ^{n}(1-x)}{x} d x , \textrm{ where }n\in N?$

Question: $$
\begin{aligned}
\int_{0}^{1} \frac{\ln (1-x)}{x} d x &\stackrel{x \rightarrow 1-x}{=} \int_{0}^{1} \frac{\ln x}{1-x} d x \\
&=\sum_{k=0}^{\infty} \int_{0}^{1} x^{k} \ln x d x \\
&=\sum_{k=0}^{\infty} \int_{0}^{1} \ln x d\left(\frac{x^{k+1}}{k+1}\right) \\
& \stackrel{I B P}{=} \sum_{k=0}^{\infty}\left(\left[\frac{x^{k+1} \ln x}{k+1}\right]_{0}^{1}-\int_{0}^1{\frac{x^{k}}{k+1}} d x\right) \\
&=-\sum_{k=0}^{\infty} \frac{1}{(k+1)^{2}} \\
&=-\zeta(2)
\end{aligned}
$$
Similarly,
$$
\begin{aligned}
\int_{0}^{1} \frac{\ln ^{2}(1-x)}{x} d x
\stackrel{x\mapsto 1-x}{=}  & \int_{0}^{1} \frac{\ln ^{2} x}{1-x} d x \\
=& \sum_{k=0}^{\infty} \int_{0}^{1} x^{k} \ln ^{2} x d x \\
\stackrel{IBP}{=} & \sum_{k=0}^{\infty} \frac{1}{k+1}\left(\left[x^{k+1} \ln ^{2} x\right]_{0}^{1}-\int_{0}^{1} 2 x^{k} \ln x d x\right) \\
\stackrel{IBP}{=}&-2 \sum_{k=0}^{\infty} \frac{1}{k+1}\left(\left[\frac{x^{k+1}\ln x}{k+1}\right]_{0}^{1}-\int_{0}^{1} \frac{x^{k}}{k+1} d x\right) \\
=& 2 \sum_{k=0}^{\infty} \frac{1}{(k+1)^{3}} \\
=& 2 \zeta(3)
\end{aligned}
$$
Replacing the power of $\ln x$ by $n$ and performing integration by parts by $n$ times yields $$
\begin{aligned}\int_{0}^{1} \frac{\ln ^{n}(1-x)}{x} d x &\stackrel{x\mapsto 1-x}{=} \int_{0}^{1} \frac{\ln ^{n} x}{1-x} d x\\ &\qquad\qquad \vdots \\&= (-1)(-2)(-3) \cdots(-n) \sum_{k=0}^{\infty} \frac{1}{(k+1)^{n+1}}\\&= (-1)^{n} n ! \zeta (n+1)\end{aligned}
$$
My Question
Is there an alternative method to evaluate the integral?
Comment: Your solution is very good. Notice that $n$ does not need to be an integer (the result will be complex, that's all). You could even use complex values for $n$.
Comment: By the way, your deleted answer with the sum in terms of $\frac{1}{k+a+1}$ is strongly reminiscent of the polygamma functions, as is your final closed form very reminiscent of their derivatives at $1$
Comment: I had fixed it . Have a look.
Answer: Right of the top of my head I can see two ways. There might be many more.
1:-
$$\int_{0}^{1} \frac{\ln^{n} (1-x)}{x} dx=\int_{0}^{1}\frac{\ln^{n}(x)}{1-x}\,dx$$.
Using $\sum_{r=0}^{\infty}x^{r}=\frac{1}{1-x}\,\,\,,|x|<1$.
Then Using DCT.
$$\sum_{r=0}^{\infty}\int_{0}^{1}\ln^{n}(x)x^{r}\,dx$$.
Let $x=e^{-t}$
Then :-
$$\sum_{r=0}^{\infty}\int_{0}^{\infty}(-1)^{n}t^{n}e^{-(r+1)t}\,\,dt=$$.
Now substituting $(r+1)t=z$ and using Gamma function you have:-
$$\sum_{r=0}^{\infty}\frac{(-1)^{n}\Gamma(n+1)}{(r+1)^{n+1}}=(-1)^{n}n!\zeta(n+1)$$.
Alternatively:-
$$\int_{0}^{1}(1-x)^{k-1}x^{m-1}\,dx=B(m,k)=\frac{\Gamma(k)\Gamma(m)}{\Gamma(m+k)}$$.
So differentiating partially wrt $m$. You have :-
$$\frac{\partial B(m,k)}{\partial m}=\int_{0}^{1}(1-x)^{k-1}x^{m-1}\ln(x)\,dx$$.
Proceeding inductively:-
$$\frac{\partial^{n} B(m,n)}{\partial m^{n}}\bigg|_{k=0,m=1}=\int_{0}^{1}\frac{\ln^{n}(x)}{1-x}\,dx$$
To differentiate the Gamma function and evaluating , you will need values of the polygamma function.
Answer: I would like to switch the integration into differentiation process by defining an integral partner $$I(a):=\int_{0}^{1} \frac{\ln(1-x)(1-x)^{a}}{x} d x.$$
Then
$$ \begin{aligned}I(a)& \stackrel{x \mapsto 1-x}{=} \int_{0}^{1} \frac{x^{a}\ln x}{1-x} d x\\&=\sum_{k=0}^{\infty} \int_{0}^{1} x^{k+a} \ln x d x
\\& \stackrel{IBP}{=} -\sum_{k=0}^{\infty} \frac{1}{(k+a+1)^2}
\end{aligned}$$
Differentiating both sides w.r.t. $a$ by $n-1$ times yields $$
\begin{aligned} \int_{0}^{1} \frac{\ln (1-x)}{x} \frac{\partial^{n-1}}{\partial a^{n-1}}(1-x)^{a} d x&=-(-2)(-3)\cdots(-n) \sum_{k=0}^{\infty} \frac{1}{(k+a+1)^{n+1}}\\\int_{0}^{1} \frac{1}{x}(1-x)^{a} \ln ^{n}(1-x) dx&= (-1)^nn!\sum_{k=0}^{\infty} \frac{1}{(k+a+1)^{n+1}}
\end{aligned}
$$
Now we can conclude that
\begin{aligned}
\int_{0}^{1} \frac{\ln ^{n}(1-x)}{x} d x &=I^{(n)}(0)\\ &=(-1)^{n} n ! \sum_{k=0}^{\infty} \frac{1}{(k+1)^{n+1}} \\
&=(-1)^{n} n !\zeta(n+1)
\end{aligned}


H-space multiplication question (homotopy)

Question: Let $(X,x_0)$ be a $H$-space with multiplication $\mu:X\times X\to X$.
Let $e$ denote the constant map $I^n\to x_0$.
Is it true (and why) that
$\begin{cases}
\mu(f(2x_1,x_2,\dots,x_n),e),&x_1\in[0,1/2]\\
\mu(e,g(2x_1-1,x_2,\dots,x_n)),&x_1\in[1/2,1]
\end{cases}$
is homotopic to $\mu(f(x_1,x_2,\dots,x_n),g(x_1,x_2,\dots,x_n))$?
I am not sure how the multiplication $\mu$ in $H$-spaces work, other than that it is continuous.
Thanks.
Comment: This looks like an Eckmann-Hilton argument.
Answer: It is true if $f|_{x_1=1}$ and $g|_{x_1=0}$ are constant maps to $x_0$, otherwise the maps that you define will be not continuous.
Let $f_t(x_1,x_2,\dots,x_n):=
\begin{cases}
f((2-t)x_1,x_2,\dots,x_n),&x_1\in[0,(1+t)/2]\\
x_0,&x_1\in[(1+t)/2,1]
\end{cases}$
and $g_t(x_1,x_2,\dots,x_n):=
\begin{cases}
x_0,&x_1\in[0,(1-t)/2]\\
g((2-t)x_1,x_2,\dots,x_n),&x_1\in[(1-t)/2,1]
\end{cases}$
Then the product $\mu(f_t(x_1,x_2,\dots,x_n),g_t(x_1,x_2,\dots,x_n))$ will be a desired homotopy.


Convergence of infinite product

Question: This could be something which is already somewhere in the website, but I am unable to locate any.
Prove $$\prod_{n=1}^{\infty} (1-z^n)$$ converges absolutely and uniformly on each compact subset of $\biggr[{|z|<1}\biggr]$.
What about $\biggr[{|z|>1}\biggr]$?
I have a feeling this need to be done with using some logarithm expansion and using Weierstrass theorem. But I do like to see more ideas of proof. I am not sure on using those ideas either.
Comment: Try taking $z=1+\epsilon$.  What happens to the size of the terms in the product?
Comment: For more references see ['Euler function'](http://en.wikipedia.org/wiki/Euler_function).
Answer: You should use the definition of absolute convergence of a product: $\prod(1+y_n)$ converges absolutely if and only if $\sum|y_n|$ converges. You can also use the fact that a necessary condition for a product $\prod(1+y_n)$ to converge is that $y_n\to0$. These two statements should allow you to prove the first statement and show that in the second case, the product diverges.
Comment: So the hint given by @Eric Naslund make sense now. Thanks Greg Martin.
Comment: You're welcome! This is a good example to show why the fundamentals of a subject are so important. We can't treat every problem like a brand new mystery unto itself; we need to build up basic techniques to run new problems by, to sort the easily solved ones from the ones that require deeper though.

Convergence of infinite product


jquery mobile changepage and refresh page

Question: I am new to web-development and have built a website consisting of:

index.html
graph.html
myScript.js

The graph.html is building up the content due to given parameter, specified on what you do in the main page (index.html). After having a look here, I came up with this changePage call in my myScript.js when a button is clicked:
$.mobile.changePage('graph.html', { dataUrl: 'graph.html?ip='+id, data: { 'ip': id }, transition: "slide", changeHash: true, reloadPage : true} );

Thereby, id is just a String (e.g.: load-21) and I make an ajax-call with the help of the id.
The resulting URL looks like this: http://192.168.131.11:18069/CoDEViewTest/#graph.html?ip=load-21
Now the first call works fine, but if I hit refresh (F5) when I am on the graph.html page, I automatically get back to the main page (index.html), but I still have the same URL (http://192.168.131.11:18069/CoDEViewTest/#graph.html?ip=load-21  ). The behaviour I would like to have, is that the graph.html is reloaded. I found out that it works, if I call changePage like this:
$.mobile.changePage('graph.html?ip=' + id, { transition: "slide", changeHash: true, reloadPage : true} );

In this case,the URL is a bit different (note: there is no '#' in the URL): http://192.168.131.11:18069/CoDEViewTest/graph.html?ip=load-21
And in this case, when refreshing the page, I stay on the graph.html.
Now my question is, what is the difference between these two calls? Also, from my first impression after googling, I think that the second call is not a good practise. Therefore, I would like to work with the first call, but I need to stay on graph.html when refreshing the page..
Thanks
Comment: If you're still struggling with this, I recently released a [plug-in](https://github.com/CameronAskew/jquery.mobile.paramsHandler) which may help you with this.
Answer: To understand this you must look at a basis of how jQuery Mobile works.
It uses AJAX to load pages into the DOM. Only first page is fully loaded, that means it HEAD and BODY content is loaded into the DOM. Every subsequent HTML page will me mostly discarded, basically only div with data-role="page" will be loaded into the DOM. Even more only one data-role="page" div will be loaded, every other page div will be discarded like rest of the page.
It is a normal state if you think about it. We already have HEAD from initial HTML page, we don't need another one.
This said, when you send parameter from one HTML page to another you are basically sending it to your initial HTML page. Remember what I have told you, subsequent pages are discarded so in your case page graph.html don't exist, its content is assimilated to index.html. Basically what was one a page inside a graph.html is now page inside a index.html.
Lets go even further. You have forced page reload with reloadPage : true but from link point of view this is still index.html. If you take a look:
http://192.168.131.11:18069/CoDEViewTest/#graph.html?ip=load-21

There's a hash # between / and graph.html. And that hash is a problem here. This is not an error, it is simply how jQuery Mobile works. If you press F5 in this case you will invoke index.html refresh.
In your other case, a situation is a little bit different. This case is working correctly mainly because you are refreshing your page and parameters set after the graph.html are preventing jQuery Mobile from attaching page hash #. This call acts as a real page reload and final link looks like this:
http://192.168.131.11:18069/CoDEViewTest/graph.html?ip=load-21

Because # don't exist thus DOM is fully empty from jQuery Mobile content there's nothing here that can hijack loading logic thus graph.html will reload again into graph.html.
EDIT :
I should also note that there's nothing wrong with your second solution, while it is not advised to use it in some situations in your case it will work just fine. Just remember one thing always have a HEAD content, this will prevent reloading problems. But there's one main difference, sides are changed now. At this point grap.html is fully loaded into the DOM and when you transit back to index.html only its data-role="page" div will be loaded into the DOM. Basically only downside of your solution is that you can have only one data-role="page" per HTML file. Where in your first case index.html could have more then one page inside.
Comment: Thanks for the good answer, just one more thing: Would you know suggest to stay with the second approach or is there a way to stay with the first approach somehow?
Comment: I'm sorry, I didn't recognize my typo early enough to change it.. I meant "Would you now..."
Comment: You can still use second solution, while it is not advised to use it in some situations in your case it will work just fine. Just remember one thing always have a HEAD content, this will prevent reloading problems. But there's one main difference, sides are changed now. At this point grap.html is fully loaded into the DOM and when you transit back to index.html only its data-role="page" DIV will be loaded into the DOM. Basically only downside of your solution is that you can have only one data-role="page" per HTML file. Where in your first case index.html could have more then one page inside.


Lognormal Distribution as Maximum Entropy Probability Distribution

Question: According to the wikipedia article on the lognormal distribution, the lognormal distribution is "the maximum entropy probability distribution for a random variate $X$ for which the mean and variance of $\log(X)$  is fixed".
Is there a not too complicated account of what this means and how this is derived?
Comment: You didn't correctly copy the sentence from wikipedia. Insert a $\ln(X)$ between 'is' and 'fixed'.
Comment: I've inserted a $\ln(X)$ before "is fixed", thanks for the hint.
Comment: The Wikipedia article references a [clear paper](http://www.wise.xmu.edu.cn/Master/Download/..%5C..%5CUploadFiles%5Cpaper-masterdownload%5C2009519932327055475115776.pdf) by Park & Bera in which the result is derived.
Answer: Note that the $\log(X)\sim \mbox{Normal}(\mu,\sigma^2)$, therefore they are actually making a claim regarding the normal distribution. For a normal distribution we have that

The normal distribution Normal$(\mu,\sigma^2)$ has maximum entropy among all real-valued distributions with specified mean $\mu$ and standard deviation $\sigma$.

Check this wikipedia entry for more details (including the proof of this result): http://en.wikipedia.org/wiki/Maximum_entropy_probability_distribution#Given_mean_and_standard_deviation:_the_normal_distribution
Comment: Thanks a lot for this hint, it was quite helpful. Also I had seen the paper linked on wikipedia, it did not look trivial though. I have one question regarding this property: We do have biological data where the data is a set of measured lenghts, and these lengths have a lognormal distribution. Knowing that in biology cost-minimization is crucial, I wondered if the Maximum Entropy property could be linked to cost-reduction? Sorry if the question is vague! P.
Comment: This is a new question, you should then ask it as a new question, not just in comments!


java.lang.IllegalStateException: The specified child already has a parent. (After editing my post)

Question: building android,location based application. I have my class that initiate google maps api work (MygoogleMapsActivator). this is constractor of this class
public MyGoogleMapsActivator(Context mContext)
    {
          this.mContext = mContext;
    }

.
Context mContext is a activity where i need to display map and address,a pass it here for getting services that i need to activate.Activity displaying the results - my location and address(location and address i am getting from MyGoogleMapsActivator)
when i want to display it on my activity i get this exception in LogCat: Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
i am getting ti from this function:
    public void SetUpTextViewWithAddress()
        {
             text = (TextView) findViewById(R.id.address);
             text.append(addressString);
             setContentView(text);
        }

How can i solved it,thanks.
This is full code of my activity:

    protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_add_new_place);

                mGoogleMapsActivator = new MyGoogleMapsActivator(this);

                Button buttonAddPlace = (Button) findViewById(R.id.buttonAddPlace);
                Button buttonAddByAddress = (Button) findViewById(R.id.buttonAddByAddress);

                fm = (SupportMapFragment ) getSupportFragmentManager().findFragmentById(R.id.map);
                buttonAddPlace.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        Intent intent = new Intent(AddNewPlaceActivity.this, AddByAddress.class);

                        mMyPlace = new Places("", city, street, number, "", LoggedWithFacebookMainActivity.GetLoggedInUserName(), myPosition.latitude, myPosition.longitude);
                        intent.putExtra("Place", mMyPlace);
                        //intent.putExtra("TheStreet", street);
                        //intent.putExtra("TheNumber", number);
                        intent.putExtra("Clarification");
                        startActivity(intent);
                    }
                });

                buttonAddByAddress.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent intent = new Intent(AddNewPlaceActivity.this, AddByAddress.class);

                        mMyPlace = new Places("", city, street, number, "", LoggedWithFacebookMainActivity.GetLoggedInUserName(), myPosition.latitude, myPosition.longitude);
                        intent.putExtra("Place", mMyPlace);
    //                  intent.putExtra("TheStreet", "Street");
    //                  intent.putExtra("TheNumber", "Number");
                        intent.putExtra("Clarification");
                        startActivity(intent);
                    }
                });

                mGoogleMapsActivator.SetUpMapIfNeed(fm);
            mGoogleMapsActivator.SetMyGoggleActivatorLocationEnabled();
            mGoogleMapsActivator.SetUpService();
            mGoogleMapsActivator.setUpListener();
            mGoogleMapsActivator.SetUpAndGetProvider();
            mGoogleMapsActivator.SetMyLocationWithListener();
            mGoogleMapsActivator.SetMyPosition();
            mGoogleMapsActivator.SetUpMyMarker();
            mGoogleMapsActivator.SetUpMapView();
            mGoogleMapsActivator.SetUpAddressFromGeocoder();
            city = mGoogleMapsActivator.getCity();
            street = mGoogleMapsActivator.getStreet();
            number = mGoogleMapsActivator.getNumber();
            addressString = mGoogleMapsActivator.getAddressString();
            SetUpTextViewWithAddress();
            mGoogleMapsActivator.AnimateCamera();

  public void SetUpTextViewWithAddress()
    {
         text = (TextView) findViewById(R.id.address);
         text.setText(addressString);
        // setContentView(text);
    }

}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="end"
    tools:context=".AddNewPlaceActivity" >

<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="370dp" />

<TextView
    android:id="@+id/address"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/buttonAddByAddress"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/map"
    android:layout_toLeftOf="@+id/buttonAddPlace"
    android:text="@string/place_address_he" />

<Button
    android:id="@+id/buttonAddPlace"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/buttonAddByAddress"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/address"
    android:background="@drawable/custom_button_main"
    android:paddingBottom="10dp"
    android:text="@string/add_place_he" />

<Button
    android:id="@+id/buttonAddByAddress"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:background="@drawable/custom_button_main"
    android:paddingTop="10dp"
    android:text="@string/add_place_manually_he" />

</RelativeLayout>

Thanks
Answer: The issue is the TextView is already attached to your view hierarchy. I'm guessing the view with address id is already inside the main layout file you are using for your activity, without the full activity code it's hard to tell. If this is true you should remove the setContentView call as it isn't needed. Make sure you want to append the text to what may already be in the TextView, if you want to replace the text you should use setText instead of append.
Comment: i removed it,but still same exception


Ficar testando até uma variável ser criada no php

Question: Estou enviando um ajax para uma tabela, porém essa tabela só pode ser criada depois de receber o valor, porém ela esta sendo criada antes em branco, como posso fazer uma verificação para a tabela ser gerada só depois de receber o valor ajax, ficar em um loop testando a variavel ser interromper o codigo php até a variavel receber o seu valor correto.
Tentei isso e não foi:
 if (isset($_POST['IdAparelho']))
            {
              $query = ("select id_principal from componentes where id_secundario = ".$_POST['IdAparelho']." ");
              $ids = mysqli_query($con,$query);
              while ($linha = mysqli_fetch_array($ids))
              {
                  $con = mysqli_connect("localhost","roberto","","manutencao");
                  $query = ("select * from componentes where id_principal = ".$linha[0]." ");
                  $componentes = mysqli_query($con,$query);
                  $resultado = mysqli_fetch_row($componentes);

                  $id_componente = $resultado[1];
                  $codigo = $resultado[2];
                  $nome = $resultado[3];
                  $entrada = $resultado[4];
                  $saida = $resultado[5];
                  $f = $resultado[6];
                  $m = $resultado[7];
                  $g = $resultado[8];
                  $gg = $resultado[9];
                  $total = ($f + $m + $g + $gg);

                  $id_componente = $resultado[1];
                  $codigo = $resultado[2];
                  $nome = $resultado[3];
                  $entrada = $resultado[4];
                  $saida = $resultado[5];
                  $f = $resultado[6];
                  $m = $resultado[7];
                  $g = $resultado[8];
                  $gg = $resultado[9];
                  $total = ($f + $m + $g + $gg);

                  print "
";
                    print "".$id_componente."	";
                    print "".$codigo."	";
                    print "".$nome."	";
                    print "".$entrada."	";
                    print "".$saida."	";
                    print "".$f."	";
                    print "".$m."	";
                    print "".$g."	";
                    print "".$gg."	";
                    print "".$total."	";
                  print "
";
                }
            }
          ?>

CÓDIGO AJAX:
     $(function () {
        $("#visualizarAparelhos").submit(function (e) {
        var index = $("#IdAparelho").attr('data-index');
        e.preventDefault();
        $.ajax({
          type: "POST",
          url: "administrador.php",
          dataType: 'html',
          data: {IdAparelho: index}
    }).done(function (data) {
        console.log(data);
    });
    });
    });

Comment: Por favor, mostre o código da criação da tabela.
Comment: Editei a postagem
Comment: Isto está sendo enviado usando Ajax: `$_POST['IdAparelho']`? Se sim, você já checou se existe algum valor dentro dessa variável?
Comment: Chequei sim, o problema é que a variável só deixa de ser nula, depois que a tabela já foi criada.
Comment: Roberto, na sua função javascript coloque um `console.log(index)` para ver se está variável está com algum valor antes de enviar para o php.
Comment: Fiz o teste, está sim passando o valor 1.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/49656/discussion-between-cesar-and-roberto-albino).
Answer: 1° - você abre uma conexão para cada linha da consulta "select id_principal from componentes where id_secundario = ".$_POST['IdAparelho']." te sugiro abrir 1 conexão só e fechar ela depois do loop
2° - esta situação não poderia ser resolvida com
if (isset($_POST['IdAparelho']))
        {
          $query = ("select * from componentes where id_secundario = ".$_POST['IdAparelho']." ");
          $ids = mysqli_query($con,$query);
          while ($linha = mysqli_fetch_array($ids))
          {

              $id_componente = $linha[1];
              $codigo        = $linha[2];
              $nome          = $linha[3];
              $entrada       = $linha[4];
              $saida         = $linha[5];
              $f             = $linha[6];
              $m             = $linha[7];
              $g             = $linha[8];
              $gg            = $linha[9];
              $total         = ($f + $m + $g + $gg);

3º - Onde você "testa a variavel que vai interromper o codigo php" ?
Comment: if (isset($_POST['IdAparelho']))  , <------ aqui, eu só posso criar a tabela depois que $_POST['IdAparelho'] ja ter o seu valor.
Comment: Você fica requisitando esta página até ter algum valor no "$_POST['IdAparelho']" ?
Comment: Estou tentando fazer isso, não consegui ainda.
Comment: Valida no Jquery se tem algo para ser enviado antes de enviar para o PHP, vai evitar de você fazer Ns requisições...
Comment: O problema é que depois que o servidor passa ali e encontra a variável vazia ele não volta mais, dai o código não é executado.
Comment: Coloca o código que faz a chamada ajax
Comment: Editei a publicação.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/49669/discussion-between-bartolomeu-s-gusella-and-roberto-albino).


Proof of Backward Kolmogorov Equation. Question on remainder of Taylor's theorem and limit of integrals on decreasing balls

Question: These are the conditions we impose on the Markov process and transition function.

Using this definition, we prove the backward Kolmogorov Equation.

Now it says that we have $u(x,t)=f(x)$ from the fact that $f \in C_b(\mathbb{R})$ and the arbitrariness of $\epsilon$. Taking $s \to t$, I can see that all we need is the middle term to $\to 0$ as $\epsilon \to 0$. But how can we ensure this here from the property of continuous boundedness of $f$?
Finally, in the use of the Taylor's theorem below, how do we get the remainder term for the second order Taylor as $\frac{1}{2}\frac{\partial^2 u(x,\rho)}{\partial x^2}(z-x)^2 \alpha_\epsilon$? I cannot find out which form of remainder gives this. I would greatly appreciate any help.
Answer: Taking $s\to t$, I can see that all we need is the middle term $\to 0$ as $\varepsilon \to 0$. But how can we ensure this here from the property of continuous boundedness of $f$?
Fix $x \in \mathbb R$. Since $f \in C_b(\mathbb R)$ we have that for any $a>0$ there exists $b>0$ (depending on $a$) s.t. $|f(x)-f(y)| < a$ for any $y$ s.t. $|x-y|<b$. Let $\omega_f(I) := \sup\{ |f(t)-f(u)|, u,t\in I\} $.
Claim: For any bounded interval $I$, $\omega_f(I)<\infty$, furthermore if $I_n$ is a shrinking system of intervals (i.e. $I_{n+1}\subset I_n$ for any $n$) s.t. $\bigcap_n I_ = \{x\}$, then $\omega_f(I_n) \searrow 0.$
Proof: Let $I$ be any bounded interval. Then for any $x,y \in I$ we have $|f(x)-f(y)| \leq |f(x)| + |f(y)| \leq 2\sup_{x\in I}|f(x)| <\infty $, due to $f\in C_b$. Hence $\omega_f(I) = \sup_{x,y\in I} |f(x)-f(y)| <\infty$.
Now suppose $I_n$ is a shrinking sequence and there exists $\varepsilon>0$ s.t. $\omega_f(I_n) \ge \varepsilon$ for all $n$. For this $\varepsilon$ due to continuity there is a $\delta>0$ s.t. $|f(x)-f(y)|<\varepsilon/4 $ for any y s.t. $|y-x|<\delta$.  Well this means that $|f(y)-f(y')|<\varepsilon/2$ whenever $|y-x|<\delta$ and $|y'-x|<\delta$, furthermore $|y-y'|<2\delta$. Since $I_n\to \{x\}$, $diam(I_n)\to 0$, meaning that there is an index $n$ s.t. $diam(I_n)<2\delta$.  This would mean that
$$ \omega_f(I_n) \geq \varepsilon $$
but due to the previous argument
$$ |f(y)-f(y')|<\varepsilon/2 $$
whenever $|y-y'|<2\delta$ and $\max\{|x-y|,|x-y'|\}<\delta$. This would mean that
$$ \sup\{|f(y)-f(y')|: y,y'\in I_n\}\leq \varepsilon/2 $$
which contradicts our original assumption.  $\Box$
Hence
$$ \big|\int_{|x-y|\le \varepsilon} (f(y)-f(x)) P(dy,t|x,s)\big|\le \int_{|x-y|\le \varepsilon} |f(y)-f(x)| P(dy,t|x,s) \le \omega_f(\overline{B(x,\varepsilon)}) P(\overline{B(x,\varepsilon)},t|x,s)<\omega_f(\overline{B(x,\varepsilon)})$$
due to our previous claim this tends to zero as $\varepsilon \to 0$.
Finally, in the use of the Taylor's theorem below, how do we get the remainder term for the second order Taylor as $\frac12 \frac{\partial^2 u(x,ρ)}{\partial x^2}(z−x)^2(1+\alpha_\varepsilon)$?
According to Taylor's theorem
$$ u(z,\rho)-u(x,\rho) = \partial_x u(x,\rho)(z-x) + \frac12 \partial^2_x u(\xi_z,\rho)(z-x)^2 $$
for some $\xi $ s.t. $|x-\xi_z|<|x-z|$. If $\partial_x^2 u$ is continuous then it can be shown that $\partial^2_x u(\xi_z, \rho) \to \partial_x^2 u(x,\rho)$ whenever $|z-x| \to 0$, i.e. $z\to x$. I don't think that the equality in (2.49) holds. It rather says that $ \partial^2u_x(z,\rho)$ is close to $\partial_x^2u(x,\rho)$ whenever $z$ is close to $x$, i.e.
$$ |\partial_x^2 u(\xi_z,\rho) - \partial_x^2 u(x,\rho) | \le \sup_{t,|x-z|\le \varepsilon} \big| \partial_x^2u(x,t) - \partial_x^2 u(z,t) \big| $$


How to open website after specific time in c++?

Question: Here is my code:

<code>#include<iostream>
#include <windows.h>
using namespace std;
int main(){
  ShellExecute(0, 0, L"www.ldjgsdoij.com", 0, 0 , SW_SHOW );
  int i;cin>>i;
  return 0;
}
</code>
How to open this web www.ldjgsdoij.com after 15 minutes even if the client
has runned exe file and closed it?
Comment: why not try `schtasks` command in windows?
Comment: @mohammedawni do you intend to stay that way? I don't see what yelling "I am novice!!!!" helps you. Just google `at` and `schtasks` then. Perhaps you'll remember a bit of it, and in some year(s) you won't be novice anymore.
Comment: I don't think it is possible , you MUST have a process running in background.
Answer:
you can use C++11 Chrono functions for time.
see also Stackoverflow answer How to create timer events using C++ 11?
I think the best way it to use Schedule Tasks in Windows or Cron in Linux
For open URLs see the following answer on open browser window


Why are users seeing UAC, when installing shared printer drivers, when they were not previously after a printer host name change?

Question: I have a Windows 2008R2 print server hosting about 40 printers. For the longest time we had a Point and Print GPO that allowed the users to install the drivers for these printers without administrative interaction. Administrative Templates\Printers\Point and Print Restrictions: Disabled. This is still in place. Recently though that is no longer working.
Take the "sales" printer for example. People have been connected to it for years now and in the last few days, when someone tries to print, their computers (All Windows 7) have been asking to install a print driver. Even new users that have not been attached to that printer before are being asked for admin rights to install the printer. This has affected about half of the printers on this printer server. So some printers users are able to install just fine. So when someone has the issue I hop on their machine and provide my rights so the print driver will install.
I am sure I know of the catalyst that caused this but I have no idea how it directly relates. For inventory purposes, I updated the host names of the printers. To clarify I went on the web interface off all the printers and in each of their network IPv4 configurations I updated the host name from its generic Ricoh to be the same as the DNS record I made for the printer. So each printer has a share name, port name on the printer server which are both the same as the physical printers host name e.g. "sales". No changes have been made to the print server hosting these printers. I don't understand how that change would cause this.
In the case of the "sales" users it is preventing them from printing. We have to allow the driver to update before they can print. That is how we knew there was an issue and was able to tie it to my inventory update. These users are not all in the same OU in AD and both have the same policies applied anyway.
I am testing different GPOs as when you look up network printer driver GPOs there are more things people change than just the one I mentioned above.
Any ideas why what I did is causing this issue? Perhaps I am chasing the wrong tail and something else is wrong?
Comment: Not sure how to phrase this shorter, title included, without leaving out information or making it too vague.
Answer: This was a recent MS security update MS16-087 that addressed an issue with the Windows Print Spooler and installation of print drivers.
The KB article here https://support.microsoft.com/en-us/kb/3170005 indicates that you'll need to update to Package Aware Print Drivers to bypass the prompting.


Convert the following code from Matlab to Python

Question: I am new to Python and I am trying to convert and modify the following code from Matlab to python:
This is what I have so far ( I am also trying to make it for 3 dimensions):
import random
import numpy as np

L = 21.1632573
x = np.random.uniform(low=0.0000,high=L,size=10000)
y = np.random.uniform(low=0.0000,high=L,size=10000)
z = np.random.uniform(low=0.0000,high=L,size=10000)

prox = 1
N = 20

#First Point
firstX = x[0]
firstY = y[0]
firstZ = z[0]

counter = 0
for k in range(1,N):
    thisX = x[k]
    thisY = y[k]
    thisZ = z[k]
    distances = np.sqrt((thisX-firstX)**2+(thisY-firstY)**2+(thisZ-firstZ)**2)
    minDistance = np.min(distances)
    if minDistance >= prox:
        firstX[counter] = thisX
        firstY[counter] = thisY
        firstZ[counter] = thisZ
        counter = counter + 1

However, I am having a problem in the last if statement:
File "/home/aperego/codes/LJ_Problem1/canonical/randomParticles.py",
line 26, in <module> firstX[counter] = thisX

TypeError: 'numpy.float64' object does not support item assignment

Any help is appreciated!
Thanks
Answer: you assign numpy float to those variables. those variables should be list
firstX = x[0]  # all numpy.float64
firstY = y[0]
firstZ = z[0]

you should append new point to list
import random
import numpy as np

L = 21.1632573
x = np.random.uniform(low=0.0000,high=L,size=10000)
y = np.random.uniform(low=0.0000,high=L,size=10000)
z = np.random.uniform(low=0.0000,high=L,size=10000)

prox = 1
N = 20

#First Point
firstX = [x[0]]
firstY = [y[0]]
firstZ = [z[0]]

for k in range(1,N):
    thisX = x[k]
    thisY = y[k]
    thisZ = z[k]
    distances = np.sqrt((thisX-firstX[0])**2+(thisY-firstY[0])**2+(thisZ-firstZ[0])**2)
    minDistance = np.min(distances)
    if minDistance >= prox:
        firstX.append(thisX)
        firstY.append(thisY)
        first.append(thisZ)

Answer: firstX, firstY and firstZ are numbers so you can't use firstX[index]. So define them as list or array (if you know the final length).
I read your matlab code, I corrected it and plotted accordingly.
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

L = 21.1632573
x = np.random.uniform(low=0.0000,high=L,size=10000)
y = np.random.uniform(low=0.0000,high=L,size=10000)
z = np.random.uniform(low=0.0000,high=L,size=10000)

prox = 1
N = 20

#First Point
firstX = [x[0]]
firstY = [y[0]]
firstZ = [z[0]]

counter = 0
for k in range(1,N):
    distances = np.sqrt((x[k]-firstX)**2+(y[k]-firstY)**2+(z[k]-firstZ)**2)
    minDistance = np.min(distances)
    if minDistance >= prox:
        firstX.append(x[k])
        firstY.append(y[k])
        firstZ.append(z[k])
        counter = counter + 1

##Plotting
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(firstX,firstY,firstZ, c='b', marker='*')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()


Is there a theoretical limit to how fast we can find prime numbers?

Question: In other words:

Given some positive integer $n$, is there a theoretical limit to how fast a computer with infinite computational power, memory, and storage, can find all the prime numbers below below $n$?

A similar question:

Given some positive integer $n$, is there a theoretical limit to how fast a computer with infinite computational power, memory, and storage, can find whether or not $n$ is prime?
Comment: https://en.wikipedia.org/wiki/AKS_primality_test. "Primes is in P" so you don't need that much time, even if your PC is "slow".
Comment: @TheBitByte Yes, that's correct.
Comment: Infinite computational power ? This would make the computer to an oracle, immediately finding the primes below $n$.
Comment: @b00nheT Are you referring to $P$ as in $\mathrm{P} = \bigcup_{k\in\mathbb{N}} \mathrm{DTIME}(n^k)$?
Answer: For simplification: Whenever I say number, I mean positive integer.
No, and your answers will have the same answer because finding all the prime numbers below n with require to check all numbers k, where k is every number less than n.
Theoretically, the brute-force method to checking primes (in this case, n or k) (which is generally never used in professional prime-finding) is to find two factors of the number by counting up from 2. If you reach n without finding any primes, then n is prime.
This requires arithmetic any computer can do at a rate exponentially proportional to its computational power, memory, and storage. Therefore, it can be modeled by a function, and as x approaches infinity, a polynomial equation with degree larger than 1 f(x) will approach infinity or negative infinity.
Basically a long way of saying no.
P.S. Unless you want me to be really nitpicky in which case I would ask about cooling systems, damage, and heat generated by computation, as well as outside influence and human error.
But ignoring all of those semi-avoidable things, no.


Single nginx configuration for multiple sub domains

Question: I have the following directory structure for my websites:
/var/www/sitename/subdomain/(public|log)
e.g /var/www/stackoverflow.com/careers/public/index.html
Can I make a single generic nginx configuration to do this? So that every domain is mapped to the right directory? I would not like to edit my nginx configuration for every website I add.
The root domain can always be mapped to the www subdomain.
Comment: The response you would get from the people who've used nginx the longest (in the IRC and on the mailing list) is to generate your configuration file automatically as it will work faster.
Answer: See this - http://cafuego.net/2009/07/15/playing-nginx
Comment: Please, give a small abstract here in the answer. That prevents this information from getting lost in the future.
Answer: See here
Comment: @mzhaase "the linked page" is hosted at stack exchange. So it would "become invalid" only if overly concerned community people deleted it. If so, why would it fit here? In any case I'm not going to invest my time.
Comment: The link you provided is dead. Could you update the link and give a small abstract here in the answer?
Comment: It was link to my answer to another question -- it seems died along with the question. I've updated the answer with another link
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/317846)


Alternative to chi-squared goodness-of-fit test for very small sample size

Question: I have a question similar to the ones described in the forum here (http://www.sthda.com/english/wiki/chi-square-goodness-of-fit-test-in-r).
I want to know whether one sex is more common than the other at a study site. Unfortunately, I am dealing with a very cryptic species and my sample size is less than 5 for each sex for a particular year.(male = 5, female = 3).
If I were to perform a chi-squared GOF test, my code would be as follows:
    sex.ratio = chisq.test(c(5,3), p = c(0.5,0.5))

Is there an alternative to the Chi-squared GOF Test that would be appropriate to run on this dataset with very small sample sizes?
Comment: Welcome to CV!  Such a test would be pointless, because the dataset is too small to conclude anything.  But what distinction are you making between "a chi-squared test" and "the Chi-squared GOF test"?
Comment: You can use a straight one sample binomial test of proportions (conditioning on the total count), but as whuber explained at the start, it really doesn't matter what test you would choose, the sample size is too small. If you want to use some $\alpha$ that's below 9/128 (ie. anything smaller than $\alpha=7.03125\%$), no reasonable two-sided test can be significant unless the split is 8-0 or 0-8 (that would be significant at the 1% level).
Comment: You use two different phrases to refer to these tests: do they mean the same thing or not?  Regardless, *no* test is about counts.  All hypothesis tests are about inherent properties of the distribution, not about the data.
Comment: I am asking if there is a similar test but for very small sample sizes. Because all the stats forums I have read mention I should not use chi-squared gof test if the sample size is <5. I came across Yates correction and Fisher's exact test, but they do not work the same way as chi-squared gof test. Anyway, it seems pointless to try and do any test with such a small sample size (which I already knew, but was hoping someone here would have other suggestions.)
Comment: Correct me if I am wrong, but I specified GOF test, because I am dealing with expected probabilities and not counts.
Comment: I meant the same thing, but as far as R coding goes, it's chisq.test(observed_vector_count, p = expected_probability_vector) for GOF test, and chisq.test(matrix) for test of independence (not what I am interested in)
Comment: @Rnoobie Your question is quite unclear, because the R code you give *is* a chi-squared goodness-of-fit test, but just after that you ask how to conduct it. It looks like you're misinterpreting what a goodness-of-fit test is, or that you are omitting some information necessary for us to understand your question.
Comment: @Rnoobie I see. I suggested an edit to the question to make it a bit less ambiguous.
Answer: Because the counts are small, you might use an exact binomial test:
binom.test(5, 8)

or a chi-square test with Monte Carlo simulation
chisq.test(c(5, 3), simulate.p.value=TRUE, B=10000)

However, think about the the meaning of the p-value in this case.  It's analogous to flipping a coin 8 times (with the null hypothesis being that the coin is fair, with a 50/50 probability of getting heads).  If you flip the coin 8 times, would it be that surprising to get 5 heads even if the coin is fair ?


prepend anything before a select

Question: I just recognized that I am not able to prepend anything in front of a SELECT-Tag with ID.
$('#foo').prepend('bar');

on
<select></select>

gives me "bar" in front of the SPAN
but on
<select id="foo"></select>

nothing is prepended. Why?
Answer: Because you can only prepend an <option> or <optgroup> to a <select>. Ex: $('#foo').prepend('<option>bar</option>');. Anything else is invalid HTML. The .prepend() method inserts the specified content as the first child of each element in the jQuery collection.

$('#foo').prepend('<option>bar</option>');

<select id="foo"></select>

In your first example, $('#foo').prepend('bar'); just puts the text bar as the content of your span #foo, and doesn't do anything with the <select>
Comment: `` also valid tag
Comment: @charlietfl true, answer updated. They're so infrequently used I rarely remember them.

prepend anything before a select


Gradient and Hessian of the product of two quadratic forms

Question: Let $Q, R \in \mathbb{R}^{n\times n}$ such that $Q, R \succ 0$. Let $g\left(\boldsymbol{x}\right) : \mathbb{R}^{n} \to \mathbb{R}$ such that
$$g\left(\boldsymbol{x}\right)=\left(\frac{1}{2}\boldsymbol{x}^{T}Q\boldsymbol{x}\right)\left(\frac{1}{2}\boldsymbol{x}^{T}R\boldsymbol{x}\right)$$
I want to find the gradient and the Hessian  of $g\left(\boldsymbol{x}\right)$.

What I tried so far
To find the gradient and the Hessian using the derivative rules and got the following:

but while I notice (2nd element of the last row at the hessian calculation Ive got the term $2R\boldsymbol{x}\cdot Q\boldsymbol{x}$ which is column vector times another column vector and that's obviously a mistake.on my calculations product rule of gradient but I don't sure if It's a valid rule at matrix calculus. So, how can I calculate the gradient and the hessian  of $g\left(\boldsymbol{x}\right)$?
Comment: [Related](https://math.stackexchange.com/q/222894/339790)
Answer: The individual terms are easy to handle:
$$\eqalign{
\def\LR#1{\left(#1\right)}
\def\fracLR#1#2{\LR{\frac{#1}{#2}}}
\def\p{\partial}
\alpha &= \tfrac{1}{2}x^TQx,
\qquad \frac{\p\alpha}{\p x} &= Qx,
\qquad \frac{\p^2\alpha}{\p x\,\p x^T} &= Q
\\
\beta &= \tfrac{1}{2}x^TRx,
\qquad \frac{\p\beta}{\p x} &= Rx,
\qquad \frac{\p^2\beta}{\p x\,\p x^T} &= R \\
\\
}$$
The calculation for their product is straight forward:
$$\eqalign{
\pi &= \alpha\beta \\
\\
\frac{\p\pi}{\p x}
 &= \beta\frac{\p\alpha}{\p x}
  + \alpha\frac{\p\beta}{\p x} \\
 &= \beta Qx \;+\; \alpha Rx \\
\\
\frac{\partial^2\pi}{\p x\,\p x^T}
 &= \beta\fracLR{\p^2\alpha}{\p x\,\p x^T}
  + \fracLR{\p\beta}{\p x} \fracLR{\p\alpha}{\p x^T}
  + \fracLR{\p\alpha}{\p x} \fracLR{\p\beta}{\p x^T}
  + \alpha\fracLR{\p^2\beta}{\p x\,\p x^T} \\
 &= \beta Q \;+\; Rxx^TQ \;+\; Qxx^TR \;+\; \alpha R \\
}$$

Update
This update addresses ordering issues raised in the comments.
Differentials are often the best approach for matrix calculus problems because, unlike gradients, they satisfy a simple product rule:
$$\eqalign{
d(A\star B)
 &= (A+dA)\star(B+dB) \;\;-\;\; A\star B \\
 &= dA\star B + A\star dB \\
}$$
where
$A$ is a {scalar, vector, matrix, tensor},
$B$ is a {scalar, vector, matrix, tensor}, and
$\star$ is any product which is compatible with $A$ and $B.\;$ This includes the Kronecker, Hadamard/elementwise, Frobenius/trace and dyadic/tensor products, as well as the Matrix/dot product.
IFF the product commutes, you can rearrange the product rule to
$$d(A\star B) = B\star dA + A\star dB$$
The Hadamard and Frobenius products always commute. The other products are commutative only in special situations. For example the Kronecker product commutes if either $A$ or $B$ is a scalar, and the dot product commutes if both $A$ and $B$ are real vectors.
The differential and the gradient are related and can be derived from one another, i.e.
$$\frac{\p\alpha}{\p x} = Qx
\quad\iff\quad d\alpha = (Qx)^Tdx = x^TQ\,dx$$
Let's examine one of the terms in the preceding hessian calculation.
First calculate its differential, and then its gradient.
$$\eqalign{
 y &= \alpha(Rx) = (Rx)\alpha
  \qquad \big({\rm the\,scalar\star vector\,product\,commutes}\big) \\
dy &= \alpha(R\,dx) + (Rx)\,d\alpha \\
   &= \alpha R\,dx \;\;\,+ Rx\;x^TQ\,dx \\
   &= (\alpha R+Rx\,x^TQ)\,dx \\
\frac{\p y}{\p x} &= \alpha R+Rx\,x^TQ \\
}$$
Comment: Here's how to handle the transposed gradients
$$\eqalign{
&1)\quad\;\frac{\partial\beta}{\partial x^T}
 &= \left(\frac{\partial\beta}{\partial x}\right)^T \\
&2)\;\;\frac{\partial^2\beta}{\partial xx^T}
 &= \frac{\partial}{\partial x}\left(\frac{\partial\beta}{\partial x^T}\right) \\
}$$ As for changing the order, since $(\alpha,\beta)$ are scalars they can be moved to any convenient position without changing the value of an expression.
Comment: where I can find the rules of derivatives according to $x^T$ (a row vector)?
(I know the rules of derivatives according to x)
Comment: ( i guess its not same as derivatives according to $x$)
Comment: and, in the 2'nd term , why did you change the order of $\alpha,\beta$? here what i did: [link](https://imgur.com/EVbfjjw) it became matrix plus scalar and that's is incorrect.
Comment: $\alpha,\beta$ are scalar but  $\frac{\partial\alpha}{\partial\boldsymbol{x}},\frac{\partial\beta}{\partial\boldsymbol{x}}$ are vectors , and I don't think you can just change their order.here what I did and encounter the same issue again: [link] (https://ibb.co/KXjY8Bs)
Comment: thanks for all the support!
just to be sure,
here what I did : https://ibb.co/F7gYMyq
originally I used product rule at (1) and got a dimensional error.
but,at (2)  I used product rule with commutative property I got the right answer.(without a dimensional error)
I think I've got a mistake while using the product rule. what am I missing?
Answer: I would suggest the following: $g(x)$ can be rewritten as
$$
g(x)=\left(\frac{1}{2}\sum_{i,j=1}^nQ_{ij}x_ix_j\right)\left(\frac{1}{2}\sum_{i,j=1}^nR_{ij}x_ix_j\right)
$$
where $Q_{ij}$ and $R_{ij}$ are the coefficients of the matrices $Q$ and $R$. Now you can proceed similarly as you did, taking derivative with respect to $x_k$, $k=1,\ldots,n$:
$$
\frac{\partial g}{\partial x_k}=\left(\frac{1}{2}\frac{\partial}{\partial x_k}\sum_{i,j=1}^nQ_{ij}x_ix_j\right)\left(\frac{1}{2}\sum_{i,j=1}^nR_{ij}x_ix_j\right)+\left(\frac{1}{2}\sum_{i,j=1}^nQ_{ij}x_ix_j\right)\left(\frac{1}{2}\frac{\partial}{\partial x_k}\sum_{i,j=1}^nR_{ij}x_ix_j\right).
$$
Can you take it from here?
Comment: Thanks!
I did that and the gradient is the same as the previous calculation,but what about the hessian?It's suppose to look like this ? (after the calculations)?
$\nabla^{2}g\left(\boldsymbol{x}\right)=\left(\frac{1}{2}\boldsymbol{x}^{T}Q\boldsymbol{x}\right)R+\left(\frac{1}{2}\boldsymbol{x}^{T}R\boldsymbol{x}\right)Q$


Find All Distinct values of x and y

Question: Let $x$ and $y$ be two positive integers such that $x+y< 537$. Under these conditions, find the sum of all distinct values of y such that $x^2+y^2=x^3$.
Unsure as to how to go about this question. I know for a fact that the answer is 812, but am not sure how to do it.
Comment: $y=xsqrt(x-1)$.  About 23 possible x value
Answer: We have that $$x^2 + y^2 = x^3$$ $$\Rightarrow y^2 = x^3- x^2 = x^2 (x-1) $$ $$\Rightarrow y = x\sqrt {x-1} $$
It is obvious that for $y$ to belong in $\mathbb Z^{+} $, we should have that $x-1 = k^2$ for $k\in \mathbb N $. Also, we have the condition that $x+y <537$. The permissible values of $k$ for which this is satisfied belongs to $[1,7] \in \mathbb N $. This can be easily checked.
Now summing up the corresponding $y$ terms gives us the value as $\boxed {812} $ confirming your thought. Hope it helps.

Find All Distinct values of x and y