text:
Q: Unable to render the multi-select and single-select based on the condition?
Am unable to render the multiselect and singleselect in the vf page, suggest me to fix this.
code:
<apex:page standardController="Account" extensions="OnlineExAnswer" sidebar="false" showHeader="false">
    <apex:form id="frm" >
        <apex:pageBlock title="Questionare">
            <apex:pageBlockSection columns="1">
                <apex:repeat value="{!onWrprList }" var="qustwrpr">
                    <apex:outputField value="{!qustwrpr.que.Question_Des__c }" rendered="{!qustwrpr.que.Question_Type__c='Multi-Select'}"/>
                    <!--  <apex:outputField value="{!qustwrpr.que.Answer_Option__c}"/> -->
                    <apex:selectCheckboxes value="{!qustwrpr.ansList}">
                        <apex:selectOptions value="{!qustwrpr.anss}"/>
                    </apex:selectCheckboxes>
                   <!-- <apex:outputField value="{!qustwrpr.que.Question_Des__c }" rendered="{!qustwrpr.que.Question_Type__c='Single-Select'}"/>
                    <apex:selectRadio value="{!qustwrpr.ansList}">
                        <apex:selectOptions value="{!qustwrpr.anss}"/>
                    </apex:selectRadio> -->

                </apex:repeat>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex:
public class OnlineExAnswer{
    public List<Question__c> questionList {get; set;}
    public List<OnlineWrapper> onWrprList {get; set;}
    public List <String> ansList {get; set;}
    private Account acc;
    public OnlineExAnswer(ApexPages.StandardController Controller){

        onWrprList=new List<OnlineWrapper>();
        acc= (Account) controller.getrecord();
        System.debug('::::::'+acc);
        Account acc1=[Select Id,MasterSetAcc__c from Account where Id=:acc.Id Limit 1]; // with this query we can get fields of Account.
        questionList= [Select Question_Des__c,Answer_Option__c, Question_Type__c  from Question__c where MasterSet1__c=:acc1.MasterSetAcc__c];
        for(Question__c que : questionList){

            OnlineWrapper owrpr = new OnlineWrapper();
            owrpr.que = que;
            if(que.Question_Type__c == 'Multi-Select'){
                system.debug('::::: answerOption String'+que.Answer_Option__c);
                List<string> ansList=que.Answer_Option__c.split(';');
                system.debug('########' + ansList);
                for(String ans:ansList){
                    owrpr.anss.add(new selectOption(ans,ans));
                }
                system.debug('@@@@@@@@@@@@'+ owrpr.anss);

                owrpr.isCheckBox= true;
            }
            else if(que.Question_Type__c == 'Single-Select'){
                List<string> ansList=que.Answer_Option__c.split(';');
                for(String ans:ansList){
                    owrpr.anss.add(new selectOption(ans,ans));
                }
                system.debug('^^^^^^^^^^^^'+ owrpr.anss);
                owrpr.isRadiobutton= true;
            }
            else{
                owrpr.isText= true;
            }
            onWrprList.add(owrpr);
        }

        system.debug('$$$$$$$$'+ questionList.size());
        system.debug('%%%%%%%%'+ onWrprList.size());

    }

    public class OnlineWrapper{
        public List<String> ansList {get; set;}
        public List<SelectOption> anss{get;set;}
        //  public List<String> selectedOptions{get;set;}
        public Question__c que {get; set;}
        public Boolean isCheckBox {get;set;}
        public Boolean isRadioButton {get;set;}
        //public String text{get;set;}
        public Boolean isText{get;set;}
        public OnlineWrapper(){
            ansList=new List<String>();
            anss=new List<SelectOption>();
            this.isCheckBox=false;
            isRadioButton=false;
            isText=false;
        }
    }
}

A: The main issue is you are not rendering properly based on Question Type. Wrap the question type options inside outputPanel and display those conditionally.
<apex:repeat value="{!onWrprList }" var="qustwrpr">
    <apex:outputPanel rendered="{!qustwrpr.que.Question_Type__c='Multi-Select'}">
        <apex:outputField value="{!qustwrpr.que.Question_Des__c }"/>
        <apex:selectCheckboxes value="{!qustwrpr.ansList}">
            <apex:selectOptions value="{!qustwrpr.anss}"/>
        </apex:selectCheckboxes>
    </apex:outputPanel>
    <apex:outputPanel rendered="{!qustwrpr.que.Question_Type__c='Single-Select'}">
       <apex:outputField value="{!qustwrpr.que.Question_Des__c }"/>
        <apex:selectRadio value="{!qustwrpr.ansList}">
            <apex:selectOptions value="{!qustwrpr.anss}"/>
        </apex:selectRadio>
    </apex:outputPanel>
</apex:repeat>

Which will finally display like this:


text:
Q: Using @media in css of HTML Email I'm trying to get a HTML email to print a table at a lesser width than it looks on screen.  I've put in:
@media print{
  .style1 {
    width: 500;
  }
}

When I print it still runs off the page.  I've set it to a ridiculously small amount with no avail.  The style1 is applied to a table which has a width of 100%, I thought the percent might be throwing it so I changed it to a width of 688 and got the same results.  there are no rows or cells that have a fixed width in the table; they all use percents.  Any suggestions?

A: If that is a direct example above, you need to provide a unit (px, em, etc.) for any values other than 0 in css definitions:
@media print{
  .style1 {
    width: 500px;
  }
}

This differs from the html attributes which assumes pixels. Hope this helps, -Matt

A: First of all, you should define a unit after the width. Most browsers still use pixel units as a failsafe though, so chance is this is not the actual problem.
What mailclient are you using?
Support for print CSS is not guaranteed across different mailclients.

redpajama_set_name: RedPajamaStackExchange


text:
Q: If $H$ is a subgroup of a group $G$, is there a standard name for subsets of the form $xHy$? Let $H$ be a subgroup of a group $G$. The right (resp. left) cosets of $H$ are the subsets of $G$ of the form $Hg$ (resp. $gH$) for some $g \in G$.
Question. Is there a standard name for the subsets of the form $xHy$ (with $x, y \in G$)?
These sets occur naturally in the study of the power monoid of $G$ (the monoid of all subsets of $G$ under the product $XY = \{xy \mid x \in X, y \in Y\}$). I thought of double cosets or bilateral cosets but it seems to be used for other purpose.

A: As @user1729 said in comments, these are conjugates of cosets. But they can also be described as left or right cosets of subgroups conjugate to $H$.
So $xHy = xy(y^{-1}Hy)$ is a left coset of the subgroup $y^{-1}Hy$.
And $xHy = (xHx^{-1})xy$ is a right coset of the subgroup $xHx^{-1}$.
I remember a while back someone asked for help with an exercise that said "prove that every left coset in a group is a right coset", and several people replied that this was wrong, but in fact it is correct because $xH = (xHx^{-1})x$.

A: To my knowledge there exists no name for these subsets of $G$. As said in the linked question from the comments, you can identify sets $xHy$ with cosets in $G \times G$ (or $(G \times G) / \{ (g,g) \mid g \in G \}$ as I pointed out in the comments).
However, this action of $G \times G$ on $H$ could be interpreted differently, reminiscent of the action of two rings on a single module, known as a Bimodule. Given $H$, we have a left action and a right action of $G$ on $H$, and both are compatible in the following sense:
$$
 (x^{-1} H)y = x^{-1} (Hy).
$$
This essentially means that, if we interpret the action in the symmetric group over the, for example, right cosets, then the permutations corresponding to the left action commute with the permutations corresponding to right action, i.e, they are contained in the centralizers of each other in the symmetric group.
So, I would suggest to call them bicosets, as was already suggested in the comments of the other question. I never encountered this name before, so, I suppose it is new.


text:
Q: Understanding the difference between relations and functions. $R=\{(1,2),(1,3)\}$ is a relation but not function.
The logic for this is that if the first element of every ordered pair must remain different, then it is said to be function. Otherwise, it's just a relation.
My question is what is the background of this distinction?

A: Part of the reason is "historical".
Function is a typical mathematical concept and has its origin in the idea of "recipe" or "procedure" which, taking an input $x$ "produce" an output $y$.
Paradigmatic examples are the simple mathematical functions like : "double of __" (i.e. $y = 2 \times x$), "square of __" (i.e. $y = x^2$).
The concept of relation is easily encountered outside of mathematics; we are all accostumed with everyday relations like : "__ is father of ..." or "__ is to the left of ...".
Only in modern times (about one century ago), the adoption of set-theoretic language in mathematics, gives us the opportunity of "modelling" relations as set of ordered pairs and thus to define functions simply as a "special" kind of relations : those satisying the "functionality" property :

a relation $R$ such that : for $x_1Ry_1$ and $x_2Ry_2$, if $y_1 \ne y_2$, then $x_1 \ne x_2$, is called a function.


text:
Q: java.lang.NullPointerException when appending information to an existing Excel file I'm trying to append information to an existing Excel file, but I keep receiving java.lang.NullPointerException. Please refer to the code and exception message below.
Code:
private WritableSheet appendingSheet;
private static File report;

public void AppendToDoc (String path) throws IOException, WriteException, BiffException {

    this.inputFile = path;
    report = new File(inputFile);

    Workbook appendingWorkbook = Workbook.getWorkbook(new File(inputFile));
    WritableWorkbook copy = Workbook.createWorkbook(new File("output.xls"),appendingWorkbook);
    appendingSheet = copy.getSheet("Sheet 1");
}

public void WriteToDoc (int option, String testName, String execDate, String time, boolean status) throws RowsExceededException, WriteException, IOException, BiffException{

    int startingRow = NumOfRows(this.inputFile) + 1; //I have a function which finds the number of existing rows in the existing document. It works.
    Label label = new Label(1, startingRow, "hello", times);
    appendingSheet.addCell(label);

}

Calling code:
AppendToDoc("C:/Users/smith/ExcelTestFile.xls");
WriteToDoc(2, "This is a test", "executed", timeStamp, true);

Exception message:

Exception in thread "main" java.lang.NullPointerException
      at jxl.write.biff.Styles.getFormat(Styles.java:214)
      at jxl.write.biff.CellValue.addCellFormat(CellValue.java:468)
      at jxl.write.biff.CellValue.setCellDetails(CellValue.java:282)
      at jxl.write.biff.LabelRecord.setCellDetails(LabelRecord.java:216)
      at jxl.write.biff.WritableSheetImpl.addCell(WritableSheetImpl.java:1199)
      at ExcelOperations.WriteToDoc(ExcelOperations.java:149)
      at ChequeImage.main(ChequeImage.java:174)

NOTE: The exception seems to be happening at the line "appendingSheet.addCell(label);".
Thanks for the help.
EDIT 1: The below image shows the contents of appendingSheet right before "appendingSheet.addCell(label)" is executed. I'm not exactly sure what it represents, but it certianly doesn't seem to be null.

A: I can't say I'm familiar with Biff, but POI seems to work in a similar fashion.  It looks as though you have created a workbook:

WritableWorkbook copy = Workbook.createWorkbook(new File("output.xls"),appendingWorkbook);

But then you don't create the sheet that you reference with:

appendingSheet = copy.getSheet("Sheet 1");

I'm guessing you're getting an NPE because "copy.getSheet("Sheet 1");" is returning null.  Unlike when you simply open a workbook in excel, the API will likely not create that default sheet for you.  I'm betting you'll have to create the sheet object before you're able to add cells.

A: So...I've managed to solve the problem.
I can't really explain why, but after I redefined "copy" and "appendingWorkbook" (not appendingSheet) as global variables instead of local to AppendToDoc(); as well as added the line copy.write(), the program worked...
Thanks everyone for the help. I really appreciate it.

A: I have face the following Exception while writing the data into an XLS file using JXL API.
Exception in thread "main" java.lang.NullPointerException
    at jxl.write.biff.Styles.getFormat(Styles.java:214)
    at jxl.write.biff.CellValue.addCellFormat(CellValue.java:468)
    at jxl.write.biff.CellValue.setCellDetails(CellValue.java:282)
    at jxl.write.biff.LabelRecord.setCellDetails(LabelRecord.java:216)
    at jxl.write.biff.WritableSheetImpl.addCell(WritableSheetImpl.java:1199)
    at com.java.report.XLS_JXLReport.main(XLS_JXLReport.java:31)

I have observed the following error is occurring due to WritableFont is empty. Source code from where the exception is raised is:
Styles.java:214
    // Do the same with the statically shared fonts
    if (format.getFont() == WritableWorkbook.ARIAL_10_PT) // Line 214
    {
      format.setFont(getArial10Pt());
    }

To avoid this error make sure to provide the Font Name.

Sample code using Java Excel API » 2.6.12
public class XLS_JXLReport {
    static String filePath = "C:/Yash/";
    public static void main(String[] args) throws IOException, JXLException {
        //Creates a writable workbook with the given file name
        jxl.write.WritableWorkbook workbook = jxl.Workbook.createWorkbook(new File(filePath+"CopyCell.xls"));
        WritableSheet sheet = workbook.createSheet("My Sheet", 0);

        // Create cell font and format
        WritableFont cellFont = new jxl.write.WritableFont(WritableFont.TIMES, 16);
            cellFont.setColour(jxl.format.Colour.BLUE);
        WritableCellFormat cellFormat = new WritableCellFormat(cellFont);
            cellFormat.setBackground(jxl.format.Colour.GRAY_25);

        //cellFormat = null; // To get the NullPointerException at Styles.java:214. Uncomment this line of code.

        // Create the label, specifying content and format
        Label label = new Label(1, 2, "ABCD", cellFormat);
        sheet.addCell(label);

        //Create copies of cell in a loop
        WritableCell copiedCell = null;
        for (int i = 0 ; i < 4 ; i ++) {
            copiedCell = label.copyTo(1, 4 + i); //Deep copy cell
            sheet.addCell(copiedCell);
        }

        closeWorkbook(workbook);
    }
    public static void closeWorkbook(WritableWorkbook workbook) throws IOException, JXLException {
        if (workbook == null)
            return;
        if (workbook.getNumberOfSheets() == 0) {
            workbook.createSheet("No data", 0); // otherwise pointer error
        }
        //Writes out the data held in this workbook in Excel format
        workbook.write();
        //Close and free allocated memory
        workbook.close();
    }
}

JXL APIwiki allows users to read, write, create, and modify sheets in an Excel(.xls) workbook at runtime. It doesn't support .xlsx format.

*

*JXL API supports Excel documents with versions Excel 95, 97, 2000, XP, and 2003. These documents hold the extension .xls

*For .xlsx use Apache POI.


text:
Q: What is the C++ idiom to replace snprintf(3)? I have some C++ code which needs to generate an error message when parsing a certain file header fails. In this case, I need to ensure that a certain 4 byte field in the header is "OggS", and if it is not, return an error message like "invalid capture_pattern: 'FooB'; expecting 'OggS'". My code looks something like this:
const string OggPage::parseHeader(void) {
  read(fd, capture_pattern, sizeof(capture_pattern)); // error handling omitted
  if (strncmp(capture_pattern, CAPTURE_PATTERN, sizeof(capture_pattern)) != 0) {
    char err[256];
    snprintf(err, sizeof(err), "Failed to read %d bytes from file descriptor %d: %s\n", sizeof(capture_pattern), fd, err);
    return err;
  }

  return "Everything was A-OK!";
}

What is the standard C++ idiom for building a string from other datatypes? I'm not wedded to the printf(3)-style format here, so feel free to suggest anything that works.

A: You can use stringstream or ostringstreamfrom C++ Standard library. If further stream will not be used to read values from it (e.g. it's istream part won't be used) ostringstream is more suitable.
#include <sstream>
#include <string>
#include <iostream>

int main() {
 std::stringstream str_stream;
 int number = 5;

 str_stream << " String with number " << number << std::endl;;

 std::string str = str_stream.str();
 std::cout << str;
}

A: C++ way of doing this is std::stringstream.
std::stringstream err;
err << "Failed to read " << sizeof(capture_pattern)
                         << " bytes from fd " << fd << std::endl;
return err.str();

A: Using string functions from cstring is definitely fine for reading. They're fast, convenient and not verbose.
For building your error messages, you can use stringstream, operators related to the string class, boost::format or, as you put it, snprintf.
You have also boost::lexical_cast for simple things:
string message = "Failed to read " + lexical_cast<string>(n) +
   " bytes from the descriptor " + lexical_cast<string>(fd) + ".";

I recommend having a look at this Gotw for a sane point of view.
I'd recommend boost::format if you have a lot of formatting to do. Use lexical_cast for simple isolated things, and use stringstream if you have requirements which makes you need them (eg. custom operator<<, cannot use boost, etc).
To be honest, snprintf is really fine.

A:
Just as a note, please don't suggest  replacements for the actual reading--there is a reason that I want to use the C standard library for I/O here. :)

You can't really ask for "idiomatic" ways to do something in C++, and then say "but I want to stick to the C standard library...
Anyway, you have three options. I don't believe any of them is idiomatic (because that would imply some kind of consensus about this being the best way):

*

*stick with the C APIs you're already using

*Use the the C++ std::stringstream, which is part the iostreams section of the standard library

*use Boost.Format

The latter has the downside that it relies on a third-party library, but the advantage that it gives you printf-like syntax, in a typesafe and extensible manner, which interoperates cleanly with C++ streams.

A: You create a stringstream, write what you want using the '<<' operator and then get the string out of stream with the member function .str().
#include <sstream>
#include <string>

using namespace std;

stringstream err;
err << "Failed to read " << sizeof(capture_pattern) << " bytes from file descriptor: " << fd << endl;
string outstr = err.str();


text:
Q: SSH connection to a router from Server I tried creating SSH connection to a router . SSH works fine .
The following scenario was tried .
Created ip address to an interface in router and added SSH configurations to this interface . Made sure that the execution server and the router are in the same subnet . Did a SSH from the execution server to the router . Works fine .
I want the SSH connection to remain even after the interface in the router goes down . Is it possible

A: No.  Doing that would make no sense at all.
It would be like asking for the light to stay on when you flip off the switch.  The only way to do that would be to invalidate the switch.


text:
Q: Expectation value of $x$ in infinite square well I'm working on a infinite square well problem and I have the wavefunction:
$$
\Psi(x,0) = \begin{cases} A\sin^3{(\frac{\pi x}{a})}&\,{\rm if}\ 0\leq x\leq a \\
0&\,{\rm otherwise}
\end{cases}
$$
which I can express like this:
$$
\Psi(x,0) = c_1\psi_1 + c_3\psi_3
$$
where
$$
\psi_1 = \sqrt{\frac{2}{a}}\sin{(\frac{\pi x}{a})} \\
\psi_3 = \sqrt{\frac{2}{a}}\sin{(\frac{3\pi x}{a})}
$$
and so,
$$
\Psi(x,t) = c_1\psi_1e^{-\frac{iE_1t}{\hbar}} + c_3\psi_3e^{-\frac{iE_3t}{\hbar}} \\
|\Psi(x,t)|^2 = (c_1\psi_1)^2 + (c_3\psi_3)^2+2c_1c_3\psi_1\psi_3\cos{\bigg(\frac{(E_3-E_1)t}{\hbar}\bigg)}
$$
I want to know the expectation value of x, $\langle x \rangle$ as a function of time. However after evaluating $\int_{0}^{a} x|\Psi(x,t)|^2 dx$, I got $\frac{a}{2}$ instead of some function of time.
I thought the first ($x(c_1\psi_1)^2$) and the second term ($x(c_3\psi_3)^2$) of the integral should be zero since it's an odd function but I get $\frac{a}{2}c_n^2$ on either terms. The cross term also gives me zero after evaluating the integral.
May I get some hint on what I did wrong/missed?


text:
Q: Can't get MSMQ to receive messages via FQDN via HTTP Context - Server 2008 R2 with private queue, IIS setup. Sending messages via HTTP from other computers. [MSMQ is not in the 'default web site'. I changed the ID of my website to 1 to install msmq (after previously un installing it)]
I could do with some help. I've read through all the 'msmq messages over http just don't get delivered' and looked into this a lot, but just can't get it working.
I CAN get the queue to receive messages if I use the IP address, not if I use the FQDN that resolves to the same IP address. I need the Domain Name to work, since my next step is to get SSL to work and obviously my cert if for the full domain name!
I have a very simple app that sends the following messages:
Private Function SendStuff() As String

    Dim output As String = "Mesages Sent To" & Environment.NewLine

    Dim Addresses As New List(Of String)
    Addresses.Add("Direct=HTTP://46.0.0.206/msmq/Private$/test.q")
    Addresses.Add("Direct=HTTPS://46.0.0.206/msmq/Private$/test.q")
    Addresses.Add("Direct=HTTP://subdomain.domain.net/msmq/Private$/test.q")
    Addresses.Add("Direct=HTTPS://subdomain.domain.net/msmq/Private$/test.q")

    For Each address In Addresses

        Dim fullAddress As String = "FormatName:" & address

        Dim mq As New System.Messaging.MessageQueue(fullAddress)
        Dim mm As New System.Messaging.Message()

        Dim body As String = "Hello via constructor " & fullAddress

        With mm
            .Body = body
            .AcknowledgeType = Messaging.AcknowledgeTypes.None
            .UseAuthentication = False
            .TimeToReachQueue = New TimeSpan(0, 20, 0)
            .Label = address.Substring(7, 14)
        End With

        mq.Send(mm)
        output = output & Environment.NewLine & fullAddress
    Next
    Return output
End Function

On the server, in the IIS logs, we get exactly this:
2014-03-07 09:04:02 46.0.0.206 POST /msmq/private$/test.q - 80 - 83.0.0.130 - 200 0 0 31
2014-03-07 09:04:02 46.0.0.206 POST /msmq/private$/test.q - 443 - 83.0.0.130 - 200 0 0 46
2014-03-07 09:04:02 46.0.0.206 POST /msmq/private$/test.q - 80 - 83.0.0.130 - 200 0 0 78

I get 1 message in the test.q, I expect 2 (both from the HTTP protocols, the httpS I don't expect yet, but would be nice :)
Messages Received:
    <?xml version="1.0"?>
<string>Hello via constructor FormatName:Direct=HTTP://46.0.0.206/msmq/Private$/test.q</string>

Can anybody inform me on what to look at next, there's nothing of interest in the Servers/Receiving computers Event log, despite me turning on 'end to end', logging I get nothing in "applications and services log\Microsoft\Windows\MSMQ' It's got 0 messages in it.
ANY help appreciated.
Thanks

A: Ok, so the solution was simple.
It seems pretty clear all the documentation was made prior to the HTTP option, hence the lack of just one example.
You need to add a redirection for MSMQ, from FQDN.com to localhost.
You do this by adding an XML file under: C:\Windows\System32\msmq\Mapping
With the following contents:
<redirections xmlns="msmq-queue-redirections.xml">
  <redirection>
      <from>http://FQDN.com/msmq/private$/test.q</from>
      <to>http://localhost/msmq/private$/test.q</to>
  </redirection>
</redirections>

Done


text:
Q: How to use LAST_INSERT_ID() in c# windows form? In database I have three tables-
patient(patientID,fName,lName)
illness(diseaseID,diseaseName)
patientDisease(patientID, diseaseID, dateChecked)

patientID and diseaseID are index.
So on in c# I have three textboxes fNameTxt and lNameTXT, diseaseTxt.I want to store the name in patient table and disease name in illness table. Besides, I have to record patientID and diseaseID in patientDisease table as well. For patient table, I used following code. I knew, I can use
SET @variable = LAST_INSERT_ID()

to get the id, but realised c#(visual studio) doesnt recognize it. Basically, I couldnt make the overall statement. Could anybody help me to get through this condition please.
string connStr = @"server=localhost; DATABASE=mario;User ID=root;Password=;";
MySqlConnection conn1 = new MySqlConnection();
conn1.ConnectionString = connStr;

MySqlCommand cmd = conn1.CreateCommand();

cmd.CommandText = "INSERT INTO patient(patientID,fName, lName)"
    + "Values("NULL",'" + fNameTxt.Text + "','" + lNameTxt.Text + "');";
conn1.Open();
cmd.ExecuteNonQuery();

I searched some other questions here, but they are almost about suggesting the use of LAST_INSERT_ID() but not how to use it.

A: You can use this to get the last inserted id:
"SELECT * FROMtable(column) WHERE id = last_insert_id();

And use this if you want to insert a last id:
"INSERT INTO table(column) VALUES (LAST_INSERT_ID())";

Hope this might be useful.

A: It will be much better if you use stored procedures
     INSERT INTO patient (patientID,patientID,lName)
            VALUES("NULL",'" + fNameTxt.Text + "','" + lNameTxt.Text + "');
   SET @last_id_in_patient  = LAST_INSERT_ID();
     INSERT INTO patientDisease (patientID,diseaseID,dateChecked)
            VALUES( @last_id_in_patient ,NULL,'text');  # use ID in second table";

Now You can update your PatientDisease table for particular PatientId.


text:
Q: ElasticSearch 6.3.2 Could not create JVM when start I have just installed elastic search 6.3.2 on my win 10 pc from msi package. But when I tried to start the elasticsearch.exe in the command line, I was promted some issues related to JVM version.
The error messages are:
Java HotSpot(TM) 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.
Invalid -Xlog option '-Xlog:gc*,gc+age=trace,safepoint:file=logs/gc.log:utctime,pid,tags:filecount=32,filesize=64m'
[0.003sError: Could not create the Java Virtual Machine.
]Error: A fatal exception has occurred. Program will exit.

[error][logging                  ] [] Error opening log file 'logs/gc.log': No such file or directory

I found there is a similar issue: https://discuss.elastic.co/t/setting-up-elasticsearch-6-0-1/111280
But it is said that elastic 6.0+ could support java 10. (https://www.elastic.co/guide/en/elasticsearch/reference/current/setup.html )
Also I have tried to download the zip installation package. When run the elasticsearch.bat, I also got the deprecated warning message, but the engine is started successfully.
D:\Software\elasticsearch-6.3.2\bin>elasticsearch.bat
Java HotSpot(TM) 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.
[2018-08-17T16:55:29,761][INFO ][o.e.n.Node               ] [ZHUZIXIAO-IBM] initializing ...
[2018-08-17T16:55:29,828][INFO ][o.e.e.NodeEnvironment    ] [ZHUZIXIAO-IBM] using [1] data paths, mounts [[Windows (C:)]], net usable_space [8.2gb], net total_space [80gb], types [NTFS]
[2018-08-17T16:55:29,829][INFO ][o.e.e.NodeEnvironment    ] [ZHUZIXIAO-IBM] heap size [1.9gb], compressed ordinary object pointers [true]

It seems a little awkard to me. Could anyone please help me with this problem?
Thanks very much!
=======
Update:
ElasticSearch can run properly after I installed java 8u181. So is it still a version incompatible issue?


text:
Q: Style Google Maps in Flutter silver or black & white I'm using Google Maps in a Flutter app. I'm looking for a way to style the map on a black and white edition. I've seen this done in web editions, but not sure if it's possible in the Flutter edition...yet.
Wonder if anyone else has achieved this and how?

A: First you have to get a style.json from: https://mapstyle.withgoogle.com/ and add it to your assets.
  assets:
    - assets/json_assets/

Then  you add this to your init State where the google Maps widget is
  @override
  void initState() {
    super.initState();
    rootBundle.loadString('assets/json_assets/map_style.txt').then((string) {
      _mapStyle = string;
    });
  }

and last but not least your Map Created function should look like this:
  void _onMapCreated(GoogleMapController controller) {
    controller.setMapStyle(_mapStyle);
    _mapController = controller;
    initMemoryClustering();
  }


text:
Q: loading spring properties files from S3 bucket We have a application which is running on amazon EC2. we are planning to migrate it to elastic beanstalk environment. our application has two configuration files which stores some endpoints and few other control parameters. currently those are loaded as spring properties and injected to respective beans. we are thinking of putting them in to a S3 bucket and read them while loading the spring context. tries different approaches but still not luck.
1) what would be best advisable way to read the properties file with aws elastic beanstalk. we do not like to put them all as environment variables?
2) I tried creating a class extending
    org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
and tried by overriding processProperties method. but it seems annotation based property injection happens before calling this method. instance was created but the processPRoperties method was not called? any idea how this could be handled will be appreciated
EDIT
I have used a custom ApplicationContextInitializer registered in web.xml
<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>com.xxx.PropertyInitializer</param-value>
</context-param>

in the initializer class injected the properties. seems it is working fine but then I'm facing another issue stated here.
Spring application context is converted to proxy after custom property injection


text:
Q: Importing a file in python I tried to import the file only using import I searched the problem and found out it happened because the file isn't in the same working directory as my current file, didn't quite understand that(I am a beginner). So I tried using this: But still I get this error No module named printer1.
Here is the code:
import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '\\' +  'C:\\Users\\Dell\\Desktop\\hello\\printer1.py'))
from printer1 import *

A: Try this solution.
import os
import sys
sys.path.append('C:\\Users\\Dell\\Desktop\\hello\\')
from printer1 import *

Let me know if it works :)


text:
Q: `glossaries` 'one off' lowercase full print out I have a glossary acronym entry like this: \newacronym{mae}{MAE}{My Acronym Entry}
I have three requirements:

*

*In the Acronyms list I would like it to print: My Acronym Entry

*For most cases, when I use \gls{mae} I would like it to print: MAE

*In some cases, when I use \gls{mae} I would like it to print: my acronym entry
Here is an MWE:
\documentclass{article}
\usepackage[acronym,automake]{glossaries}
\makeglossaries

\newacronym{mae}{MAE}{My Acronym Entry}

\begin{document}
\printglossary[type=\acronymtype]

\begin{itemize}
    \item First use: \gls{mae}
    \item Second use: \gls{mae}
    \item Long use: \acrlong{mae}
    \item Lower case use: ??
\end{itemize}

\end{document}

I know how to handle the first two requirements. How do I handle the third?

A: You could use an 'user' field to specifiy your desired format along with the definition of your entry.
\documentclass{article}
\usepackage[acronym,automake]{glossaries}
\makeglossaries

\newacronym[user1={my acronym entry}]{mae}{MAE}{My Acronym Entry}

\begin{document}
    \printglossary[type=\acronymtype]

    \begin{itemize}
        \item First use: \gls{mae}
        \item Second use: \gls{mae}
        \item Long use: \acrlong{mae}
        \item Lower case use: \glsuseri{mae}
    \end{itemize}

\end{document}


text:
Q: How to find the time axis of inverse Fourier transform in python? I have a pulse (experimental points) in the frequency domain. I used the code
func_t = ifft(ifftshift(func_w))

to transform it to the time domain. The problem I am facing now is how to get the corresponding time axis "t" so that I can plot:
plt.plot(t, func_t )

A: You need to calculate it by using the sampling frequency 'Fs' so your time array would be
import numpy as np
t = np.arange(0, n/Fs, 1/Fs)

where n is you number of points in your signal and Fs the sampling frequency
Note: Your sampling frequency is double your maximum frequency in your original signal if you follow the Nyquist sampling theorem


text:
Q: How to hide RuntimeException details from EJB client? I have a JEE5 application that exposes services using (local) session beans.
When an internal fault occurs during service execution, a RuntimeException is thrown and encapsulated by JBoss(5.0.1) in a javax.ejb.EJBTransactionRolledbackException.
The problem is that client applications receiving this EJBTransactionRolledbackException can access detailled informations about the cause runtime exception, exposing internal architecture of my application. And I don't want that.
Instead, I would like JBoss to always encapsulate RuntimeException thrown by exposed session beans into a single (and simple) TechnicalException (with no cause).
What's the best way to achieve this ? (Using interceptors ? Using JBoss configuration ?)

A: Finally, based on previous answer and my personal researches, I retained the folowing solution.
I've created an interceptor dedicated to manage server faults :
public class FaultBarrierInterceptor {

@AroundInvoke
public Object intercept(final InvocationContext invocationContext) throws Exception {
    try {
        return invocationContext.proceed();
    } catch (final RuntimeException e) {
        final Logger logger = Logger.getLogger(invocationContext.getMethod().getDeclaringClass());
        logger.error("A fault occured during service invocation:" +
                "\n-METHOD: " + invocationContext.getMethod() +
                "\n-PARAMS: " + Arrays.toString(invocationContext.getParameters()), e);
        throw new TechnicalException();
    }
}}

The thrown technical exception extends EJBException and does not expose the cause RuntimeException:
public class TechnicalException extends EJBException {}

I use this interceptor in all public services :
@Stateless
@Interceptors({FaultBarrierInterceptor.class})
public class ShoppingCardServicesBean implements ShoppingCardServices { ...

This is an implementation of the Fault Barrier pattern.
Any runtime exception is catched, logged and a fault is signaled to the client (without internal details) using a TechnicalException. Checked exceptions are ignored.
RuntimeException handling is centralized and separated from any business methods.

A: Any RuntimeException extends java.lang.Exception.
The EJB spec provides handling for 2 types of exceptions (Application and System)
If you'd like to throw a System Exception, you would usually do it like so:
try {
.... your code ...
}catch(YourApplicationException ae) {
   throw ae;
}catch(Exception e) {
   throw new EJBException(e); //here's where you need to change.
}

To hide the internal details of your system exception, simply replace:
throw new EJBException(e);

with:
throw new EJBException(new TechnicalException("Technical Fault"));

Hope this is what you were looking for.
Cheers


text:
Q: Bean method in onclick is fired on rendering The following works as expected, only when a click-event occurs:

but this is already called while page-rendering:

Why is the bean method called while rendering?

A: onclick expects a javascript function, not a method expression. #{bean.someMethod()} has to be resolved to some string (alert('test') in your example) when the page is rendered, that's why it is called.  only makes sense if someMethod() returns a string which is valid javascript code.
This is not to be confused for JSF action attribute for example, like <h:commandButton action="#{bean.someMethod()}", which is called when the button is clicked.


text:
Q: Coldfusion and Foundation 5 - will it work? I have a big existing website (hundreds of dynamic pages) built in Coldfusion - we don't CF for any of the display stuff, that's just css and html.
We're about to implement a new front end design and it has been suggested that we use the Foundation 5 framework for the html and css - I don't have any experience with using frameworks and can't get my head around what the Foundation 5 framework is and if it'll get in the way of coldfusion (or vice versa)
Does anyone have any information that will help me gain an understanding as to what the framework actually does please /how it'd integrate with CF?
Thanks ever so much.
Nick

A: Foundation (or bootstrap) will be completely independent of the ColdFusion backend. They're simply separate technologies.
Foundation is a CSS framework - it doesn't have any serverside components (unless you count things like grunt + various ways of custom building the result).


text:
Q: Haskell make a list of the variables of a list Suppose I have the data
data Expense = MkExpense Double String deriving (Eq,Ord)

and a function
balanced :: [Expense] -> Double -> Bool
balanced expenses epsilon =
  let amounts = ...
  in maximum amounts - minimum amounts < epsilon;

which computes wether the list of expenses is balances (i.e. everyone paid the same with a maximum difference of epsilon due to floating point errors), the epsilon has a value of 0.01.
The alogrithm is correct, but where the three dots are, I want to extract a list of doubles; i.e. the doubles of all the expenses in my parameter. How can I do that without changing the datatype?

A: You can proceed as follows:
balanced :: [Expense] -> Double -> Bool
balanced expenses epsilon =
  let amounts = map extractExpense expenses
  in maximum amounts - minimum amounts < epsilon

And extractExpense would be the unwrapper of the Double value of your data:
extractExpense :: Expense -> Double
extractExpense (MkExpense expense _) = expense

Or more concise:
balanced :: [Expense] -> Double -> Bool
balanced expenses epsilon =
  let amounts = map extractExpense expenses
  in maximum amounts - minimum amounts < epsilon
    where extractExpense (MkExpense e _) = e


text:
Q: Behaviour of the Gamma function near zero The Gamma function on the positive real half-line is defined via the reknown formula
$$
\Gamma(z)=\int_0^\infty x^{z-1}e^{-x}dx, \quad z>0.
$$
A classical result is Stirling's formula, describing the behaviour of $\Gamma(z)$ as $z$ diverges to infinity,
$$
\Gamma(z)\sim \sqrt{\frac{2\pi}{z}} \left( \frac{z}{e}\right)^z, \quad z \to \infty.
$$
Is there any such approximation formula for $z \downarrow 0$, describing the speed at which the Gamma function diverges near the origin?

A: Around $z=0$
$$\Gamma(z)=\frac{1}{z}-\gamma +\sum_{n=1} a_n z^n$$
$$a_1=\frac{1}{12} \left(6 \gamma ^2+\pi ^2\right)\qquad a_2=-\frac{1}{6} \left(2 \zeta (3)+\gamma ^3+\frac{\gamma  \pi ^2}{2}\right)$$
$$a_3=\frac{1}{24} \left(8 \gamma  \zeta (3)+\gamma ^4+\gamma ^2 \pi ^2+\frac{3 \pi
   ^4}{20}\right)$$
Edit
A quite good approximation is given by
$$\Gamma(z)\sim \frac 1 z \frac{1+\frac{\left(\pi ^2-6 \gamma ^2\right) }{12 \gamma }z } {1+\frac{\left(\pi ^2+6 \gamma ^2\right) }{12 \gamma }z  }$$


text:
Q: ForEach NavigationLink with State and Binding I'm trying to generate a ForEach with a NavigationLink and use State and Binding to pass some entity around:
struct ContentView: View {
    @Environment(\.managedObjectContext) var moc

    @FetchRequest(
        entity: MyEntity.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \MyEntity.name, ascending: true)
        ]

    ) var entries: FetchedResults<MyEntity>

    var body: some View {
        NavigationView {
            List {
                ForEach(entries, id: \.self) { (entry: MyEntity) in
                    NavigationLink(destination: DetailView(myEntry: $entry)) {
                        Text(entry.name!)
                    }
                }.
            }
        }
    }
}

And then the following view:
struct DetailView: View {
    @Binding var myEntry: MyEntity

    var body: some View {
        Text(myEntry.name!)
    }
}

The problem is I can not pass the value to Detail view since the error:
Use of unresolved identifier '$entry'

What is wrong here and how to solve this?
If I just have a simple @State its no problem to pass it via the binding, but I want/need to use it in the ForEach for the FetchedResults
EDIT: If I remove the $ I get Cannot convert value of type 'MyEntity' to expected argument type 'Binding<MyEntity>'
EDIT2: The purpose is to pass some object to DetailView and then pass it back later to ContentView

A: Use the following in ForEach
   ForEach(entries, id: \.self) { entry in
        NavigationLink(destination: DetailView(myEntry: entry)) {
            Text(entry.name!)
        }
    }

and the following in DetailView
struct DetailView: View {
    var myEntry: MyEntity

    var body: some View {
        Text(myEntry.name!)
    }
}

The MyEntity is class, so you pass object by reference and changing it in DetailView you change same object.

A: FetchedResults<MyEntity> entities does not conform to Binding or DynamicProperty. For the $ symbol to workout must conform to Binding.
You can make a FetchedResultsController in an ObservableObject to get the same functionality as an @FetchRequestand have the ability to pass the values in an EnvironmentObject or ObservedObject.


text:
Q: How can I define vertices of a plane that is always parallel to the camera? I am trying to draw a rectangle (basically a plane) that is always parallel to the camera. I want to restrict plane to a certain size (lets say height = 2 and width = 2 units). However, I do not understand  how to set position to the vertices such that rectangle will always be parallel to the camera.
First I am calculating camera normal (direction) using:
glm::normalize(mPosition - mTargetPos); // normal

and then I am using  point-normal equation to define the plane:
normal = (A, B, C)
point = (a, b, c)  // this point will serve as a center to the plane
A(x−a)+B(y−b)+C(z−c) = 0

Question: How can I define vertices of the plane?

A: *

*Take some normilized vector UpDir for up direction (it can be UpDir=(0,1,0) or UpDir=(0,0,1) depending on your coordinate system, or it can be computed somehow)

*Compute cross product SideDir of the normal and the UpDir.

*Now you can use the SideDir and UpDir as basis for your plane's coordinate system, and compute four vertices of the rectangle as point+width*SideDir+height*UpDir, point+width*SideDir-height*UpDir, point-width*SideDir-height*UpDir, point-width*SideDir+height*UpDir

A: I recommend to define the points in view space. Finally transform the points by the inverse view matrix.
In view space the points are parallel to the view if they have the same z coordinate. The z-coordinate has to be negative and its amount has to greater than the distance to the near plane and less than the distance to the far plane:
near < -z < far

Compute the view matrix (view_mat) and define the points in view sapce:
glm::mat4 view_mat = glm::lookAt(mPosition, mTargetPos, mUp);
float z =

glm::vec3 pt1View(x1, y1, z);
glm::vec3 pt2View(x2, y2, z);
// [...]

Transform the points from view space to world space:
glm::mat4 inverse_view_mat = glm::inverse(view_mat);

glm::vec3 pt1World = glm::vec3(inverse_view_mat * glm::vec4(pt1View, 1.0f));
glm::vec3 pt2World = glm::vec3(inverse_view_mat * glm::vec4(pt2View, 1.0f));
// [...]


text:
Q: Loss of stability (unphysical energy gain) for simple pendulum equation? I am simulating a pendulum using MATLAB and noted a curious issue.
When I use zero velocity and (pi - 0.1) angular position as starting conditions for my second order ODE, the solution deviates from what physically and analytically expected after some short time (the pendulum gains energy, after Swinging back and forth it starts revolving).
The trivial code I used is as follows
f1 = @(t,Y) [Y(2); -sin(Y(1))];
[z1,z2] = ode45(f1,[0:0.001:80],[ pi - 0.1,0])
plot(z1,z2(:,1))
Using ODE15s actually makes the phenomenon to occur earlier.
Any hint on what I am doing wrong? What is causing all this?
Thanks a lot

A: This is not too surprising.  Energy is conserved in the true solution to the system, but the numerical approximations won't conserve it exactly.  If on the average the system gains a little bit of energy at each step, after enough steps the gain will become noticeable.
EDIT:
In this system, the energy is $y_2^2/2 - \cos(y_1)$.  The initial energy is
$-\cos(\pi - .1) \approx .995004$, very close to the energy ($1$) required to reach the vertical position, so even quite a slow accumulation of energy is enough to put you over the top.
One thing you can try, if you know a conserved quantity (energy in this case), is to use a change of variables in which that quantity is one of the new variables.  In this case with $E = y_2^2/2 - \cos(y_1)$, you know that the
solution curves should be closed curves around the origin (at which $E=-1$),
so you can write $E + 1 = y_2^2/2 + 2\sin^2(y_1/2)$.  Then with
$\theta$ defined by $ \cos(\theta) = \sqrt{2/(E+1)} \sin(y_1/2)$ and $\sin(\theta) = y_2/\sqrt{2(E+1)}$ I get (if I haven't made any mistakes)
$$ \dot{\theta} = -\sqrt{1 - (E+1)\cos^2(\theta)/2}$$
So you solve that differential equation and take $y_1 = 2 \arcsin(\sqrt{(E+1)/2} \cos(\theta))$ and $y_2 = \sqrt{2(E+1)} \sin(\theta)$.


text:
Q: average on dataframe segments In the following picture, I have DataFrame that renders zero after each cycle of operation (the cycle has random length). I want to calculate the average (or perform other operations) for each patch. For example,  the average of [0.762, 0.766] alone, and [0.66, 1.37, 2.11, 2.29] alone and so forth till the end of the DataFrame.

A: So I worked with this data :
    random_value
0   0
1   0
2   1
3   2
4   3
5   0
6   4
7   4
8   0
9   1

There is probably a way better solution, but here is what I came with :
def avg_function(df):
    avg_list = []
    value_list = list(df["random_value"])
    temp_list = []
    for i in range(len(value_list)):
        if value_list[i] == 0:
            if temp_list:
                avg_list.append(sum(temp_list) / len(temp_list))
                temp_list = []
        else:
            temp_list.append(value_list[i])
    if temp_list:  # for the last values
        avg_list.append(sum(temp_list) / len(temp_list))
    return avg_list

test_list = avg_function(df=df)
test_list

[Out] : [2.0, 4.0, 1.0]

Edit: since requested in the comments, here is a way to add the means to the dataframe. I dont know if there is a way to do that with pandas (and there might be!), but I came up with this :
def add_mean(df, mean_list):
    temp_mean_list = []
    list_index = 0  # will be the index for the value of mean_list

    df["random_value_shifted"] = df["random_value"].shift(1).fillna(0)
    random_value = list(df["random_value"])
    random_value_shifted = list(df["random_value_shifted"])

    for i in range(df.shape[0]):
        if random_value[i] == 0 and random_value_shifted[i] == 0:
            temp_mean_list.append(0)
        elif random_value[i] == 0 and random_value_shifted[i] != 0:
            temp_mean_list.append(0)
            list_index += 1
        else:
            temp_mean_list.append(mean_list[list_index])
    df = df.drop(["random_value_shifted"], axis=1)
    df["mean"] = temp_mean_list
    return df

df = add_mean(df=df, mean_list=mean_list

Which gave me :
df

[Out] :
    random_value    mean
0   0               0
1   0               0
2   1               2
3   2               2
4   3               2
5   0               0
6   4               4
7   4               4
8   0               0
9   1               1


text:
Q: Unicorn + nginx - upstream prematurely closed connection while reading response header from upstream -504 Gateway Timeout I'm getting 504 Gateway Timeout error message in browser when I am trying to download the records in excel format. As I did the investigation about this, there was a timeout issue when the query execution is going long. Hence, I have changed the unicorn workers timeout value to 240 (even I tested with 1000+) and nginx proxy_*_timeout values from 300 to 600. But, again failed.
My implementation is to export the user details as excel format but I'm calculating everything on the fly only. Four queries should be run for exporting single record. So, I'm trying 8000 records for testing.

8000 (records) * 4 (queries) = 32000 queries

If you have any other idea to export long run query result in excel, please let me know. thx.
PFB for the configuration and error details.
unicorn.rb
worker_processes 4
working_directory "/home/mrblack/myproject" # available in 0.94.0+
listen "/home/mrblack/myproject/tmp/.unicorn.sock", :backlog => 64
timeout 240

pid "/home/mrblack/myproject/tmp/unicorn.pid"

stderr_path "/home/mrblack/myproject/log/unicorn.stderr.log"
stdout_path "/home/mrblack/myproject/log/unicorn.stdout.log"

preload_app true
GC.respond_to?(:copy_on_write_friendly=) and
  GC.copy_on_write_friendly = true

check_client_connection false

before_fork do |server, worker|
  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.connection.disconnect!
end

after_fork do |server, worker|

  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.establish_connection
end

nginx-conf
user              ngnix;
worker_processes  1;
error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;
timer_resolution  500ms;

worker_rlimit_nofile 10240;
events {
    use epoll;
    worker_connections 10240;
}

http {
    add_header X-Frame-Options SAMEORIGIN;
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    server_name_in_redirect off;
    server_tokens           off;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile       on;
    tcp_nopush     on;

    keepalive_timeout  70s;
    tcp_nodelay        off;

    client_body_timeout   60s;
    client_header_timeout 60s;

    client_header_buffer_size 128;
    client_max_body_size      8m;

    open_file_cache           max=1000 inactive=20s;
    open_file_cache_valid     30s;
    open_file_cache_min_uses  2;
    open_file_cache_errors    on;

    proxy_cache_path  /var/cache/nginx/  levels=1:2   keys_zone=cache:80m inactive=1d  max_size=2500m;
    proxy_cache_key   "$scheme$request_method$host$request_uri";
    proxy_cache       cache;

#    proxy_temp_path   /var/lib/nginx/proxy;

    proxy_cache_valid  200 302  1d;
    proxy_cache_valid  301      1d;
    proxy_cache_valid  any      1m;

    #proxy_ignore_headers  "X-Accel-Redirect" "X-Accel-Expires" "Expires" "Cache-Control" "Set-Cookie";

    proxy_connect_timeout 600s;
    proxy_send_timeout    600s;
    proxy_read_timeout    600s;
    send_timeout          600s;

    proxy_buffer_size           32k;
    proxy_buffers               4 32k;
    proxy_busy_buffers_size     32k;
    proxy_temp_file_write_size  32k;

    gzip              on;
    gzip_http_version 1.0;
    gzip_disable      "MSIE [1-6]\.(?!.*SV1)";

    gzip_buffers    4 16k;
    gzip_comp_level 2;
    gzip_min_length 0;

    gzip_types    text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_proxied  expired no-cache no-store private auth;

    # Load config files from the /etc/nginx/conf.d directory
    # The default server is in conf.d/default.conf
    include /etc/nginx/conf.d/*.conf;

    upstream app_server {
      server unix: /home/mrblack/myproject/tmp/.unicorn.sock;
    }

    server {
        listen 80;
        add_header X-Frame-Options "DENY";
        client_max_body_size 4G;
        server_name localhost;
        keepalive_timeout 5;
        root /home/mrblack/myproject/public;
        try_files $uri/index.html $uri.html $uri @app;
        location @app {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass http://app_server;
        }

        error_page 500 502 503 504 /500.html;
        location = /500.html {
            root /home/mrblack/myproject/public;
        }
    }

}

unicorn-stderr
I, [2014-08-04T15:11:47.966332 #30951]  INFO -- : listening on addr=/home/mrblack/myproject/tmp/.unicorn.sock fd=10
I, [2014-08-04T15:11:47.992843 #30970]  INFO -- : worker=0 ready
I, [2014-08-04T15:11:47.998725 #30951]  INFO -- : master process ready
I, [2014-08-04T15:11:48.002149 #30973]  INFO -- : worker=1 ready
I, [2014-08-04T15:11:48.013117 #30976]  INFO -- : worker=2 ready
I, [2014-08-04T15:11:48.015180 #30979]  INFO -- : worker=3 ready
E, [2014-08-04T15:17:16.262433 #30951] ERROR -- : worker=0 PID:30970 timeout (61s > 60s), killing
E, [2014-08-04T15:17:16.363226 #30951] ERROR -- : reaped #<Process::Status: pid 30970 SIGKILL (signal 9)> worker=0
I, [2014-08-04T15:17:16.384091 #31476]  INFO -- : worker=0 ready

ngnix-error

upstream prematurely closed connection while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET /users/download_excel.xls?sEcho=1&iColumns=7&sColumns=c0%2Cc1%2C%2C%2C%2C%2C&iDisplayStart=0&iDisplayLength=10&mDataProp_0=0&mDataProp_1=1&mDataProp_2=2&mDataProp_3=3&mDataProp_4=4&mDataProp_5=5&mDataProp_6=6&sSearch=&bRegex=false&sSearch_0=&bRegex_0=false&bSearchable_0=true&sSearch_1=&bRegex_1=false&bSearchable_1=true&sSearch_2=&bRegex_2=false&bSearchable_2=true&sSearch_3=&bRegex_3=false&bSearchable_3=true&sSearch_4=&bRegex_4=false&bSearchable_4=true&sSearch_5=&bRegex_5=false&bSearchable_5=true&sSearch_6=&bRegex_6=false&bSearchable_6=true&iSortCol_0=1&sSortDir_0=asc&iSortingCols=1&bSortable_0=true&bSortable_1=true&bSortable_2=true&bSortable_3=false&bSortable_4=false&bSortable_5=true&bSortable_6=false HTTP/1.1", upstream: "/home/mrblack/myproject/tmp/.unicorn.sock:/users/download_excel.xls?sEcho=1&iColumns=7&sColumns=c0%2Cc1%2C%2C%2C%2C%2C&iDisplayStart=0&iDisplayLength=10&mDataProp_0=0&mDataProp_1=1&mDataProp_2=2&mDataProp_3=3&mDataProp_4=4&mDataProp_5=5&mDataProp_6=6&sSearch=&bRegex=false&sSearch_0=&bRegex_0=false&bSearchable_0=true&sSearch_1=&bRegex_1=false&bSearchable_1=true&sSearch_2=&bRegex_2=false&bSearchable_2=true&sSearch_3=&bRegex_3=false&bSearchable_3=true&sSearch_4=&bRegex_4=false&bSearchable_4=true&sSearch_5=&bRegex_5=false&bSearchable_5=true&sSearch_6=&bRegex_6=false&bSearchable_6=true&iSortCol_0=1&sSortDir_0=asc&iSortingCols=1&bSortable_0=true&bSortable_1=true&bSortable_2=true&bSortable_3=false&bSortable_4=false&bSortable_5=true&bSortable_6=false", host: "localhost", referrer: "localhost/users/members"


text:
Q: get facebook user's display pic with cover pic into iphone i wish to display a facebook user's friends' dp along with their respective cover pic. I am successful in fetching the dp only by the following code:
NSString *imgUrl = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture",[[data objectAtIndex:i ] objectForKey:@"id"]];
    NSData *mydata = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];

output:

but i wish to have an output like below: [WITHOUT THE UPDATE INFO AND ACTIVITY LOG BUTTONS]

How do i do this? I mean what do i need to change in the url to achieve the desired putput?

A: Call the url https://graph.facebook.com/kingofbliss?fields=cover
where kingofbliss is my user id ;)
will return the data,
{
   "cover": {
      "id": "379218405451233",
      "source": "http://sphotos-b.ak.fbcdn.net/hphotos-ak-ash3/s720x720/579338_379218405451233_1152151936_n.jpg",
      "offset_y": 0
   },
   "id": "100000892310267"
}

The source has the url for cover image. Then proceed further...!!!


text:
Q: Mysql structure for something like Facebook I'm thinking of starting a facebook style website with bio pages, friend requests etc, roughly what sort of database tables would be advisable?
Ie. Users, status?
A rough list would help?
Thanks

A: Everything about FB is people so you would definitely need a Person table with self-referencing many-to-many relationship.  You would really want to do this with PHP ORM such as doctrine, and it will greatly simplify your life.
Person:
 id: int,
 name: string
RelatedPerson:
 person_id: int,
 related_person_id: int,
 relationship_id: int
Relationship:
 id: int,
 name: string
There are many more tables, but sorry I can't list them all.  A piece of advise is that everything should be around people. What exact thing you are planning to do?

A: I'm going to have to agree with Dmitri on this one.
When mysql databases reach a certain size it can get VERY hard to make it run as fast and smooth as Facebook (sometimes) does.
As to your question, you're going to need at least users, users-friends, status, friend-requests and so on. I'd recommend starting out small.

A: If/when you site grows to millions or records, you will find that mysql is your worst enemy. Facebook has already been there, they started with Mysql then switch to Cassandra. If you want to write your Facebook, then do a research to see how/what facebook is using. They are actually pretty open about it, they open source Cassandra, which Twitter now uses also.
My advice will be to NOT use MySQL at all, it's a ticking time bomb. What I mean is it starts off wonderfully, fast, happy times. Then as your database grows in size you will find youself in never-ending optimization battle against MySQL, the battle you can't win.


text:
Q: Stuck with WMP in C# I want to fetch 5 media files from a Directory [not with dialog box] and play with axwindowsmediaplayer in C# one after one. Songs to be played as playlist.
I am new to C#.
private void Form1_Load(object sender, EventArgs e)
{
    /*
    foreach(string dir in Directory.GetDirectories(@"E:\\Project"))
    {
        DirectoryInfo info = new DirectoryInfo(dir);
        this.listBox1.Items.Add(info.Name);
    }
    foreach(string file in Directory.GetFiles("E:\\Project\\Surprise"))
    {
        FileInfo FileInfo = new FileInfo(file);
        this.listBox1.Items.Add(FileInfo.Name);
    }
    */
    string path = @"E:\\Project\\Surprise";
    foreach (string s in Directory.GetFiles(path, "*.mp4").Select(Path.GetFileName))
        listBox1.Items.Add(s);
    listBox1.SelectedItems.Clear();
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    axWindowsMediaPlayer1.URL = listBox1.SelectedItem.ToString();
    axWindowsMediaPlayer1.Ctlcontrols.play();
}


text:
Q: Why am i getting curly braces in the my function even though the dom render the correct values I'm trying to get my function work, I need to pass a parameter so that's why I'm using curly braces, the problem is, I'm getting the curly braces in my JS function as a string the strange thing is that all values are rendering correct in the dom
what Im getting in my JS function (console):
{{relative.name}}{{desease.name}}
what the dom rendered:

                                                                        <input
                                                                            ng-model="isChecked"
                                                                            ng-init="isChecked = iterator('{{relative.name}}{{desease.name}}') !== undefined"
                                                                            class="custom-control-input"
                                                                            name="{{relative.name}}{{desease.name}}"
                                                                            id="{{relative.name}}{{desease.name}}"
                                                                            type="checkbox"
                                                                            ng-change="inheritedDiseasesFunction(relative.name, desease.name)"
                                                                            >

$scope.iterator = (id) => {
        console.log(id);
        return $scope.inheritedDiseases.find( x => x.id === id);
    };


text:
Q: What would be the opposite of delighted? On a scale/axis that represents emotional response with regard to satisfaction, what would be the opposite of "delighted"?

*

*delighted

*satisfied

*neutral

*dissatisfied

*???

If it helps, a paper on measuring satisfaction in banking says this about "delight":

Traditionally, delight has been thought of a blend of joy and surprise (Kumar, Olshavsky, & King, 2001). However, a recent study suggested that customer can be delighted without being surprised (Kumar et al., 2001). Although joy remains an important element of delight, the study explained that a greater number of people are exhilarated, thrilled and to a lesser extent exuberant (Kumar et al).
Satisfied customers are purely at ease. Delighted customers on the other hand have greater admiration for the firm and its services. Paul (2000, p. 34) stated 'Unfortunately, people don't talk about adequate service. Instead, they tell anyone who will listen about really bad or really delightful services'.

There are of course many antonyms in the dictionary to choose from – what I'm after is the most appropriate/apt choice given the context.
I am of course looking for a single word and not a phrase as I'll be using it as a marker on the axis/scale (and all the other points are single-words).
There's a survey instrument that collects data which can then be plotted on a graph, with one axis of "a scale/axis that represents emotional response with regard to satisfaction". So, the broader context is in commerce/marketing/product-design (vs. say literature).

A:
Dismay
  [dis-mey]
  /verb (used with object)

*to surprise in such a manner as to disillusion.

*to alarm; perturb.
/noun

*sudden disillusionment.

*agitation of mind; perturbation; alarm.
Source: Dictionary.com


text:
Q: 'builtin_function_or_method' object is not subscriptable on Python
result=[]
taken=[]
for i in range(len(pos[0])):
    taken.append[pos[0][i]]

I get not subscriptable error on the 'taken.append'. I declared taken as an empty array, but the it seems like the computer took it as an int.


text:
Q: Included mysqli_connect inside a function fails, why? I've seen a few people with this same issue, yet none of the answers solved my problem. This is what I have in three files:
index.php:
 $dbconnect = connectDB("mydb","connect");
 mysqli_query($dbconnect,"INSERT INTO `mytable` (field1,field2) values ('value 1','value 2')");
 connectDB("","kill",$dbconnect);

functions.php
 function connectDB($db_name,$connectorkill,$link) { include('connectDB.inc.php'); }

connectDB.inc.php
 $host="localhost";
 $user="myusername";
 $pass="mypassword";
 if($connectorkill == "connect") {
 if($dblink = mysqli_connect($host, $user, $pass, $db_name)) {
 echo "dblink created.";
  return $dblink;
 } else { echo "Error connecting to database."; }
 } elseif($connectorkill == "kill") { mysqli_close($link); }

and what I get is:
 Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/username/public_html/members/index.php on line 2

which looks like the connectDB function is not doing its job, specifically the return of the $dblink variable in connectDB.inc.php. I went ahead and moved the code from connectDB.inc.php to inside the functions.php and it solved the problem, but I don't want it set up that way. Is there a way to solve this error?

A: Two solutions:
Solution 1: Refractor your code, something along the lines of:
config.php:
$config = array(
    "databases" => array(
        "my_database" => array(
            "host"  =>  "localhost",
            "user"  =>  "myusername",
            "pass"  =>  "mypassword"
        )
    )
);

functions.php:
require("config.php");

function connectDB($dbname)
{
    global $config;

    if (!isset($config["databases"][$dbname]))
        return; // error, database info not in $config

    $dbc = $config["databases"][$dbname];

    $dbcon = mysqli_connect($dbc["host"], $dbc["user"], $dbc["pass"], $dbname);
    if (!$dbcon)
        return; // unable to connect error goes here

    return $dbcon;
}

Note that this is just the bare minimum of a connectDB function. There really should be more error checking in there (for example, on each of the $dbc keys. It also needs proper error reporting and such, this is just a general hint in the right direction.
Solution 2: Add return in front of your include...
function connectDB($db_name,$connectorkill,$link) { return include('connectDB.inc.php'); }

Regardless of the solution: You really need some error checking code in your index.php because no matter what you do: Your connectDB function isn't always going to return a valid database connection.


text:
Q: How to make a object accessible through all files in C# I have a class object which i want to access in all the files in c# project
Ofcourse i dont want 'static' qualifiers because i want to serialize this object finally.

A: Make the class public.
You should then be able to create instances wherever you need.
If you want a single instance to be accessible throughout your entire project, I would suggest checking out the Singleton pattern.

A: If you want to you to use only one instance of this class - use one of the most popular pattern Singleton:
http://msdn.microsoft.com/en-us/library/ff650316.aspx
using System;

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}


text:
Q: Trying to implement parallax scroll view in flutter but its is not reflecting in the UI I am trying to implement a parallax effect in the flutter web and have followed up the procedure to bring that effect in it but it seems it is not reflecting in the UI as expected.
I tried adding all the necessary stuffs but still the effect is not showing up.
I added all the positioned widgets, declared variables as topOne and topTwo, added the notification listener.
Here's my code snippet:
    body: SingleChildScrollView(
            child: NotificationListener(
              onNotification: (v) {
                if (v is ScrollUpdateNotification) {
                  setState(() {
                    topOne = topOne - v.scrollDelta / 3;
                    topTwo = topTwo - v.scrollDelta / 1;
                  });
                }
              },
              child: SafeArea(
                child: Column(
                  children: [
                    Stack(
                      children: [

                        NavBar(
                          h: h / 1.2,
                          w: w / 1,
                          sel0: false,
                          sel1: false,
                          sel2: true,
                          sel3: false,
                          sel4: false,
                        )
                      ],
                    ),
                    SizedBox(
                      height: h / 12,
                    ),
                    Container(
                      height: h / 1,
                      width: w / 1,
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter,
                            colors: [
                              Colors.transparent,
                              Colors.grey[100],
                              AppColors.getWhite(),
                            ]),
                      ),
                      child: Stack(
                        children: [
                          Positioned(
                            top: 30,
                            left: 30,
                            child: Text(
                              'F L EX',
                              style:
                                  TextStyle(fontSize: 500, color: Colors.white),
                            ),
                          ),
                          Positioned(
                            top: topOne, //I wanted this to move in the normal speed
                            left: 100,
                            child: Container(
                              height: h / 1.1,
                              width: w / 1.2,
                              decoration: BoxDecoration(color: Colors.white,
                                  // borderRadius: BorderRadius.circular(8),
                                  boxShadow: [
                                    BoxShadow(
                                      color: AppColors.getGrey(),
                                      blurRadius: 60.0,
                                    ),
                                  ]),
                            ),
                          ),
                          Positioned(
                            top: 80,
                            left: 150,
                            child: RotationTransition(
                              turns: new AlwaysStoppedAnimation(50 / 360),
                              child: Container(
                                height: h / 6,
                                width: w / 12,
                                decoration: BoxDecoration(
                                    border: Border.all(
                                        color: AppColors.getGrey(), width: 4)),
                              ),
                            ),
                          ),
                          Positioned(
                            top: topTwo, // I wanted this to move slow than the above
                            left: 200,
                            child: Text(
                              'WE DO IT ALL.',
                              style: GoogleFonts.roboto(
                                  fontSize: 30,
                                  fontWeight: FontWeight.normal,
                                  color: AppColors.getBlack()),
                            ),
                          ),


text:
Q: Do custom price logic during ordering based on customer's choices of options? I'm new to Magento.  What I need is to calculate a new base price for an item, depending on the options chosen when ordering/adding to cart.
Example:
Customer chooses a cable.  Customer picks 4, 8, or 12 cores.  Customer specifies a length between 1 and 1000m.  The core option will affect the price per meter, which is why I need to do some custom logic when ordering to update the base price (unless there's some way to do this in stock Magento + Advanced Product Options extension).
So my plan was to create a "core" option, with child "length" options for each core option.  These length children will use the price field for the price per meter.  Then when ordering, I would use the child of the selected core option to get the price per meter and math to apply the price per meter to the input length amount.  Then update the base price for the item.
Would something like this work?  Any suggestions of going about doing this?  I don't expect a full tutorial, just something to point in the right direction because I'm a little overwhelmed with the way Magento's codebase is structured.
Update: I've discovered the _applyOptionsPrice method in Catalog\Model\Product\Type\Price.php
However, changes to this do not seem to affect the final price... Is there something else I need to do?


text:
Q: Covariance of derivative of Gaussian Process Regression There are a quite a few questions and answers which discuss how to calculate the gradients/derivatives of the posterior of Gaussian Process Regression (see here, here). These include the equations for calculating the mean but the calculation of the covariance is less clear. How can we calculate the covariance of the gradient?

A: You may find McHutchon (2013) useful; everything you need is there, but in case the link goes dead, I'll put a streamlined version here.
As you noted, multiple answers here cover
$$
\mathbb{E} \left[ \frac{\partial \mathbf{f}_\ast}{\partial \mathbf{x}_\ast} \right] = \frac{\partial k\left(\mathbf{x}_\ast, \mathbf{X}\right)}{\partial \mathbf{x}_\ast} K^{-1} \mathbf{y},
$$
but how do we get
$$
\mathbb{V} \left[ \frac{\partial \mathbf{f}_\ast}{\partial \mathbf{x}_\ast} \right]?
$$
We consider an additional test point $\mathbf{x}_\ast + \boldsymbol\delta$. Then
\begin{align}
f \left( \mathbf{x}_\ast \right) & = \bar{f} \left( \mathbf{x}_\ast \right) + \mathbf{z}_\ast \\
f \left( \mathbf{x}_\ast  + \boldsymbol\delta \right) & = \bar{f} \left( \mathbf{x}_\ast  + \boldsymbol\delta \right) + \mathbf{z}_\delta \\
\end{align}
and
$$
\begin{bmatrix}
    \mathbf{z}_\ast \\
    \mathbf{z}_\delta
\end{bmatrix}
\sim
\mathcal{N}
\left(
    \mathbf{0},
    \begin{bmatrix}
        k_{\ast\ast} - \mathbf{k}_\ast^T K^{-1} \mathbf{k}_\ast
        & k_{\ast\delta} - \mathbf{k}_\ast^T K^{-1} \mathbf{k}_\delta \\
        k_{\delta\ast} - \mathbf{k}_\delta^T K^{-1} \mathbf{k}_\ast
        & k_{\delta\delta} - \mathbf{k}_\delta^T K^{-1} \mathbf{k}_\delta \\
    \end{bmatrix}
\right).
$$
Taking the limit as $\boldsymbol\delta \to \mathbf{0}$,
\begin{align}
\frac{\partial \mathbf{f}_\ast}{\partial \mathbf{x}_\ast}
& =
\lim_{\boldsymbol\delta \to \mathbf{0}} \frac{f \left( \mathbf{x}_\ast  + \boldsymbol\delta \right) - f \left( \mathbf{x}_\ast \right)}{\mathbf{x}_\ast + \boldsymbol\delta - \mathbf{x}_\ast} \\
& =
\frac{\partial \bar{\mathbf{f}}_\ast}{\partial \mathbf{x}_\ast}
+
\lim_{\boldsymbol\delta \to \mathbf{0}} \frac{\mathbf{z}_\delta - \mathbf{z}_\ast}{\boldsymbol\delta},
\end{align}
we find
$$
\mathbb{V} \left[ \lim_{\boldsymbol\delta \to \mathbf{0}} \frac{\mathbf{z}_\delta - \mathbf{z}_\ast}{\boldsymbol\delta} \right]
=
\mathbb{V} \left[ \frac{\partial \mathbf{f}_\ast}{\partial \mathbf{x}_\ast} \right]
=
    \frac{\partial^2 k \left(\mathbf{x}_1^\ast, \mathbf{x}_2^\ast \right)}{\partial \mathbf{x}_1^\ast \partial \mathbf{x}_2^\ast}
    -
    \frac{\partial k \left(\mathbf{x}_\ast, \mathbf{X} \right)}{\partial \mathbf{x}_\ast}
    K^{-1}
    \frac{\partial k \left(\mathbf{x}_\ast, \mathbf{X} \right)}{\partial \mathbf{x}_\ast}^T .
$$
Please note that in
$$
\frac{\partial^2 k \left(\mathbf{x}_1^\ast, \mathbf{x}_2^\ast \right)}{\partial \mathbf{x}_1^\ast \partial \mathbf{x}_2^\ast},
$$
$\mathbf{x}_1^\ast = \mathbf{x}_2^\ast = \mathbf{x}_\ast$,
but we must do it in this cross-partial way to avoid negatives on the diagonal.
All credit for this presentation of the derivation goes to McHutchon (2013), like I say, I simply reproduce relevant parts here for completeness of the answer.


text:
Q: Install Android application silently Over-The-Air like Google Play does I need to install apk file without any user prompt like Google PlayStore does.
I know this question has been asked many times but still i didn't found any solvable answer.
I am just installing app from my sdcard and i tried following way,
public void getInstall(Context context) {

        File file = new File(Environment.getExternalStorageDirectory()
                + "/Demo.apk");
        Uri mPackageURI = Uri.fromFile(file);

        ApplicationManager appMgr = null;

        try {
            appMgr = new ApplicationManager(context);
        } catch (SecurityException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchMethodException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        int installFlags = 1;
        PackageManager pm = context.getPackageManager();

        Method method = null;

        try {
            method = pm.getClass().getMethod(
                    "installPackage",
                    new Class[] { android.net.Uri.class,
                            android.content.pm.IPackageInstallObserver.class,
                            Integer.TYPE, String.class });
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String installerPackageName = "com.myapp.demo";
        PackageInstallObserver observer = appMgr.new PackageInstallObserver();

        try {

            method.invoke(pm, new Object[] { mPackageURI, observer,
                    installFlags, installerPackageName });

        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

But I am getting error Neither user 10057 nor current process has android.permission.INSTALL_PACKAGES even though i added this permission in my manifest file.
My device is not rooted and i want it to do without rooting , In many answers i found that it is not possible as per security reason they are not allowing but if it is possible with PlayStore and AndroidLost app then why not with us?
Please i need help if it is possible !
Thank you,

A:
My device is not rooted and i want it to do without rooting

This is not possible on Android for third party apps. Google Play is able to do it because it is installed to /system/app instead of /data/app. If you can convince any OEM or ROM maker to have your app on the system partition, you can utilize the INSTALL_PACKAGES permission, as that is only granted to system apps.
In any case, this is an Android anti pattern. If you were allowed to arbitrarily install apps without user consent, it would be a serious security hole, and the user would no longer be in charge of the device.


text:
Q: What Is this the correct way of Testing RESTFUL Web Service and How do I increase my code coverage Below I have a REST API Im trying to test. I seem to have 69% Using the test class I have set up. Is this the correct way of testing my API and if so how do I increase the code coverage here. I read something about creating sample data within the test class itself and doing the test. I dont know if it applies here or not.
Here is my API
@RestResource(urlMapping = '/candidate/*')
global with sharing class RESTCandidateController {
    @HttpPost
    global static Id postCandidate() {
        RestRequest req = RestContext.request;
        String jid = req.params.get('jid');
        RestResponse response = RestContext.response;
        String JSONBody = req.requestBody.toString();
        //Variables
        PCandidate c;
        Contact contact; Job__c job; Qualification__c qualification; Candidate__c candidate;
        Job_Requisition__c jobRequisition;
        if (jid != null) {
            JSONBody = JSONBody.replace('"currency"', '"currency_x"');
            JSONParser parser = JSON.createParser(JSONBody);
            while (parser.nextToken() != null) {
                if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                    if (parser.getCurrentName() == null) {
                        c = (PCandidate)parser.readValueAs(PCandidate.class);
                    }
                }
            }
            if (c != null) {
                contact = createContact(c);
                try {
                    candidate = new Candidate__c(
                        candidate__c = contact.Id,
                        Job_Requisition__c = [SELECT Id FROM Job_Requisition__c WHERE nid__c =: jid].Id
                    );
                    insert candidate;
                } catch (DmlException e) {
                    for (Integer m = 0; m < e.getNumDml(); m ++) {
                        System.debug(e.getDmlMessage(m));
                    }
                }
            }
        }
        return contact.Id;
    }

    private static Contact createContact(PCandidate c) {
        Contact contact; Job__c job; Qualification__c qualification;
        Map<String, Schema.SObjectField> fieldObjectMap = schema.SObjectType.Contact.Fields.getMap();
        List<Schema.SObjectField> fieldObjectMapValues = fieldObjectMap.values();
        String query = 'SELECT ';
        if (c != null) {
            try {
                contact = new Contact();
                if (c.email != null) {contact.Email = c.email;}
                if (c.fName != null) {contact.FirstName = c.fName;}
                if (c.mName != null) {contact.MiddleName = c.mName;}
                if (c.lName != null) {contact.LastName = c.lName;}
                if (c.maidenName != null) {contact.maidenName__c = c.maidenName;}
                if (c.dob != null) {contact.Birthdate = c.getDob();}
                if (c.gender != null) {contact.gender__c = c.gender;}
                if (c.idNumber != null) {contact.idNumber__c = c.idNumber;}
                if (c.passportNumber != null) {contact.passportNumber__c = c.passportNumber;}
                if (c.race != null) {contact.race__c = c.race;}
                if (c.nationality != null) {contact.nationality__c = c.nationality;}
                if (c.about != null) {contact.about__c = c.about;}
                if (c.interests != null) {contact.interests__c = c.interests;}
                if (c.location != null) {contact.MailingStreet = c.location.street1 + ', ' + c.location.suburb;
                    contact.MailingCity = c.location.city;
                    contact.MailingState = c.location.province;
                    contact.MailingPostalCode = c.location.postalCode;
                    contact.MailingCountry = c.location.country;}
                if (c.tel != null) {contact.Phone = c.tel;}
                if (c.cell != null) {contact.MobilePhone = c.cell;}
                if (c.careerObjectives != null) {contact.careerObjectives__c = c.careerObjectives;}
                if (c.currentJob != null) {contact.currentEmployer__c = c.currentJob.employer;
                    contact.currentPosition__c = c.currentJob.position;}
                if (c.highestQualification != null) {contact.highestQualification__c = c.highestQualification;}
                if (c.skills != null) {contact.skills__c = c.stringSkills();}
                if (c.personality != null) {contact.personality__c = c.stringPersonality();}
                if (c.languages != null) {contact.languages__c = c.stringLanguagesPicklist();}
                if (c.seeking != null) {contact.seekingPositions__c = c.seeking.stringPositions();
                    contact.seekingType__c = c.seeking.type;
                    contact.seekingSalaryCurrency__c = c.seeking.salary.currency_x;
                    contact.seekingSalaryAmount__c = Decimal.valueOf(c.seeking.salary.amount);
                    contact.seekingSalaryType__c = c.seeking.salary.type;}
                if (c.relocation != null) {contact.relocation__c = Boolean.valueOf(c.relocation);}
                if (c.social != null) {contact.facebook__c = c.social.facebook;
                    contact.twitter__c = c.social.twitter;
                    contact.linkedIn__c = c.social.linkedIn;
                    contact.gtalk__c = c.social.gtalk;
                    contact.skype__c = c.social.skype;}
                if (c.homepage != null) {contact.homepage__c = c.homepage;}
                if (c.blog != null) {contact.blog__c = c.blog;}
                if (c.disabled != null) {contact.disabled__c = Boolean.valueOf(c.disabled);}
                if (c.source != null) {contact.source__c = c.source;}
                if (c.achievements != null) {contact.achievements__c = c.achievements;}
                if (c.noticePeriod != null) {contact.noticePeriodNumber__c = c.noticePeriodNumber();
                    contact.noticePeriodType__c = c.noticePeriodPeriod();}
                if (c.id != null) {contact.id__c = c.id;}
                insert contact;
                //Job History
                if (c.jobHistory != null) {
                    fieldObjectMap = schema.SObjectType.Job__c.Fields.getMap();
                    fieldObjectMapValues = fieldObjectMap.values();
                    query = 'SELECT ';
                    for (Schema.SObjectField s : fieldObjectMapValues) {
                        String name = s.getDescribe().getName();
                        query += name + ', ';
                    }
                    query = query.subStringBeforeLast(',');
                    query += ' FROM Job__c WHERE contact__c = \'' + contact.Id + '\'';
                    List<Job__c> currentJobs = Database.query(query);
                    if (currentJobs.size() == 0) {
                        for (Integer i = 0; i < c.jobHistory.size(); i ++) {
                            try {
                                //Create new Job

                                job = new Job__c(
                                    contact__c = contact.Id,
                                    employer__c = c.jobHistory[i].employer,
                                    position__c = c.jobHistory[i].position,
                                    industry__c = c.jobHistory[i].industry,
                                    type__c = c.jobHistory[i].type,
                                    fromDate__c = c.jobHistory[i].getFromDate(),
                                    toDate__c = c.jobHistory[i].getToDate(),
                                    duties__c = c.jobHistory[i].duties,
                                    reasonForChange__c = c.jobHistory[i].reasonForChange
                                );
                                insert job;
                            } catch (DmlException e) {
                                for (Integer j = 0; j < e.getNumDml(); j ++) {
                                    System.debug(e.getDmlMessage(j));
                                }
                            }
                        }
                    } else {
                        for (Job__c currentJob : currentJobs) {
                            for (Integer k = 0; k < c.jobHistory.size(); k++) {
                                if (currentJob.employer__c.equals(c.jobHistory[k].employer) &&
                                    currentJob.position__c.equals(c.jobHistory[k].position) &&
                                    currentJob.industry__c.equals(c.jobHistory[k].industry) &&
                                    currentJob.type__c.equals(c.jobHistory[k].type) &&
                                    currentJob.fromDate__c.format().equals(c.jobHistory[k].getFromDate().format()) &&
                                    currentJob.toDate__c.format().equals(c.jobHistory[k].gettoDate().format()) &&
                                    currentJob.reasonForChange__c.equals(c.jobHistory[k].reasonForChange)
                                ) {
                                    c.jobHistory.remove(k);
                                }
                            }
                        }
                        if (c.jobHistory.size() != 0) {
                            for (Integer l = 0; l < c.jobHistory.size(); l ++) {
                                try {
                                    //Create new Job
                                    job = new Job__c(
                                        contact__c = contact.Id,
                                        employer__c = c.jobHistory[l].employer,
                                        position__c = c.jobHistory[l].position,
                                        industry__c = c.jobHistory[l].industry,
                                        type__c = c.jobHistory[l].type,
                                        fromDate__c = c.jobHistory[l].getFromDate(),
                                        toDate__c = c.jobHistory[l].getToDate(),
                                        duties__c = c.jobHistory[l].duties,
                                        reasonForChange__c = c.jobHistory[l].reasonForChange
                                    );
                                    insert job;
                                } catch (DmlException e) {
                                    for (Integer m = 0; m < e.getNumDml(); m ++) {
                                        System.debug(e.getDmlMessage(m));
                                    }
                                }
                            }
                        }
                    }
                    update contact;
                }
                //Qualifications
                if (c.qualifications != null) {
                    fieldObjectMap = schema.SObjectType.Qualification__c.Fields.getMap();
                    fieldObjectMapValues = fieldObjectMap.values();
                    query = 'SELECT ';
                    for (Schema.SObjectField s : fieldObjectMapValues) {
                        String name = s.getDescribe().getName();
                        query += name + ', ';
                    }
                    query = query.subStringBeforeLast(',');
                    query += ' FROM Qualification__c WHERE contact__c = \'' + contact.Id + '\'';
                    List<Qualification__c> currentQualifications = Database.query(query);
                    if (currentQualifications.size() == 0) {
                        for (Integer i = 0; i < c.qualifications.size(); i++) {
                            try {
                                //Create new Qualification
                                qualification = new Qualification__c(
                                    contact__c = contact.Id,
                                    institution__c = c.qualifications[i].institution,
                                    achievement__c = c.qualifications[i].achievement,
                                    degreeLevel__c = c.qualifications[i].degreeLevel,
                                    achieved__c = c.qualifications[i].getAchieved()
                                );
                                insert qualification;
                            } catch (DmlException e) {
                                for (Integer j = 0; j < e.getNumDml(); j ++) {
                                    System.debug(e.getDmlMessage(j));
                                }
                            }
                        }
                    } else {
                        for (Qualification__c currentQualification : currentQualifications) {
                            for (Integer k = 0; k < c.qualifications.size(); k ++) {
                                if (currentQualification.institution__c.equals(c.qualifications[k].institution) &&
                                    currentQualification.achievement__c.equals(c.qualifications[k].achievement) &&
                                    currentQualification.degreeLevel__c.equals(c.qualifications[k].degreeLevel) &&
                                    currentQualification.achieved__c.format().equals(c.qualifications[k].getAchieved().format())
                                ) {
                                    c.qualifications.remove(k);
                                }
                            }
                        }
                        if (c.qualifications.size() != 0) {
                            for (Integer l = 0; l < c.qualifications.size(); l ++) {
                                try {
                                    //Create new Qualification
                                    qualification = new Qualification__c(
                                        contact__c = contact.Id,
                                        institution__c = c.qualifications[l].institution,
                                        achievement__c = c.qualifications[l].achievement,
                                        degreeLevel__c = c.qualifications[l].degreeLevel,
                                        achieved__c = c.qualifications[l].getAchieved()
                                    );
                                    insert qualification;
                                } catch (DmlException e) {
                                    for (Integer m = 0; m < e.getNumDml(); m ++) {
                                        System.debug(e.getDmlMessage(m));
                                    }
                                }
                            }
                        }
                    }
                    update contact;
                }
            } catch (DmlException e) {
                for (Integer i = 0; i < e.getNumDml(); i ++) {
                    System.debug(e.getDmlMessage(i));
                }
            }
        }
        return contact;
    }
}

And here is my test class
@isTest
private class RESTCandidateControllerTest {
    static testMethod void testPostCandidate() {
        RestRequest req = new RestRequest();
        req.addParameter('jid', '00000');
        req.addHeader('Content-Type', 'application/json');
        req.requestURI = 'https://cs80.salesforce.com/services/apexrest/candidate';
        req.httpMethod = 'POST';
        req.requestBody = Blob.valueOf('{"email":"joe58@example.com","fName":"Jan","lName":"Doe","maidenName":"Dingle","dob":"30/12/1990","gender":"female","idNumber":"9012305006058","passportNumber":"9012305006058","race":"Black","nationality":"RSA","about":"Lorem ipsum..","interests":"Lorem ipsum..","location":{"street1":"99 Acme street","suburb":"Lonehill","city":"Johannesburg","province":"Gauteng","postalCode":"2129","country":"South Africa"},"tel":"+27123123412","cell":"+27123123412","careerObjectives":"Lorem ipsum","currentJob":{"employer":"Acme Inc.","position":"Senior bottle washer"},"jobHistory":[{"employer":"Example Inc.","position":"Junior receptionist","industry":"Construction","type":"Permanent","fromDate":"12/2010","toDate":"01/2014","reasonForChange":"Lorem ipsum"}],"highestQualification":"BSc IT","qualifications":[{"institution":"University of life","achievement":"BSc IT","degreeLevel":"Diploma","achieved":"2012"}],"skills":["HTML","Coocking"],"presonality":["Friendly","Hardworking"],"languages":["English","Afrikaans"],"seeking":{"positions":["Accountant","Web developer"],"type":"Permanent","salary":{"currency_x":"ZAR","amount":"10000","type":"annual"}},"relocation":true,"social":{"facebook":"username","twitter":"username","linkedIn":"username","gtalk":"username","skype":"username"},"homepage":"http://www.example.com/homepage","blog":"http://www.example.com/homepage","disabled":true,"source":"test system","achievements":"lorem ipsum","noticePeriod":"30 days"}');

        RestResponse res = new RestResponse();
        RestContext.request = req;
        RestContext.response = res;
        RESTCandidateController.postCandidate();
    }
}

A: Your REST class queries Job__c and Qualification__c and does different things depending on whether values are found. So your test class will need to have test cases where you insert matching Job__c and Qualification__c as well as where you do not insert matching values to cover both cases before the postCandidate method is called. This should increase the code coverage a bit.
I think you should have currency in your test request body string not currency_x.
Rather than a literal string in your tests to specify the JSON, you can use the same objects that the REST class created from the JSON to build the test requests and then use JSON.serialize to turn that data into the JSON string. This makes it easier to create variations of the data.
As well as calling the postCandidate method, your tests should assert that the method has done what you expect by querying for changes and using multiple calls to methods like System.assertEquals.
It is not unusual for the tests class to be bigger than the class being tested because there may be many permutations of the inputs to check and many details to be checked in the results. To avoid unhelpful code duplication in the test class, you can use nested utility classes or helper methods shared by several test methods. You should look at the class you are testing and ensure that your tests cause most/all of the paths through the code to be taken. Achieving test coverage of about 90% is an indicator that you have pretty much done that.
In your REST class, this sort of error handling:
        } catch (DmlException e) {
            for (Integer i = 0; i < e.getNumDml(); i ++) {
                System.debug(e.getDmlMessage(i));
            }
        }

is just about never a good idea. A year from now no-one if going to be looking at the debug log but they are going to be wondering why the inserts and updates to the database are not handling. If the DmlException's are an unexpected error condition, return a status such as HTTP 400 and some explanatory information (collected from the DmlException) as the return value. (You will have to change the return type from ID to String to do that; the ID can still be returned with the String return type. And the caller needs to know to check the HTTP status and took for the error information in the response body.)


text:
Q: HttpClient connection issue to WebAPI hosted using Asp.NetCore TestServer In the unit Test cases, TestServer is used for in-memory hosting of the WebAPI. After this, we are trying to make HttpConnection to this hosted WebAPI using some code like this:
HttpClient client= new HttpClient();
client.BaseAddress("url");
client.GetAsync("url").Result();

This code gives an exception, with the error message

"Connection refused".

But if we get the HttpClient object using the below code and follow the above steps, it works fine.
TestServer.CreateClient()

What could be the reason behind it? Is it because it's an in-memory hosted WebAPI? No actual Http context is there??

A: That's by design. When you call TestServer.CreateClient() a client with special HttpMessageHandler is created. That handler allows to directly call APIs under test without exposing it as HTTP server:
public class TestServer : IServer, IDisposable
{
    public HttpClient CreateClient()
    {
        HttpClient httpClient = new HttpClient(this.CreateHandler());
        ...
    }
}

That should be faster and suitable enough for unit-testing. For integration testing, run a Kestrel server at test startup.
P.S. I hope your application design became better with DI instead of explicit building. That's nice you resolved the problem this way.