text:
Q: how to access localhost(xampp) from other computer I have installed XAMPP on my computer.I want to access my localhost when typing my ip address in another computer.But when i type my ip address it takes me to my modem settings page.Please help me.(I am using the ip address from whatismyip.com)

A: If you're trying to access your local XAMPP from another computer on your local network, you'll need to use a local ip address.  Likely something like 192.168.x.x.  (on a Windows box, you can type 'ipconfig' into a command prompt to get this IP)
If you're trying to access from outside your local network, you'll need to port-forward port 80 through your router to the computer that is running your XAMPP.

A: You need to open port 80 (Or whatever port you are using for Apache) on your firewall. This is pretty well documented here http://portforward.com/ for most routers.
I would also recommend you get something like DynDNS, makes dynamic IPs less of a hassle.

A: First, you need to configure your computer to get a static IP from your router. Instructions for how to do this can be found: here
For example, let's say you picked the IPaddress . After the above step is completed, you should be able to get to the website on your local machine by going to both "http://localhost" and "http://theipaddress", since your computer will now always have that IP address on your network.
If you look up your IP address (such as "http://www.ip-adress.com/"), the IP you see is actually the IP of your router. When your friend accesses your website, you'll give him this IP. However, you need to tell your router that when it gets a request for a webpage, forward that request to your server. This is done through port forwarding.
Two examples of how to do this can be found here and here, although the exact screens you see will vary depending on the manufacturer of your router (Google for exact instructions, if needed).
For the Linksys router I have, I enter "http://192.168.1.1/", enter my username/password, Applications & Gaming tab > Port Range Forward. Enter the application name (whatever you want to call it), start port (80), end port (80), protocol (TCP), ip address (using the above example, you would enter 192.168.1.102, which is the static IP you assigned your server), and be sure to check to enable the forwarding. Restart your router and the changes should take effect.
Having done all that, your  should now be able to access your webpage by going to to web browser on his machine and entering "http://IP.address.of.your.computer" (the same one you see when you go here ).
As mentioned earlier, the IP address assigned to you by your ISP will eventually change whether you sign offline or not.
I hope this helps.


text:
Q: Why is this not reading my file? I'm having problems getting my program to read an input file from the same directory.
code is in Main, included the whole just incase i have done something outside of main that is causing this.
import java.io.*;
import java.util.*;

public class Final
{
    public static int readData(BusinessDirectory [] array, Scanner input,Scanner inputFile)
    {
        int lastChar = 0;
        int count =0;
        int dirChoice = 0;

        int area,
            exchange,
            number,
            extension;
        String name;

        while(inputFile.hasNextLine() && count < array.length)
        {

            String Og = inputFile.nextLine();
            lastChar = (Og.length()-1);
            dirChoice = Integer.parseInt(Og.substring(0,1));
            if(dirChoice == 1)
            {
                area = Integer.parseInt(Og.substring(2,5));
                exchange = Integer.parseInt(Og.substring(6,9));
                number = Integer.parseInt(Og.substring(10,14));
                name = Og.substring(15,lastChar);
                array[count].DirectorySet(area, exchange, number, name);

            }

            if(dirChoice == 2)
            {
                area = Integer.parseInt(Og.substring(2,5));
                exchange = Integer.parseInt(Og.substring(6,9));
                number = Integer.parseInt(Og.substring(10,14));
                extension = Integer.parseInt(Og.substring(15,19));
                name = Og.substring(20,lastChar);
                array[count].BusinessDirectorySet(area, exchange, number, extension, name);
            }
        }
        return count;
        }

    public static void main(String[]args)throws IOException
    {
        String infile;
        int count=0;;

        //Directory[]array = new Directory[25];
        BusinessDirectory[]array = new BusinessDirectory[25];
        Scanner in = new Scanner(System.in);
        System.out.print("What is the input file: ");
            infile = in.next();

        try
        {
            File inputFile = new File(infile);
            Scanner fin = new Scanner(inputFile);
            readData(array, in, fin);
            System.out.println(BusinessDirectory.getName());
        //  System.out.println("test");
            //count = readData(array,in,inputFile);
        }

        catch(Exception e)
        {
            System.out.println("\"" + infile + "\" not found. Program will terminate.");
            System.exit(0);
        }

        }
    }

it always throws the Exception from the Catch.
("test.txt" not found. Program will terminate.)
e.printStackTrace();
gets me
What is the input file: test.txt
java.lang.NullPointerException
"test.txt" not found. Program will terminate.
    at Final.readData(Final.java:36)
    at Final.main(Final.java:69)

Error seems to be in my Directory Class
public class Directory
{
    //data members
    static int Area;
    static int Exchange;
    static int Number;
    static String Name;
    static int cause;

    public Directory()
    {
        Area = 999;
        Exchange = 999;
        Number = 9999;
        Name = "";
        cause = 0;
    }
    public Directory(int area, int exchange, int number, String name)
    {
        DirectorySet(number, number, number, name);
    }

    public void DirectorySet(int area, int exchange, int number, String name)
    {
        try
        {
            if(area >= 200 && area <= 999 && area != 911)
            {
                if(exchange >= 200 && exchange <= 999 && exchange !=911)
                {
                    if(number >= 0 && number <= 9999)
                    {
                        Area = area;
                        Exchange = exchange;
                        Number = number;
                        Name = name;
                    }else
                        {
                        cause = 1;
                        MyOwnException error = new MyOwnException();
                        MyOwnException.Message = error.setMessage(cause);
                        throw error;
                        }
                    }else if(exchange == 911 || area == 911)
                        {
                        cause = 4;
                        MyOwnException error = new MyOwnException();
                        MyOwnException.Message = error.setMessage(cause);
                        throw error;
                        }

                cause = 2;
                MyOwnException error = new MyOwnException();
                MyOwnException.Message = error.setMessage(cause);
                throw error;
                }else
                    {
                    cause = 3;
                    MyOwnException error = new MyOwnException();
                    MyOwnException.Message = error.setMessage(cause);
                    throw error;
                    }
            }
        catch(MyOwnException error)
        {
            System.out.println(toString());
            System.out.println(MyOwnException.Message);
            //System.out.println(Directory.toString());
        }

    }

    public void toString(int area, int exchange, int number, String name)
    {
        System.out.println(name + " (" + area + ") " + exchange + " -" + number);
    }
    public String toString()
    {
        return (Name + " (" + Area + ") " + Exchange + " -" + Number);
    }
    public static String getName()
    {
        return Name;
    }

    public static int getArea()
    {
        return Area;
    }

    public static int getExchange()
    {
        return Exchange;
    }

    public static int getNumber()
    {
        return Number;
    }

    public void setName(String name)
    {
        Name = name;
    }
    public void setArea(int area)
    {
        Area = area;
    }
    public void setExchange(int exchange)
    {
        Exchange = exchange;
    }
    public void setNumber(int number)
    {
        Number = number;
    }

}

..
Final.readData(Final.java:37)
array[count].DirectorySet(area, exchange, number, name);

Final.main(Final.java:73)
readData(array, fin);

A: Try:
File inputFile = new File(infile);
System.out.println(inputFile.getAbsolutePath());

This will give you a hint about your working directory and you can fix your input (absolute or relative paths)
Also it is recommended that if you're not sure about the relative location and do not wish to use absolute paths, use the File.exists() API to make a decision within your code.

A: Your NullPointerException seems to be thrown at this line :
array[count].DirectorySet(area, exchange, number, name);

The problem is that you correctly created the array this way :
BusinessDirectory[]array = new BusinessDirectory[25];

But that creates only the space for 25 object pointers, that doesn't actually creates 25 objects.
You have to create each object one by one, in your case you should probably do this :
array[count] = new Directory(area, exchange, number, name);

instead of this :
array[count].DirectorySet(area, exchange, number, name);

Also you don't seem to increment count anywhere.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does bash import variables from inner file at second and deeper levels? I have these files:
# ~/.bashrc

# I expect that variables in that file will be exported
. ~/env_vars.sh

# ~/env_vars.sh

# I expect it expands parent's vars
export VAR=test

What happens when I run bash:
$ echo $VAR
$

Nothing.
but when I place my variables directly in .bashrc
# ~/.bashrc
VAR=test

Then it works:
$ echo $VAR
test

Is it possible to import variables from inner files?
About versions:
bash --version
GNU bash, version 4.4.12(1)-release (x86_64-unknown-linux-gnu)

$ uname -a
Linux user-pc 4.9.38-1-MANJARO #1 SMP PREEMPT Sat Jul 15 12:04:06 UTC 2017 x86_64 GNU/Linux

I do know that ~ works and ~/env_vars.sh have sourced:
# ~/env_vars.sh
touch ~/env_sourced.test

$ bash
$ file ~/env_sourced.test
~/env_sourced.test: empty


text:
Q: If $\sigma=a-e^{1-b\epsilon}$ and $\frac{d\sigma}{d\epsilon}=\sigma$, find $\epsilon$ in terms of $a$ and $b$.
So for this problem, I was given that $$\sigma = a - e^{1-b\epsilon}$$
  and $${d\sigma\over d\epsilon}=\sigma$$
I'm tasked with finding $\epsilon$ in terms of $a$ and $b$.

This is what I've done so far:
Set the equations equal to each other and take the integral.
$${d\sigma\over d\epsilon}=a - e^{1-b\epsilon}$$
$$\int d\sigma=\int(a-e^{1-b\epsilon})d\epsilon$$
$$\sigma=a\epsilon+\frac 1 b e^{1-b\epsilon}$$
From here, I set the first given equation and the most recent equation equal to each other in an attempt to get rid of the $\sigma$.
$$a - e^{1-b\epsilon}=a\epsilon+\frac 1 b e^{1-b\epsilon}$$
To try to simplify this and get $\epsilon$ by itself, I tried to rearrange the equation.
$$a(1-\epsilon)=(1+\frac 1 b)e^{1-b\epsilon}$$
$$\epsilon=1-(1+\frac 1 b)\frac 1 a e^{1-b\epsilon}$$
Unfortunately, I'm not sure how to get past the fact that there is an $\epsilon$ in the exponential that is difficult to reconcile with the $\epsilon$ I've put on the left of the last equation. Thanks for your help, guys.

A: You can follow this method:
$$\sigma = a- e^{1-b\epsilon}$$
Differentiate this equation with respect to $\epsilon$
$$\frac{d\sigma}{d\epsilon}=be^{1-b\epsilon}$$
$$e^{1-b\epsilon}= \frac{1}{b} \frac{d\sigma}{d\epsilon}= \frac{\sigma}{b}............(A)$$
Put this value of $e^{1-b\epsilon}$ in the  first equation
$$\sigma = a - \frac{\sigma}{b}$$
$$\sigma = \frac{ab}{b+1}$$
Now substitute this value of $\sigma$ in (A)
$$e^{1-b\epsilon} = \frac{a}{b+1}$$
Take natural logarithm on both sides
$$1-b\epsilon = log_e(\frac{a}{b+1})$$
$$\epsilon = \frac{1-log(\frac{a}{b+1})}{b}$$
Hope this helps...........:-)


text:
Q: Firth's regression with many fixed effects I've got a sample (n=7000) with a binary dependent variable with many 0s and only a few 1s (150 total) and therefore want to run a Firth's biased reduced regression to estimate the probability of the 1s. So far so good, but my explanatory variables are fixed effects for the individuals (=their individual names). Each individual has between 2 and 50 cases in the data, and all in all there are about 120 individuals. An individual's covariate values can change from trial to trial. As I want to include the individuals as fixed effects I convert them as Dummies. Running Firth's regression with the R logistf package produces several errors now, because of the big number of 'IndividualDummies'. Is there a way to include a big amount of dummies in another way like (1|Individual) in glmer package? Would be great to make it more handy for Firth's regression.

A: I am not aware of any generalization of the Firth's penalized likelihood approach to mixed effect models (i.e. not clear how one ought to penalize the hierarchical scale parameter in this setting).
However, note that Firth's penalized likelihood approach is basically a Bayesian maximum a-posteriori approach using Jeffreys prior. Thus, one thing you could do is to use software that's intended for (amongst other things) fitting Bayesian generalized linear mixed effects models. There is a number of convenient R packages like brms (or also rstanarm) that would easily allow you to do something like that using familiar R formula syntax. You'd simply have to decide on appropriate prior distributions, for which you might e.g. choose something rather weakly informative in order to obtain something that's not too different from the Firth approach in simple settings (assuming that is desirable to you).
In general, Bayesian approaches with proper priors are pretty good (i.e. they often have better frequentist operating characteristics for plausible scenarios than competing frequentist methods) at dealing with sparse binary/binomial data, if you set sensible prior distributions.

A: The big problem here is the small number of events per predictor, as you want to include the individuals as fixed effects. It's not clear that the Firth penalization is the best solution to that problem.
To avoid overfitting you typically need about 10-20 cases in the minority class (events) per predictor  in the model. With only 150 events and 120 individuals treated as fixed effects, plus other covariates, you are approaching just 1 event per predictor. Some type of penalization is called for, but it's not clear that Firth's is the best choice.
First, the original Firth method penalizes both the regression coefficients and the intercept toward values of 0. As it reduces small-sample bias in predictor coefficients it thus also biases the intercept toward 0 so that probability predictions are biased toward 0.5. The logistf package now provides modifications that help avoid that problem.
Second, penalization is tricky with dummy variables.* As Frank Harrell explains in Section 9.10 of the second edition of Regression Modeling Strategies, with penalization "one will get different predictions depending on which cell is chosen as the reference cell when constructing dummy variables." For a categorical predictor having multiple levels, he recommends penalizing the sum of squared differences of the individual regression coefficients from their mean. The lrm() and pentrace() functions in his rms package can implement that approach in the broader context of penalized maximum likelihood.
Another choice would be a simple mixed-effect model, with the individuals treated as random effects and fixed effects limited to the covariates. In that case, the much higher event/predictor ratio might get around the small-sample coefficient bias for covariates adequately for your purposes. Random intercepts for the individuals would represent their differences from the log-odds at baseline covariate values and thus still provide some basis for examining differences among them.
If you are intent on treating the individuals as fixed effects, I suppose that Björn's suggestion to use a Bayesian approach (+1) could be extended to a fixed-effects model.
Finally, I'd suggest that you read this related thread. The answer from StasK shows how to treat clusters (individuals in your case) as fixed effects with a Firth regression.* If you want to use a Bayesian approach in a mixed model, the answer from Ben Bolker illustrates how to use the blme package, a Bayesian-modeling wrapper for lme4, to use a weak prior on the fixed effects to accomplish something similar to the Jeffreys prior that corresponds to Firth penalization.

*Did you set up the dummies yourself, or did you set up a single Individual categorical predictor including all individuals and let R define the corresponding dummies? The latter is much less error-prone. Errors in defining dummy variables can lead to error messages when you try to fit a model.


text:
Q: DB2 SYSADM Windows - NO LUCK I have installed DB2 10.5 Enterprise Edition on a Windows 2012 server but can't get a SYSADM access with anything. I also have restored a DB2 database taken from a similar server to the new one but can't gain SYSADM permisisons to browse data. The new installation was installed with a domain account as the instance owner and the 2 Local groups (DB2ADMNS and DB2USERS) were created with the instance owner and Administration accounts added to DB2ADMNS group. WHat ever I did, can't browse the data on the database I restored with any of the members of DB2ADMNS group (Local or domain). I have setup SYSADM_GROUP to DB2ADMNS and global registry to DB2_GRP_LOOKUP=local but still no luck. I restarted DB2 everytime I made a change or log out and in but still no luck.
What am I missing to gain SYSADM access to DB2 at least via the instance owner account ?
Thanks.

A: To recover, drop the restored database(s), then try the below.
Before you perform the RESTORE of the database, you must first do (in the db2cmd administrator window) these commands:
db2set DB2_RESTORE_GRANT_ADMIN_AUTHORITIES=ON
db2stop force
db2start

Ensure all commands complete successfully. Now retry the restore and check what rights you have.
This is documented.
If you still get problems after following the above, you need to EDIT your question to show exactly all the commands and the results, the old and new instance-names, the syscat.dbauth entries for both of them, and additionally show the output of db2set -all and also the exact messages that appear in db2diag.log when the instance-owner account attempts to access data.
In many cases, simply studying the contents of syscat.dbauth will indicate the problem, once you've connected to the database and that view has PUBLIC select.  Users that have DATAACCESS need to be able to connect the the database on the new environment, so in a domain environment DB2_GRP_LOOKUP should be same as the originating Db2-server.  If there are large numbers of rows in syscat.dbauth you can filter with SQL like this SELECT * FROM TABLE (SYSPROC.AUTH_LIST_GROUPS_FOR_AUTHID ('YOUR_ACCOUNT')) AS T

A: SYSADM authority (starting from 9.7) in DB2 doesn't necessarily allows user to 'browse data' as it was noted by @Ian Bjorhovde.
select *
from table(auth_list_authorities_for_authid('YOUR_ACCOUNT', 'U'))
where authority in ('SYSADM', 'DBADM', 'DATAACCESS');

AUTHORITY  D_USER D_GROUP D_PUBLIC ROLE_USER ROLE_GROUP ROLE_PUBLIC D_ROLE
---------- ------ ------- -------- --------- ---------- ----------- ------
SYSADM          *       Y        *         *          *           *      *
DBADM           N       N        N         N          N           N      *
DATAACCESS      N       N        N         N          N           N      *

According to the results of this query, your YOUR_ACCOUNT user does have SYSADM authority, but doesn't have DBADM or DATAACCESS authorities in the database.
This probably means, that you get SQL0551N errors on various data access attempts.
If you want to get DBADM / SECADM access for this user, you can either:

*

*use DB2_RESTORE_GRANT_ADMIN_AUTHORITIES registry variable before the RESTORE DATABASE command

*grant these authorities to your user from some another user which has SECADM
authority (query the SYSCAT.DBAUTH table to get it)


text:
Q: Primes and $x^2+2y^2+4z^2$ A few months ago, I have asked a question about primes represented by ternary quadratic forms. I got two wonderful answers, which showed me how the theory was way richer and more complex that I naively expected from the case of binary forms. I
 was also given a lot of references
to read. They were interesting but unfortunately I got submerged by the amount of theory to learn and by other things to do, and I still don't have a clear overview of how the theory works.
I hope it is not abusing the patience of the readers of this site, and in particular of the experts in that theory, to come back again with a new question, this time
by stating a very specific result that I have obtained as a by-product of some study of modular forms, and to ask
whether this theorem can be proved using the general theory of ternary quadratic forms (which I very much believe), and if it can, how?

Proposition : a prime $p$ is represented an odd number of times by the form $x^2+2y^2+4z^2$,
  with $x,y,z$ odd positive integers, if and only if $p \equiv 7 \pmod{16}$

I hope the answer will lead me to the part of this large theory I need to learn to understand better this kind of questions (I have (infinitely) many results of the above type, and I'd like to understand how they fit in the general theory) . Also, if someone finds an elementary argument for proving the proposition, I'd be quite interested too.

A: Here's a simpler argument. We may assume p is 7 mod 8. Let N be the number of triples of squares (r,s,u) with r+2s+4u=p. We will show that N is odd if p is 7 mod 16 and even if p is 15 mod 16. Let M be (1/64)(the number of representations of p by xx+yy+zz+tt). Jacobi's 4 square theorem (which has elementary proofs using quaternions for example) shows that M=(p+1)/8. So it suffices to show that M and N have the same parity. Now if p=xx+yy+zz+tt, then just one of x,y,z,t is even. So M=(1/16)(the number of representations of p by xx+yy+zz+4tt). In other words, M is the number of ordered quadruples of squares (r,s,t,u) with r+s+t+4u=p. Now the involution (r,s,t,u)-->(r,t,s,u) on this set of quadruples has the N fixed points (r,s,s,u), giving the result.

A: You are doing something unusual here. Taking a diagonal form and insisting on the variables being nonnegative is possible but is not really natural. One counts a representation with some $x$ as distinct from the same representation with $-x.$
However, this is what you did. I can fill in the beginning of the story, enough for those expert in quadratic fields to finish it. First, for all odd numbers $n,$ the number of primitive representations with $\pm$ being considered distinct is $h(-32n),$ being the class number of positive binary quadratic forms of the same discriminant has $f(x,y) = x^2 + 8ny^2.$
Now, there is typically no reason for the number of representations, or number of primitive representations, by a diagonal ternary form $a x^2 + b y^2 + c z^2$ to be divisible by 8. However, once we restrict $n \equiv 7 \pmod 8,$ we immediately find that $x,y,z$ are odd. Odd means nonzero. Furthermore, $1,2,4$ are distinct. So there is no permutation of a given $x,y,z$ that gives the same value. As a result, each triple has exactly eight full versions with the possible $\pm$ on each of three positions.
So far, with your positive variables, the number of primitive representations is $$h(-32n)/8.$$
Alright, you wanted primes. So primitive representations agree with representations. The other effect is that the number of genera of (positive binary forms of) discriminant $-32p$ is four.
Finally we get to distinguish $7 \pmod {16}$ and $15 \pmod {16}.$ When $p \equiv 15 \pmod {16},$ the number of classes in the principal genus is divisible by 4, because the number of fourth powers in the class group is even. For a given $p \equiv 15 \pmod {16},$ the fourth powers include $\langle 1,0, 8p \rangle$ and $\langle 8,8, p+2 \rangle$ and add up to an even number of classes, should there be any others. For a given $p \equiv 7 \pmod {16},$ the fourth powers include $\langle 1,0, 8p \rangle$ (but not the other one, it is a square but not a fourth power) and add up to an odd number of classes, should there be any others. Put those together, the principal genus has either a multiple of four classes or twice an odd number, multiply by four genera and you get either a multiple of sixteen or $8 \pmod {16},$ finally divide by 8 and you get either an even number or an odd number.
Probably enough. Relating primitive representations by ternaries (of numbers relatively prime to the discriminant) to a class number goes back to Gauss and the Disquisitiones. As David pointed out, Joel had actually required that $x,y,z$ be odd, so primes $1,3,5 \pmod 8$ are simply not represented in the requested manner. If we remove the oddness restriction, we still get $h(-32p),$ and $x$ must still be odd, but either $y$ or $z$ will be $0$ in some representations, meaning we lose the strict eight to one ratio of representations to nonnegative representations.
Bonus paragraph: the group of fourth powers is a subgroup of the principal genus, for positive binary forms. Sometimes it coincides with the squares, sometimes it is  smaller. Here it is a subgroup of index two. The reason for my interest is an article of Estes and Pall, in which they show that the spinor kernel is precisely the fourth powers, two binary forms of the same discriminant are in the same genus if their ratio is a square, and in the same spinor genus if their ratio is a fourth power in the class group. If we take the principal form  $x^2 + ny^2,$ then a form in the principal genus that is not a fourth power, then add some $k n^2 z^2,$ if there are no 2-adic problems the resulting ternary forms are in the same genus but distinct spinor genera. So this is a source of interesting examples.
NOTE: by a few trivial lines, the condition I am referring to as "a fourth power in the class group" is the same as "the square of a form that is in a genus containing an ambiguous form." For our discriminant, the two ambiguous forms mentioned occur in the principal genus, and two others, $\langle 4,4, 2p +1 \rangle$ and $\langle 8,0, p \rangle$ are together in a second genus. There are two genera without ambiguous forms. This is from Dennis Estes and Gordon Pall,   Spinor Genera of Binary Quadratic Forms, Journal of Number Theory, vol. 5 (1973), pages 421-432.
Furthermore, it should be noted that the four genera are separated quite easily by the odd values they represent modulo 8. It's traditional. The principal genus represents only $1 \pmod 8,$ as in the displayed values $1,p+2.$ The other genus containing ambiguous forms represents only $7 \pmod 8,$ as in $p, 2p+1.$ One of the genera without ambiguous forms represents only $3 \pmod 8,$ the other only $5 \pmod 8.$ So there.


text:
Q: The field date must be a date in mvc in chrome I'm doing a simple MVC4 Internet application, which allows to add some items to the categories.
Here is what i've done so far.
I've a datepicker in mvc view. The script for the datepicker is like this.
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
    $(function () {
        $('#dtItemDueDate').datepicker({
            dateFormat: 'dd/mm/yy',
            minDate: 0
        });
    });
</script>

My model property :
        [DisplayName("Item DueDate")]
        [Required]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode = true)]
        [DataType(DataType.DateTime)]
        public DateTime? dtItemDueDate { get; set; }
        public char charCompleted { get; set; }

and in my view i've done this:
@Html.TextBoxFor(m => m.dtItemDueDate)
@Html.ValidationMessageFor(m => m.dtItemDueDate)

The error is like this:
The field Item DueDate must be a date.

The strange this is that it does work in IE and mozilla, but doesnot work in Chrome.
I found many posts on SO, but none of them help
Any ideas/suggestions ?

A: Rowan Freeman solution wont work for me since .toLocaleDateString(value) doesn't parse value strings
here's the solution i came up with =>
in jquery.validate.js find this function definition: "date: function (value, element)" and replace the code with:
// http://docs.jquery.com/Plugins/Validation/Methods/date
date: function (value, element) {
    var d = value.split("/");
    return this.optional(element) || !/Invalid|NaN/.test(new Date((/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) ? d[1] + "/" + d[0] + "/" + d[2] : value));
},

A: Below is the working code that may helpful for some one to fix the date picker issue in chrome and safari:
Model:
public DateTime? StartDate { get; set; }

View:
@Html.TextBoxFor(model => model.StartDate, "{0:dd/MM/yyyy}", new { @type = "text", @class = "fromDate" })

js:
$(function () {
    checkSupportForInputTypeDate();

    $('#StartDate').datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy'
    });
});

//Function to configure date format as the native date type from chrome and safari browsers is clashed with jQuery ui date picker.
function checkSupportForInputTypeDate() {
    jQuery.validator.methods.date = function (value, element) {
        var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
        var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
        if (isSafari || isChrome) {
            var d = new Date();
            return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
        } else {
            return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
        }
    };
}

A: Here's Maxim Gershkovich's solution spelled out a little more:
jQuery.validator.methods.date = function (value, element) {
    if (value) {
        try {
            $.datepicker.parseDate('dd/mm/yy', value);
        } catch (ex) {
            return false;
        }
    }
    return true;
};

Notes:

*

*This depends on the jQuery datepicker method that comes with jQuery UI

*This is actually more robust that the native date validation that comes with jQueryValidate.
According to the docs on date validation:

Returns true if the value is a valid date. Uses JavaScript's built-in Date to test if the date is valid, and therefore does no sanity checks. Only the format must be valid, not the actual date, eg 30/30/2008 is a valid date.

Whereas parseDate will check that the date is valid and actually exists.

A: Without changing jquery.validate.js, you can use the code snip below in $(document).ready():
jQuery.validator.methods.date = function (value, element) {
    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
    if (isChrome) {
        var d = new Date();
        return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
    } else {
        return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
    }
};

A: Editor note: This answer is no longer valid, as of jQuery 1.9 (2013) the $.browser method has been removed

According to this post it's a known quirk with Webkit-based browsers.
One solution is to modify jquery.validate.js by finding the function date: function (value, element) and put this code in it:
if ($.browser.webkit) {
    //ES - Chrome does not use the locale when new Date objects instantiated:
    var d = new Date();
    return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
}
else {
    return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}

A: I solved this issue by changing from DateTime to String.
This is the best solution for a good maintance that I can think at the moment.


text:
Q: Are virtual pions necessary to mediate the residual strong interaction? In relation to another question I asked recently, I was wondering if the forces between the up and down quarks of the protons and neutrons in nuclei would be sufficient to keep the nuclei bound together without invoking virtual pions as pseudo-Goldstone bosons for the residual strong interaction.
Also, a quick note on the detection of these pions via proton-proton collisions, it seems like pions would be produced anyway and that this says little about the residual strong interaction. That is, it doesn't prove that these virtual pions do indeed mediate that interaction.
Any help is much appreciated.

A: You seem to be misunderstanding what the effective theory with the residual nuclear force between hadrons mediated by pions is: It is an effective theory which is a good approximation of the underlying nuclear force between quarks mediated by gluons. It is not that one of these is correct and the other false, or that they represent two different forces - they are both descriptions of fundamentally the same phenomenon at different levels of detail.
You cannot detect virtual particles mediating an interaction anyway - since a virtual particle is just a mathematical fiction arising from the diagrammatic description of our perturbation series used to compute QFT amplitudes, it does not "exist" in the sense that it could be detected.


text:
Q: Why was off-topic flag declined? I flagged this question as off-topic. But since I didn't - and still don't - think it falls within the possibilities given as default off-topic reasons, I flagged it for moderator attention.
If we go through the OT-reasons:

*

*It's not about general hardware and software.

*It's not about code he's written.

*He doesn't have minimal understanding of what SO is about, but that doesn't really apply here.

*It's not about professional server stuff.

*He doesn't solicit for tools or libraries.

That the last one doesn't apply is in my opinion, because that was later the close on-hold reason. As I read the question, the OP comes to SE and asks whether there are anybody on this site willing to help him.
We tell him "No, you can't come here fishing for off-site resources." That doesn't add up to me, I simply don't see how the OP get any wiser from that.
In my opinion, this question doesn't belong anywhere on the SE-sites, so it is off-topic.
I flagged it for moderator attention and wrote "off-topic". I'll refer to Shog9's (downvoted) answer to a question here on Meta regarding what to do when the provided off-topic reasons are not sufficient. I have a feature request to the same effect (that has not received any replies).

If you see a post that should be closed for an unusual reason, you have the option of flagging for moderator attention, selecting "other" and describing that reason in detail.

After Shog9 wrote the above, he marked the question status-by-design.
While I agree that I didn't add much detail in the flag, I think I wrote enough as this is a slam-dunk as an off-topic question.
As mentioned above the question was subsequently put on hold, but my flag was declined with the reason:

flags should only be used to make moderators aware of content that requires their intervention

I'm guessing that a mod got annoyed by being bothered by a trivial flag, and I fully understand that. But how should I have flagged this? Is the question really fishing for off-site resources? "Too broad" and "Unclear what you're asking" are just as accurate and no more helpful.
I think this part of the system is broken, because I really don't believe that mods should be bothered with trivial off-topic stuff, but I have dutifully followed Shog9s decree above. And just off-topic is - apparently - an unusual reason, since it's not common enough to be in the dialog.
Could you please reconsider your status-by-design and update the dialog so that it includes a sensible It's just off-topic and doesn't belong here at all option that doesn't bother the mods?

A: I declined this flag. The post was blatantly off-topic that much I agree with. My reasons for declining however is largely around the use of the "other flag".
With the new close votes system in place moderators no longer see regular close votes. There's no need to in > 90% of cases where it's a "slam-dunk" case that can be handled by the community.
Using a custom flag to alert moderators sidesteps this new system, which is something we've been trying to figure out how to address. When the content in question isn't particularly abusive (just misguided),  and where the community driven system is working custom flags  don't help much - it's just noise.
There are cases where you might want to escalate things still, using custom flags:

*

*if it's a persistent pattern

*something outright abusive

*there's some astroturfing tag-team activity going

*something isn't right about the community close handling and the process has had a chance to run

In cases like that detailed custom flag messages are exceedingly helpful, but in general we don't need to see every single off-topic post.
In this specific instance I saw this question and your flag as part of a group:

*

*I did not infer from your flag message that you were asking for a more detailed reason to be used. (I assumed it to be another "hurry up please" flag)

*By the time I got to the flag it was already closed. (I'm not going to reopen and then close it just to change the message without a really good reason)

A: In my humble opinion, the question does fit the "recommend or find a tool, library or favorite off-site resource" closure reason: a co-worker or teacher who regularly assists you with your code is an off-site resource.
As you can see, all of the users who voted to close (myself included) have indeed chosen this very reason.


text:
Q: How to find all the terms of a polynomial that contain a specific variable in Matlab? Let say that we have the polynomial f=a^2*b+b^2*c+c*d.
I would like to know if, in Matlab, I could find all the terms of f that
contain specific polynomials of variables a, b, c and d.
For example, if I have a polynomial of variable c, that is g=b,
then I want to find out the terms: a^2+b*c.
If I have a polynomial of variable b, that is g=c,
then I want to find out the terms: b^2+d.
It is like to take a common factor (polynomial of a variable) and then to find the terms that contains this factor.
I know that I can use factor(), but I have polynomials in which the usage of factor() does not work, because they cannot be written as a product of polynomials.

A: Your question is confusingly worded. As far as I can tell, you have a polynomial in several variables, and want to reduce the power on all of a given variable by 1, and remove the terms which are constant with respect to that variable. Here is a way to do that:
syms a b c d
f=a^2*b+b^2*c+c*d

[p,q] = coeffs(f,c)
% p = [ b^2 + d, a^2*b]
% q = [ c, 1]

sum(p(1:end-1).*q(2:end))

coeffs returns the coefficients of the various powers of c in the expression f, returning the coefficients in p and the powers of c in q. Then multiply the i-th entry of p by the I+1-th entry of q and add them up.


text:
Q: What's wrong with my deleting duplicate rows code? I have bunch of excel files (approximately 1000 files ) which I want to merge them together and delete duplicate rows of them.
I have the following excel vba macro to do this.
    Sub simpleXlsMerger()
Dim bookList As Workbook
Dim counter As Integer
counter = 1
Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object
Application.ScreenUpdating = False
Set mergeObj = CreateObject("Scripting.FileSystemObject")

'change folder path of excel files here
Set dirObj = mergeObj.Getfolder("C:\Users\dalakada\Desktop\deneme google drive keywords 100 tane")
Set filesObj = dirObj.Files
For Each everyObj In filesObj
Set bookList = Workbooks.Open(everyObj)

'change "A2" with cell reference of start point for every files here
'for example "B3:IV" to merge all files start from columns B and rows 3
'If you're files using more than IV column, change it to the latest column
'Also change "A" column on "A65536" to the same column as start point
Range("A2:N" & Range("A1000000").End(xlUp).Row).Copy
ThisWorkbook.Worksheets(1).Activate

'Do not change the following column. It's not the same column as above
Range("A1000000").End(xlUp).Offset(1, 0).PasteSpecial
If counter Mod 90 = 0 Then
    Call RemoveDuplicatesCells_EntireRow
End If

Application.CutCopyMode = False
bookList.Close
counter = counter + 1
Next
End Sub

With this sub, I just basically open each files in a specified folder and merge them into one excel file.
Everything works here.
Sub RemoveDuplicatesCells_EntireRow()
'PURPOSE: Remove the entire row of duplicate cell values within a selected cell range
'SOURCE: www.TheSpreadsheetGuru.com

Dim rng As Range
Dim x As Integer

'Optimize code execution speed
  Application.ScreenUpdating = False

'Determine range to look at from user's selection
  On Error GoTo InvalidSelection
    Set rng = Range("B2:B1000000")
  On Error GoTo 0

'Ask user which column to look at when analyzing duplicates
  On Error GoTo InputCancel
    x = InputBox("Which column should I look at? (Number only!)", _
      "Select A Column", 1)
  On Error GoTo 0

'Optimize code execution speed
  Application.Calculation = xlCalculationManual

'Remove entire row if duplicate is found
  rng.EntireRow.RemoveDuplicates Columns:=x

'Change calculation setting to Automatic
  Application.Calculation = xlCalculationAutomatic

Exit Sub

'ERROR HANDLING
InvalidSelection:
  MsgBox "You selection is not valid", vbInformation
  Exit Sub

InputCancel:

End Sub

This is the removing duplicate rows sub.
This code works also independently. The problem is If I use this code combined with simpleXlsMerger code that I wrote. It does not work. And It gave me blank space worksheet.
What are your thoughts ?
Thank you so much.


text:
Q: Ansible dynamic inventory - how to inject values to an inventory source Here is some background first.
I have a dynamic inventory which pulls data from an external source. I have various playbooks which does a few tasks using this inventory, and I run them by either an adhoc ansible-playbook command, and via Ansible AWX.
When testing connectivity to managed hosts, I can run commands such as ansible -m ping -i inventories/ linuxnode.servers.fqdn, and this works totally fine. I also have an inventory sync in AWX, and that works fine as well.
This works using an inventory source within inventories/ in YAML format, wherein I pass some values to the custom inventory script the_custom_plugin. Sample YAML file datacenter1.yml:
plugin: the_custom_plugin
url: "https://externalapp.servers.fqdn"
username: poweruser
privatekey: secretpassword

Now, I want to get rid of the username and password for obvious security reasons, and instead, hide them:

*

*In environment variables when running via the ansible-playbook command; and

*In AWX credentials when running via AWX.

The problem is, there doesn't seem  a way to inject values to variables in the inventory souce. Even a very simple change like this does not work (i.e. the custom plugin fails):
plugin: the_custom_plugin
url: "https://externalapp.servers.fqdn"
temp_username: poweruser
username: "{{ temp_username }}"
privatekey: secretpassword

Is there any secret YAML syntax for an inventory source file which uses an external plugin? Or is the issue somehow in the custom plugin code? I'm very much perplexed that this doesn't even work:
temp_username: poweruser
username: "{{ temp_username }}"

Cheers.


text:
Q: Creating HA NAT on AWS with Terraform The two common strategies for building HA NATs within AWS are:

*

*"Route Takeover" where an instance updates a route table to point to itself.

*"ENI Attaching" where an instance attaches an ENI to itself  and the route tables are setup to point the default route to the ENI.

Both these methods involve an instance that updates the configuration of a resource (i.e. route table or ENI) either triggered by a "heartbeat script" or when created by an autoscale group.
This works fine with CloudFormation as an update to the stack doesn't override these changes that have happened after that fact. This is not the case with Terraform.
Terraform will detect that the config for either resource has changed and will try and "fix the config" by removing any changes that happened outside of Terraform.
I get the philosophy here, but it's preventing the deployment of HA NATs using the common strategies.
So, does anyone have any idea how to accomplish an HA NAT solution within the confines of how Terraform operates?
Thanks,
Joe

A: As an update to this question, Terraform now supports the managed NAT gateways with the aws_nat_gateway resource

A: As of version 0.6.2, terraform  no longer attempts to remove the attachment for an ENI that was attached out-of-band https://github.com/hashicorp/terraform/pull/2943


text:
Q: Bounce invalid email timing In one Journey Builder, we have the need to use an engagement bounce after 24 h from the email send.
As stated in the documentation, the best practice is to wait for the bounce at least 72h.
Our client wants to get the bounce caused by an "invalid email" within 24h.
Is it available to use this time if we want to get those specific kinds of bounce (user unknown and domain unknown)?
Is there any statistics that states this percentage of bounce/time, for instance:

*

*60% come within 24h

*20% after 48h

If not, are there any other solutions that I could use?


text:
Q: Проблема при подключении библиотеки в Intelij IDEA При подключении библиотеки dom4j-1.6.1.jar в Intelij IDEA вроде всё хорошо, но при компиляции следующего класса выдает ошибку.
package com.tutorialspoint.xml;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class DOM4JParserDemo {
    public static void main(String[] args) {
        try {
            File inputFile = new File(("src/com/tutorialspoint/xml/input.txt"));
            SAXReader reader = new SAXReader();
            Document document = reader.read( inputFile );

            System.out.println("Root element :" + document.getRootElement().getName());

            Element classElement = document.getRootElement();

            List<Node> nodes = document.selectNodes("/class/student" );
            System.out.println("----------------------------");
            for (Node node : nodes) {
                System.out.println("\nCurrent Element :" + node.getName());
                System.out.println("Student roll no : " + node.valueOf("@rollno") );
                System.out.println("First Name : " + node.selectSingleNode("firstname").getText());
                System.out.println("Last Name : " + node.selectSingleNode("lastname").getText());
                System.out.println("First Name : " + node.selectSingleNode("nickname").getText());
                System.out.println("Marks : " + node.selectSingleNode("marks").getText());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}

Текст ошибки
Error:(6, 17) java: package org.dom4j does not exist
Error:(7, 17) java: package org.dom4j does not exist
Error:(8, 17) java: package org.dom4j does not exist
Error:(9, 17) java: package org.dom4j does not exist
Error:(10, 20) java: package org.dom4j.io does not exist
Error:(16, 13) java: cannot find symbol
  symbol:   class SAXReader
  location: class com.tutorialspoint.xml.DOM4JParserDemo
Error:(16, 36) java: cannot find symbol
  symbol:   class SAXReader
  location: class com.tutorialspoint.xml.DOM4JParserDemo
Error:(17, 13) java: cannot find symbol
  symbol:   class Document
  location: class com.tutorialspoint.xml.DOM4JParserDemo
Error:(21, 13) java: cannot find symbol
  symbol:   class Element
  location: class com.tutorialspoint.xml.DOM4JParserDemo
Error:(23, 18) java: cannot find symbol
  symbol:   class Node
  location: class com.tutorialspoint.xml.DOM4JParserDemo
Error:(25, 18) java: cannot find symbol
  symbol:   class Node
  location: class com.tutorialspoint.xml.DOM4JParserDemo
Error:(33, 18) java: cannot find symbol
  symbol:   class DocumentException
  location: class com.tutorialspoint.xml.DOM4JParserDemo

То есть говорится что пакета не существует, хотя я с IDE спокойно захожу в те пакеты во внешней библиотеке и могу просматривать код.
Предполагаю что проблема возникла из-за использования Maven(но вполне вероятно что ошибаюсь).
При создании нового проекта и ручного подкючения библиотек всё хорошо работает.
При последующем подключении библиотек через Maven в том проекте всё так же нормально работает.
В старом проекте, что при ручном подключении, что при автоматическом, ошибка остается.
Знает ли кто-нибудь из-за чего возникает эта проблема и как её решить?

A: Я решил проблему следующим образом: удалил с папки проекта папку .idea и файл "ProjectName".iml. После этого всё стало добавляться нормально. Но хотелось бы разобраться из-за какой настройки возникла эта проблема. Если у кого-то есть подробная информация, поделитесь пожалуйста.


text:
Q: How to print child, father, mother from these two tables? Below are the tables:
relation table

cid
pid

101
202

566
322

875
345

people table

id
name
gender

101
Riya
F

566
Aman
M

202
Rakesh
M

875
lucky
M

202
Reena
F

322
Raina
F

345
Rohit
M

322
Mohit
M

345
Meena
F

output

Child
Mother
Father

Riya
Reena
Rakesh

Aman
Raina
Mohit

Lucky
Rohit
Meena

I tried this:
SELECT     mother,
           father
FROM      (
                      SELECT     id,
                                 name,
                                 sum(
                                 CASE
                                            WHEN gender = 'F' THEN 1
                                            ELSE 0) AS mother,
                                 sum (
                                 CASE
                                            WHEN gender = 'M' THEN 1
                                            ELSE 0) AS father
                      FROM       people
                      INNER JOIN relation
                      ON         people. id = relation.p_id
                      GROUP BY   id,
                                 name) t1
INNER JOIN relation
ON         relation.p_id = t1.id

Please let me know the query, for how to fetch this output. this above query does not work, I am not able to figure how to output child also.

A: You must join relation to 2 copies of people.
The 1st copy will return the child's name and the 2nd copy will return the names of the parents.
Then group by child and use conditional aggregation to get the names of the parents in one row:
SELECT c.name Child,
       MAX(CASE WHEN p.gender = 'F' THEN p.name END) Mother,
       MAX(CASE WHEN p.gender = 'M' THEN p.name END) Father
FROM relation r
INNER JOIN people c ON c.id = r.cid
INNER JOIN people p ON p.id = r.pid
GROUP BY r.cid, c.name;

See the demo.

A: You can join twice and then PIVOT:
SELECT *
FROM   (
  SELECT c.name AS child,
         p.name AS parent,
         p.gender
  FROM   relations r
         INNER JOIN people c
         ON r.cid = c.id
         INNER JOIN people p
        ON r.pid = p.id
)
PIVOT (
  MAX(parent) FOR gender IN (
    'M' AS father,
    'F' AS mother
  )
)

Which, for the sample data:
CREATE TABLE people (id, name, gender) AS
SELECT 101, 'Riya',   'F' FROM DUAL UNION ALL
SELECT 566, 'Aman',   'M' FROM DUAL UNION ALL
SELECT 202, 'Rakesh', 'M' FROM DUAL UNION ALL
SELECT 875, 'lucky',  'M' FROM DUAL UNION ALL
SELECT 202, 'Reena',  'F' FROM DUAL UNION ALL
SELECT 322, 'Raina',  'F' FROM DUAL UNION ALL
SELECT 345, 'Rohit',  'M' FROM DUAL UNION ALL
SELECT 322, 'Mohit',  'M' FROM DUAL UNION ALL
SELECT 345, 'Meena',  'F' FROM DUAL;

CREATE TABLE relations (cid, pid) AS
SELECT 101, 202 FROM DUAL UNION ALL
SELECT 566, 322 FROM DUAL UNION ALL
SELECT 875, 345 FROM DUAL;

Outputs:

CHILD
FATHER
MOTHER

Riya
Rakesh
Reena

Aman
Mohit
Raina

lucky
Rohit
Meena

db<>fiddle here

A: Try this one
with cte as
(
 select name as child, r.pid as pid
   from people p
   join relation r
     on p.id=r.cid
)
select ee.child as child,
       (select name from people PM where id=ee.pid and PM.gender='F') as Mother,
       (select name from people PP where id=ee.pid and PP.gender='M') as Father
  from cte ee

A: You can try below query -
SELECT P.name Child, p2.name mother, p3.name father
  FROM relation R
  JOIN people P ON R.cid = P.id
  JOIN people P2 ON R.pid = P.id
                AND P.gender = 'F'
  JOIN people P3 ON R.pid = P.id
                AND P.gender = 'M'

A: SELECT DISTINCT P1.NAME AS CHILD,(SELECT NAME FROM PEOPLE PM WHERE ID=T.PID AND PM.GENDER='F') AS MOTHER,
       (SELECT NAME FROM PEOPLE PP WHERE ID=T.PID AND PP.GENDER='M') AS FATHER FROM
(SELECT R.CID,NAME,R.PID,P.GENDER FROM PEOPLE P,RELATIONS R
WHERE P.ID=R.PID) T,PEOPLE P1
WHERE T.CID=P1.ID;

A: select * from
(select * from
(select  p.firstname as child, (select p1.firstname from persons p1 where r.p_id=p1.id and p1.gender='M') as father
from persons p inner join relations r on
p.id=r.id
) t
where t.father is not null
) as table1
inner join
(select * from
(select  p.firstname as child, (select p1.firstname from persons p1 where r.p_id=p1.id and p1.gender='F') as mother
from persons p inner join relations r on
p.id=r.id
) t
where t.mother is not null ) as table2
on table1.child=table2.child

A:     SELECT l.cid       AS id,
           r.NAME      AS Child,
           mother.NAME AS Mother,
           father.NAME AS Father
    FROM   testdb.dbo.people r
           JOIN testdb.dbo.relation l
             ON l.cid = r.id
           JOIN (SELECT l.cid AS id,
                        r.NAME
                 FROM   testdb.dbo.people r
                        JOIN testdb.dbo.relation l
                          ON l.pid = r.id
                             AND gender = 'F') AS mother
             ON l.cid = mother.id
           JOIN (SELECT l.cid AS id,
                        r.NAME
                 FROM   testdb.dbo.people r
                        JOIN testdb.dbo.relation l
                          ON l.pid = r.id
                             AND gender = 'M') AS father
             ON l.cid = father.id

A: Query that prints the names of a child and his parents in individual columns respectively in order of the name of the child.
SELECT c.name as child,
    MAX(CASE WHEN p.gender = 'F' THEN p.name END) AS mother,
    MAX(CASE WHEN p.gender = 'M' THEN p.name END) AS father
FROM relations r
INNER JOIN public."People" c on c.id = r.cid
INNER JOIN public."People" p on p.id = r.pid
GROUP BY r.cid, c.name ORDER BY c.name;

A: select b.name as child,c.name as father,d.name as mother from   relation a join people b on a.cid=b.id
join people c  on  a.pid=c.id
join people d on  a.pid=d.id where c.gender='m' and d.gender='f'


text:
Q: Using MySQL Connector/NET with NHibernate web application I have an IIS server with MySQL Connector/NET version 6.2.3 installed on it. I'm using NHibernate, and I'm not entirely sure how to set up my web application to use this driver. Am I correct in saying that I can use any version of the .NET connector so long as it's referenced by the application? If so, where/how do I reference the driver in Web.config?
I initially was using version 6.3.6, which had an installer and didn't require me to add any references in my project. However, upon deploying to the server, I discovered that the version installed there was 6.2.3, which gave this error:
Unable to find the requested .Net Framework Data Provider.  It may not be installed.

A: I figured it out. Just needed to set providerName to MySql.Data.MySqlClient in connectionStrings.


text:
Q: Coroutine only works the first time I assume that there is something fundamental about coroutines that I don't understand because I cannot get my head around why this is happening.
I have this coroutine that works perfectly as intended the first time but completely fails the second time I try to use it.
public IEnumerator CharacterDialogue()
{
    inDialogue = true;
    playerController.enabled = false;
    mouselook.enabled = false;
    Cursor.lockState = CursorLockMode.None;
    Cursor.visible = true;
    dialogueMenu.SetActive(true);

    yield return new WaitForEndOfFrame();

    for (int i = 0; i < dialogueStrings.Length; i++)
    {
        while (!Input.GetKeyDown("e"))
        {
            yield return null;
        }
        yield return new WaitForEndOfFrame();
        dialogueText.text = dialogueStrings[i];
    }

    yield return new WaitForEndOfFrame();

    while (!Input.GetKeyDown("e"))
    {
        yield return null;
    }
    yield return new WaitForEndOfFrame();

    QuestManager.Instance.SpawnDouxland();
    inDialogue = false;
    playerController.enabled = true;
    mouselook.enabled = true;
    Cursor.lockState = CursorLockMode.Locked;
    Cursor.visible = false;
    dialogueMenu.SetActive(false);
}

It is pretty straightforward: I disable the controls of my player and make the dialogue window pop. I then wait for the input of the player between each string of text so that he may read at his own pace. Once he's done reading I reactivate the controls and close the dialogue window.
This code works exactly like I want the first time but the second time it just goes through the for loop without waiting for the input.
What am I doing wrong here and why does it work the first time?
Edit:
Comments pointed out that the issue must be in the way I call the coroutine. This now makes sense to me as I use the same key (e) to call the coroutine. So maybe it reads the key as pressed and runs through the for loop. Bu why would it only do so the second time?
Here's the snippet of code where I call my coroutine:
        if (hit.collider.CompareTag("Character"))
        {
            raycastedObj = hit.collider.gameObject;
            CrosshairActive();
            interactionManager.InteractiveFeedbackTextCall("CharacterQuest");
            if (Input.GetKeyDown("e"))
            {
                Debug.Log("I have interacted with: " + hit.collider.gameObject.name + ".");
                StartCoroutine(canvasAnimManager.CharacterDialogue());
            }
        }

A: Thanks to some comments I figured out what the issue was.
if (Input.GetKeyDown("e"))
        {
            Debug.Log("I have interacted with: " + hit.collider.gameObject.name + ".");
            StartCoroutine(canvasAnimManager.CharacterDialogue());
        }

I thought the idea of GetKeyDown was that it was triggered only once... there must be something I'm not getting. Anyways the issue was that this was called multiple times and it make the coroutine go through the loop even after I was finished with my dialogue.
I just added a little bool check to fix the issue:
            if (Input.GetKeyDown("e") && !canvasAnimManager.inDialogue)
            {
                Debug.Log("I have interacted with: " + hit.collider.gameObject.name + ".");
                StartCoroutine(canvasAnimManager.FoukiDialogue());
            }

Cheers and thanks for the help!


text:
Q: How can you reliably move files from android to windows pc? I'm trying to set up a bash script that can move video files (.mp4) from my android phone to my windows PC (or more accurately, to an external SSD). The goal is to save time transferring files as I will be doing this multiple times a day in between other things, so I want to do it automatically.
I know that it's possible to use adb pull to move the files and then use adb shell to delete them on the phone afterwards, but I am worried that if adb pull fails, it might delete some of the video files. Hence, I am looking for a solution that checks if the files were transferred correctly before deleting them from the phone.

A: Check the exit status of the command and delete if there is not error
#!/bin/bash

file=/data/local/tmp/file1
if adb pull "$file"
then
    adb shell rm "$file"
fi


text:
Q: Silverlight Unit Tests on Bamboo I'm using Microsoft.Silverlight.Testing and MS Tests for the silverlight testing.
Is it possible to run the silverlight unit tests with a Bamboo CI server?

A: I've found the way how to do this.
There is a good project StatLight which allows to run Silverlight unit tests inside the embeded container.


text:
Q: Image link few pixels off on every browser except Opera I have an issue with the site I am working on.
The top logo seems to have some kind of margin to the top, even though I have specifically set it to have no margin and its parents' have no padding.
body{
    margin: 0;
    padding: 0;

    min-width: 320px;

    background-image: url('../images/templates/background.png');

    font-family: 'Open Sans';
    font-size: 12px;
    color: #303030;
}

Here's an image with different browsers I tested:

As you can see, only Opera seems to work properly. Now is there anything wrong in it? Or is it an issue of browsers?
If this is an issue with browsers, what would be the easiest way to solve the issue?

A: It's line 98 in main.css thats causing your issue.
.menuAvatar {
vertical-align: middle; // THIS LINE
margin: 0 5px 0 -15px;
}

When vertical align is removed the image aligns correctly.  You can either find a different way to accomplish what you are using the vertical-align for, or you can use the following ways to compensate.
.menuAvatar {
vertical-align: middle;
margin: -3px 5px 0 -15px;
}

I added -3px to margin-top to force it to align back in Chrome.  (not tested in firefox and others).
OR use this to avoid negative margins.
.menuAvatar {
vertical-align: top;
margin: 0 5px 0 -15px;
}

A: On line 98 of main.css, you have the following rule:
.menuAvatar{
    vertical-align: middle;
    margin: 0 5px 0 -15px;;
}

I would recommend setting vertical-align to top, resulting in:
.menuAvatar{
    vertical-align: top;
    margin: 0 5px 0 -15px;
}


text:
Q: При изменение поле completed, попадаю два раза в блок 'if' и при выходе не получаю изменение,как можно исправить? При выполнение данной фунции
const toggleHandler = (id: number) => {
    setTodos((prev) =>
      prev.map((todo) => {
        if (todo.id === id) {
          todo.completed = !todo.completed;
        }
        return todo;
      })
    );
  };
попадаю в блок if два раза хот значение id не повторяются

export const TodosPage: React.FC = () => {
  const [todos, setTodos] = useState<ITodo[]>([]);
  useEffect(() => {
    const saved = JSON.parse(localStorage.getItem("todos") || "[]") as ITodo[];
    setTodos(saved);
  }, []);
  useEffect(() => {
    localStorage.setItem("todos", JSON.stringify(todos));
  }, [todos]);
  const addHandler = (title: string) => {
    const newTodo: ITodo = {
      title: title,
      id: Math.random(),
      completed: false,
    };

    setTodos((prev) => [newTodo, ...prev]);
  };
  const toggleHandler = (id: number) => {
    setTodos((prev) =>
      prev.map((todo) => {
        if (todo.id === id) {
          todo.completed = !todo.completed;
        }
        return todo;
      })
    );
  };
  const removeHandler = (id: number) => {
    setTodos((prev) => prev.filter((todo) => todo.id !== id));
  };
  return (
    <>
      <TodoForm addHandler={addHandler} />
      <ToDoList
        todos={todos}
        onTogggle={toggleHandler}
        onRemove={removeHandler}
      />
    </>
  );
};

A: Мутация данных не желательная практика в реакте, желательно избегать её. Можно написать примерно так:
const toggleHandler = (id) => {
    setTodos((prev) =>
      prev.map((todo) =>
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  };


text:
Q: Tidy evaluation inside package and devtools::check() notes Let's create a package, use dplyr and the magrittr pipe, and craft a new function:
usethits::create_package("TidyEvalInsidePackage")
usethis::use_package_doc()
usethis::use_package("dplyr")
usethis::use_pipe(export = F)
devtools::document()
usethis::use_r("foo")

Inside foo.R:
foo <- function() {
  df <- data.frame(N = 1:10)
  df %>%
     dplyr::select(N) ## This will produce a note when I run devtools::check()
}

Produces: foo: no visible binding for global variable 'N'
This note could be easliy removed with this:
 df %>%
     dplyr::select( df$N )

But now if want to use mutate like this:
foo <- function() {
  df <- data.frame(N = 1:10)
  df %>%
     dplyr::mutate(X = pi^N,
                   Y = X / N))
}

The trick no longer works:
df
  %>% dplyr::mutate(X = pi^df$N,
                    Y = df$X / df$N) ## coz at this line df$X does not exist

Is there any way to preserve the pipe workflow and do this without producing notes when checking the package?

EDIT: @Hong oi proposed a workaround and decided to close the question but the workaround is not the proper way to do it.
The cleaner way is to use the .data$var construct. This is where I have found the answer : https://community.rstudio.com/t/how-to-solve-no-visible-binding-for-global-variable-note/28887/3


text:
Q: jQuery not executing .then() I am having trouble with a .when() .then() call in jQuery.
I am a teacher taking attendance in class by scanning student IDs. So I have a form that the ID scanner successfully populates and then hits the submit button. This successfully triggers a .when() call and the .ajax() successfully calls my code that populates a Google Sheet.
What I want is a list of students that I have successfully scanned to appear at the bottom of the page. I try to append to this list in the .then() call but it doesn't seem to execute.

<!DOCTYPE html>

  <title>Student Automations</title>

  <link rel="stylesheet" type="text/css" href="../css/main.css" />

  <form id='studIdForm'>Student ID: <input type='text' name='studentId' id='studentId' value=''>
    <input type='hidden' name='spreadsheetId' value='mygooglesheetid' id='spreadsheetId'>
    <input type='hidden' name='worksheet' value='Sheet1' id='worksheet'>
    <input type='hidden' name='studentIdCol' value='A' id='studentIdCol'>
    <button>Submit</button>
  </form>

Already scanned:

Edit:
Thank you all for so much quick input. I had a few things wrong, including the fact that the URL that I was calling was not returning JSON which meant that the success: statements were not being called. I removed the .when and have added some bells and whistles and ended up with this.
<!DOCTYPE html>

    <title>Student Automations</title>

    <link rel="stylesheet" type="text/css" href="../css/main.css" />

<form id='studIdForm'>Student ID: <input type='text' name='studentId' id='studentId' value=''>
    <input type='hidden' name='spreadsheetId' value='mygooglesheetid' id='spreadsheetId'>
    <input type='hidden' name='worksheet' value='Sheet4' id='worksheet'>
    <input type='hidden' name='studentIdCol' value='A' id='studentIdCol'>
    <button>Submit</button>
</form>

Already scanned:


text:
Q: Data/signal from a black hole to observe a singularity I wonder if a situation is possible where, we measure some signal/property concerning a black hole. Supposing the measurement we make with some telescope, gets us the Fourier transform coefficients of the signal, and then by using the Fourier coefficients...we make some calculations which suggest a possibility of a singularity in the signal/parameter. I know its not possible to confirm a singularity by finite computations experimentally but I guess its innteresting to see the data suggesting something like a singularity. I hope to use this result on the measured Fourier coefficients.
All I need is a data measurement of this type, if possible and appreciate some suggestions of possibility.

A: This is actually more subtle than you would think it would be.  First, remember that a fourier transform is defined, for some time-dependent signal $F(t)$, as${}^{1}$:
$$F(\omega) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^{+\infty} dt\, e^{i\omega\,t} F(t)$$
Well, this is great in special relativity, but in general relativity, what time do we actually use?  The natural choices are the time of the distant observer that is taking the measurment, or the time as measured by some local, freely falling observer.   It turns out that these choices are inequalvent, and that, in fact, this is the heart of one of the mechanisms by which you can find Hawking radiation${}^{2}$.
All of this is a long way of saying that the means by which GR rotates time into space will prevent us from "integrating" over the portion of the field that enters into the black hole horizon.  There is no way to use Fourier transforms to probe into the whole.  No causal influence can come out of the hole, at least classically.
${}^{1}$If we're being properly covariant, I guess I should write this as $F(x^{a})$, and have the transform be $F(k^{a}) $, and have the exponent be $e^{ik^{a}x_{a}}$, but this basic problem still persists.
${}^{2}$Remember that the definition of the vacuum state, and thus the whole Fock space of quantum field theory, is based upon taking Fourier transforms of the fields, finding a basis of the space of free fields, and then defining normal ordering and counting operators.  What is a "particle" and what is an "anti-particle" depends on these processes.


text:
Q: How to do authentication in UIWebView properly? I would like to support HTTP Basic Authentication in my UIWebView.
At the moment, I am canceling requests in
webView:shouldStartLoadWithRequest:navigationType: then handle them in my own NSURLConnectionDelegate to check for and provide credentials if needed. I then use loadData:MIMEType:textEncodingName:baseURL: to present HTML in the web view. That works fine for any URLs that are passed to the delegate.
My problem is that the delegate is never called for embedded elements, like images, JavaScript or CSS files. So if I have an HTML page which references an image which is protected with basic authentication, that image cannot be loaded properly. Additionally, webView:didFinishLoad: is never called, because the web view could not fully load the page.
I have checked that case with Terra, a third-party browser available on the App Store, and it can fully cope with that situation. I think it would be possible to solve this by providing my own NSURLProtocol, but that seems too complicated. What am I missing?

A: The secret to HTTP basic authentication using cocoa is knowing NSURL and the related classes.

*

*NSURL

*NSURLRequest/NSMutableURLRequest

*NSURLConnection

*NSURLCredential

*NSURLCredentialStorage

*NSURLProtectionSpace

*UIWebView/WebView/NIWebController etc.

The real magic comes from NSURLConnection. In the words of the devDocs, "An NSURLConnection object provides support to perform the loading of a URL request." If you want to load some a URL in the background without displaying it you would use NSURLConnection. The real power of the NSURLConnection is in the method
+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate

The NSURLConnectionDelegate protocol has methods for responding to successful connections, fatal errors, and authentication challenges. If you are trying to access data Protected by HTTP basic authentication this is how Cocoa does it. At this point an example should bring some clarity.
//basic HTTP authentication
NSURL *url = [NSURL URLWithString: urlString];
NSMutableURLRequest *request;
request = [NSMutableURLRequest requestWithURL:url
                              cachePolicy:NSURLRequestReloadIgnoringCacheData
                          timeoutInterval:12];
[self.webView openRequest:request];
(void)[NSURLConnection connectionWithRequest:request delegate:self];

This creates a URL. From the URL a URLRequest is created. The URLRequest is then loaded in the web view. The Request is also used to make a URLConnection. We don't really use the connection, but we need to receive notifications about authentication so we set the delegate. There are only two methods we need from the delegate.
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
    NSURLCredential * cred = [NSURLCredential credentialWithUser:@"username"
                                                    password:@"password"
                                                 persistence:NSURLCredentialPersistenceForSession];
[[NSURLCredentialStorage sharedCredentialStorage]setCredential:cred forProtectionSpace:[challenge protectionSpace]];

}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection;
{
    return YES;
}

Whenever there is an authentication challenge a credential is added to the credential storage. You also tell the connection to use the credential storage.

A: I've just implemented this by setting basic auth credentials using an NSMutableURLRequest for the UIWebView.  This also avoids the round trip incurred when implementing sharedCredentialStorage (of course there are tradeoffs involved).
Solution:
    NSString *url = @"http://www.my-url-which-requires-basic-auth.io"
    NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
    NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
    NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]];
    NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [mutableRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
    NSURLRequest *request = [mutableRequest copy];
    NSURLRequest *request = [NSURLRequest basicAuthHTTPURLRequestForUrl:url];
    [self.webView loadRequest:request];

You can grab the NSData+Base64 category which implements the base64EncodedString for NSData  from Matt Gallagher's page (it was at the bottom of the blog post when I downloaded it)

A: Try to use sharedCredentialStorage for all domains you need to authenticate.
Here is working sample for UIWebView it was tested against Windows IIS having only BasicAuthentication enabled
This is how to add your site credentials:
NSString* login = @"MYDOMAIN\\myname";
NSURLCredential *credential = [NSURLCredential credentialWithUser:login
                                                         password:@"mypassword"
                                                      persistence:NSURLCredentialPersistenceForSession];

NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
                                         initWithHost:@"myhost"
                                                 port:80
                                             protocol:@"http"
                                                realm:@"myhost" // check your web site settigns or log messages of didReceiveAuthenticationChallenge
                                 authenticationMethod:NSURLAuthenticationMethodDefault];

[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential
                                                    forProtectionSpace:protectionSpace];
[protectionSpace release];

Edit: same code in Swift 4
let login = "MYDOMAIN\\myname"
let credential = URLCredential(user:login, password:"mypassword", persistence:.forSession)
let protectionSpace = URLProtectionSpace(host:"myhost", port:80, protocol:"http", realm:"myhost", authenticationMethod:NSURLAuthenticationMethodDefault)
URLCredentialStorage.shared.setDefaultCredential(credential, for:protectionSpace)

Your webView is supposed to work now, if it does not work use next code to debug, especially check log messages of didReceiveAuthenticationChallenge.
    #import "TheSplitAppDelegate.h"
    #import "RootViewController.h"

    @implementation TheSplitAppDelegate

    @synthesize window = _window;
    @synthesize splitViewController = _splitViewController;
    @synthesize rootViewController = _rootViewController;
    @synthesize detailViewController = _detailViewController;

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // Override point for customization after application launch.
        // Add the split view controller's view to the window and display.
        self.window.rootViewController = self.splitViewController;
        [self.window makeKeyAndVisible];

        NSLog(@"CONNECTION: Add credentials");

        NSString* login = @"MYDOMAIN\\myname";
        NSURLCredential *credential = [NSURLCredential credentialWithUser:login
                                                                 password:@"mypassword"
                                                              persistence:NSURLCredentialPersistenceForSession];

        NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
                                                 initWithHost:@"myhost"
                                                 port:80
                                                 protocol:@"http"
                                                 realm:@"myhost" // check your web site settigns or log messages of didReceiveAuthenticationChallenge
                                                 authenticationMethod:NSURLAuthenticationMethodDefault];

        [[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace];
        [protectionSpace release];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://myhost/index.html"]
                                                               cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                           timeoutInterval:12
                                        ];

        NSLog(@"CONNECTION: Run request");
        [[NSURLConnection alloc] initWithRequest:request delegate:self];

        return YES;
    }

    - (void)applicationWillResignActive:(UIApplication *)application
    {

    }

    - (void)applicationDidEnterBackground:(UIApplication *)application
    {

    }

    - (void)applicationWillEnterForeground:(UIApplication *)application
    {

    }

    - (void)applicationDidBecomeActive:(UIApplication *)application
    {

    }

    - (void)applicationWillTerminate:(UIApplication *)application
    {

    }

    - (void)dealloc
    {
        [_window release];
        [_splitViewController release];
        [_rootViewController release];
        [_detailViewController release];
        [super dealloc];
    }

    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
    {
        NSLog(@"CONNECTION: got auth challange");
        NSString* message = [NSString stringWithFormat:@"CONNECTION: cred cout = %i", [[[NSURLCredentialStorage sharedCredentialStorage] allCredentials] count]];
        NSLog(message);
        NSLog([connection description]);

        NSLog([NSString stringWithFormat:@"CONNECTION: host = %@", [[challenge protectionSpace] host]]);
        NSLog([NSString stringWithFormat:@"CONNECTION: port = %i", [[challenge protectionSpace] port]]);
        NSLog([NSString stringWithFormat:@"CONNECTION: protocol = %@", [[challenge protectionSpace] protocol]]);
        NSLog([NSString stringWithFormat:@"CONNECTION: realm = %@", [[challenge protectionSpace] realm]]);
        NSLog([NSString stringWithFormat:@"CONNECTION: authenticationMethod = %@", [[challenge protectionSpace] authenticationMethod]]);
    }

    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
        // release the connection, and the data object
        [connection release];

        // inform the user
        NSLog(@"CONNECTION: failed! Error - %@ %@",
              [error localizedDescription],
              [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    }

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
    {
        NSLog(@"CONNECTION: received response via nsurlconnection");
    }

    - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection;
    {
        NSLog(@"CONNECTION: USE!");
        return YES;
    }

    @end

The final solution for WebView authentication was based on custom protocol implementation. All protocols registered as a stack, so if you redefine HTTP protocol it would intercept all requests coming from webView, so you have to check attributes assotiated with incoming request and repack it into new request and send it again via your own connection. Since you are in stack, your request immidiatly comes to you again and you have to ignore it. So it goes down protocol stack to real HTTP protocol implementation, since your request is not athenticated you'll get authenticaiton request. And after authenticaiton you'll get a real response from server, so you repack response and reply to original request received from webView and that's it.
Don;t try to create new requests or responses bodies, you have to just resend them. The final code would be aproximetly 30-40 lines of code and it is quite simple, but requires a lot of debuging and tetsing.
Unfortunatlly I cannot provide code here, since I am assigned to different project already, I just wanted to say that my post is wrong way, it stucks when user changes password.

A: For TKAURLProtocolPro  [http://kadao.dir.bg/cocoa.htm]
For SVWebViewController [https://github.com/samvermette/SVWebViewController]

A: Make sure to remember that logging out is not so easy with sessions and UIWebView credentials. See answer here: https://stackoverflow.com/a/18143902/2116338.


text:
Q: Why formik is losing focus immediatelly I hit the second field? I have a form with formik that is losing focus at the second field.
It's seems to be a really basic stuff, but I can't find the problem.
Check this sandbox: https://codesandbox.io/s/create-react-app-forked-m145g
Click on the e-mail field, type anything (or nothing), hit tab to jump to the next field and watch the focus going away.
As you can see, the field is beeing validated, so, I don't know (and would find quite unlikely) if my custom handleBlur function had something to do with it:
const customHandleBlur = (e) => {
  if (!values.recaptcha) this._reCaptchaRef.current.execute();
  handleBlur(e);
};

This function is responsible to execute Google's recaptcha v3.
What am I doing wrong?

A: Try changing your customHandleBlur to only execute if you have a value for both email and description.
  const customHandleBlur = (e) => {
     if (!!values.email && !!values.description && !values.recaptcha) this._reCaptchaRef.current.execute();
    handleBlur(e);
  };

This will keep the description from losing focus when the this._reCaptchaRef.current.execute() function is called.
It looks like there are other issues to... but this will keep your description field from losing the focus, which is what your question was.


text:
Q: Java heap space errors I'm not a programmer, I only want to setup a document server with regain.
It's normal, that the process of indexing needs a lot of memory so when I start indexing I type to the code -Xmx512m. But after some hours, I've got these messages:
java.lang.OutOfMemoryError: Java heap space
    at org.apache.lucene.util.UnicodeUtil.UTF16toUTF8(UnicodeUtil.java:383)
    at org.apache.lucene.store.DataOutput.writeString(DataOutput.java:112)
    at org.apache.lucene.index.FieldsWriter.writeField(FieldsWriter.java:212)
    at org.apache.lucene.index.StoredFieldsWriterPerThread.addField(StoredFieldsWriterPe
rThread.java:58)
    at org.apache.lucene.index.DocFieldProcessorPerThread.processDocument(DocFieldProces
sorPerThread.java:263)
    at org.apache.lucene.index.DocumentsWriter.updateDocument(DocumentsWriter.java:766)
    at org.apache.lucene.index.IndexWriter.addDocument(IndexWriter.java:2060)
    at org.apache.lucene.index.IndexWriter.addDocument(IndexWriter.java:2034)
    at net.sf.regain.crawler.IndexWriterManager.createNewIndexEntry(IndexWriterManager.j
ava:758)
    at net.sf.regain.crawler.IndexWriterManager.addToIndex(IndexWriterManager.java:732)
    at net.sf.regain.crawler.Crawler.run(Crawler.java:575)
    at net.sf.regain.crawler.Main.main(Main.java:128)

I'm using jdk 1.8 and tomcat7
Its running on a Windows Server 2016 with 4GB Memory, but i dont think that this process needs more than 1GB memory...
Now I don't know how to solve this problem...
Does anyone know how to solve this problem?

A: try -Xmx512m instead of -Xnx512m

A: Run with -Xmx, which sets the maximum size of the heap.
See here for details
Ex : -Xmx512m

A: Please suggest which version of java you are using??
Below are some solution that you can apply ..
->Increase Heap and permGem space (temporary fix)
->Find memory leaks , fix it then right high performance code .
->catch java.lang.OutOfMemoryError and free all resources that you know might use a lot of memory, close connections and so forth, then do a System.gc().
->use JDK 1.8 :þ welcome to the MetaSpace
->The solution was to add these flags to JVM command line when Tomcat is started:
-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled
hope this will help you :-)


text:
Q: wget Will not download a dir that has an index.* file How to recursively get files in a directory if that directory has an index.* file?
I need to copy several directories on different websites located on shared hosting (no SSH) to their new home on a VPS.  Trying to do it server to server.
wget -r -e robots=off --no-parent --user=myusername --password=mypass http://mywebsite.com/mydir/

This works great retrieving all of the files and sub directories at and below "mydir" with one deal killer of an issue.  If any of the directories has an index.html, index.php etc.  It will not download the contents of that directory.  It will either only download the index.html or if an index.php download it, changing the file to index.html.
I have tried many different combinations of -p -m --no-cookies --ftp flags etc. and nothing gets the directories that have the index.* file.
I'm attempting to get this to work without creating a tar on the source server and downloading it exclusively.
There are vast numbers of articles on SO and other sites about the creation of the index.html file but I could find no info about it skipping a directory if an index file was present.  It would be nice for the copy to not create the index.html but now my main concern is getting the full directory if there is a index.* file.
Thanks for any help.
UPDATE: @Reeno got me on track.  Re-tried with a fresh FTP account with the following command and all directories including files with index.* can be successfully downloaded now.
wget -r --ftp-user=myftpname@mywebsite.com --ftp-password=mypass ftp://ftp.mywebsite.com/mydir/

A: wget never downloads whole directories over http. What you get is that sometimes the webserver allows directories to be represented as a list of its contents. The actual format is a html page so wget then recursively fetch whatever the links in that page are pointing at.
If you have ftp access to the site you can use ftp instead. Unlike http ftp is a designed for transferring files from a file system to another. Most ftp clients have the possibility to retrieve whole directories (including subdirectories) without selecting each and every file. There are numerous choices but just putting ftp://your.hostname.com in the location bar of your file manager usually prompts for username and password and you can drag and drop whole directories in most OSes.

A: I solved it by changing Apache its httpd.conf file. In section  I put an extra X in the 'index' name, as the following:
<IfModule dir_module>
    DirectoryIndex indexx.php indexx.php3 indexx.html indexx.htm
</IfModule>

Then I restarted the server and tried again. And it worked perfectly.


text:
Q: Symfony2 error: The service "templating" has a dependency on a non-existent service "templating.globals" I have just installed a bundle using the following command to activate Mustache templates in my project but now I get the following error;
The service "templating" has a dependency on a non-existent service "templating.globals".
The command I used was:
composer.phar require bobthecow/mustache-bundle
Of course I know I am missing the templating.globals service but How do I include this and why is it not included automatically?

A: The templating.globals service is only created by the symfony/framework-bundle if you have php in the list on templating engines.
As you can see in the Resources/config/templating_php.xml the service is created.
This file is only loaded in the extension if php is in the list of templating engines.
TL;DR Add php to the templating engines in your app/config/config.yml.
# app/config/config.yml
framework:
    # ...
    templating:
        engines: ['twig', 'php']

A: If you are running Symfony 4.x then You've to add the following to the config/packages/framework.yaml:
framework:
    # ... other stuff ...

    templating:
        engines: ['twig', 'php']


text:
Q: Selenium Grid, Xvfb node and Jenkins Getting following error while running tests in firefox browser in Xvfb node using Jenkins job
    Starting Xvfb firefox setup
FAILED CONFIGURATION: @BeforeMethod setUp("firefox", "http://xxxx:5555/wd/hub")
org.openqa.selenium.WebDriverException: java.util.HashMap cannot be cast to java.lang.String
Command duration or timeout: 295 milliseconds
Build info: version: '2.52.0', revision: '4c2593cfc3689a7fcd7be52549167e5ccc93ad28', time: '2016-02-11 11:22:43'
System info: host: 'bg-bci-sip', ip: '192.168.78.44', os.name: 'Linux', os.arch: 'amd64', os.version: '2.6.32-279.el6.x86_64', java.version: '1.7.0_111'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:158)
    at com.sip.helper.BrowserFactory.getDriver(BrowserFactory.java:84)
    at com.sip.tests.JbpmWorkflowTest.setUp(JbpmWorkflowTest.java:85)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
    at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564)
    at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:653)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.access$000(SuiteRunner.java:37)
    at org.testng.SuiteRunner$SuiteWorker.run(SuiteRunner.java:368)
    at org.testng.internal.thread.ThreadUtil$2.call(ThreadUtil.java:64)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.String
    at org.openqa.selenium.firefox.FirefoxDriver.getBinary(FirefoxDriver.java:200)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:128)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.openqa.selenium.remote.server.FirefoxDriverProvider.callConstructor(FirefoxDriverProvider.java:91)
    at org.openqa.selenium.remote.server.FirefoxDriverProvider.newInstance(FirefoxDriverProvider.java:68)
    at org.openqa.selenium.remote.server.DefaultDriverFactory.newInstance(DefaultDriverFactory.java:60)
    at org.openqa.selenium.remote.server.DefaultSession$BrowserCreator.call(DefaultSession.java:222)
    at org.openqa.selenium.remote.server.DefaultSession$BrowserCreator.call(DefaultSession.java:1)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:176)
    ... 3 more

Following is my setup
Machine A (CentOS) -
1) Executed following commands....
yum install Xvfb firefox
Xvfb :1 -screen 0 1024x768x24 &
export DISPLAY=:1

2) Installed Jenkins
3) Started Grid Hub
4) Started Grid Node (Xvfb) using following command
xvfb-run java -jar selenium-server-standalone-2.25.0.jar -role node -hub http://localhost:4444/grid/register

Following is my test code
BrowserFactory.java class
public class BrowserFactory {
static RemoteWebDriver driver;
static String baseUrl;
static String nodeUrl;
public static RemoteWebDriver getDriver(String browser, String remoteUrl) throws MalformedURLException {
    return new RemoteWebDriver(new URL(remoteUrl), getBrowserCapabilities(browser));
}

private static DesiredCapabilities getBrowserCapabilities(String browserType) {
    DesiredCapabilities capabillities = null;
    switch (browserType) {
    case "firefox":
        System.out.println("Starting Xvfb firefox setup");
        String Xport = System.getProperty("lmportal.xvfb.id", ":1");
        final File firefoxPath = new File(System.getProperty("lmportal.deploy.firefox.path", "/usr/bin/firefox"));
        FirefoxBinary firefoxBinary = new FirefoxBinary(firefoxPath);
        firefoxBinary.setEnvironmentProperty("DISPLAY", Xport);
        capabillities=new DesiredCapabilities().firefox();
        capabillities.setCapability(FirefoxDriver.BINARY,firefoxBinary);
        capabillities.setBrowserName("firefox");
        capabillities.setPlatform(Platform.LINUX);
        return capabillities;
    case "chrome":
        System.out.println("Opening chrome driver");
        System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
        capabillities= new DesiredCapabilities().chrome();
        capabillities.setBrowserName("chrome");
        capabillities.setPlatform(Platform.VISTA);
        return capabillities;
    default:
        System.out.println("browser : " + browserType + " is invalid, Launching Firefox as browser of choice..");
        return DesiredCapabilities.firefox();
    }
    }

JbpmWokflowTest.java class
public class JbpmWorkflowTest {
static RemoteWebDriver driver;
public static LoginPage loginPage;
public static BasePage basePage;
public static EmailConnectorRoutinePage emailConnectorRoutine;
public static EmailTemplateEditorPage emailTemplateEditorPage;
public static MailboxScannerPage mailboxScannerPage;
public static ProcessDeploymentPage processDeploymentPage;
public static ProcessDefinitionPage processDefinitionPage;
public static CommonActions commonActions;
private static ExtentReports report;
ExtentTest logger;

@BeforeSuite
public void beforeSuite() {
    report= new ExtentReports("result-output/SIP-UI-Automation.html", true);
}

@BeforeMethod
@Parameters({ "browser", "remoteUrl" })
public void setUp(String browser, String remoteUrl) throws MalformedURLException {
    System.out.println("*******************");
    driver = BrowserFactory.getDriver(browser,remoteUrl);
    driver.get("http://xxxxxx:8080/jbpm-console");
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    commonActions = new CommonActions(driver);
}

@Parameters({ "username", "password", "browser" })
@Test
public void checkValidUser(String username, String password, String browser) throws Exception{
    try{
        System.out.println("-----------------------------Starting Checkvalid user test case----------------------");
        logger= report.startTest("checkValidUser"+browser+"");
        loginPage = PageFactory.initElements(driver, LoginPage.class);
        loginPage.LogIn_Action(username,password);
        logger.log(LogStatus.INFO, "Login Details Entered "+browser+"");
        basePage = PageFactory.initElements(driver, BasePage.class);
        basePage.UserDropDownClick();
        logger.log(LogStatus.INFO, "User Drop down clicked");
        Assert.assertEquals(true,basePage.VerifyPresenceLogout());
        logger.log(LogStatus.PASS, "User logged in successfully");

    }
    catch(Exception e)
    {
        e.printStackTrace();
        throw new Exception(e.getMessage());
    }
 }
@AfterMethod
    protected void afterMethod(ITestResult result)
    {
        if (result.getStatus()==ITestResult.FAILURE){

            String screenShot_path=commonActions.captureScreenshot(driver, result.getName());
            String image=logger.addScreenCapture(screenShot_path);
            logger.log(LogStatus.FAIL,result.getName(),image );
        }
        report.endTest(logger);
        report.flush();
        //driver.close();
        driver.quit();
    }
}