How to register a custom built jar file as maven main artifact?

Question: I have a project expected to deliver a jar file:
<packaging>jar</packaging>

but the jar is built in a custom way, so the default packaging done with jar:jar has been disabled
<plugin>
  <artifactId>maven-jar-plugin</artifactId>
  <version>2.3.2</version>
  <executions>
    <execution>
      <id>default-jar</id>
      <phase>none</phase>
    </execution>
  </executions>
</plugin>

but then when I want to apply shade:shade on the existing jar I get an error

The project main artifact does not exist.

I assume that maven doesn't know about the .jar file created by my custom tool. How to let it know, because antrun attachArtifact doesn't work
<attachartifact file="./bin/classes.jar" classifier="" type="jar"/>

the error I get is

An Ant BuildException has occured: org.apache.maven.artifact.InvalidArtifactRTException: For artifact {:jar}: An attached artifact must have a different ID than its corresponding main artifact.

So this is not the method to register main artifact... Is there any (without writing custom java plugin)?
Thanks,
Lukasz
Answer: I checked the sources of JarMojo and it gave me an idea how to solve it with Groovy (via gmaven)
<plugin>
  <groupId>org.codehaus.gmaven</groupId>
  <artifactId>gmaven-plugin</artifactId>
  <version>1.3</version>
  <executions>
    <execution>
      <id>set-main-artifact</id>
      <phase>package</phase>
      <goals>
        <goal>execute</goal>
      </goals>
      <configuration>
        <source>
          project.artifact.setFile(new File("./bin/classes.jar"))
        </source>
      </configuration>
    </execution>
  </executions>
</plugin>

and it works!:)
Answer: Something like this
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.8</version>
    <executions>
        <execution>
            <id>attach-artifacts</id>
            <phase>package</phase>
            <goals>
                <goal>attach-artifact</goal>
            </goals>
            <configuration>
                <artifacts>
                    <artifact>
                        <file>${basedir}/bin/classes.jar</file>
                        <type>jar</type>
                    </artifact>
                </artifacts>
            </configuration>
        </execution>
    </executions>
</plugin>

Comment: This won't work -- you will have the same error as in the question: An attached artifact must have a different ID than its corresponding main artifact.
Answer: We were having the same problem, with getting the "attached artifact must have a different ID than its corresponding main artifact" error.  We found the solution in the following excellent blog post:
embed-and-run-ant-tasks-and-scripts-from-maven
As detailed in this section, you can fix the problem by adding a classifier so Maven can distinguish between the ant-built jar and the maven-built jar.  Since you're using antrun attachartifact, you'd need this:
<attachartifact file="./bin/classes.jar" classifier="foo" type="jar"/>

Note you'll also need to include that classifier (along with groupId, artifactId and version) whenever you want to grab this jar as a dependency in other projects.
Answer: While your solution may work for a build to the install+ phase or where there are no dependencies in the reactor, in cases where only building to the compile or test phase the unpackaged classes won't be found by dependencies.
Building to compile happens when using plugins like the maven-release-plugin.
Extending your chosen solution to include identifying the unpacked classes during compile
<plugin>
  <groupId>org.codehaus.gmaven</groupId>
  <artifactId>gmaven-plugin</artifactId>
  <version>1.3</version>
  <executions>
    <execution>
      <id>set-main-artifact-compile</id>
      <phase>compile</phase>
      <goals>
        <goal>execute</goal>
      </goals>
      <configuration>
        <source>
          project.artifact.setFile(new File("./bin/classes"))
        </source>
      </configuration>
    </execution>
    <execution>
      <id>set-main-artifact</id>
      <phase>package</phase>
      <goals>
        <goal>execute</goal>
      </goals>
      <configuration>
        <source>
          project.artifact.setFile(new File("./bin/classes.jar"))
        </source>
      </configuration>
    </execution>
  </executions>
</plugin>

By default the maven-install-plugin will use the identified artifact along the lines of
 ${project.build.directory}/${project.finalname}.jar
So another option might go something like this
<build>
    <directory>bin</directory>
    <outputDirectory>bin/classes</outputDirectory>
    <finalName>classes</finalName>
</build>

Comment: in multi-module relative paths don't work. I set `${basedir}/../jars-bundle/xxx.jar` and use `project.properties["prebuilt.jar"]` in groovy


JSoup BodyAsBytes connection to FileOutputStream to save temp file doesn't work?

Question: I used JSoup to parse a website with cookies. I want to download a file from the website using JSoup and the cookies which were saved in a hashmap using this piece of code:
Connection.Response res = Jsoup.connect("http://www.webpage.com/downloadpage).execute();
Map<String, String> cookies = res.cookies();

So when I try to download the file, I use this:
downloadFile(Jsoup.connect("http://www.webpage.com/file.ext).cookies(cookies).ignoreContentType(true).execute().bodyAsBytes());

and
private void downloadFile(byte[] fileByteArray) {
    try {
        File temprFile = File.createTempFile("tempfile", "ext", getCacheDir());
        temprFile.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(temprFile);
        fos.write(fileByteArray);
        fos.close();

        }  catch (MalformedURLException e){
            e.printStackTrace();
        } catch (IOException ex) {
        String s = ex.toString();
        ex.printStackTrace();
    }
}

The program runs without errors, but when I try to open the temporary file, it appears the file isn't complete. Each time, exactly 1.408.576 bytes are downloaded. For example when I download an mp3-file this way, the temporary file contains only 40 seconds of the original file. What am I missing here?
Help would be appreciated.
Thanks.
Comment: I just tried to download a file from a website, using `Jsoup`, as you describe in your question. I get the same length - the problem is the `byte[]` - it can hold more than 1.048.576 bytes...
Besides, it doesn't look like `Jsoup` is designed to download files ;-)
Comment: @Darwin the array limit in java is close to max integer and that is more than the number in the examples above. but thanks to your effort, it was  obvious that jsoup is limiting the array. searching on SO lead to the following post where the accepted answers shows that JSoup limits the download by default to 1MB. but it can be changed as seen there. http://stackoverflow.com/questions/11511614/how-to-limit-download-size-with-jsoup
Comment: Have you checked the basics? Does the temp file wind up being the same size as the HTTP response? Is the original file on the remote server actually complete, or could it really just be the first 40 seconds of the track?
Comment: I'm not sure, if this could be the case, but you're saving to the `cacheDir` of `Android`. According to the documentation there could be a limitation as to how much you can save there. See here: http://developer.android.com/training/basics/data-storage/files.html#WriteInternalStorage
Comment: Thanks for the fast replies. The file on the server is definitely complete, no problem streaming in Chrome on Win7. I've also tried saving the file to the external sd-card, but it ends up the same way. From each file on the server exactly 1.048.576 bytes are downloaded and written into a file in the cache memory or the sd card.
Comment: @BramDeBacker is it from the same place, you're trying to download or have you tried different websites to download from?
Comment: can you log the length of fileByteArray in the beginning of the "downloadFile" method? this way you will know if you are recieving incomplete data or if the system is limiting your writing into the temporary file.
Comment: @Darwin it can or it can't?
Comment: Interesting - and the explanation makes sense; to avoid memory leaks ;-) But as it seems like Jsoup can only return a byte[] and not a stream (or maybe it can) it wouldn't be suitable for bigger downloads anyways.
Answer: Guess I came to soon here to ask my question. Found the solution myself in the GitHub docs for JSoup. Thanks anyway for the responses!
https://github.com/jhy/jsoup/blob/master/src/main/java/org/jsoup/Connection.java
/**
 * Set the maximum bytes to read from the (uncompressed) connection into the body, before the connection is closed,
 * and the input truncated. The default maximum is 1MB. A max size of zero is treated as an infinite amount (bounded
 * only by your patience and the memory available on your machine).
 * @param bytes number of bytes to read from the input before truncating
 * @return this Connection, for chaining
 */
public Connection maxBodySize(int bytes);

Thanks anyway!
Answer: I added 0 to maxBodySize(0) and got full video downloaded. example Jsoup.connect(url).maxBodySize(0).ignoreContentType(true).execute().bodyAsBytes()


UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9d in position 0: invalid start byte when I execute the ` b.decode()`

Question: I have a code like bellow:
cn_bytes = [157, 188, 156]

cn_str = ""
clen = len(cn_bytes)
count = int(clen / 3)
for x in range(count):
    i = x * 3
    b = bytes([cn_bytes[i], cn_bytes[i + 1], cn_bytes[i + 2]])

    print(b)

    cn_str += b.decode()

when I execute it, I will get bellow error:
Traceback (most recent call last):
  File "/Users/dele/Desktop/TestIOS/TestPython/testDemo01/testDemo01/test08.py", line 30, in <module>
    cn_str += b.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9d in position 0: invalid start byte

there says:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9d in position 0: invalid start byte
Comment: I want to get the `cn_str`, but the b.decode() get error now.
Comment: In the truth this is part of my [question](https://stackoverflow.com/questions/56036745/how-to-run-a-webserver-module-in-my-distributed-project),  when I run the websocket server there I get this error.
Answer: Actually I think you can't convert entire list as bytes using bytes() . But still You can convert it into bytes by iterate through individual elements.
b = [cn_bytes[i], cn_bytes[i + 1], cn_bytes[i + 2]]

cn_str =  [bytes(i)for i in b]


What is the kubectl command for removing a subject from a rolebinding or cluserrolebinding

Question: I want to use kubectl to add/delete subjects from a k8s rolebinding or cluserrolebinding
Following kubectl command adds a subject to a rolebinding or cluserrolebinding
kubectl set subject clusterrolebinding <name> --user=<user>

But I couldn't figure out how I can delete a subject using kubectl
Answer: kubectl set subject doesn't support removing subjects from created ClusterRoleBindings or RoleBindings.
If you create a RoleBinding or ClusterRoleBinding from a file you can remove extra subjects by using
kubectl auth reconcile -f <config.yaml> --remove-extra-subjects

The kubectl auth reconcile command-line utility creates or updates a manifest file containing RBAC objects, and handles deleting and recreating binding objects if required to change the role they refer to.
This is preferred to 'apply' for RBAC resources so that
  semantically-aware merging of rules and subjects is done.


Warning :mounting fs with errors, running e2fsck is recommended

Question: Linux server will hang and when I restart it will take around 2 hours to come up and resume normal operations.
I checked the system log files and found mounting fs with errors, running e2fsck is recommended
I found some solution here, which says says using below commands
tune2fs -c 100 /dev/sdx1

tune2fs -i 90d /dev/sdx1

Got one more solution
/etc/fstab file looks like this:
file system           dir           type         options              dump  pass

UUID=123-456-ABC-DEF   /             ext4     defaults,noatime        0       0

we need to change pass value from 0 to 1 so that it will allow disk clean up
I'm really afraid as its a production box and if something goes wrong I should reconfigure.
what is the best approach and any suggestions are welcome.
Answer: Does you try to run e2fsck(or fsck)? It may help...
Also I could recommend to check  hardware status of your disks. Try to install smartmontools and check error log of your disk. You can use command for this:
smartctl --all /dev/sdx

And I am strongly recommend to made a backup before doing something.
Comment: can u please tel me how to run e2fsck(or fsck)
Comment: In most cases, you just need to run command `fsck /dev/sd[abc][12345]`. See this for more [examples](http://www.thegeekstuff.com/2012/08/fsck-command-examples/)
Answer: Make sure your backups are intact and workable before making major changes to the host filesystem. The following could possibly be classified as "major changes".
You're able to mount this filesystem, so it's not that damaged. You should definitely enable "pass" on the fstab to make sure your filesystems get checked regularly. EXT4 is a filesystem that requires offline maintenance like this every so often. Always use a pass option for it.
However, before you check and repair the filesystem on /, make sure the underlying disk is healthy. smartctl is a great tool for that, as user2986553 already mentioned. If your underlying block device has problems, running a filesystem repair has the potential of causing more problems than it would normally fix.
Once you've ensured your disk is healthy, run an offline check on your root filesystem. You will have to reboot for this, as EXT4 cannot be repaired while online, and read-only checks on an active mount will provide unreliable results. The easiest way to ensure this happens on your next reboot is to create a file named "forcefsck" on the root of the filesystem.
Create a file named "forcefsck" to force a check at the next mount attempt:
# touch /forcefsck
Reboot, and you should see the check run. When it completes and mounts the filesystem, it should delete that "forcefsck" file. You may want to make sure it's gone and delete it if it's not.
This will very likely go well and fix any problems. EXT4 can be automatically repaired very easily, and can be fixed after some pretty impressive failures.


Mental block playing rolling chords

Question: I am playing a piece in Grade 6 which starts with a rolling chord in left hand.  For some reason I find it really difficult to start and my little finger bounces up and down without being able to start the chord.  It seems to be a mental block. Can anyone help with breaking this?
Comment: A pic of the dots would help, or even saying what the notes are. Does it start on a black or a white key? Even this will have a bearing on helping.
Comment: If you can play arpeggios, you can play rolled chords - just "forget" to take your fingers off each note after you play it!
Answer: The longest journey starts with the first step.  Just place your hand in the right position for rolling the chord and play only the first note and imagine the rest of the rolled chord only.  Only once you are satisfied with this first note as the beginning of the rolled chord, start actually adding the rest.
Rolling a chord in the right hand makes the little finger come last which just makes it fall into place.  The little finger is weakest and shares a sinew sheath with the ring finger, so its movement is somewhat dependent on the next finger.
So when you start with the little finger, you are starting with the weakest finger.  Just practice it without the others at first, until you have confidence in its delivery.

Mental block playing rolling chords


Calling from javascript to WCF

Question: I created a WCF service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace ISTL
{
    public class MatchesListService : IMatchesListService
    {
        public bool AcceptRequestToChangeMatchTime(int matchId)
        {
            return MatchesListManager.AcceptRequestToChangeMatchTime(matchId);
        }
    }
}

That implements this contract:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace ISTL
{
    [ServiceContract(Namespace = "ISTL")]
    public interface IMatchesListService
    {
        [OperationContract]
        bool AcceptRequestToChangeMatchTime(int matchId);
    }
}

And this is in the web.config:
  <system.serviceModel>
    <services>
      <service name="ISTL.MatchesListService">
        <endpoint binding="webHttpBinding" contract="ISTL.IMatchesListService"></endpoint>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior>
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

And in the masterPage:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    <Services>
        <asp:ServiceReference Path="~/MatchesListService.svc" />
    </Services>
</asp:ScriptManager>

I am trying to call my WCF service from my javascript code:
ISTL.IMatchesListService.AcceptRequestToChangeMatchTime(matchId);

But calling the WCF fails.
When I debug with FireBug, when I reach the calling line, then the error occurs. matchId is a valid value.
FireBug recognizes the ISTL namespace, but regarding IMatchesListService it says its value is 'undefiend'.
Someone know what I'm doing wrong ?
Thanks for helping !
Comment: you need to pass onSuccess , onFailure delgate check this http://stackoverflow.com/questions/712238/wcf-newbie-question-calling-methods-from-javascript                                                                                I would recommend you to close this question.
Answer: you need to pass onSuccess , onFailure delgate check this WCF Newbie Question: Calling Methods from JavaScript … I would recommend you to close this question.
Comment: I have read the question in that post before posting my issue.
The delegates to onSuccess and onFailure are not mandatory. The call should occur also without them.
But anyway I tried adding the delegates now, and the problem persists.

Calling from javascript to WCF


Setting up backup systems when hosting own SVN, Jira, etc

Question: I like using hosted services. It's easy, they give you a SLA and you can generally trust they run at  big enough scale to have serious back-up.
But it's a bit more expensive and loses you some flexibility. Since I'm likely to have SVN, bug-tracking, forums, website, some actual web-apps to host, getting a VPS seems a good choice.
However I know nothing about how to sort out backups. All the decent providers will let me get a backup add-on, but this is often doubles the entire cost of the package. So I wondered how easy it is to add this on myself, buying a separate 3rd-party storage facility.
EDIT: An example of a "do your own backup" is something like www.idrive.com. Is there any reason I can't get a VPS and run such a tool to cheaply mirror something like my SVN repo or Jira database? I don't need super-amazing backup.
Answer: "you can generally trust they run at big enough scale to have serious back-up" -- objection m'lud, assumes facts not in evidence.  Plenty of big SaaS providers don't have decent backups; in fact, many of them weasel out of providing it by having somewhere in the fine print that it's your responsibility to have backups of the data held in the app (often this is coupled with a complete inability to export your data out of the app; yeah, awesome catch 22 there)
As far as doing your own backups of data stored on your own server, yes it's generally possible.  However telling you how to do it in general isn't possible, because different apps/services require different procedures -- you need to run one tool for SVN, another for MySQL, and so on.
For commercial products, it can be very difficult to do a backup without their tool, because they've done something "interesting" with their data storage.  Personally, any product that didn't come with the tools required to properly back it up would get sent back as "not fit for purpose" -- if you can't back it up, it effectively isn't managed.  Charging extra for a backup tool smacks of extortion.  One of the benefits of using practically-all Free Software.
EDIT: I think I misunderstood your question, and you're actually complaining about the costs of the backups provided by VPS providers.  That's just standard marketing -- the low up-front cost of the system (so you can advertise your $0.89/decade VPS deals), then the eye-watering cost for all add-ons that people don't consider until they've signed the contracts (so you can actually make a profit).  Pretty standard stuff -- I'm surprised you're not already familiar with it.  Yes, you can use an off-site backup that's cheaper, although getting your data back onto the machine after a failure needs to be considered too.
Don't skimp on your backups, though.  What most people consider to be "super-amazing" backup is, at the end of the day, about the bare minimum that's actually useful.  I'm willing to bet that you've never restored a full system backup under time pressures from customers or bosses who are breathing down your neck wondering why you can't just press a magic button and have everything "restored from backup NOW!".  Take some time while now, you've got a bit spare, to setup backups properly, because if you need to use them, they really, really do need to be super-amazing.
Comment: I don't really want to back up specific tools in that way. I just want a backup running of my server in case it dies or is hacked or (more likely) I accidentally screw it up. Hosting providers typically offer such services like daily backups, but at very high price. That's all I want to consider doing myself.
Comment: What you want is immaterial.  You can't backup a file if it's going to change underneath you, and that's exactly what a service-specific "backup tool" does -- take a consistent snapshot or whatever of the data so you get a useful backup.  I think I misunderstood your question, though, so I'll update my answer to match.
Answer: Whatever you do make sure you test your backups and procedures, otherwise they're worth nothing. Make sure you or you colleagues know exactly which steps to take to recover that repository or db.
Since we don't entirely trust the backup procedures of a hoster that hosts some of our LAMP servers, we do our own off-site backups as well. We're using Jungle Disk Server Edition for that. It's a program that you install on each server ($5/mnth*server + storage fees (10GB free/server)), and manage via a Client app. The backups are stored off-site on Amazon S3 and/or Rackspace Cloud Files, whichever your choice. Both the server software and the management app are available for Windows, Linux and Mac, which makes it well suited for our various servers.
We're backing up about 150GB of data and Jungle Disk appears to be very efficient in de-duplicating and compressing it so the actual transfers are fast.  We went with Rackspace CF due to their lower cost. The total cost is very acceptable to us, but of course will vary according to amount of data, compressibility, retention period, percentage of data that changes, etc.
It's your responsibility to put the data you want to backup somewhere, so for example you could make a pre-backup script that does an mysqldump of your databases into a directory, which is then backed up by Jungle Disk. Similar with svn-hot-backup for your subversion repos. JD allows pre and post-backup scripts.
All in all, we're very happy with the software. It's easy to install and manage and cheap as well. I would prefer it over a self-built VPS backup solution, since it's simply one less server to manage and easier to restore from.
Answer: I use systemimager, it uses a combination of scripts to build an image that can be redeployed on other servere, or to rebuild the original exactly as it was when the image was taken. As it uses rsync it happily does incremental backups so pulling the image offsite is trivial once the initial image has been pulled.
Its designed for a bare-metal server, but there shouldn't be a problem with running it on a VPS.
You can rebuild the system from a PXE boot, or by booting off a CD (designed for bare metal restores remember), but it can also re-image by running a script on a server to overwrite itself - which is exactly what you'd want after the ISP restores a fresh VPS image once disaster has struck.
You can also use it to create new servers based on the original - even for different hardware, which is quite cool. It was originally used to deploy a single image to many PCs.
Tutorial here.
Mind you, if all you're doing is backing up a website then you just need to rsync the /home directory, then dump all mysql databases to a file and back that up too. To restore, import your DB file to MySql, then upload the /home backup (or wherever you put your website files). This assumes you are not reconfiguring a lot of other files like firewall, logrotate, apache host configs, etc (or you'd make a backup of the changed files in /etc too - run AIDE to see which files you change after the ISP gives you the bare VPS image).


Generate pseudodata by Monte Carlo

Question: What does it mean for "Generate pseudodata by Monte Carlo"?
For the text I was reading it says suppose that the real data $Z_n \sim N(\mu(\theta), \Sigma (\theta))$, then the pseudodata are generated by Monte Carlo according to a normal distribution based on a chosen initial $\theta$.
I though the Monte Carlo method is kind of generating the random number then take the average, I am not quite sure how is this method works here.
Thanks for any help!
Comment: "generating the random number then take the average"  might be called Monte Carlo Integration. You can use inverse CDF methods to generate random numbers according to some distributions, or accept-reject algorithm when inverse CDF cannot be obtained.
Answer: pseudo-data are often used in error propagation to avoid theoretical estimation.
Theoretical estimation is usually more complicated and also might be inaccurate (because it is based on linearization: famous formula with square root of sum of squares of errors of inputs).
Pseudo-data approach is a genuine error propagation approach with the only limitation: statistics (or computer time if you want).
Imagine you have a published data with erros $(q_i,\delta q_i)$ and you want to compute something from them $R = f(q_i,\delta q_i)$. As an example: you have set of measured values of a function $(y_i,\delta y_i)$, assuming corresponding ($x_i$) are known numbers (without error) you want to compute integral $ R = \int_a^b y(x)dx$ using trapezoidal rule. You ask the question: what is error on $R$?
In pseudo-data approach you simulate. You have information about standard deviations $\delta q_i$ but (usually) you do not know the whole distribution. Therefore you assume, often Gaussian distribution (or maybe some other, you you have some reasons to believe it). Using random numbers you produce many (=$N$) clones of the initial $q_i$  data $\{q_i^{[j]}\}_{j=1}^{j=N}$. Each individual $q_i^{[j]}$ you produce as a random number from assumed distribution, the distribution having $q_i$ as mean and $\delta y_i$ as standard deviation. For each data clone you compute you $R^{[j]}$ (integral, in our example). With enough statistic this provides you full distribution for $R$, you can compute for example mean $R_{mean} = \frac{1}{N} \sum_{j=1}^{j=N}R^{[j]}$ or the error on R (which you are interested in) $$ R_{error} = \sqrt{ \frac{1}{N} \sum_{j=1}^{j=N} (R^{[j]}-R_{mean})^2 }$$.
Pseudo data fully respects all correlations among inputs ${q_i}$, as told, it's only limitation is statistics.

Generate pseudodata by Monte Carlo


How to approach the following differential equation

Question: I have a differential equation of the form
$$
\frac{\mathrm{d}g}{\mathrm{d}x} = f(x) + \int_0^x g(y)f(x-y)\mathrm{d}y + \alpha g(x).
$$
$f$ is a monotonous decreasing function, satisfying $\int_0^\infty f(x)\mathrm{d}x = 1$.
To solve it, I thought of getting the second derivative to handle the integral but the convolution does not let me get rid of it.
Laplace transform might work here, but I am not sure the integral term on the right side qualifies as convolution such that I can use Laplace transform of $f$.
Before trying to find the Laplace transform of $f$, which would be pretty messy, I wanted to ask if this is the best way to approach such a differential equation?
Comment: Not sure if this is gonna work, but I would differentiate both side and see what you get; to differentiate the integral, you can use Leibniz's rule: https://en.wikipedia.org/wiki/Leibniz_integral_rule
Comment: @CheeHan I thought of that but differentiating the convolution-like part does not eliminate the integral. It gives me $\int_0^x g(y)f^\prime(x-y)\mathrm{d}y+f(0)g(x)$, if I did it correctly.
Comment: How messy is $f(x)$?
Comment: @Cesareo I haven't exactly calculated that. I have two versions though. One version that is for large $x$ involves $\vartheta_4$, and one version for small $x$ involves $_3F_2$. It is messy, at least for me :) Do you think it will help if you know $f(x)$?
Comment: Do you just want to prove that a solution exists or do you need a (more or less) explicit solution formula?
Comment: @junjios I am interested in a framework which allows me to calculate $g$ with arbitrary precision when I insert $f$. Approximations are fine though. I will at one point use a piecewise approximation of it in Python.
Answer: The equation is linear in $g(x)$, and its special form does allow for a solution using the Laplace transform, using the convolution theorem and denoting
$$ (F,G)(s):=\int_0^\infty (f,g)(t)e^{-st}dt$$
we obtain by directly Laplace transforming the equation:
$$sG(s)-g(0)=F(s)+F(s)G(s)+\alpha G(s)$$
which can then be solved for $G$
$$G(s)=\frac{g(0)+F(s)}{s-F(s)-\alpha}$$
I don't think that there is a better way to analytically constructing solutions for integrodifferential equations like this, since most of them don't even have an analytical solution. Approximating with piecewise constant $f$ should be easy since the resulting equation has simple solutions in terms of exponentials, all one needs to do is to determine the constants of integration by demanding continuity of the solution at each point where $f$ has a jump discontinuity. Numerically inverting the Laplace transform is also possible for arbitrary, reasonably well behaved $f$.
Comment: Thanks a lot. This is what I reached as well with the Laplace transform. I'll wait a few days before accepting this answer.


Remover Duplicidade de Array multidimensional javascript

Question: Não sei como fazer para não incluir duplicados, ou remover duplicados depois de adicionado, podem me ajudar por favor?
obs: verifiquei outros códigos que encontrei no stakoverflow e em outros sites, porém não funcionaram para mim.
agendaOff.length = 2

agendaOff[0][0] = 1
agendaOff[0][1] = "17/04/2018 20:25:40"

agendaOff[1][0] = 1
agendaOff[1][1] = "17/04/2018 20:25:40"

// Método que utilizo para adicionar itens no array:
$.getJSON('json/json_query_requisicao.asp',function(data){
    if(data.length > 0){ v1='';v2='';v3='';var opt ='';
        $.each(data,function(w,itens){
            v1 = data[w].id_tiporequisicao;
            v2 = data[w].datahora;
            agendaOff.push([v1,v2]);
        });
    }
});

Answer: Não existe uma maneira extremamente prática para comparar objetos/arrays. Se você quisesse um array com valores únicos de números, strings, ou outra primitiva, bastaria utilizar new Set(agendaOff). Mas como agendaOff possui arrays, você tem que usar uma função para comparar esses array.
Um método popularmente utilizado, é utilizar filter + indexOf para procurar por um item, e comparar sua posição com a encontrada. Se a posição do item for diferente da que o foi encontra, significa que outro item com o mesmo valor, logo é uma duplicata.
$.getJSON('json/json_query_requisicao.asp', function(data) {
    agendaOff = agendaOff
        .concat(data.map((item) => [item.id_tiporequisicao, item.datahora]))
        .filter((item, i, self) => self.findIndex((itemF) => item[0] === itemF[0] && item[1] === itemF[1]) === i);
});

Comment: Funcionou perfeitamente Obrigado, eu tinha construído algo parecido mais sem o filter, vlw obrigado.


I have this scenario. When I hover to my button, the swf is loaded on stage, but its audio is playing. I just want it to be muted

Question: **    >I have this scenario.  When I hover to my button, the swf is loaded on stage, but its audio is playing.  I just want it to be muted.**
Answer: <code>import flash.media.SoundMixer;

SoundMixer.stopAll();
</code>
Comment: I also tried it, but the background music in my main stage will be affected too. I want the swf file only when I hover on my button.


Proving $\csc (x) +\cot( x)=\frac{\sin (x)}{1-\cos(x)}$

Question: I have this problem: Prove that $\csc (x) +\cot( x)=\dfrac{\sin (x)}{1-\cos(x)}$
From LHS I tried using $\sin^2x+\cos^2x = 1$ and ended up nowhere.
I tried rearranging RHS but ended up with $\dfrac{1+\cos (x)}{\sin (x)}$. I'm really stuck with this one. Any suggestions?
Comment: I reformatted your question. Please check that I didn't alter the meaning of what you typed.
Answer: You have $\dfrac{\sin(x)}{1-\cos(x)}$ Mutiply numerator and denominator by $1+\cos x$ to get $\dfrac{\sin x(1+\cos x)}{1-\cos^2(x)}$
Now $1-\cos^2(x)=
\sin^2(x)$. Therfore we are left with $\dfrac{1+\cos(x)}{\sin(x)}$ which is $\csc(x) +\cot(x)$:
$\csc(x) + \cot(x)$ = $\dfrac{1}{\sin(x)} + \dfrac{\cos(x)}{\sin(x)}$ = $\dfrac{1 + \cos(x)}{\sin(x)}$
Comment: @user111835 That's call multiplying by its [conjugate](http://www.mathsisfun.com/algebra/conjugate.html) and because you multiply a set of terms with only the sign in the middle being different, you'll end up with a difference of squares. The difference of squares you would end up with in this case would be a trig identity.
Comment: Thank you! But how did you figure to multiply numerator and denominator by 1 + cosx?
Comment: It is just practice and experience. These methods will click fast if you get enough of practice.
Answer: We have $$\cos^2x+\sin^2x=1$$
$$\iff \sin^2x=1-\cos^2x=(1-\cos x)(1+\cos x)$$
$$\implies \frac{\sin x}{1-\cos x}=\frac{1+\cos x}{\sin x}=\frac1{\sin x}+\frac{\cos x}{\sin x}=\cdots$$
Answer: Or from the left : csc + cot = (1 + cos)/sin then multiply top and bottom by (1 - cos) and simplify using diff of squares and sin^2 + cos^2 = 1 identity.


Calculating the limit $\lim_{x\to\infty}\frac{\sin^2\left( \sqrt{x+1}-\sqrt{x}\right)}{1-\cos^2\frac{1}{x}}$

Question: I'm having a really tough time trying to evaluate the limit for this expression
$\lim_{x\to\infty}\frac{\sin^2\left( \sqrt{x+1}-\sqrt{x}\right)}{1-\cos^2\frac{1}{x}}$
The only hint I was given is that $\lim_{x\to\infty}\frac{\sin(x)}{x} = 0$.
By using trigonometric identities I can see that this leads to $\lim_{x\to\infty}\frac{\sin^2\left( \sqrt{x+1}-\sqrt{x}\right)}{\sin^2(\frac{1}{x})}$. I proceeded then to do multiply everything by $\frac{1}{x}$ which leaves me with $\lim_{x\to\infty}\frac{x^{-1}\sin^2\left( \sqrt{x+1}-\sqrt{x}\right)}{1}$ (according to the hint I was given).
However, now I don't know how to simplify the expression in the numerator. Any tips would be really appreciated.
Thanks
Comment: The Simplest approach would be to get rid of $\infty$ by putting $t = 1/x$ so that $t \to 0+$ as $x \to \infty$. Then you need to do some simplification (as explained in various answers below) and use the following standard limit: $\lim_{t \to 0}(\sin t)/t = 1$
Answer: Hint: In the argument of sine, multiply by $$\frac{\sqrt{x+1}+\sqrt{x}}{\sqrt{x+1}+\sqrt{x}}.$$
Answer: $$\sin^2(\sqrt{x+1}-\sqrt{x})\sim \sin^2(1/(2\sqrt{x})) \sim {1\over4x},$$ as $x\to\infty$.
Answer: $\sin^2\left(\dfrac{1}{x}\right) \approx \dfrac{1}{x^2}$ for very large $x$ rather than your $\dfrac{x^{-1}}{1}$ or perhaps $\dfrac{1}{x^{-1}}$.
A more helpful hint might have been:    $\displaystyle\lim_{y\to 0}\dfrac{\sin(y)}{y} = 1$


A proper integral which can't be evaluated if improper

Question: If you would like to find the electric potential of a conducting disc in space you would have several approaches.

Laplace Equation.(not so great approach though!)
Finding the charge on a conducting ellipsoid(this problem itself has many appraoches,so diverse!)then you take the limit when the ellipsoid becomes a disk.so you have the charge density and must integrate to get potential.
Use a conducting rod as image charge and again taking a limit.

Its so fascinating that doing 1 leads to an infinite series (infinite series), 2 leads to a though integral and the (calculus), and 3 leads to finding the Real part of a very big Ln (arithmetic). And all these will give the same answer as they should. Three things so diffrent in "shape" but they turn out to be the same!
My situation is: I want to evaluate the integral which I got while doing $2$. Also I'd like to evaluate $3$ and know the real part and imaginary part of that gigantic Ln. (it would be an $X+iY$ representation.)!
Comment: What is your question?
Comment: Even after editing there is still no question. The integral can be evaluated using the complete elliptic integral of the first kind, try e.g. Wolfram Alpha
Comment: thats the point!it can be made simpler than complete elliptic integral!and by the way of you look at it that way 90% of integral quesions in this site can be evaluated by wolfram.and as for the second question:that Ln(..) equals X+iY .find X and Y.dont you see?every complex function can be represented that way.this Ln again gets simplified.It should(I know it from the physics of the problem)
Comment: at least tell me what you think!dont you get the queston or is it not solvable?Im sure the integral can be simplyfied and as for the Ln(..) whats the problem?
Answer: $\displaystyle{\large%
?
\equiv
\int_{0}^{a}
{{\rm d}x \over \sqrt{x^{2} + c^{2}\,}\ \sqrt{a^{2} - x^{2}\,}}\,,
\quad a > 0}$.
With the change $x \equiv a\,\sin\left(\theta\right)$, we
get
$\displaystyle{%
? = \int_{0}^{\pi/2}
{{\rm d}\theta \over \sqrt{a^{2}\sin^{2}\left(\theta\right) + c^{2}}}
}$.
Now, we use la identity
$\displaystyle{%
\sin^{2}\left(\theta\right) = {1 - \cos\left(2\theta\right) \over 2}
.\quad}$ $?$ becomes:
\begin{align}
?
&=
\int_{0}^{\pi/2}
{{\rm d}\theta
 \over
 \sqrt{a^{2}\left\lbrack 1 - \cos\left(2\theta\right)\right\rbrack/2 + c^{2}}}
=
\sqrt{\vphantom{\large A}2\,}\int_{0}^{\pi/2}
{{\rm d}\theta
 \over
 \sqrt{a^{2} + 2c^{2} - a^{2}\cos\left(2\theta\right)}}
\\[3mm]&=
{\sqrt{\vphantom{\large A}2\,} \over 2}\int_{0}^{\pi}
{{\rm d}\theta
 \over
 \sqrt{a^{2} + 2c^{2} - a^{2}\cos\left(\theta\right)}}
=
{\sqrt{\vphantom{\large A}2\,} \over 2}\,
{2 \over \sqrt{\left(a^{2} + 2c^{2}\right) + a^{2}\,}}\,
{\bf E}\,\left(%
\sqrt{2c^{2} \over \left(a^{2} + 2c^{2}\right) + a^{2}}
\right)
\end{align}
where ${\bf E}\left(k\right) \equiv {\rm E}\left(\pi/2,k\right)$ is the Complete Elliptic Integral of the Second Kind.
$\displaystyle{{\rm E}\left(\varphi,k\right)
\equiv
\int_{0}^{\varphi}
 \sqrt{1 - k^{2}\sin^{2}\left(\alpha\right)\,}\ {\rm d}\alpha}$ is the Elliptic Integral of the Second Kind. In the derivation we used the identity:
$$
\int_{0}^{\pi}{{\rm d}x \over \sqrt{\alpha \pm \beta\cos\left(x\right)\,}}
=
{2 \over \alpha + \beta}\,
{\bf E}\,\left(\sqrt{2\beta \over \alpha + \beta\,}\,\right)\,,
\qquad
\alpha > \beta > 0
$$
$$
\begin{array}{|c|}\hline\\
\color{#ff0000}{\large\quad\int_{0}^{a}
{{\rm d}x \over \sqrt{x^{2} + c^{2}\,}\ \sqrt{a^{2} - x^{2}\,}}
=
{1 \over \sqrt{a^{2} + c^{2}\,}}\,
{\bf \color{#000000}{E}}\,\left(\left\vert c\right\vert \over \sqrt{a^{2} + c^{2}\,}\right)\,,\quad a > 0,\ c\not= 0\quad}
\\ \\ \hline
\end{array}
$$


CONNECTIVITY_ACTION intent received twice when Wifi connected

Question: In my app I have a BroadcastReceiver that is launched as a component through a <receiver> tag, filtering android.net.conn.CONNECTIVITY_CHANGE intents.
My goal is simply to know when a Wifi connection was established, so what I am doing in onReceive() is this:
NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {
    // Wifi is connected
}

It works fine, but I always seem to get two identical intents within about one second when a Wifi connection is established. I tried to look at any info I could get from the intent, the ConnectivityManager and WifiManager, but I can't find anything that distinguishes the two intents.
Looking at the log, there is at least one other BroadcastReceiver that also receives the two identical intents.
It is running on a HTC Desire with Android 2.2
Any idea why I seem to get a "duplicated" intent when Wifi connects or what the difference between the two might be?
Comment: https://www.youtube.com/playlist?list=PLrnPJCHvNZuBqr_0AS9BPXgU6gvNeai5S
A good understanding of recent methods of implementing broadcast receivers
Answer: NOTE: For a recent, up-to-date answer, see this one below!
After a lot of googling and debugging, I believe this is the correct way to determine if Wifi has connected or disconnected.
The onReceive() method in the BroadcastReceiver:
public void onReceive(final Context context, final Intent intent) {

if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
    NetworkInfo networkInfo =
        intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
    if(networkInfo.isConnected()) {
        // Wifi is connected
        Log.d("Inetify", "Wifi is connected: " + String.valueOf(networkInfo));
    }
} else if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
    NetworkInfo networkInfo =
        intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
    if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI &&
        ! networkInfo.isConnected()) {
        // Wifi is disconnected
        Log.d("Inetify", "Wifi is disconnected: " + String.valueOf(networkInfo));
    }
}
}

Together with the following receiver element in AndroidManifest.xml
<receiver android:name="ConnectivityActionReceiver"
    android:enabled="true" android:label="ConnectivityActionReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        <action android:name="android.net.wifi.STATE_CHANGE"/>
    </intent-filter>
</receiver>

Some explanation:

When only considering ConnectivityManager.CONNECTIVITY_ACTION, I always get two intents containing identical NetworkInfo instances (both getType() == TYPE_WIFI and isConnected() == true) when Wifi connects - the issue described in this question.
When only using WifiManager.NETWORK_STATE_CHANGED_ACTION, there is no intent broadcasted when Wifi disconnects, but two intents containing different NetworkInfo instances, allowing to determine one event when Wifi is connected.

NOTE: I've received one single crash report (NPE) where the intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO) returned null. So, even if it seems to be extremely rare to happen, it might be a good idea to add a null check.
Cheers,
Torsten
Comment: I'd like to mention here that, at least sometimes, the `WifiManager.NETWORK_STATE_CHANGED_ACTION` intent is broadcasted a short moment before the data connection is completely set up (DHCP configuration not complete) and that at that moment, `ConnectivityManager.getActiveNetworkInfo()` might still return a `NetworkInfo` with type `TYPE_WIFI`.
Comment: I can personally confirm everything written by Torsten. Thank you for your solution. I find it frustrating that there is not a cleaner and simpler solution. The most surprising thing is that this behaviour doesn't take place when wifi is disconnected. I'm not saying it is necessarily a bug, but it could be better documented.
Comment: Getting the NetworkInfo from the intent is now depreciated.
However its not clear why "they" don't expect this to remain stable.

Is anyone finding instability in getting the Networkinfo from the intent?
Comment: intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO) is deprecated.
Comment: @BrillPappin Getting it from ConnectivityManager is deprecated, but this answer's discussion is focused on getting it from WifiManager which is still fine.  However, like the others I still get strange sequences of notifications.
Comment: Thanks, I asked the accounts to be merged!
Comment: android.net.conn.CONNECTIVITY_CHANGE is also deprecated in N, just letting future people be aware..
Answer: If you're listening on WifiManager.NETWORK_STATE_CHANGED_ACTION you'll receive this twice because there are 2 methods in the NetworkInfo

isConnectedOrConnecting()
isConnected()

First time isConnectedOrConnecting() returns true and isConnected() false
Second time isConnectedOrConnecting() and isConnected() return true
Cheers
Comment: both methods return true for both events for me :)
Comment: This answer is not correct, `isConnected()` can return `true` both times.
Answer: This is the proper way to register for connectivity changes on API 21 and higher. The following code can be placed in a base activity and that way you can expect every screen in your app (that inherits from this activity) to get these callbacks.
First, create a network callback which will monitor connectivity changes.
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private val networkCallback: ConnectivityManager.NetworkCallback = object : ConnectivityManager.NetworkCallback() {

    // Implement the callback methods that are relevant to the actions you want to take.
    // I have implemented onAvailable for connecting and onLost for disconnecting.

    override fun onAvailable(network: Network?) {
        super.onAvailable(network)
    }

    override fun onLost(network: Network?) {
        super.onLost(network)
    }
}

Then, register and unregister this callback in the relevant spots.
override fun onResume() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
        cm?.registerNetworkCallback(NetworkRequest.Builder().build(), networkCallback)
    }
}

And unregister when appropriate.
override fun onPause() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
        cm?.unregisterNetworkCallback(networkCallback)
    }
}

Notice that there is a check for Build.VERSION_CODES.LOLLIPOP. This functionality is only available in Lollipop and above. Be sure to have a plan for how to handle network status changes in Pre-Lollipop devices if you support less than API 21 in your app.
Answer: Updated the code of Torsten, such that when WIFI gets disconnected, only the single appropriate broadcast is acted upon.
Used NetworkInfo.getDetailedState() == DetailedState.DISCONNECTED for the checking.
public void onReceive(final Context context, final Intent intent) {
    if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
        NetworkInfo networkInfo = intent
            .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        if (networkInfo.isConnected()) {
            // Wifi is connected
            Log.d("Inetify","Wifi is connected: " + String.valueOf(networkInfo));
        }
    } else if (intent.getAction().equals(
        ConnectivityManager.CONNECTIVITY_ACTION)) {
        NetworkInfo networkInfo = intent
            .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        if (networkInfo.getDetailedState() == DetailedState.DISCONNECTED) {
            // Wifi is disconnected
            Log.d("Inetify","Wifi is disconnected: "+String.valueOf(networkInfo));
        }
    }
}

Comment: For whoever wonders the change is `if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI && ! networkInfo.isConnected())` ___to___ `if (networkInfo.getDetailedState() == DetailedState.DISCONNECTED)`
Comment: What about Wifi and Cellular data? I believe both will cause the BroadcastReceiver to trigger causing more calls.
Answer: If you registered the activity as an intent listener then you will recieve the same message twice. Specifically, you need to choose whether you want to listen on the Package level (XML) or the programatic level.
If you set up a class for a broadcast reciever and attach the listen to it AND you attach an intent filter to the activity, then the message will be replicated twice.
I hope this solves your issue.
Comment: Finally I can comment on this one... your answer is certainly correct, but I had registered the BroadcastReceiver only in the manifest.
Comment: This is correct, you either create a Broadcast listener in the class OR the manifest, but not both.
Answer: I solved twice call by using SharedPref with Time.
private static final Long SYNCTIME = 800L;
private static final String LASTTIMESYNC = "DATE";
SharedPreferences sharedPreferences;
private static final String TAG = "Connection";

@Override
public void onReceive(Context context, Intent intent) {
     Log.d(TAG, "Network connectivity change");
     sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

     final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
     final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();

        if (ni != null && ni.isConnected()) {

            if(System.currentTimeMillis()-sharedPreferences.getLong(LASTTIMESYNC, 0)>=SYNCTIME)
            {
                sharedPreferences.edit().putLong(LASTTIMESYNC, System.currentTimeMillis()).commit();
                // Your code Here.
            }
     }
     else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
            Log.d(TAG, "There's no network connectivity");

    }
}

Because there is small delay between 1.call and 2.call (About 200 milisec).
So in IF with time second call will stop and just first will continue.
Comment: As bad as this one sounds as a solution, it worked for me. I have tried semaphores and also synchronized blocks and none have worked well for me.
Answer: I solved if with
in
onCreate()
       intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
       intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
       intentFilter.addAction("android.net.wifi.STATE_CHANGE");
       ctx.registerReceiver(outgoingReceiver, intentFilter);

in
BroadcastReceiver
 public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                NetworkInfo networkInfo =
                        intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                if(networkInfo.getType() == ConnectivityManager.TYPE_WIFI &&
                        networkInfo.isConnected()) {
                    // Wifi is connected
                    Log.d("Inetify", "Wifi is connected: " + String.valueOf(networkInfo));

                    Log.e("intent action", intent.getAction());
                    if (isNetworkConnected(context)){
                        Log.e("WiFi", "is Connected. Saving...");
                        try {
                            saveFilesToServer("/" + ctx.getString(R.string.app_name).replaceAll(" ", "_") + "/Temp.txt");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }}

 boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null) {
            Log.e("NetworkInfo", "!=null");

            try{
                //For 3G check
                boolean is3g = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                        .isConnectedOrConnecting();
                //For WiFi Check
                boolean isWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                        .isConnected();

                Log.e("isWifi", "isWifi="+isWifi);
                Log.e("is3g", "is3g="+is3g);
                if (!isWifi)
                {

                    return false;
                }
                else
                {
                    return true;
                }

            }catch (Exception er){
                return false;
            }

        } else{
            Log.e("NetworkInfo", "==null");
            return false;
        }
    }

Answer: I solved this problem by using the intent extra for NetworkInfo.
In the example below, onReceive event is fired only once if wifi is connected or mobile.
if (intent.getAction().equalsIgnoreCase(ConnectivityManager.CONNECTIVITY_ACTION)) {

        NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

        boolean screenIsOn = false;
        // Prüfen ob Screen on ist
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            screenIsOn = pm.isInteractive();
        } else {
            screenIsOn = pm.isScreenOn();
        }

        if (Helper.isNetworkConnected(context)) {
            if (networkInfo.isConnected() && networkInfo.isAvailable()) {
                Log.v(logTAG + "onReceive", "connected");

                if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    Log.v(logTAG + "onReceive", "mobile connected");

                } else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    Log.v(logTAG + "onReceive", "wifi connected");
                }
            }
        }

and my helper:
    public static boolean isNetworkConnected(Context ctx) {
    ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();

    return ni != null;
}

Answer: If you only want to receive it once, you can simply control it through variables.
 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                NetworkInfo activeNetwork = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                if (activeNetwork != null) { // connected to the internet
                    if (activeNetwork.isConnected() && !isUpdated) {
                        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                            // connected to wifi
                        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                            // connected to the mobile provider's data plan
                        }

                        isUpdated = true;
                    } else {
                        isUpdated = false;
                    }
                }
            }

Answer: When turning WIFI ON,

With MOBILE data ON, two broadcasts are sent:
 Broadcast #1 : MOBILE data disconnected, and
 Broadcast #2 : WIFI connected
With MOBILE data OFF, only one broadcast is sent:
 Broadcast #1 : WIFI connected

Similar behavior can be observed while turning the WIFI OFF under the above two conditions.
To distinguish between the two, please follow #2 and #3 below:
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "*** Action: " + intent.getParcelableExtra("networkInfo"));

            NetworkInfo netInfo = intent.getParcelableExtra("networkInfo");

            if(intent.getAction().equalsIgnoreCase("android.net.conn.CONNECTIVITY_CHANGE")) {
                ConnectivityManager connectivityManager
                        = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
                if (activeNetInfo != null) {
                    if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        if (netInfo.getState().name().contains("DISCONNECTED")
                                && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                            Log.d(TAG, "WIFI disconnect created this broadcast. MOBILE data ON."); // #1
                        } else if (netInfo.getState().name().contains("CONNECTED")
                                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            Log.d(TAG, "WIFI connect created this broadcast."); // #2
                        }
                    } else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        if (netInfo.getState().name().contains("DISCONNECTED")
                                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            Log.d(TAG, "MOBILE data disconnect created this broadcast. WIFI ON."); // #3
                        } else if (netInfo.getState().name().contains("CONNECTED")
                                && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                            Log.d(TAG, "MOBILE data connect created this broadcast."); // #4
                        }
                    }
                } else {
                    Log.d(TAG, "No network available");
                }
            }
        }

Answer: The way I handled it, was simply by saving the state of the network and then comparing it to see if there was a change.
public class ConnectivityChangedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        boolean previouslyConnected = MyApp.getInstance().isNetworkPreviouslyConnected();
        boolean currentlyConnected = MyApp.getInstance().isNetworkConnected();

        if (previouslyConnected != currentlyConnected) {
            // do something and reset
            MyApp.getInstance().resetNetworkPreviouslyConnected();
        }
    }

}

If this is the approach you take, it's important to reset it in onResume of your fragment or activity, so that it holds the current value:
@Override
public void onResume() {
    super.onResume();
    MyApp.getInstance().resetNetworkPreviouslyConnected();
}

I did that in my BaseFragment, a parent of all fragments in my app.
Answer: check networkType from intent
and compare activeNetworkInfo.getType()
                 Bundle bundle = intent.getExtras();
                 ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                 NetworkInfo ni = manager.getActiveNetworkInfo();

                 if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
                     if(bundle.getInt("networkType") == ni.getType()) {
                         // active network intent
                     }
                 }

Answer: Found a special case for network connectivity saying there is no internet but actually there is. It turns out getActiveNetworkInfo will always return you DISCONNECTED/BLOCKED in a specific case when network is changed while battery level is low and app was just switched
Check out this post
Answer: Only listen to action "android.net.conn.CONNECTIVITY_CHANGE". It's broadcasted whenever connection is established or destroyed.
"android.net.wifi.STATE_CHANGE" will be broadcasted when connection established. So you get two triggers.
Enjoy!
Comment: The problem is that it sends two events for each sate change.


Integer solutions of $n^2+n+1=m^3$

Question: How can I find all $m,n\in\mathbb{Z}$ satisfying $n^2+n+1=m^3$?
Comment: I was able to reduce it to the two equations a^3 - 3a^2b + b^3 = +/- 1 and a^3 + 3a^2b - 6ab^2 + b^3 = +/- 1 but I have not figured out how to solve them yet.
Answer: There may well be more elementary solutions, but one way to go is to rewrite the equation as
$E: y^2 + y = x^3 - 1$.
That is, we wish to find all integral points on the elliptic curve $E$.  For this,
the integral points contain all torsion points of $E(\mathbb{Q})$, with equality iff the Mordell-Weil rank is zero.  Moreover it is easy to find all torsion points.  So one hopes that the rank is zero (which happens, according to conventional wisdom, about half the time).
Using the MAGMA computer algebra package:

$\gt$ E := EllipticCurve([0,0,1,0,-1]);
  $\gt$ E;
  Elliptic Curve defined by y^2 + y = x^3 - 1 over Rational Field
  $\gt$ TorsionSubgroup(E);
  Abelian Group of order 1
  $\gt$ MordellWeilRank(E);
  1

So no luck: the Mordell-Weil rank is 1, so there are infinitely many $\mathbb{Q}$-rational points on $E$ and in fact no torsion points (other than the point at infinity $[0:1:0]$ which is missing from our affine equation for $E$).
So we move on to the built-in algorithm for computing all integral points on an elliptic curve:

$\gt$ I := IntegralPoints(E);
  $\gt$  I;
  [ (1 : 0 : 1), (7 : -19 : 1) ]
  $\gt$ P1 := I1;
  $\gt$ P1;
  (1 : 0 : 1)
  $\gt$ -P1;
  (1 : -1 : 1)
  $\gt$ P2 := I2;
  $\gt$ P2;
  (7 : -19 : 1)
  $\gt$ -P2;
  (7 : 18 : 1)

The answers here are in projective form $(X,Y,Z)$ so correspond to affine coordinates
$(x,y) = (X/Z,Y/Z)$.  Of course we want integral points, so it is no surprise that the $Z$-coordinate is equal to $1$ in every case.  Note that I did a little more than just
running the IntegralPoints command, because according to the fine print here or here the command only returns integral points "up to negation", which I took to mean that one has to also compute the Mordell-Weil inverses of the all the points on the list.  Thus we get that there are four affine integral points on $E$:
$(x,y) = (1,0), \ (1,-1), \ (7,-19), \ (7,18)$.
I should say that although I am a fairly regular MAGMA user, I don't have much experience with the IntegralPoints package, so this answer is provided without warranty...
Comment: Thanks! But why $E$ is an elliptic curve? I have read that an elliptic curve has three parameters, not just $x$ and $y$. The definition I read was from Qing Liu: Algeraic Geometry and Arithmetic Curves page 217.
Comment: You are thinking about the projective form of an elliptic curve, obtained by "homogenizing" the polynomial: $y^2z + yz^2 = x^3 - z^3$.  But the notion of "integral point" really is particular to the (given) affine equation: in projective space, there is no difference between integral points and rational points, because $(a,b,c)$ is regarded as the same point as $(\lambda a, \lambda b, \lambda c)$ for any nonzero $\lambda$.

Integer solutions of $n^2+n+1=m^3$


Ruby Single versus Double Quotes

Question: Is there some sort of Ruby to_s method that changes a variable to a single-quoted string instead of double quotes?
Say I have
date = Time.now
date.to_s

and I want the output to be '2012-08-01 22:00:15'. How do I go about doing this? Or is there a method to convert "" strings to '' strings?
Thanks!
EDIT - More Detail
I'm using Rails to display some data in a database. I've created the @instanceVar as an array of arrays from my Controller/Model.
<% outer = [] %>
<% inner = [] %>

<% @instanceVar.each do |events| %>
  <% events.each do |event| %>
    <% inner << [event.date, event.total] %>
  <% end %>
  <% outer << inner %>
<% end %>

I need event.date to be a single quoted string.
    <% inner << ['event.date', event.total] %>

just literally adds the words event.date to the array, and
    <% inner << ["#{event.date}", event.total] %>

puts the date in double quotes.
EDIT2

Comment: What do you want to achieve with this?
Answer: Strings are strings in ruby. They are all equal. The only difference is how you declare them (single quotes, double quotes, here-docs and maybe something else). Once you've got a string value in a variable, it doesn't matter how it was declared.
s1 = 'single quoted'
s1 # => "single quoted"

So, if your strings don't leave the rubyland (that is, you don't render them as javascript or whatever), you shouldn't worry about the quotes.
Response to edit 2
It seems that you have to build your json object in a more manual manner, rather than relying on default behaviour of Array#to_s
To emit ruby string as javascript single-quoted string literal you can do something like this:

<%= %> construct will render passed string without quotes. You supply the quotes yourself.
Comment: Yeah, I get that, but I'm using jqPlot to create a line graph with a date x-axis. The date parameter needs to be a string for the dateAxisRenderer to function. If I insert something double quoted, jqPlot escapes the quotes into `"`. Using `html_safe` does nothing.
Comment: So, where's the part where you render those vars as javascript?
Comment: So there's no way of doing this outside the script? I'm going to have to run my loop inside, okay, thanks.
Answer: Double-quotes as a string constructor allow you to interpolate variables.  Single quotes are for literals.  As mentioned, a string is a string once instantiated, displaying quotes is better left to the caller.
Comment: See my comment to Sergio for details as to why this matters.

Ruby Single versus Double Quotes


Which significance test is the best for measuring the response to two survey questions are significantly different?

Question: I have a survey where there are two questions designed in a Likert Scale (1-7). Let's say:
Q1: Your ratings for apples.
Q2: Your ratings for pears.
By counting the frequency of the likert response.  I found out more people rated apples higher. Now, I want to know if people rate apples significantly differently than pears.
So, it's the same group of people, and no time difference (like pre/post). And the response are ranked. What's the most appropriate tool for this situation?
Comment: If you are willing to treat (ordinal) Likert-7 data as if it were numerical, you might be able to use a paired t test, provided Likert scores are approximately normal (roughly symmetrical with no extreme outliers). Otherwise, perhaps, a paired Wilcoxon signed rank test (unless excessive ties are a problem)). // One may wonder why there was no straightforward question directly comparing apples and pears. (0 = Very strongly prefer pears, ..., 7 = Very strongly prefer applies.)
Answer: It would be easier to answer directly if you had provided data. I will answer
by illustrating with fictitious data. If issues arise with your data that are
not covered here, please edit your question to provide pertinent information, and maybe someone will respond.
Suppose the sample size is $n = 200$ subjects, and that the sample
distribution of the differences d between Likert scores for Apples and Pears
is as follows.
mean(appl); mean(pear)
[1] 4.815
[1] 4.545
cor(appl, pear, meth="spearman")
[1] 0.783856

On average, there are higher scores for Apples, and people who like one
seem to like the other (Spearman rank correlation is $0.78.)$
d = appl - pear
table(d)
d
-2 -1  0  1  2
15 29 70 59 27

A paired Wilcoxon signed rank test is a test on the differences 'd'. There are
many tied values, but with $n$ as large as 200, the P-value is an approximation
that deals appropriately with ties. The null hypothesis that the population is centered at $0$ is strongly rejected with P-value about $0.001 < 0.05 = 5\%.$
wilcox.test(d)

        Wilcoxon signed rank test
        with continuity correction
data:  d
V = 5582, p-value = 0.001299
alternative hypothesis: true location is not equal to 0

Even with $n=200$ it seems quite a reach to view a discrete distribution with
only five integer values as normal, but for the record a paired t test also
gives a very small P-value.
t.test(d)$p.val
[1] 0.0006454586

Finally, of the $200 - 70 =130$ subjects who expressed a clear preference, only $14+29=44$ preferred pears. So a 2-sided exact binomial test rejects equal preferences for apples and pears with P-value $0.0003 < 0.05 = 5\%.$
pbinom(44, 130, .5)*2
[1] 0.0002895488

Note: Here is how I used R to sample the fictitious data used in the samples above.
set.seed(123)
appl = sample(1:7, 200, rep=T, p=c(1,2,3,4,5,5,4) )
dif = sample(-2:2, 200, rep=T, p=c(1,1,2,2,1))
pear = appl - dif
pear[pear>7]=7;  pear[pear < 1]=1


Pass variable values to velocity template in Node.js

Question: I have Velocity templates stored in a database which contain loops as follows:
#foreach($project in $projects)${project.name}#end

I want to pass value to project names via a form in Nodejs application, designed in marko templating engine.
Answer: I made a layer of velocity template engine in between


Is there any gradient boosting package that allows controlling the features set used in each estimator?

Question: I am thinking about a problem in which features comes in batches and in different moments of time/environments.
My current problem set is the following:
Let's say you have n datasets with an arbitrary number of features. Is it possible to set for the boosting optimization to use the first dataset in the first k estimators? And then tell it to use all the features from datasets 1 and 2 from the estimators k to k+p?
Comment: 0. Welcome to CV.SE. 1. Fun question (+1), what you want is doable in all major packages but it takes a bit of tinkering. Please see my answer below for more details.
Answer: Formally speaking no, but we can fake it.
In particular we can make use of capabilities of the fit method to continue training an old model. As such we do the following:

We make $X_{\text{whole}}$ to store the data from  dataset $X_1$ as well as $X_2$. $X_1$  features are available data at the start of the project. $X_2$ features are unavailable so we explicitly sets them a fixed value (say 42). It is important that all of them are fixed because in that way: a. they don't covary with any of the known features in $X_1$ and b. any splitting algorithm will ignore them as no splitting can ever result in a reduction to our loss.
We train for the first $k$ iterations normally using $X_{\text{whole}}$ such that $X_{\text{whole}} = [X_1 , X_2]$. Our booster up until that iteration uses (by necessity) only information from $X_1$.
After $k$ iteration have passed/move to new environment, etc. $X_2$'s feature information are now available. We update our $X_{\text{whole}}$ such that it now holds the relevant $X_1$ features it did before but now $X_2$ contains the newly available information.
We train for the rest $k+1$ to whatever total number of iteration we expect using the updated  $X_{\text{whole}}$. The first $k$ trees are preserved doing splits only with information from the features available in $X_1$ but the subsequent tress starting from $k+1$ can using features from $X_1$ or $X_2$ depending on the feature's informativeness.

To my knowledge all three major Python GBM implementations have training continuation capabilities in their fit methods. XGBoost, LightGBM and CatBoost suggest that in their documentation. (Links provided, albeit with slightly different ways of achieving this - LightGBM & CatBoost use a init_model argument, while XGBoost straight-up retrains an existing booster.)
Comment: That's an interesting solution! Would you consider decreasing the feature weights for $X1$ once $X2$ data is available? This can be controlled in XGBoost with the `feature_weights` argument.
Comment: Thank you! Based on the task at hand, I would not consider it. If anything I would want the booster to still find the best solution even if that means "ignoring" $X_2$
provided features.


Piano action too stiff after tuning, what's happened?

Question: My new second hand schimmel 112 upright had its first tune three weeks ago. We bought it 8 weeks ago, let it rest and acclimatise then had it tuned with a mini service. The piano is 25yo and its last tune before we got it was 3 yrs beforehand, but it wasn't that badly out of tune till it was moved, and is in good condition.
Although there were a few stiff keys here and there, and this was mentioned to the technician, now the whole action is a LOT stiffer, to the degree that even to play  a trill I have to really put some force into it, whereas before it would trill without sticking!?? I saw him oil all the pins, so it wasn't that, also I'm sure he went through with a screwdriver or other instrument and optimised the hammers etc...I left him to it, so don't know exactly.
Am I right in thinking he's over tightened it somehow? Surely it shouldn't be the case that the whole piano action is significantly stiffer after tuning?
Thanks!
Comment: Too late now, but would have been best if you'd tested the action before he left.  Get him back and have him re-adjust the keyboard.
Comment: Hiya, I did mention to him at the time that it was a lot stiffer, but he fobbed me off and said it would be fine and get easier, from which I took get looser. But it hasn't. I've written him an email, so am just waiting his response.
Comment: " I saw him oil all the pins" - what????? Depending what *you* mean by "pins" the result would vary from "waste of time and money" to "oops, if you are lucky and the "pins" were part of the action, this guy just completely wrecked your piano and the only cure is a complete replacement action - and if they were the tuning pins, the only cure is a new *piano*, not a new action."
Answer: The instrument's action may need a treatment with a proper lubricant to resolve the problem.  A more experienced technician will know what to use: a liquid called Protek CLP (cleaner, lubricant, protectant). This magic substance can flush out the bad oil and leave the pin and bushing refreshed and lubricated, freeing the key action.


Kinect v1.8 SDK with Unity3D

Question: Am developing a football game in Unity3D . in which I need only the foot orientation of the users from which I can detect the angle of the kick.
Am now tracking the whole skeleton data , but I can't able to get the foot orientation angles precisely.
Is there anyway that I can track only the foot of the user without going for the method of Tracking whole skeleton.
Answer: I have developed some games with unity and kinect. what I did is,
I could access the transform.position of each joints represent the skeleton. then by using relative positions of several joints, I detected the body gestures.
Hope this helps
let me know if you need any assistance
Comment: As I said, I need to track the foot only which is to be detected as an Object, not as a skeleton. Because when I am inhibiting the skeleton tracking procedure the kinect has to track the whole body, from which I can't able to get the precise angles of the foot orientations.
Comment: But thanks for answering, but I can do that skeletal tracking FYI. And I have did that too. I need help in somewhat tracking some objects, using kinect.

Kinect v1.8 SDK with Unity3D


Is the following a Convex Set?

Question: Is the following set convex?
$$\{(x_1,x_2,x_3): x_3= |x_2|, x_1\leq 4\}$$
Comment: It contains $(0,1,1)$ and $(0,-1,1)$, but not the point $(0,0,1)$ in between
Comment: So because the point (0,0,1) is on the segment from (0,1,1) and (0,-1,1) you can evaluate it? With respect to lambda how could show this algebraically ?
Comment: A convex set $\Omega$ has the property that if points $A$ and $B$ belong to $\Omega$, then every point on the line segment connecting $A$ and $B$ also belongs to $\Omega$.  Can you visualize your set and just see visually that this is not the case?
Comment: Honestly I could visualize the half plane and see the point but I was trying to approach the problem algebraically to look at it differently. and use lambda and 1-lambda to show it.
Comment: I think you should keep it simple and just visualize the set, which makes it obvious that the set is not convex.  Once you have visualized the set, it's easy to pick two points such as the ones that @HagenvonEitzen selected, then you can give an algebraic proof of non-convexity.
Comment: As a general rule, nonlinear equality constraints are almost never convex. The exceptions are almost entirely manufactured.
Answer: Just writing the Hagen's example. Every point of the form
$$(0,1,1)\cdot k+(1-k)(0,-1,1)=(0,2k-1,1) \text{ for $k \in [0,1]$}$$
It should be in the set. But if you take $k=1/2$ then you will get the point $(0,0,1)$ which is not in the set and so it is not convex.
Comment: This is exactly what I was wondering and also makes it so much more clear!
Comment: I am happy that you got it.
Answer: To say a set $S$ is convex means that if $u \in S$ and $v \in S$ then every point on the line segment joining $u$ and $v$ belongs to $S$.
Visually, it's clear that the line segment joining the points $u = (0,1,1)$ and $v = (0,-1,1)$ goes outside your set.  To give an algebraic proof, just select a value of $\lambda$ such that $0 < \lambda < 1$ and $\lambda u + (1 - \lambda) v$ does not belong to your set.  In this case, we can just pick $\lambda = 1/2$, so that $\lambda u + (1 - \lambda) v$ is the midpoint of $u$ and $v$.  In other words:
$$
\lambda u + (1 - \lambda) v = (0,0,1),
$$
which is a point that does not belong to your set.

Is the following a Convex Set?


Exercise in Well Orderings

Question: Prove that if $\prec$ is a well-ordering on a set X and if  $Y \subseteq X$, then $\prec_Y=\{(x,y) \mid (x \in Y) \wedge (y \in Y) \wedge (x \prec y)\}$ is a well ordering on Y.
I am a little confused on where to start. Also I don't really know what $\prec_Y$ really means.
Comment: "I don't really know what $\prec≺_Y$ really means." It means *exactly* what you wrote in line 2. Nothing more and nothing less.
Comment: Alright do you mind telling me if I got the reasoning down? So I need to show that $\prec$ is a well ordering on Y, and when I do that I need to show that $x$ is the smallest element?
Answer: The relation $\prec_Y$ is the restriction of $\prec$ to $Y$. This means that $\prec_Y$ is only defined when both elements are from $Y$, and then it agrees with the original $\prec$.
Now you have to show that $(Y,\prec_Y)$ is a well-ordered set. This means linearly ordered, and if $A\subseteq Y$ is non-empty, then it has a minimal element. Note that all these properties follow from the fact that $(X,\prec)$ is a well-ordered set.
Comment: @Johambo No, you copied a typo from my answer (which I know fixed). And I wouldn't say $Y\subseteq X$ is the main reason why $\prec _Y\subseteq \prec$, but it is necessary.
Comment: @Johambo: (1) Don't write $(x,z)\in Y$ (as in the first comment). It's not true. $0$ and $1$ are elements of $\{0,1\}$. But is $(0,1)\in\{0,1\}$? No. (2) If you fix $x,y,z\in Y$ then you can't say "Let $x\prec_Y y$ and $y\prec_Y z$" anymore. What if the $x,y,z$ that you have *fixed* don't satisfy these relations, what if $z\prec_Y x$? Other than that, the proof is okay.
Comment: Suppose ($X, \prec$) is a well-ordered set. Because $Y \subseteq X$, then $\prec \subseteq \prec_Y$. Do I have a good start?
Comment: How about this for a start? Suppose $\prec$ is a well ordering on the set $X$. Then for all $\forall Y \subseteq X: \exists x \in Y: \forall y \in Y: x \preceq y$.
Comment: @Johambo: Your assumption is that $\prec$ is a well-ordering of $X$. You don't need to "suppose" it. Write down the definition of a well-order. Then verify that $\prec_Y$ satisfies these requirements. Remember to *use* the fact that $\prec$ satisfies these requirements (on a larger domain).
Comment: $\prec$ is a well-ordering on the set X if for every non empty subset $A \subseteq X$, there is an element $x \in A$ such that $\forall b \in A ((a=b) \vee (a \prec b))$. Since $\prec_Y \subseteq \prec$ then what it true for the larger set is true for the smaller set. So $\prec_Y$ satisfies the requirements of a well ordered set.
Comment: @Johambo: You forgot the linear order part, but let's assume that you already know that a restriction of a linear order to a subset of the domain is a linear order of that subset; In your comment you didn't prove anything. You have to prove that $\prec_Y$ is a well-ordering of $Y$. So you need to show that if $A\subseteq Y$ is a non-empty set, then there is some $a\in A$ such that for all $b\in A$, $a=b$ or $a\prec_Y b$. Just saying "it's true for this so it's true for that" does not constitute as a proof (at least not at the level where you get asked this sort of question.)
Comment: @AsafKaragila Sorry about being so late. But I revisited this problem and made some sense of what you were saying. So I need to show that $\prec_Y$ is transitive and asymmetric. I also need to show that given any $x,y\in Y$, either $x=y$, $x\prec_Y y$ or $y\prec_Y x$. And finally that given any non-empty $S\subseteq Y$, there is a $x\in S$ such that for all $y\in S$, if $x\neq y$, then $x\prec_Y y$.
Comment: @Johambo: That's good.
Comment: @AsafKaragila Check out my edit
Comment: So for showing that $\prec_Y$ is transitive. I was thinking of starting out with $(x,y) \in \prec_Y$ and $(y,z) \in \prec_Y$.
Comment: @Johambo: You need to show that $\prec_Y$ is transitive and *irreflexive*. The rest is fine. And proving transitivity often starts with picking two such ordered pairs. Now use the fact that $x,y,z\in Y$ and that $\prec_Y\subseteq\prec_X$. The rest of the proof is a repeated application of this principle (that your elements are from $Y$ and that $\prec_Y$ is a subset of $\prec_X$).
Comment: Irreflexive: Let $(x,y) \in \prec_Y$. So $x \in Y$ and $y \in Y$. Thus $x \in X$ and $y \in X$ because $Y \subseteq X$. Notice that x cannot equal y, so $\prec_Y$ is not reflexive.
Comment: @Johambo: Yes, that's the general sentiment. Note, however, that "not reflexive" is not the same thing as "irreflexive".
Comment: $(x,y) \in \prec_Y$ and $(y,z) \in \prec_Y$. Thus $(x,y) \in Y$ and $(y,z) \in Y$. Since $Y \subseteq X$, then $(x,y) \in X$ and $(y,z) \in X$. Considering X is a well ordered set, $(x,y) \in \prec_X$ and $(y,z) \in \prec_X$. Thus $\prec_Y \subseteq \prec_X$. I don't know how this means its transitive though.
Comment: @Johambo: First note that it's not $(x,y)\in Y$ it's $x$ and $y$ which are in $Y$. Similarly $z$. Since $\prec_X$ is transitive, and $(x,y),(y,z)\in\prec_X$ what does it mean? Now we have that $x$ and $z$ are in $Y$... and?
Comment: Oh I think I know where you are getting at. Since we are trying to prove that $\prec_Y$ is transitive, we should show that it is a subset of a relation that we know to be transitive by definition, $\prec_X$. So for what you are asking me: $x \prec_X y$ and $y \prec_X z$. Since $\prec_X$ is transitive, then $x \prec_X z$.
Comment: Yes, so $(x,z)\in\prec_X$. How do you get from that it is in $\prec_Y$ as well?
Comment: But then, $\prec_Y \subseteq \prec_X$ so $(x,z) \in \prec_Y$.
Comment: @Johambo: No, $\Bbb N\subseteq\Bbb R$. Does that mean that $\sqrt2$ is a natural number? To have $(x,z)\in\prec_Y$ you need to show that $(x,z)$ satisfies the definition of $\prec_Y$. And to do that you need to connect the dots that I have left in previous comments.
Comment: Well first off, I know that $(x,z) \in Y$ since it $x,z$ are elements in Y.
Comment: @AsafKaragila Fix $x,y,z \in Y$. Let $x \prec_Y y $ and $ y \prec_Y z$. Since $Y \subseteq X$ then we know that $x,y,z \in X$. By the definition of $\prec_Y$, $(x,y) \in \prec_X$ and $(y,z) \in \prec_X$.  Since we know that $\prec_X$ is transitive by definition, then we can say that $(x,z) \in \prec_X$. Notice that $x,z  \in Y$, and $ x \prec z$. Therefore $x \prec_Y z$ by the definition of $\prec_Y$. Ergo $\prec_Y$ is transitive.

Exercise in Well Orderings


Replacing ActiveX with Custom Protocol Handler?

Question: I am trying to update a system that still uses ActiveX for certain things.  For example it uses this javascript to have a user login and access the internet (from our intranet)
var workingDirectory = "c:\\program files\\internet explorer";
var filename = "c:\\program files\\internet explorer\\iexplore.exe";
var arguments = referrer;
var obj = new ActiveXObject("FHS.ProcessLauncherUtility");
processId = obj.LaunchProcessReturnProcessId(domain, username, password,
workingDirectory, filename, arguments);

Obviously I would prefer to do something like a custom protocol handler to deal with this and pass arguments to, however I'm not entirely that will work here since it checks the login of the user before continuing.
Answer: The ActiveX was calling a DLL which then communicated back to the ASPX page via JavaScript.   I replaced the call with a custom protocol handler to an exe (client side) which handles everything the ASPX page did within the windows application.  This made everything a lot easier.  The call to start the exe looks like this:

    <form id="frmMain" runat="server">
        Internet Login
    </form>


Rational Numbers Proof

Question: Apologies for the vagueness before, I'm new here. I hope this clears it up:
Show that, for all non zero $b\in \Bbb Z$, $${(0,b)}=((a',b')\in F:a'=0)$$ $$F=((a,b)\in \Bbb Z*\Bbb Z: b\ne 0))$$ where F defines $\Bbb Q$
The problem states that it is a special class and to show that $(0,b)$ is the identity for sum. Because of that, define $0\in \Bbb Q$ as $(0,b)$
I'm confused on how to solve it. I know that $(a,b) \sim (a',b') <=> ab'-ba'=0$ and that addition in $\Bbb Q$ is defined as $(a,b)+(a',b')=(ab'+a'b,bb')$
Comment: Welcome to stackexchange. As written, your question makes no sense. What are the pairs in parentheses? What are the primed variables? What is $F$? Please [edit] the question to include all the necessary words (not just symbols) and show us what you tried and where you are stuck. Then perhaps we can help.
Comment: This doesn't make any sense without context...and without definitions at all.
Answer: Without some context, it's hard to tell what theorems you're allowed to use here.  But maybe you can multiply  both sides of your equation by $b'$ to get $(0,b) = (a,1)$?  Now the right side is an integer.
Comment: I'd say it's hard to even know what is this about at all. To begin with, what is $\;F\;$ , anyway?! And those ordered pairs seem to belong to a cartesian product with some further constraints...
Answer: I assume you should have been taught that $(a,b) = (c,d)$ if and only if $a\times d = b\times c$.  Further, you should have been taught that the second entry may never be zero.
As such, you will have $(0,b)=(a',b')$ if and only if $0\times b' = b\times a'$.  In other words, you have $0=b\times a'$, but remembering that $b\neq 0$ that implies that $a'$ must be zero since $a$ and $b$ are elements of the integers which are well known to be an integral domain.
Similarly, $(b,b)=(a',b')$ if and only if $b\times b' = b\times a'$.  By subtracting to one side and factoring, we have $0 = b\times (b'-a')$.  By again noting the fact that $b$ is not allowed to be zero and the fact that the integers are an integral domain we get that it must be true that $(b'-a')$ must be zero.  So we have $b'-a'=0$ which by adding implies that $b'=a'$

Rational Numbers Proof


How to remove a failed DC from AD?

Question:
We have two redundant domain controller servers of Win server 2003(server1 , server2) .
Recently server1 got crashed (Complete Harddisk failure)
Inserted new harddisk, Imported Acronics image backup of server2 into server1.
Changed the IP address of server1 => OK
Trying to change the name of Server => throwing error messagethat name is already available
Guess need to remove the Server1 name from AD.
when trying to remove using DCPROMO => throwing error message(not able to remove from AD)
" I want rename to server1, with all the AD configurations intact(client machines) and to work both server in redundant mode  "
Kindly suggest me how to proceed on this?

Thanks in advance.
Answer: First, you failed here:

Inserted new harddisk, Imported Acronics image backup of server2 into server1.

DON'T DO THAT. Get a Windows 2003 installation CD and install from scratch. Join it to the domain with a completely new name. Then promote it to a domain controller.
Once you've done that, you can follow these steps: https://support.microsoft.com/en-us/kb/216498

How to remove a failed DC from AD?


Why do most electric guitar string sets include a plain steel vs. a wound G string and what are the advantages/disadvantages?

Question: I have noticed that it is more common than not for a set of guitar strings for electric guitar to have a plain steel G string instead of a wound G string as would be found on a set of acoustic strings.
The steel core of a wound G string is actually thinner than a plain steel string so the plain steel will usually require more tension to tune to the same pitch. I have seen .18 gauge wound G strings which probably have like a .07 core meaning it will have far less tension than say a .13 gauge plain steel string which has a .13 gauge steel core.  So I don't think the plain steel G string offers lower tension or easier bending.
I know some electric sets do have a wound G string and I have seen sets that include both a wound and plain steel G string.  So what are the advantages/disadvantages of a plain steel G string over a wound G string and what are the practical applications that favor one verses the other?
I personally find a plain wound G string in .20 or .18 gauge far more forgiving on my fingertips and easier to fret and bend than a .14 -.16 gauge plain steel string tuned to G.  But I assume there must be a good reason most electric sets include the plain steel string for the G string.
Comment: "de gustibus..."  , so if you're happy w/ your setup, no reason to change. If you find that certain effects (bending or otherwise) are easier to produce w/ nonwound strings, then consider changing.
Comment: I've used .012" for G on a lot of my guitars, for many years. No trouble bending those! Be interesting to see charts of tension - which a lot of string manufacturers publish, for direct comparison of wound v. plain.
Answer: It's 40 plus years since I played electric with a wound 3rd, but a plain is easier to bend. The core isn't the be-all and end-all, as tension is less in a plain string. The 3rd is a string that gets used a lot in bends, also, a plain is slightly better to slide up or down a fret or two. As mentioned in another answer, we used to use banjo strings or a second (both plain), as there was no alternative except the wound 3rd, which wasn't as good for bends.
Comment: Mainly about bends, as @Tim says; I wonder if somewhere along the line slide guitarists influenced it as well, since slide on 3 plain strings gives quite a different sound from 2 plain + 1 wound.


Histogram values from Pandas DataFrame

Question: I would like to get histogram values from a DataFrame:
%matplotlib inline
import pandas as pd
import numpy as np

df=pd.DataFrame(60*np.random.sample((100, 4)), pd.date_range('1/1/2014',periods=100,freq='D'), ['A','B','C','D'])

Taking into account pd.cut() it is possible to do it with only one column, as in example:
bins=np.linspace(0,60,5)
df.groupby(pd.cut(df.A,bins)).count()

Is it possible to get whole histogram values for all columns in one DataFrame?
The desired output would look like this:
            A   B   C   D
(0, 15]     21  10  1   2
(15, 30]    14  24  21  24
(30, 45]    10  0   22  30
(45, 60]    25  5   25  25

Answer: How about this technique, essentially list comphrension and a pd.concat()
np.random.seed(1)
bins=np.linspace(0,60,5)
df=  pd.concat([df[x].groupby(pd.cut(df[x],bins)).count() for x in df.columns],axis=1)
df.index.names = [None]
print df

which for me produces:
           A   B   C   D

(0, 15]   26  20  31  23
(15, 30]  23  23  20  18
(30, 45]  24  32  24  29
(45, 60]  27  25  25  30

Histogram values from Pandas DataFrame


Interpreting Regression Coefficients in time series model with seasonal & trend component AND a lagged variable

Question: I'm working on a time series model which predicts daily sales.
The model is based on seasonal-trend decomposition by Loess, basically.
(I'm using an R package similar to Prophet by facebook.)
Since the time series I want to model has large PACF for lag 1, I added 1st-order lagged variable to this stl-based model.
To summarize, my model has the following form.
Today's Sales ~ trend + seasonality + some indicator variables + Yesterday's Sales + error
This 'some indicator variables' mean dummy variables whose values are 1 when a specific kind of marketing campaign is ON, 0 when OFF.
I want to interpret the regression coefficients of these dummy variables as the average effect of a marketing campaign category on Sales.
Then there arises a problem. The coefficients are much smaller when I put Yesterday's Sales to the model. (about 1/3 ~ 1/4) But the sign and relative size of these coefficients (compared to the coefficients of the other dummies) remains almost the same.
Yesterday's Sales (lag 1 variable) is highly significant(p<0.0000001) and the coefficient of this lagged variable is about 0.6.
Is it OK to maintain this lagged variable in my model?
Is it reasonable to interpret the coefficients of the indicator variables as the campaign effect?
Thanks in advance.
Comment: It looks like yesterday's sales is an important predictor whose effect is not otherwise captured in your model, this strongly hints that it needs to be included. @IrishStat's answer points to various ways you can account for yesterday's sales effect on today's sales.
Answer: Yes if you have also accounted for level shifts in the series as compared to only dealing with trends. Also if you have identified and incorporated indicator variables to deal with 1 time amomalies. Also if you have incorporated the lead and lag structure around holidays .
Care must also be taken to deal with parameters that are transient over time or error variance that changes at specific points in time.
Another variation of this model might be more effective if you introduced a SARIMA component rather than just a lag of the endogenous (output) series.
Only a comprehensive analysis of your data could expose possible flaws in your current approach. http://autobox.com/cms/index.php/afs-university/intro-to-forecasting/doc_download/53-capabilities-presentation slide 51 is an example in this regard.
Comment: Thank you for your answer, IrishStat. It helped me a lot.
I have incorporated level shifts, one time anomalies, etc.

I'm still confused with the dramatic decrease in the value of the coefficients when I include this lagged variable.

Does it mean that without this lagged variable, the coefficients of the campaign dummies is NOT controlled for this lagged variable, so it can be overestimated?

I have to choose between the model with or without lag, but the coefficients differ significantly(about 3 ~ 4 times higher in absolute value when the lag is not included in the model).
Comment: I am a data guy . For me to help you with your question I need to see your data and your models. If it is proprietary and you don't want to share it with the list then email it to  me and I will treat it confidentially.


Showing flagged content to users

Question: I have flagged contents in a block.But only admin can see the these flagged contents(contents are product variations).I want to show these contents to all authenticated users and anonymous users.Is it possible?Can you help me to solve this issue.
Answer: Sounds like a permission issue, each flag you create has it's own permission settings. Have a look under admin/people/permissions
Comment: I have give flag/unflag permission to all users.Permission "Bypass content access control"(this for administrator) can now see this.

Showing flagged content to users


Why doesn't P(Calvin wins the match by winning 2 more games than his opponent) = $P(C|W_1)P(W_1)+P(C|L_1)P(L_1) = (p)(p) + (1-q)(q)$?

Question:
Calvin and Hobbes play a match consisting of a series of games, where Calvin has probability $p$ of winning each game (independently). They play with a "win by two" rule: the first player to win two games more than his opponent wins the match. Find the probability that Calvin wins the match (in terms of $p$), in two different ways.

Blitzstein, Introduction to Probability (2019 2 edn), Chapter 2, Exercise 50, p 94.
My attempt
Let event $C$ be "Calvin wins."
$$P(C) = P(C|W_1)P(W_1)+P(C|L_1)P(L_1) = (p)(p) + (1-q)(q)$$
This doesn't match the answer key, $\frac{p^2}{p^2+q^2}$.
I think the conceptual misunderstanding is $P(C|W_1)$, $P(C|L_1)$. For $P(C|W_1)$, my thinking is: if we interpret this problem as the gambler ruin's problem, $i$ is originally at 2, but given that $W_1$, we have that $i=3$. Thus, because C occurring corresponds to $i=4$, $$P(C|W_1) = \text{ (the probability that we move from } i=3 \text{ to } i = 4) = p$$ The same goes for $P(C|L_1)$: $i$ is originally at 2, but given that $L_1$, we have that $i=1$. Thus, because C not occurring corresponds to $i=0$, $$P(C|L_1) = 1 - P(C^c|L_1) = 1 -\text{ (the probability that we move from } i=1 \text{ to } i = 0) = 1-q$$
I know this is wrong because the gambler ruin's problem would interpret, for example, $P(C|W_1) = p_{i+1}$. When I first learned the gambler ruin's problem, this made sense. However, now that I'm actually doing a problem that's kind of related, I'm left questioning this: why can't we just $P(C|W_1) = p^{n-i-1}$, where $n$ represents the # of wins to win the series, $i$ is the original starting spot, and one represents winning the first game

And yet, I also don't think the gambler's ruin problem totally applies here; the biggest difference is that given $W_1$ or $L_1$, the important thing is that we are one spot away from the edge, so the probability of winning or losing one spot from the edge is either $p$ or $q$, whereas if we were at an $i$ in the "middle," $i$ can shift left, right, and back left, and left some more.
Answer: You are missing the chance that Calvin can win the first game, lose the second, and still win the match.  Your conversion of $P(C|W_1)P(W_1)$ to $p^2$ says the only way Calvin can win given that he won the first game is to win the second as well.  You should use the fact that the games are independent to say if Calvin wins the first game, either he wins the second and wins the match or he loses the second and has the same chance of winning the match as he started with.  Similarly, if he loses the first game and wins the second he is back where he started.
Comment: Ahhh. Thank you. I correctly redid the problem by solving it as a gambler ruin's problem. But, there's a second part to this problem which is to condition using the LOTP. How else can I condition $P(C)$?
Comment: I would have to see how you state the law of total probability to know how to use it.  I don't know a law by that name.