text:
Q: How to call Json Object from two Arrays using Volley I have below format json data:
[
  [
    {
      "jsonObject":"jsonObject",
      "jsonObject":"jsonObject",
      "jsonObject":"jsonObject"
    },
    {
      "jsonObject1":"jsonObject1",
      "jsonObject1":"jsonObject1",
      "jsonObject1":"jsonObject1"
    }
  ],
  [
    {
      "jsonObject2":"jsonObject2"
    },
    {
      "jsonObject2":"jsonObject2"
    }
  ]
]

How i get this json format and set into listview using volley i tried below code but i am not getting any object:
{
    JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, SUBSCRIPTION_Url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    if (response.equals("success")) {
                    } else {
                        try {
                            for (int i = 0; i < response.length(); i++) {

                                JSONArray ja = (JSONArray) response.get(i);
                                JSONObject jb = (JSONObject) ja.get(i);

                                title_array_sub.add(jb.getString("payment_id").toString());
                                notice_array_sub.add(jb.getString("period").toString());
                                title1_array_sub.add(jb.getString("renewal_date").toString());
                                notice1_array_sub.add(jb.getString("auto_renewal").toString());
                                invoice_array_sub.add(jb.getString("invoice").toString());
                                adapter1 = new CustomBaseAdapter(Transaction.this, title_array_sub, notice_array_sub,
                                        title1_array_sub, notice1_array_sub, invoice_array_sub);
                                list2.setAdapter(adapter1);
                            }

                        } catch (JSONException e1) {
                        } catch (ParseException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(KEY_MOVIE_ID, user_id);
                map.put(KEY_USER_ID, User_type);
                Log.d("movie_on_description", String.valueOf(map));
                return map;
            }
    };
    RequestQueue requestqueue = Volley.newRequestQueue(Transaction.this);
    requestqueue.add(request);
}

Please Help i also try without using loop and getting value in single string with 0 index and i am getting value but not getting values while using loop.
Thankyou

A: try this in onSuccess
    if (response.equals("success")) {
            } else {
                try {
                    for (int i = 0; i < response.length(); i++) {

                        JSONArray ja = response.getJsonArray(i);
                        for(int j=0;j<ja.length();j++){
                            JSONObject jb = ja.getJsonObject(j);

                            title_array_sub.add(jb.getString("payment_id").toString());
                            notice_array_sub.add(jb.getString("period").toString());
                            title1_array_sub.add(jb.getString("renewal_date").toString());
                            notice1_array_sub.add(jb.getString("auto_renewal").toString());
                            invoice_array_sub.add(jb.getString("invoice").toString());
                        }

                    }
    adapter1 = new CustomBaseAdapter(Transaction.this, title_array_sub, notice_array_sub, title1_array_sub, notice1_array_sub, invoice_array_sub);
                        list2.setAdapter(adapter1);
                } catch (JSONException e1) {

                } catch (ParseException e1) {
                    e1.printStackTrace();
                }
            }

and also you can use this link for json parsing

A: You keep making a new Adapter in your for loop and setting it to your listview. Move the creating and assigning outside of your for loop.
for (int i = 0; i < response.length(); i++) {
    JSONArray ja= (JSONArray) response.get(i);
    JSONObject jb = (JSONObject) ja.get(i);

    title_array_sub.add(jb.getString("payment_id").toString());
    notice_array_sub.add(jb.getString("period").toString());
    title1_array_sub.add(jb.getString("renewal_date").toString());
    notice1_array_sub.add(jb.getString("auto_renewal").toString());
    invoice_array_sub.add(jb.getString("invoice").toString());
}
adapter1 = new CustomBaseAdapter(Transaction.this, title_array_sub, notice_array_sub, title1_array_sub, notice1_array_sub,invoice_array_sub);
list2.setAdapter(adapter1);

Your response consists of more JSONArrays, to retrieve these use response.getJSONArray(Integer.valueOf(i))
Your JSONArrays consists of JSONObjects, you can loop through these objects again with
for (int i = 0; i < array.length(); i++) {
    JSONObject obj = array.getJSONObject(i);
    // do something
}

Look here for more examples: JSON Array iteration in Android/Java

A: It will be classified by two arrays 1) Array[0] and Array[1] . So in order of getting these json data i done this way:
         StringRequest strRequest = new StringRequest(Request.Method.POST, SUBSCRIPTION_Url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {

                                Log.d("responsetrans_sub",response);

                                if (response.trim().equals("success")) {

                                } else {

                                    try {
                                        JSONArray jsonObj = new JSONArray(response);

                                        JSONArray contacts =  jsonObj.getJSONArray(0);
                                        JSONArray contacts1 =  jsonObj.getJSONArray(1);
                                        for (int i = 0; i < contacts.length(); i++) {
                                            JSONObject contacting = contacts.getJSONObject(i);
                                            title_array_sub.add(contacting.getString("payment_id").toString());
                                            notice_array_sub.add(contacting.getString("period").toString());
                                            notice1_array_sub.add(contacting.getString("auto_renewal").toString());
                                            ivoice_array_sub.add(contacting.getString("invoice").toString());

                                        }
                                        for (int i = 0; i < contacts1.length(); i++) {

                                            JSONObject contacting1 = contacts1.getJSONObject(i);
                                            title1_array_sub.add(contacting1.getString("renewal_date").toString());

                                            adapter1 = new CustomBaseAdapter(Transaction.this, title_array_sub, notice_array_sub,title1_array_sub, notice1_array_sub,ivoice_array_sub);
                                            list_subscription.setAdapter(adapter1);

                                        }

                                    } catch (JSONException e1) {

                                    } catch (ParseException e1) {
                                        e1.printStackTrace();
                                    }

                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put(KEY_USER_ID, user_id);
                        map.put(KEY_USER_TYPE, User_type);

                        return map;
                    }
                };
                RequestQueue requestqueue = Volley.newRequestQueue(Transaction.this);
                requestqueue.add(strRequest);**


text:
Q: Error changing background image I'm trying to change the background image of a different page through jQuery with an overlay, though, I'm doing something wrong. Can someone please point out what I'm doing wrong?
$("html").css({"background-image": "url("+../images/pattern copy.png+")", "url("+../images/visuals/visual3-edit.jpg+")", "center" "center" "fixed no-repeat;"});

I hope I'm using StackOverflow correct, it's the first time I'm attempting this.
Kind regards.

A: Use this instead:
$("html").css({ "background": "url('../images/visuals/visual3-edit.jpg') center center fixed no-repeat" });

or if you are just changing the image...
$("html").css({ backgroundImage: "url('../images/visuals/visual3-edit.jpg')" });

Not sure what you mean by a different page.  Can you be more specific?
Also, try:
$("html").css({ "background-image": "url('../images/pattern%20copy.png'), url('../images/visuals/visual3-edit.jpg')", "background-position": "center", "background-repeat": "no-repeat", "background-attachment": "fixed"  });

Also, if you have a space in your filename, like this:  pattern copy.png, than the actual filename path will be:  pattern%20copy.png

redpajama_set_name: RedPajamaStackExchange


text:
Q: From training score, how to calculate predicted outcomes using predict_proba for a multi-class target variable I'm using a diabetics dataset which has 3 classes for the target variable. I have used Decision Tree Classifier for the same and optimized the hyperparameters using RandomizedSearchCV of sci-kit learn package and fitted the model to training data. Now, I have found the probability values for the test data which gives the probability for assigning the outcome variable to the 3 classes. Now, I want to calculate the cutoff value such that I can use it to assign the classes. For this purpose, I'm using F1 score to find the appropriate cut off value.
Now, I'm stuck how to find the F1 score. Will the F1 score metric help me to find it?
Here is the dataset
After preprocessing the data, I have spitted the data into training and testing set.
dtree = DecisionTreeClassifier()
params = {'class_weight':[None,'balanced'],
              'criterion':['entropy','gini'],
             'max_depth':[None,5,10,15,20,30,50,70],
             'min_samples_leaf':[1,2,5,10,15,20],
             'min_samples_split':[2,5,10,15,20]}
grid_search = RandomizedSearchCV(dtree,cv=10,n_jobs=-1,n_iter=10,scoring='roc_auc_ovr',verbose=20,param_distributions=params)
grid_search.fit(X_train,y_train)
mdl.fit(X_train,y_train)
test_score = mdl.predict_proba(X_test)

The following formula I have created for cutoff for binary classifier -
cutoffs = np.linspace(0.01,0.99,99)
true = y_train
train_score = mdl.predict_proba(X_train)[:,1]
F1_all = []
for cutoff in cutoffs:
    pred = (train_score>cutoff).astype(int)
    TP = ((pred==1)&(true==1)).sum()
    FP = ((pred==1)&(true==0)).sum()
    TN = ((pred==0)&(true==0)).sum()
    FN = ((pred==0)&(true==1)).sum()
    F1 = TP/(TP+0.5*(FP+FN))
    F1_all.append(F1)
my_cutoff = cutoffs[F1_all==max(F1_all)][0]
preds = (test_score1>my_cutoff).astype(int)

A: There is no cutoff value for the softmax output of a multiclass classifier in the same sense as the cutoff value for binary classifier.
When your output is normalized probabilities for multiple classes and you want to convert this into class labels, you just take the label with the highest assigned probability.
Technically you could design some custom schema such as

*

*if class1 has probability of 10% or more, choose class1 label, otherwise
pick a class with the highest assigned probability

which would be sort of a cutoff for class 1 but this is rather arbitrary and I have not seen anyone doing this in practice. If you have some deep insight into your problem which is suggesting that something like this may be useful then go ahead and build your own "cutoff" formula, otherwise you should just stick with the general approach (argmax of the normalized probabilities).


text:
Q: Parse json to android applcation from data in mongodb by php web service I am looking to pull data from by mongodb by the use of php, then convert it to a json object which i can parse to my android applcation.
I can do this for mysql without any problems, but i am finding it hard to get the right format to be able to read to android.
If anyone has any advice tips or tutorials please let me know

A: You can try with Gson, a JSON parser to java objects. It's an easy-to-use library and in its web has a nice user guide.


text:
Q: Streaming polyline while adding records to related tables in ArcPad I'm designing an ArcPad solution for our field staff; we collect point data and use lines to identify the amount of 'effort' (and to maintain accountability).
While collecting a 'streaming polyline' (Add verticies continuously from GPS) as our field staff's "track" (daily effort) we need to also collect point data along the way.
Every time you collect add a record to a point feature class in a related table in the poly-line streaming stops.  This forces our staff to manually turn the polyline streaming back on for every record they collect.  Human error is just about guaranteed over the course of editing 50 points in a day.
I know that event handling is built into ArcPad through ArcPad Studio, but I haven't had any luck triggering the polyline streaming with the onOK event of related table's form.
Any help putting together an event handler would be appreciated.  The help files aren't nearly as useful as the Python sample code associated with ArcMap on the desktop.  Here's a quick look at the direction I've been leaning. I'm not fully sure how to even compose a full even handling script for ArcPad.

From help files:   'gpsstream' => Add Vertices continuously from GPS
Form (onOk event):
Application.ExecuteCommand("gpsstream")

A: Rather than coding a solution, have you considered using the GPS Tracklog instead of a streaming polyline?
The tracklog saves at a defined interval GPS coordinates provided the GPS is on and receiving in a shapfile and displays it in ArcPad. However it is not an edit feature, so it does not stop when yuo add a new record to your edit feature (such as your point feature class).
As a bonus the tracklog saves a bunch of GPS information, including height, time, gps fix quality, etc, which should come in handy through your auditing process.


text:
Q: Spark UDF Causing Job Abort I am trying to do very simple UDF operations on a data frame and I am met with errors
I am working with an example straight from the PySpark API, the only difference is I am using different data (and that mine doesn't work)
Here is my DF:
parq.show(3)

+-------------------+---+----------+---------+--------------------+------+--------------+----------------+---------+---------+---------+-------------------+--------+
|  registration_dttm| id|first_name|last_name|               email|gender|    ip_address|              cc|  country|birthdate|   salary|              title|comments|
+-------------------+---+----------+---------+--------------------+------+--------------+----------------+---------+---------+---------+-------------------+--------+
|2016-02-03 07:55:29|  1|    Amanda|   Jordan|    ajordan0@com.com|Female|   1.197.201.2|6759521864920116|Indonesia| 3/8/1971| 49756.53|   Internal Auditor|   1E+02|
|2016-02-03 17:04:03|  2|    Albert|  Freeman|     afreeman1@is.gd|  Male|218.111.175.34|                |   Canada|1/16/1968|150280.17|      Accountant IV|        |
|2016-02-03 01:09:31|  3|    Evelyn|   Morgan|emorgan2@altervis...|Female|  7.161.136.94|6767119071901597|   Russia| 2/1/1960|144972.51|Structural Engineer|        |
+-------------------+---+----------+---------+--------------------+------+--------------+----------------+---------+---------+---------+-------------------+--------+

Here is the relevant schema entry:
parq.printSchema()
 |-- salary: double (nullable = true)

Then doing a simple udf operation to square the salary column
square_udf = F.udf(lambda z: z**2, DoubleType())
parq.select(square_udf(F.col("salary"))).show(10)

This yields:
org.apache.spark.SparkException: Job aborted due to stage failure ...
In my mind there is absolutely no reason that it should be doing this, if someone could clarify my thinking that would be great.

A: Thanks to @Gocht to testing my code and saying it works. I had nulls in my salary column interfering so I ran this first:
parq_nn = parq.select("*").where("salary is not null")

And it worked


text:
Q: Reading from CSV with fgets() and strtok() FULL DISCLOSURE: SCHOOL ASSIGNMENT
I've been working on some code to pull data from a CSV and display it, however I keep encountering this error I can't seem to overcome.
The code would be pretty simple, but the problem is that our CSV can have spaces before or after the comma, which means you can't just strtok() because it will include the space. Therefore, you need to remove the spaces before printing. I attempted to achieve this by strtok() the CSV, then running said token through a function to eliminate any spaces. However, this seems to be where the issue is happening. I keep getting a "read access violation" on line 12 that I don't understand. Any help would be appreciated. I've posted the database.c code and database.csv that it's accessing.
database.c:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char show[] = "SHOW";
char delete[] = "DELETE";
char add[] = "ADD";

void noSpaces(char* s) {
    const char* d = s;
    do {
        while (*d == ' ') {
            ++d;
        }
    } while (*s++ = *d++);
}

void showStuff() {
    FILE* csv = fopen("database.csv", "rt");
    if (csv == NULL) {
        printf("\n File opening failed");
        exit(1);
    }
    char buffer[800];
    char* Gptr, *ID, *name, *cAge, *cGPA;
    int counter = 1;
    while (fgets(buffer, sizeof(buffer), csv)) {
        ID = strtok(buffer, ",");
        noSpaces(ID);
        name = (strtok(NULL, ","));
        noSpaces(name);
        cAge = (strtok(NULL, ","));
        noSpaces(cAge);
        int age = atoi(cAge);
        cGPA = (strtok(NULL, ","));
        noSpaces(cGPA);
        double GPA = strtod(cGPA, &Gptr);
        printf("Record %d: ID=%-3s NAME:%-3s AGE:%-3d GPA:%-3f\n", counter, ID, name, age, GPA);
        counter++;
    }
    fclose(csv);
}

void deleteStuff(char givenID[]) {
    FILE* csvread = fopen("database.csv", "rt");
    if (csvread == NULL) {
        printf("\n File opening failed");
        exit(1);
    }
    FILE* csvwrite = fopen("database.tmp", "wt");
    char buffer[800];
    char* ID;
    int oneAndDone = 0;
    while (fgets(buffer, sizeof(buffer), csvread)) {
        ID = strtok(buffer, ",");
        noSpaces(ID);
        if ((strcmp(ID, givenID) == 0) && (oneAndDone == 0)) {
            oneAndDone++;
            continue;
        }
        else {
            fputs(buffer, csvwrite);
        }
    }
    system("rm database.csv");
    system("mv database.tmp database.csv");
    fclose(csvread);
    fclose(csvwrite);
    if (oneAndDone == 0) {
        printf("Sorry, the user was not found. Nothing was deleted.\n");
        exit(1);
    }
}

void addStuff(char gID[], char gName[], char gAge[], char gGPA[]) {
    char* Gptr;
    int age = atoi(gAge);
    double GPA = strtod(gGPA, &Gptr);
    FILE* csvappend = fopen("database.csv", "at");
    if (csvappend == NULL) {
        printf("\n File opening failed");
        exit(1);
    }
    fprintf(csvappend, "%s,%s,%d,%f", gID, gName, age, GPA);
    fclose(csvappend);
}

void main(int argc, char* argv[]) {
    if (argc == 1) {
        printf("Your did not provide any arguments. Please enter: ./database CMD OPT1 OPT2 OPT3 OPT4 \n");
        exit(1);
    }
    if (strcmp(argv[1], show) == 0) showStuff();
    else if (strcmp(argv[1], delete) == 0) {
        if (argc <= 2) {
            printf("Name of record to delete is missing\n");
            exit(1);
        }
        deleteStuff(argv[2]);
    }
    else if (strcmp(argv[1], add) == 0) {
        if (argc <= 3) {
            printf("Missing ID, Name, AGE, and GPA Arguments");
            exit(1);
        }
        addStuff(argv[2], argv[3], argv[5], argv[5]);
    }
    else printf("The command you requested in invalid. Please select from one of these: SHOW, DELETE, ADD");
}

database.csv:
10,bob,18, 3.5
15,mary,20,4.0
5,tom, 17, 3.8


text:
Q: EV1HMC245AQS16 bidirectional capability I want to use EV1HMC245AQS16 as a RF multiplexer. I have a IoT device that I need to test with 3 different antennae. The IoT module will be connected to 3 different antennae via the RF multiplexer. I will be using this RF multiplexer to test the reliability of the firmware running on the IoT device as the different antennae will provide different RSSI for the IoT module. Basically I want to test the reliability of the firmware with different RSSI values of the network.
What I want to know is, will this evaluation  board be fine for this purpose?
It should be able to handle bidirectional RF data transmission and also reception at the same time when one antennae is connected to IoT module.
The connection will be as follows:

Iot Module antennae connection - J1 (RFC)
Antennae 1 - J2 (RF1)
Antennae 2 - J3 (RF3)
Antennae 3 - J4 (RF2)

I have a raspberry PI to control which antennae gets connected to IoT module according to the truth table mentioned above.
Can you tell me, whether EV1HMC245AQS16 is suitable for this application?


text:
Q: localstorage not retaining data after page reload I am trying to retain data in a localstorage after reload but it is not working
this is my attempt
<script>
window.onbeforeunload = function() {
    localStorage.setItem(name, $('#inputName').val());

}

window.onload = function() {

    var name = localStorage.getItem(name);
    if (name !== null) $('#inputName').val(name);
    alert(name);

}

</script>
<html>

<body>

 <input type="text" id="inputName" placeholder="Name" required>

</body>

</html>

on refreshing the page after entering data on the form it keeps alerting null. kindly assist

A: In your onbeforeunload, name is the name of the window (because you haven't given it any other value, and browsers have a global name property which is the name of the window — it's usually blank).
In this line:
var name = localStorage.getItem(name);

...it's undefined, because of the var name.
You need to use a proper name, for instance:
window.onbeforeunload = function() {
    localStorage.setItem("your-setting-name", $('#inputName').val());
};

window.onload = function() {
    var name = localStorage.getItem("your-setting-name");
    if (name !== null) $('#inputName').val(name);
    alert(name);
};

Also note charlietfl's oint that if you don't want to alert null on the first visit to the page, you need to put the alert in the body of the if:
window.onload = function() {
    var name = localStorage.getItem("your-setting-name");
    if (name !== null) {
        $('#inputName').val(name);
        alert(name);
    }
};

Otherwise, it'll alert null on the first visit and then whatever the last value was otherwise.
(Also note that I've added some missing ;. Automatic Semicolon Insertion will add these particular ones, but it's an error-correction mechanism, so I'd advise not relying on it.)

Other issues:

*

*You're using jQuery functions, but haven't shown any script tag including jQuery on the page.

*You have the closing </html> tag before the <input ...> tag.

Here's a fiddle with the above fixed (can't use Stack Snippets with local storage): https://jsfiddle.net/un86not0/ Full working page:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Example</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
window.onbeforeunload = function() {
    localStorage.setItem("your-setting-name", $('#inputName').val());
};

window.onload = function() {
    var name = localStorage.getItem("your-setting-name");
    if (name !== null) {
        $('#inputName').val(name);
        alert(name);
    }
};
</script>
<input type="text" id="inputName" placeholder="Name" required>
</body>
</html>

A: The variable name haven't been initiated yet you already used it as a value reference. Maybe it wasn't working well because of that?
Here in this solution, you can separately reference the local storage item without using the variable name which might have caused it not to work.
<script>
window.onbeforeunload = function() {
    localStorage.setItem('myItem', $('#inputName').val());

}

window.onload = function() {

    var name = localStorage.getItem('myItem');
    if (name !== null) $('#inputName').val(name);
    alert(name);
}

</script>


text:
Q: Mantener color en una fila con GridView Tengo un código, si la celda se edita, esta se marca de color verde, si la celda se marca con problema (Se despliega un menú para marcarla) se pinta de rojo, pero a la hora de refrescar el Form se pierden los colores, ¿Alguien sabe cómo se pueden mantener?, adjunto ejemplo cúando se marca problema:
foreach (GridViewCellInfo cell in grdRP.SelectedRows[0].Cells)
                {
                    cell.Style.CustomizeFill = true;
                    cell.Style.BackColor = Color.IndianRed;
                    cell.Style.ForeColor = Color.White;
                    cell.Style.NumberOfColors = 1;
                    cell.Style.DrawFill = true;
                }

¿Algún ejemplo o código que pueda guardarme el color de la fila cada vez que inicia el form?, ejemplo:

https://i.stack.imgur.com/FUL3m.png


text:
Q: why must we initialize DS And ES registers in MS-DOS? in MS-DOS ,Why  the initialization of the DS and ES registers must be done manually by the programmer, although it's operating system responsibility to initialize these registers.
why mustn't we do this for CS and SS registers ? Which feature of MS-dos Leads into this?

A: It's just a choice of the OS designer.
DOS is a minimal OS, so it does the minimum possible. The CS and SS registers must be set. Without CS set for you, your code could not run. SS must be set because DOS uses one stack for everything. Interrupts are using the stack over 30 times per second even while your program is running. (This is why you must turn off interrupts when modifying SS.) The other segments are needed only if your program uses them (and it's certainly possible to write code that doesn't), so DOS isn't concerned.
Actually in DOS versions I remember (and it's been many years so this could be wrong), DS and ES were set equal to CS, which is what you want for very small programs with at most 64k of code+data+stack requirement.

A: EXE files might not have a single or other special segment to default init DS at all, and have multiple static data segments.  IOW all globals are FAR.
The first load of DS is then to the segment of the first variable that needs to be loaded.


text:
Q: Reference or tutorial to clarify object reference confusion Working with my ongoing TFrames-based component set project, I'm coming across various instances where I am wanting to replace one of the TFrame's components (usually non-visual)  at runtime with one that is generated dynamically at runtime.
I think I've probably found the answer to my immediate problem here, but in my own digging around and experimenting prior to finding that, it's become clear I've got quite a bit to learn about how Delphi handles object references, particularly with respect to forms/frames, and (in general) class properties which are object references rather than non-pointer values.
A specific example of one experiment is here:
(On a form with three TButtons)
procedure TForm1.Button3Click(Sender: TObject);
var
  MyButton : TButton;

begin
  MyButton := TButton.Create(Self);
  MyButton.Caption := 'New Button';
  MyButton.Parent := Form1;
  Form1.Button2 := MyButton;
  Form1.Repaint;
  ShowMessage('Button2 caption = ' + Form1.Button2.Caption);
end;

Doesn't replace Button2 with the created button, but does show both on the form.  The ShowMessage results indicates Button2's caption still = "Button2"
I find myself asking questions like, "Is this 'non-replacement' unique to forms, or would that be true for other classes as well?" etc. In short, I've discovered yet another sinkhole of my own ignorance. ;-) I find in working with instances/object references/derefencing/class definitions/class properties etc, that oftentimes things behave exactly as they expect them to, but other times, not at all, and not even close.
It's clear I need to study up on this area. Rather than post stupid question after stupid question revolving around this subject, I thought I'd ask this instead:
What is a really good reference or tutorial for getting a better grasp on the subtle distinctions re: how Delphi handles such things?
Thanks in advance for all your help!

A: Those fields on the forms are there purely for your convenience when writing code.  You can delete them from the .pas file and they'd still show up.  The form's layout is defined in the DFM, and the form object holds an internal list of references to the controls placed on it, just like any other visual control.
I don't know about tutorials on the subject, but I do know how you can replace a button.  You've got it mostly right, but you also have to free Form1.Button2 before you overwrite the reference.  That will cause the button to remove itself from the form's control list as part of its destruction process.  Or, if you want to save the button somewhere instead of destroying it, call Form1.RemoveControl(Button2); instead.


text:
Q: How to change default date_format in MemSQL 4.0 Is there a way to change the default date_format in MemSQL -  I'd like to change it to "%m/%d/%Y" instead of the default "%Y-%m-%d", so that i can load data in that format from csv files.
I got error message when try to set it.
mysql> SET @@GLOBAL.date_format = '%m/%d/%Y';
ERROR 1238 (HY000): Variable 'date_format' is a read only variable
Appreciate for any help.

A: Unfortunately MemSQL follows MySQL for a lot of system variables and as you can see in their docs the default date_format variable is unused: http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_date_format
Furthermore, currently MemSQL does not support transforming a particular column during a load.
Keep an eye out to some awesome solutions to this and other similar problems in our next release.


text:
Q: NHibernate Unit Tests Not Working Correctly On many-to-one table Okay so here is the problem I am having.  I have several unit tests for a repository, I get a green light on all of them individually.  Yet when I run all the tests together, the first one succeeds and then I get a foreign key constraint error for the others, this is only happening where I have a many-to-one relationship.  I have tried playing with the cascade option and I removed the first test to see if it was corrupting the test data but all that happened was I got a green light on the first test and the rest went red.  Again in isolation I got a green light on all tests.
Most of this code is based upon the "Your first NHibernate based application" tut on NHForge.com
The error is occuring on the StockTransactionRepository.  I have tried to include the relavent code, if you need more let me know.  I suspect there is something glaringly obvious here.
The error:
NHibernate.Exceptions.GenericADOException : could not insert: [rapidstk_base.Domain.StockTransaction#f305a5d4-9-c6e-bcdf-9d4dd16337ff][SQL: INSERT INTO StockTransaction (stkitm_StockItemToTransact, dcm_StockTransactionAmount, stkloc_StockLocation, dt_StockTransactionDate, Id) VALUES (?,?,?,?,?)]
   ---->MySql.Data.MySqlClient.MySqlException:  Cannot add or update a child row:  a foreign key constraint fails (`rpdstkdb`.`stocktransaction`, CONSTRAINT `FK37E1C2103E2BF85C` FOREIGN KEY (`stkitm_StockItemToTransact`) REFERENCES `stockitem` (`ID`))

hbm.xml code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                assembly="rapidstk_base"
                namespace="rapidstk_base.Domain"
                auto-import="false">
<class name="rapidstk_base.Domain.StockTransaction">
    <id name="Id">
        <generator class="guid" />
    </id>
    <many-to-one name="stkitm_StockItemToTransact" class="StockItem" cascade="all" />
    <property name="dcm_StockTransactionAmount" />
    <many-to-one name="stkloc_StockLocation" class="StockLocation" cascade="all" />
    <property name="dt_StockTransactionDate" />
</class>
</hibernate-mapping>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                assembly="rapidstk_base"
                namespace="rapidstk_base.Domain"
                auto-import="false">
<class name="rapidstk_base.Domain.StockItem">
    <id name="Id">
        <generator class="guid" />
    </id>
        <property name="str_StockItemName" />
        <property name="str_StockItemDescription" />
        <property name="dtm_StockItemCreationDate" />
</class>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                assembly="rapidstk_base"
                namespace="rapidstk_base.Domain"
                auto-import="false">
<class name="rapidstk_base.Domain.StockLocation">
    <id name="Id">
        <generator class="guid" />
    </id>
    <property name="s_StockLocationName" />
    <property name="s_StockLocationDescription" />
</class>
</hibernate-mapping>

Unit Tests:
using NUnit.Framework;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NHibernate;
using System;
using System.Collections.Generic;

using rapidstk_base.Domain;
using rapidstk_base.Repositories;
using rapidstk_base;

namespace rapidstk_base_test
{
[TestFixture]
public class StockTransactionRepositoryTest
{
    private ISessionFactory _sessionFactory;
    private Configuration _configuration;

    private readonly static StockItem[] _stockitems = new[]
    {
        new StockItem { str_StockItemName = "Orgone Accumulator", str_StockItemDescription = "Social Integrator." },
        new StockItem { str_StockItemName = "Perpetual Dingle", str_StockItemDescription = "Everlasting Bliss." },
        new StockItem { str_StockItemName = "Apple", str_StockItemDescription = "Golden Delicious." },
        new StockItem { str_StockItemName = "Nepenthe", str_StockItemDescription = "The answer." },
        new StockItem { str_StockItemName = "Bobbins Gourd", str_StockItemDescription = "Follow The Gourd." },
    };

    private readonly static StockLocation[] _stocklocations = new[]
    {
        new StockLocation() { s_StockLocationName="Bay 1", s_StockLocationDescription="Upstairs next to the coffee machine."},
        new StockLocation() { s_StockLocationName="Bay 2", s_StockLocationDescription="Under the Shrubbery."},
        new StockLocation() { s_StockLocationName="Bay Watch", s_StockLocationDescription="Bouncing on the Beach."},
        new StockLocation() { s_StockLocationName="My Pocket", s_StockLocationDescription="Lintville."},
        new StockLocation() { s_StockLocationName="Secret Lair", s_StockLocationDescription="Next to the coke machine."},
    };

    private readonly StockTransaction[] _stockTransactions = new[]
    {
        new StockTransaction { stkitm_StockItemToTransact = _stockitems[0], stkloc_StockLocation = _stocklocations[0], dcm_StockTransactionAmount = 10.0M },
        new StockTransaction { stkitm_StockItemToTransact = _stockitems[1], stkloc_StockLocation = _stocklocations[1], dcm_StockTransactionAmount = -10.0M },
        new StockTransaction { stkitm_StockItemToTransact = _stockitems[2], stkloc_StockLocation = _stocklocations[2], dcm_StockTransactionAmount = 1.0M },
        new StockTransaction { stkitm_StockItemToTransact = _stockitems[3], stkloc_StockLocation = _stocklocations[3], dcm_StockTransactionAmount = 2.9M },
        new StockTransaction { stkitm_StockItemToTransact = _stockitems[4], stkloc_StockLocation = _stocklocations[4], dcm_StockTransactionAmount = 155.0M, dt_StockTransactionDate=DateTime.Parse("2011/11/30") },
        new StockTransaction { stkitm_StockItemToTransact = _stockitems[4], stkloc_StockLocation = _stocklocations[4], dcm_StockTransactionAmount = -50.0M, dt_StockTransactionDate=DateTime.Parse("2011/12/01") },
        new StockTransaction { stkitm_StockItemToTransact = _stockitems[4], stkloc_StockLocation = _stocklocations[4], dcm_StockTransactionAmount = -50.0M, dt_StockTransactionDate=DateTime.Parse("2011/12/02") },
        new StockTransaction { stkitm_StockItemToTransact = _stockitems[4], stkloc_StockLocation = _stocklocations[4], dcm_StockTransactionAmount = -50.0M, dt_StockTransactionDate=DateTime.Parse("2011/12/03") },
    };

    private void CreateInitialData()
    {
        using (ISession session = _sessionFactory.OpenSession())
        {
            using(ITransaction transaction = session.BeginTransaction())
            {
                foreach(var tr in _stockTransactions)
                {
                    session.Save(tr);
                }
                transaction.Commit();
            }
        }
    }

    [TestFixtureSetUp]
    public void TestFixtureSetup()
    {
        _configuration = new Configuration();
        _configuration.Configure ();
        _configuration.AddAssembly(typeof(rapidstk_base.Domain.StockTransaction).Assembly);
        _sessionFactory = _configuration.BuildSessionFactory();
    }

    [SetUp]
    public void SetupContext()
    {
        var schema = new SchemaExport(_configuration);
        schema.Create(true, true);
        CreateInitialData();
    }

    [Test]
    public void CanAddTransaction ()
    {
        var newStkTransaction = new StockTransaction{ stkitm_StockItemToTransact=_stockitems[0], stkloc_StockLocation=_stocklocations[3], dcm_StockTransactionAmount=42.0M };
        IStockTransactionRepository repository = new StockTransactionRepository();
        repository.Add(newStkTransaction);

        using(ISession session = _sessionFactory.OpenSession())
        {
            var fromdb = session.Get<StockTransaction>(newStkTransaction.Id);
            Assert.IsNotNull(fromdb);
            Assert.AreNotSame(newStkTransaction, fromdb);
            Assert.AreEqual(newStkTransaction.stkitm_StockItemToTransact.str_StockItemName, fromdb.stkitm_StockItemToTransact.str_StockItemName);
            Assert.AreEqual(newStkTransaction.stkitm_StockItemToTransact.str_StockItemDescription, fromdb.stkitm_StockItemToTransact.str_StockItemDescription);
            Assert.AreEqual(newStkTransaction.stkloc_StockLocation.s_StockLocationName, fromdb.stkloc_StockLocation.s_StockLocationName);
            Assert.AreEqual(newStkTransaction.stkloc_StockLocation.s_StockLocationDescription, fromdb.stkloc_StockLocation.s_StockLocationDescription);
            Assert.AreEqual(newStkTransaction.dcm_StockTransactionAmount, fromdb.dcm_StockTransactionAmount);
        }

    }

    [Test]
    public void CanRemoveTransaction()
    {
        IStockTransactionRepository repository = new StockTransactionRepository();
        Guid id = _stockTransactions[0].Id;
        repository.Remove(_stockTransactions[0]);

        using(ISession session = _sessionFactory.OpenSession())
        {
            var fromdb = session.Get<StockLocation>(id);
            Assert.IsNull(fromdb);
        }
    }

    [Test]
    public void CanUpdateTransaction()
    {
        IStockTransactionRepository repository = new StockTransactionRepository();
        var stkTransaction = _stockTransactions[1];
        stkTransaction.dcm_StockTransactionAmount = 150.0M;
        repository.Update(stkTransaction);

        using(ISession session = _sessionFactory.OpenSession())
        {
            var fromdb = session.Get<StockTransaction>(stkTransaction.Id);
            Assert.AreEqual(stkTransaction.dcm_StockTransactionAmount, fromdb.dcm_StockTransactionAmount);
        }
    }

    [Test]
    public void CanGetAllTransactionForAProduct()
    {
        IStockTransactionRepository repository = new StockTransactionRepository();
        StockItem queryItem = _stockitems[4];
        var fromdb = repository.GetByStockItem(queryItem);

        Assert.AreEqual(4, fromdb.Count);
        Assert.IsTrue(IsInCollection(_stockTransactions[5], fromdb));
        Assert.IsTrue(IsInCollection(_stockTransactions[6], fromdb));
    }

    private bool IsInCollection(StockTransaction stkTrns, ICollection<StockTransaction> fromdb)
    {
        foreach(var item in fromdb)
            if(stkTrns.Id == item.Id)
                return true;
        return false;
    }

    [Test]
    public void CanGetAllTransactionsUpToADate()
    {
        IStockTransactionRepository repository = new StockTransactionRepository();
        StockItem queryItem = _stockitems[4];
        var fromdb = repository.GetByStockItem(queryItem, DateTime.Parse ("2011/12/02"));

        Assert.AreEqual(3, fromdb.Count);
        Assert.IsTrue(IsInCollection(_stockTransactions[5], fromdb));
        Assert.IsTrue(IsInCollection(_stockTransactions[6], fromdb));
        Assert.IsFalse(IsInCollection(_stockTransactions[7], fromdb));
    }

    [Test]
    public void CanGetAllTransactionsBetweenDates()
    {
        IStockTransactionRepository repository = new StockTransactionRepository();
        StockItem queryItem = _stockitems[4];
        var fromdb = repository.GetByStockItem(queryItem, DateTime.Parse ("2011/12/01"), DateTime.Parse ("2011/12/03"));

        Assert.AreEqual(3, fromdb.Count);
        Assert.IsFalse(IsInCollection(_stockTransactions[4], fromdb));
        Assert.IsTrue(IsInCollection(_stockTransactions[5], fromdb));
        Assert.IsTrue(IsInCollection(_stockTransactions[6], fromdb));
        Assert.IsTrue(IsInCollection(_stockTransactions[7], fromdb));
    }
}
}

Stock Transaction Repository Code:
using System;
using System.Collections.Generic;
using rapidstk_base.Domain;
using NHibernate;
using NHibernate.Criterion;

namespace rapidstk_base.Repositories
{
public class StockTransactionRepository : IStockTransactionRepository
{
    public void Add(StockTransaction stkTransaction)
    {
        using(ISession session=NHibernateHelper.OpenSession())
            using(ITransaction transaction = session.BeginTransaction())
        {
            session.Save(stkTransaction);
            transaction.Commit();
        }
    }

    public void Remove(StockTransaction stkTransaction)
    {
        using(ISession session=NHibernateHelper.OpenSession())
            using(ITransaction transaction = session.BeginTransaction())
        {
            session.Delete(stkTransaction);
            transaction.Commit();
        }
    }

    public void Update(StockTransaction stkTransaction)
    {
        using(ISession session = NHibernateHelper.OpenSession())
            using(ITransaction transaction = session.BeginTransaction())
        {
            session.Update(stkTransaction);
            transaction.Commit();
        }
    }

    public ICollection<StockTransaction> GetByStockItem(StockItem item)
    {
        using(ISession session = NHibernateHelper.OpenSession())
        {
            var transactions = session.CreateCriteria(typeof(StockTransaction))
                                .Add(Restrictions.Eq("stkitm_StockItemToTransact", item))
                                .List<StockTransaction>();
            return transactions;
        }
    }

    public ICollection<StockTransaction> GetByStockItem(StockItem item, DateTime endDate)
    {
        using(ISession session = NHibernateHelper.OpenSession())
        {
            var transactions = session.CreateCriteria(typeof(StockTransaction))
                                .Add(Restrictions.Eq("stkitm_StockItemToTransact", item))
                                .Add(Restrictions.Le("dt_StockTransactionDate", endDate))
                                .List<StockTransaction>();
            return transactions;
        }
    }

    public ICollection<StockTransaction> GetByStockItem(StockItem item, DateTime startDate, DateTime endDate)
    {
        using(ISession session = NHibernateHelper.OpenSession())
        {
            var transactions = session.CreateCriteria(typeof(StockTransaction))
                                .Add(Restrictions.Eq("stkitm_StockItemToTransact", item))
                                .Add(Restrictions.Le("dt_StockTransactionDate", endDate))
                                .Add(Restrictions.Ge("dt_StockTransactionDate", startDate))
                                .List<StockTransaction>();
            return transactions;
        }
    }

    public StockTransactionRepository ()
    {

    }
}
}

A: It does not look like you have a teardown to roll back the transaction. Remember that a many-to-one relationship will be persisted the moment you add a item (it does not have to go through a flush necessarily. My guess is that you have dirty data. Just add a teardown and roll back the nhibernate transaction and I think you should be fine.

A: I think what is happening is because your StockItems, StockLocations, and Stocktransactions are static, NHibernate associates them with the session on the first test and replaces any associates with proxies. Then on subsequent tests, they are not persisted properly and you're getting this FK constraint error. Try making them non static and initialize them just before your CreateInitialData call. So your Seetup might look something like:
[SetUp]
public void SetupContext()
{
    var schema = new SchemaExport(_configuration);
    schema.Create(true, true);
    InitializeData();    //create your StockItems, StockLocations, and StockTransactions
    CreateInitialData();
}


text:
Q: Variance and covariance in the context of deterministic variables Questions:

*

*Can we talk about:
variance of a deterministic variable?;
covariance between a deterministic variable and a stochastic variable?;
covariance between two deterministic variables?

*Are these concepts well defined in sample?; in population?

Motivation
Take a simple regression
$$y = \beta_0 + \beta_1 x + \varepsilon.$$
Suppose the regressor $x$ is stochastic. The OLS estimate of $\beta_1$ will be
$$\hat{\beta}_1=\frac{\widehat{\text{Cov}}(x,y)}{\widehat{Var}(x)}$$
where hats denote sample counterparts of the population concepts. No problem here.
Now suppose $x$ is deterministic. I am not sure if I can use terms like variance and covariance in this context. Should I exchange $\hat{\beta}_1=\frac{\widehat{\text{Cov}}(x,y)}{\widehat{Var}(x)}$ for something like
$$\hat{\beta}_1=\frac{\frac{1}{n-1}\sum(x_i-\bar{x})(y_i-\bar{y})}{\frac{1}{n-1}\sum(x_i-\bar{x})^2}$$
to be correct? But then again, how meaningful is $\bar{x}$ when $x$ is deterministic? So should I go all the way to
$$\hat{\beta}_1=\frac{\frac{1}{n-1}\sum_{i=1}^n(x_i-\frac{1}{n}\sum_{j=1}^n x_j)(y_i-\frac{1}{n}\sum_{j=1}^n y_j)}{\frac{1}{n-1}\sum(x_i-\frac{1}{n}\sum_{j=1}^n x_j)^2}?$$
I am picking on details here and this may not be too important; my main questions are listed at the top of the post.

A: All five questions have "yes" answers--but we have to be careful about what they mean.

*

*"Variance of a deterministic variable."
Let's understand a "deterministic variable" to be a univariate dataset.  It's just a bunch of values $X=x_1, x_2, \ldots, x_n$, with no probability model.  By definition its variance is
$$\text{Var}(X) = \frac{1}{n}\sum_{i=1}^n \left(x_i - \bar X\right)^2$$
where $$\bar X = \frac{1}{n}\sum_{i=1}^n x_i$$ is its mean.  There is no justification whatsoever to use $n-1$ instead of $n$ in any of these fractions--and this is never legitimately done--because no estimates are being made.
We may always think of $X$ as defining a "population."  This is the definition of a population variance.

*"Covariance between a deterministic variable and a stochastic variable."
One way to understand this is to assume it refers to a sequence of the form $(x_1, Y_1), (x_2,Y_2), \ldots, (x_n,Y_n)$ where the $x_i$ are numbers and the $Y_i$ are random variables.  Then we may define the random variable $$\bar Y = \frac{1}{n}\sum_{i=1}^n Y_i,$$ via which the covariance of $x$ and $Y$ is defined as
$$\text{Cov}(x,Y) = \frac{1}{n}\sum_{i=1}^n (x_i - \bar x)(Y_i - \bar Y).$$
It is a linear combination of the $Y_i$ and consequently is itself a random variable.  This notation is frequently used as a shorthand in linear regression calculations.

*"Covariance between two deterministic variables."
"Two deterministic variables" can be considered a dataset of ordered pairs $(x_1, y_1), (x_2,y_2), \ldots, (x_n,y_n)$.  The covariance can be defined exactly as in (2) and interpreted similarly.  In fact, this is a direct consequence of (1): after all, covariances are variances.

*"Are these concepts well defined in samples?"
Because they are well-defined for any dataset, they are well-defined for a sample.  Note that similar expressions with $n-1$ in the (outer) denominator are estimators: they are not the sample variance or sample covariance.

*"Are these concepts well defined in populations?"
Because they are well-defined for any dataset, and a population can be considered a dataset (when fully enumerated), they are well-defined for a population.

A: The simple answer to your first three questions is no: it makes no sense in general to talk about variance or covariance involving a deterministic variable.
However, if we begin with a deterministic variable but then use some method of imposing a probability distribution on it, it then becomes a random variable, and the concept of variance then makes sense. For example, any deterministic variable can become a random variable simply by imposing a degenerate (i.e., constant) distribution on it; in this case, the variance (along with its covariance with any other random variable) becomes 0.
A more interesting way of imposing a distribution on deterministic random variables is to use the empirical distribution, based on an observed sample. That is, if you observe $x_1,\dots,x_n$ in a sample, then we can define a discrete probability distribution on $x$ by $$P(x=x_0)=\frac1n \cdot\text{the number of $i$ such that $x_i=x_0$}$$
for all $x_0$. For example, in the case where $x_1,\dots,x_n$ are all distinct, we get $P(x=x_i)=\frac1n$ for each $i=1,\dots,n$. If we use this probability distribution on $x$, then the mean of $x$ becomes simply the sample mean $\overline x=\frac1n\sum_{i=1}^n x_i$, and the variance of $x$ becomes $\hat\sigma^2=\frac1n\sum_{i=1}^n (x_i-\overline x)^2$.
This same idea can be applied in the situation where we have observed vectors $(x_1,y_1),\dots,(x_n,y_n)$. We can define a joint probability distribution on $(x,y)$ again by using the empirical distribution, and the covariance between $x$ and $y$ then becomes $$\text{Cov}(x,y)=\frac1n\sum_{i=1}^n (x_i-\overline x)(y_i-\overline y)$$


text:
Q: PCA application and interpretration I want to apply principal component analysis (PCA) to get an index. There are 6 dimensions covering 21 indicators. I took the average of the indicators in each dimension and applied PCA on 6 dimensions. I also used the Rotate command. My questions are:

*

*Should I apply PCA on each indicator separately, or is my procedure right?

*Should the Rotate command be applied or not? If so, why is it good?


text:
Q: Convergence to Delta-distribution I was trying to prove that function $\frac{\sin{nx}}{\pi x}$ sutisfies these conditions:
1) $ \forall D \; \exists c : \forall a,b \;\; |a|<D, \; |b|<D \quad \left|\int_a^b  \frac{\sin{nx}}{\pi x} dx\right| \leq c$
2) $ \underset{n \to \infty}{\lim} \int_a^b  \frac{\sin{nx}}{\pi x} dx = \begin{cases} 1 & 0\in(a,b) \\
              0 & 0\notin(a,b)\\
\end{cases} $
Then it converges to $\delta$-distribution. I do not know how I can show that the function sutisfies these conditions. Can someone please explain how I should proceed or at least give some hints?

A: First, we enforce the substitution $x\to x/n$ to obtain
$$\int_a^b \frac{\sin(nx)}{\pi x} \,dx=\frac1\pi \int_{na}^{nb}  \frac{\sin(x)}{ x}\,dx \tag 1$$

PART $(1):$
Using $\frac{\sin(x)}{x}\le 1$ for $x\in [-\pi ,\pi]$, it is easy to see that for any $na$ and $nb$ we have
$$\left| \frac1\pi \int_{na}^{nb}\frac{\sin(x)}{x}\,dx\right| \le \frac2\pi\int_0^\pi (1)\,dx=2$$

PART $(2)$:
Using $(1)$, we have
$$\lim_{n\to \infty}\int_a^b \frac{\sin(nx)}{\pi x}\,dx=
\begin{cases}
\frac1\pi\int_{-\infty}^\infty \frac{\sin(x)}{x}\,dx=1 &,a<0<b\\\\
\frac1\pi\int_{\infty}^\infty \frac{\sin(x)}{x}\,dx=0 &,0<a<b\\\\
\frac1\pi\int_{-\infty}^{-\infty} \frac{\sin(x)}{x}\,dx=0 &,a<b<0
\end{cases}$$

NOTE:
To show that $\lim_{n\to \infty}\int_{na}^{nb}\frac{\sin(x)}{x}\,dx=0$ for $0<a<b$ or $a<b<0$, we integrate by parts with $u=1/x$ and $v=-\cos(x)$ to write
$$\lim_{n\to \infty}\int_{na}^{nb}\frac{\sin(x)}{x}\,dx=\lim_{n\to \infty}\left(\frac{\cos(na)}{na}-\frac{\cos(nb)}{nb}-\int_{na}^{nb}\frac{\cos(x)}{x^2}\,dx\right)=0$$
To show that $\int_0^\infty \frac{\sin(x)}{x}\,dx=\pi/2$, we write
$$\int_0^\infty \frac{\sin(x)}{x}\,dx=\int_0^\infty \sin(x)\int_0^\infty e^{-kx}\,dk\,dx$$
Now, since we have for any $L>0$
$$\int_0^L\int_0^\infty \left|e^{-kx}\sin(x)\right|\,dk\,dx\le L$$
the Fubini-Tonelli Theorem guarantees that
$$\begin{align}
\int_0^L\int_0^\infty e^{-kx}\sin(x)\,dk\,dx&=\int_0^\infty \int_0^L e^{-kx}\sin(x)\,dx\,dk\\\\
&=\int_0^\infty \frac{1-e^{-kL}(k\sin(L)+\cos(L))}{k^2+1}\,dk\\\\
&=\frac\pi2-\int_0^\infty \frac{e^{-kL}(k\sin(L)+\cos(L))}{k^2+1}\,dk
\end{align}$$
Finally, since $\left|\frac{e^{-kL}(k\sin(L)+\cos(L))}{k^2+1}\right|\le g(k)$ where $g(k)$ is given by
$$g(k)= \begin{cases}e^{-k}&,k\ge 1\\\\\frac{1+\sqrt2}{2}&,k\le 1\end{cases}$$
and $\int_0^\infty g(k)\,dk <\infty$, we can apply the Dominated Convergence Theorem to obtain
$$\begin{align}\lim_{L\to \infty}\int_0^L\int_0^\infty e^{-kx}\sin(x)\,dk\,dx&=\lim_{L\to \infty}\int_0^\infty\int_0^L e^{-kx}\sin(x)\,dk\,dx\\\\
&=\int_0^\infty \lim_{L\to \infty}\left(\frac{1-e^{-kL}(k\sin(L)+\cos(L))}{k^2+1}\right)\,dk\\\\
&= \pi/2
\end{align}$$


text:
Q: HiddenType in Symfony Form not Mapping I'm trying to pass a random number to my form and use it as the value of a HiddenType. I'm using 'attr' => [ 'value' => '$options['editId'] to put the value in the textbox but when the form is submitted, the value isn't inserted into the table.
Listing.php
/**
 * @ORM\Column(type="integer", nullable=false, name="edit_id")
 */
protected $editId;
    /**
     * @return mixed
     */
    public function getEditId()
    {
        return $this->editId;
    }
    /**
     * @param mixed $editId
     */
    public function setEditId($editId)
    {
        $this->editId = $editId;
    }

So I've set the name of the variable to $editId and as far as I know, the variable name is what doctrine uses to map it to the corresponding field (using the field name)
ListingType.php
    ->add('editId', HiddenType::class, [
      'required' => true,
      'disabled' => true,
      'mapped' => true,
      'attr' => [
        'value' => $options['editId']
      ]
    ])

I checked the value of the editId textbox and the value is there but it's just not being inserted.
editId
<input type="hidden" id="listing_editId" name="listing[editId]" disabled="disabled" required="required" value="952726647">


text:
Q: Using Jsoup to get image First sorry for my bad english. Im new in programming (2 year in collage). Im trying to get image from zomato. Yep, API only give us link. ( https://www.zomato.com/jakarta/ayam-keprabon-express-tambora/photos) so I need to manually get the image from web.
I already done this in iOS using Kana.
func parseHTML(html:String){
    if let doc = Kanna.HTML(html: html, encoding: String.Encoding.utf8){
        for show in doc.css("div[class^='photobox']"){
            let getA = show.css("a").first
            let image = getA!.css("img[class^='res-photo']").first?["data-original"]
            let imageUrl = image!.components(separatedBy: "?")[0]
            linkImageArray.append(imageUrl)
            print("jumlah gambar = \(linkImageArray.count)")
        }
    }
    foodCV.reloadData()
}

And my question how to do that in Jsoup?
This how i got HTML
Call<ResponseBody> photos = client.getPhotos();
    photos.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
            if (response.isSuccessful()){
                    Log.i("retrofit: ","response "+response.body().toString());
                    getPhotos(response.body().toString());
            }else{
                Log.i("retrofit: ","notSuccess");
            }
        }

Now im stuck with this. Photobox.toString empty.
public void getPhotos(String stringResponse){
    Document doc = Jsoup.parse(stringResponse);
    Elements photobox = doc.getElementsByClass("container");
    Log.i("html : ",""+photobox.toString());
    Toast.makeText(this, photobox.toString(), Toast.LENGTH_SHORT).show();
    for (Element data:photobox){
        Log.i("html : ",""+data.select("img[class^='res-photo']"));
        Log.i("html : ",""+data.select("img[class^='res-photo']").first().select("data-original"));
        data.select("img[class^='res-photo']").first().select("data-original");
    }
}

And im sure i cannot use this Jsoup: how to get an image's absolute url?. It will return all image. I would like to get img with 'data-original'.
<img class='res-photo-thumbnail thumb-load lazy-photo-inner'
        src='https://b.zmtcdn.com/images/photoback.png'
        title='Coffee Sisters - Coffee Sisters's photo'
        alt='Coffee Sisters - Coffee Sisters's photo'
        data-original='https://b.zmtcdn.com/data/reviews_photos/e4a/04b8e0669945bfe03fd0789cbd42be4a.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A'
        data-type='res'
        data-photo_id='u_NDY5NzEwNzI1MD'
        data-index='27'
        data-category='all'
         />

A: Just changing some lines of code i get what i want~
Call<ResponseBody> photos = client.getPhotos();
    photos.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
            if (response.isSuccessful()){
                    Log.i("retrofit: ","response "+response.body().toString());
                    getPhotos(response.body());

            }else{
                Log.i("retrofit: ","notSuccess");
            }
        }

I only change to pass response.body, instead response.body.string.toString .
public void getPhotos(ResponseBody body){
    try {
        Document doc = Jsoup.parse(body.string());
        Elements photobox = doc.select("img[class=res-photo-thumbnail thumb-load lazy-photo-inner]");Toast.LENGTH_SHORT).show();
        for (Element data : photobox) {
            String imagelink = data.attr("data-original").toString();
            String[] parts = imagelink.split("[?]");
            imageList.add(parts[0]);
            Log.i("imagelink : ",parts[0]);
        }
    }catch (IOException e){
        e.printStackTrace();
    }
}


text:
Q: Visual Studio highlighting source code in bold While editing HTML/ASPX/ASCX etc in visual studio 2005; whenever I select an html tag, visual studio highlights the entire tag in black and bold; the black I'm not so fussed about but the bold changes the length of the line and really messes up the formatting.
Is there a way to disable this?
Thanks,
Chris

A: In VS2010: Select menu Tools - Options, select Environment / Fonts and Colors, look for Brace Matching (Rectangle) in the Display items list. Uncheck the Bold checkbox and click on Ok to confirm.

A: In VS2008, go to the Tools >> Options menu, expand the Environment category in the treeview and select Fonts and Colors. Under Display Items, select HTML Attribute Name and uncheck the "Bold" checkbox.


text:
Q: Zurb Foundation: Semi transparent top bar possible? Is there any way to have a semi-transparent top bar with Zurb Foundation?
I have defined all the relevant variables, from what I can tell, in my _settings.scss file:
$topbar-bg-color
$topbar-bg
$topbar-dropdown-bg
$topbar-dropdown-link-bg
$topbar-dropdown-label-bg

And have tried all number of variations (of rgba's with alpha values from 0-0.5) and have always ended up with either a fully transparent bar or a semi-transparent bar with the dropdowns/buttons stacking their background on top and thus appearing darker/more opaque.

Is there any way to have a topbar that is semi-transparent throughout?
I can see in the stylesheet that .top-bar-section li a:not(.button) is always getting a background colour. I know I could manually override this in my own stylesheet, but I feel like there must be a way to setup the variables so these buttons don't appear darker?

A: The background on the links on the right side of your screenshot are being set by the $topbar-dropdown-bg variable. You'll need to change that to none or transparent.
The other steps are:

*

*Set the background color variables to none.

*Set the $topbar-bg-color to a semi-transparent value, like rgba(#333,0.5).

Here's a demo. I've tried to comment all the variables I set the background to none.

A: try this.
.top-bar { background-color: transparent; }
.top-bar-section { background-color: transparent !important;  }
.top-bar-section li { background-color: transparent !important;  }
.top-bar-section li a { background-color: transparent !important;  }

A: I tried following code, and sounds fine to me. I added few lines to Juni Brosas codes.

header,div.contain-to-grid.sticky, nav.top-bar {

    background: none;}

    li.has-dropdown.a{background: none;}

.top-bar { background-color: transparent; }
.top-bar-section { background-color: transparent !important;  }
.top-bar-section li { background-color: transparent !important;  }
.top-bar-section li a { background-color: transparent !important;  }


text:
Q: Passing value from 1 android spinner to the next spinner Hey i would like to ask how i can pass a selected value from 1 spinner to the next. Example if:
Spinner 1 = "School" is selected
Spinner 2 = Shows sub items for the selected item "School"

OR
Spinner 1 = "Office" is selected
Spinner 2 = Shows sub items for the selected item "Office".

A: Bind data in second spinner (Spinner 2)in onItemSelected listner of first spinner (Spinner 1)
Spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {

          // bind data in second spinner as per you select
          // in this first spinner (Spinner 1)
        }

        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

A: Check out this sample code , this will surely help you out
public class MainActivity extends Activity {

Spinner s1,s2;
Button btn;
String s;
TextView tv;
ArrayAdapter<String> adap1,adap2,adap3;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    s1=(Spinner)findViewById(R.id.spinner1);
    s2=(Spinner)findViewById(R.id.spinner2);
    btn=(Button)findViewById(R.id.button1);
    tv=(TextView)findViewById(R.id.tv1);

    String[] v1=getResources().getStringArray(R.array.c1);
    String[] v2=getResources().getStringArray(R.array.c2);
    String[] v3=getResources().getStringArray(R.array.c3);

    adap1=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, v1);
    adap2=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, v2);
    adap3=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, v3);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
public class ItemSelectedListenerr implements OnItemSelectedListener  {

    String[] v=getResources().getStringArray(R.array.c1);
    public String s;
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub

        s=arg0.getItemAtPosition(arg2).toString();
        if(arg2==0)
        {
            s2.setAdapter(adap1);
        }
        if(arg2==1)
        {
            s2.setAdapter(adap2);
        }
        if(arg2==2)
        {
            s2.setAdapter(adap3);
        }

        tv.setText(s);
        Log.i("hahaha", "item selected is"+s);

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

}

}

It will work like charm 100 %. :D


text:
Q: Detecting Items in a Printer Queue Using Java I'm looking for a way to detect the presence or absence of items in a Windows printer-queue using Java (preferably just Java, but I'll take what I can get).  The count of queued items in the printer-queue could be of some use, but I'm more interested in the mere fact that items are queued and not-yet printed.
There are a few other similar questions here on Stackoverflow, but I couldn't find any that I could extrapolate an answer from.
The purpose of knowing if things are queued or not is to pause a process from injecting more things in the queue, if the queue is non-empty.  The process which is adding to the queue is not a Java application, but a Windows application (e.g., Word, Adobe Reader, etc.)


text:
Q: Node js open ssl(not secured) https services issue in android app I integrated node js open SSL(not secured) https services In my android app. but it is not working. if I integrated in web app first time it is showing an error message that "Your connection is not secured" then in advance setting i am allowing then it is working but in android app it throwing same exception. how to solve this issue.

A: *

*Add certification file in your assets folder.

*Run the following code to make android trust this certification.
Call below trustCert() method like this -
httpsURLConnection.setSSLSocketFactory(trustCert().getSocketFactory());
     private SSLContext trustCert()throws CertificateException,

        IOException,KeyStoreException,

    NoSuchAlgorithmException,KeyManagementException{

    AssetManager assetManager=getAssets();

    CertificateFactory cf=CertificateFactory.getInstance("X.509");

    Certificate ca=cf.generateCertificate(assetManager.open("fileName.crt"));

    // Create a KeyStore containing our trusted CAs

    String keyStoreType=KeyStore.getDefaultType();
    KeyStore keyStore=KeyStore.getInstance(keyStoreType);
    keyStore.load(null,null);
    keyStore.setCertificateEntry("ca",ca);

     // Create a TrustManager that trusts the CAs in our KeyStore

    String tmfAlgorithm=TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf=TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

     // Create an SSLContext that uses our TrustManager
    SSLContext context=SSLContext.getInstance("TLS");
    context.init(null,tmf.getTrustManagers(),null);
    return context;
    }


text:
Q: AutoMapper Object Collections not mapping I am trying to map a class which has an identical layout to the class I am trying to map to. All goes well except when I try to map Object collections. For example when I try to map this property defined in the source class:
[System.Xml.Serialization.XmlElementAttribute("trust", typeof(Trust))]
[System.Xml.Serialization.XmlElementAttribute("valuation", typeof(Valuation))]
[System.Xml.Serialization.XmlElementAttribute("waiver_of_premium_ind", typeof(YesNo))]
[System.Xml.Serialization.XmlElementAttribute("written_under_trust_ind", typeof(YesNo), IsNullable = true)]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
public object[] Items
{
    get { return this.itemsField; }
    set { this.itemsField = value; }
}

I find that it does not map but remains in the same namespace as the source object even though it is a collection in the destination object.
I wonder if you have any ideas on this matter?
EDIT:
More information by way of an example - source class:
namespace Namespace1
{
public class Person
{
    public int PersonID { get; set; }
    public List<Arm> Arms { get; set; }

    [System.Xml.Serialization.XmlElementAttribute("_arms", typeof(Arm))]
    [System.Xml.Serialization.XmlElementAttribute("_hand", typeof(Hand))]
    public object[] Items { get; set; }
}

public class Arm
{
    public Hand Hand { get; set; }
}

public class Hand
{
    public int HandID { get; set; }
    public string HandSide { get; set; }
    public List<Fingers> Fingers { get; set; }
}

public class Fingers
{
    public int FingerNumber { get; set; }
}
}

Destination Class:
namespace Namespace2
{
public class Person
{
    public int PersonID { get; set; }
    public List<Arm> Arms { get; set; }

    [System.Xml.Serialization.XmlElementAttribute("_arms", typeof(Arm))]
    [System.Xml.Serialization.XmlElementAttribute("_hand", typeof(Hand))]
    public object[] Items { get; set; }
}

public class Arm
{
    public Hand Hand { get; set; }
}

public class Hand
{
    public int HandID { get; set; }
    public string HandSide { get; set; }
    public List<Fingers> Fingers { get; set; }
}

public class Fingers
{
    public int FingerNumber { get; set; }
}
}

Code to map the two types and all the nested types within the two namespaces:
public static void CreateMappings(string nsFrom, string nsTo, Type typeFrom)
{
    Assembly assembly = Assembly.GetAssembly(typeFrom);
    var TypesInNamespace = assembly.GetTypes().Where(type => type.Namespace == nsFrom);
    foreach (var sourceType in TypesInNamespace)
    {
        Type destinationType = Type.GetType(sourceType.FullName.Replace(nsFrom, nsTo));
        Mapper.CreateMap(sourceType, destinationType);
    }
}

I then create my person object from Namespace1 and create the mappings using the function above like so:
CreateMappings("Namespace1", "Namespace2", typeof(Namespace1.Person));

After that I call the map function like so:
var result = Mapper.Map<Namespace2.Person>(person);

This maps all the properties of the Person class just fine EXCEPT for the Items object array. It transfers the objects accross but they still belong to the Namespace1 instead of the Namespace2 namespace.
Image of the problem from the watch window can be found here
You can download the console app if you like here
Thanks for any help you can give.
M

A: I have tried the following and it seem working;
public class Tester
{
    public void Test()
    {
        AutoMapper.Mapper.CreateMap<FirstObject, SecondObject>();

        FirstObject t = new FirstObject();
        t.Items = new object[] { new Item() { Id = 1 }, new Item() { Id = 2 } };

        SecondObject result = AutoMapper.Mapper.Map<SecondObject>(t);
    }
}

public class FirstObject
{
    public object[] Items { get; set; }

}

public class SecondObject
{
    public object[] Items { get; set; }
}

public class Item
{
    public int Id { get; set; }
}

A: I know this is really old but I did find the answer (at least for the latest version of AutoMapper (8.0 at time of this answer).  You need to write a custom ITypeConverter for Person that does the mapping of the object[].
In my case i had an object like this (xml attributes removed):
namespace bob {
    public class sally
    {
        public bob.MyEnum[] SomeVarName {get;set;}
        public object[] SomeValueVar {get;set;}
    }
}

namespace martin {
    public class sally
    {
        public martin.MyEnum[] SomeVarName {get;set;}
        public object[] SomeValueVar {get;set;}
    }
}

The custom type converter looked like this:
public class LocationTypeResolver : ITypeConverter<bob.sally,martin.sally>
{
    public martin.sally Convert(bob.sally source, martin.sally destination, ResolutionContext context)
    {
        var retVal = new martin.sally
                     {
                         SomeValueVar = new object[source.SomeVarName.Length],
                         SomeVarName  = new martin.MyEnum[source.SomeVarName.Length]
                     };

        for (int i = 0; i < source.Items.Length; i++)
        {
            retVal.SomeVarName[i] = (martin.MyEnum)Enum.Parse(typeof(martin.MyEnum), source.SomeVarName[i].ToString());

            switch (source.ItemsElementName[i])
            {
                //map any custom types
                default:
                    retVal.SomeValueVar[i] = source.SomeValueVar[i]
            }
        }

        return retVal;
    }
}


text:
Q: Using LINQ to get all object with the same value property? I have a list of items like this:
Item1: Id=1, Name="name1"
Item2: Id=2, Name="name1"
Item3: Id=3, Name="Test2"

What I want to perform is to get reduced list like this:
Item1: Id=1, Name="name1"
Item2: Id=2, Name="name1"

So basically I want to have items that have the same value of given property.
So all the items that have the same value of given property.
I have tried to Group them but I don't know what to do next.
items.OrderBy(x => x.Name);

Edit to explain.
It seams that I did not understand the question. The Answer is expected but there is already a solution here:
Right answer!

A: Using this input ...
Item1: Id=1, Name="name1"
Item2: Id=2, Name="name1"
Item3: Id=3, Name="name3"
Item4: Id=4, Name="Test2"
Item5: Id=5, Name="name1"
Item6: Id=6, Name="name3"

... this gets all the items occurring more than once:
var result = items
    .GroupBy(x => x.Name)        // Group by name
    .Where(g => g.Count() > 1)   // Select only groups having duplicates
    .SelectMany(g => g);         // Ungroup (flatten) the groups

Result:
Item1: Id=1, Name="name1"
Item2: Id=2, Name="name1"
Item5: Id=5, Name="name1"
Item3: Id=3, Name="name3"
Item6: Id=6, Name="name3"

... this gets all the items occurring more than once and renumbers them
var result = items
    .GroupBy(x => x.Name)        // Group by name
    .Where(g => g.Count() > 1)   // Select only groups having duplicates
    .SelectMany(g => g)          // Ungroup (flatten) the groups
    .Select((x, i) => new Item { Id = i + 1, Name = x.Name });

Result:
Item1: Id=1, Name="name1"
Item2: Id=2, Name="name1"
Item3: Id=3, Name="name1"
Item4: Id=4, Name="name3"
Item5: Id=5, Name="name3"

Note that Select has an overload providing a zero-based index.
Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,TResult>)

However, your example input is too simplistic, therefore it is difficult to say what you expect to happen in more complex cases.
If you want entries with a specific name:
string specificName = "name1";
var result = items
    .Where(x => x.Name == specificName);

A: Group items by Name, then pick first item from each group to store into reduced list:
var groupedItems = items.GroupBy(x => x.Name).Select(g => g.First()).ToList();


text:
Q: iPad touch detected only in 320x480 region I'm upgrading iPhone app and so far everything is going well (managed to resize screen display for most forms). However, I can't solve one problem - the touch is detected only in old, 320x480 region. Any ideas how can I solve that?
Thanks
EDIT: Here are the results when code for fetching superview bounds executes:

CGFloat wdth = self.view.superview.bounds.size.width;
NSLog(@"%d", wdth);
CGFloat hgth = self.view.superview.bounds.size.height;
NSLog(@"%d", hgth);

Result:

2010-04-16 14:25:36.268 xxx[14871:207] 0
2010-04-16 14:25:36.269 xxx[14871:207] 1073741824

Result for (%f):

2010-04-16 14:37:26.048 xxx[15053:207] -1.998374
2010-04-16 14:37:26.049 xxx[15053:207] 0.000000

Result for (%g):

2010-04-16 14:37:41.113 xxx[15084:207] -1.99837
2010-04-16 14:37:41.115 xxx[15084:207] 9.48221e-38

A: http://iphonedevelopment.blogspot.com/2010/04/converting-iphone-apps-to-universal.html
In you AppDelegate:

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

// stupid Apple...
CGRect rect = [[UIScreen mainScreen] bounds];
[window setFrame:rect];

// now, display your app
[window addSubview:rootController.view];
[window makeKeyAndVisible];
}

A: In interface builder make sure that mainwindow-iPad "Full screen at launch" window attribute is checked.

A: I have seen similar behavior when a container view is set too small. The subviews will display fine but touches will not fire because the touches are happening outside of the superview.

A: The real problem here is that in the file MainWindow-iPad.xib, the Window object gets created with a size of 320 x 480.  As ayman2010 mentions, setting the "Full screen at launch" fixes this.
Why would apple create an iPad window so small!!!???

A: You may also open the (automatically created) MainWindow-iPad.xib in Interface Builder, select File/Create iPad Version, close the MainWindow-iPad.xib and save the unnamed new XIB (which has the correct size) over the old one.
BurninLeo


text:
Q: What integer does DateTime.CompareTo actually return? I have been looking for an answer for some time now, but nowhere could I actually find it.
I was especially looking at this page. There it says that the CompareTo method returns an integer indicating if it is earlier, the same, or later. I understand the use of it and I understand that for earlier times the integer is negative, for the same it is 0 etc.
But what is this integer? Does it return the difference in seconds, milliseconds, ticks, or maybe nothing at all? I hope you can help me with this and if anyone can find another post with this question, please tell me. I am honestly quite surprised that I couldn't find a question on this topic straight away...

A: The documentation is actually in the IComparable interface page (that DateTime implements):
http://msdn.microsoft.com/en-us/library/system.icomparable.aspx

The implementation of the CompareTo(Object) method must return an Int32 that has one of three values, as shown in the following table.
Less than zero: The current instance precedes the object specified
by the CompareTo method in the sort order.
Zero: This current instance occurs in the same position in the sort order as the object specified by the CompareTo method.
Greater than zero: This current instance follows the object specified by the CompareTo method in the sort order.

A: It is an implementation detail that you should never need to know and can change at any time. The only 3 categories are:

*

*negative

*zero

*positive

If you find yourself using anything more than that, then something is wrong.

A: There is nothing specified, according to MSDN:
if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";
else
   relationship = "is later than";

If you want to compare days between 2 DateTimes you should be looking for something like this:
if ((expiryDate - DateTime.Now).Days < 30)

A: As far as I can tell the number is always -1, 0, or 1.

A: It is implementation of IComparable.CompareTo. This means it will return 0 if equal, positive integer if bigger and negative integer when smaller.

A: You can choose the specific units to compare with TimeSpan
DateTime local_time = DateTime.Now;                  //current time
DateTime remote_time = DateTime.Now.AddMinutes(-2);  //two minutes delayed
TimeSpan time_difference = (local_time - remote_time);
if (time_difference.Minutes <= 5)                    //compare specific units desired
{
bool within_tollerance = true;
}


text:
Q: Add a purchase condition to WooCommerce products I ma trying to add a purchase condition to my WooCommerce products with the following:
{$current_user = wp_get_current_user();

if ( current_user_can('administrator') || wc_customer_bought_product($current_user->email, $current_user->ID,
// return true
return true;}

But I don't know if this code is correct and an advise will be helpful.

A: The product Id argument is missing from wc_customer_bought_product() function, and you can get more easily the WP_User object. Here is a usage example:
global $current_user;

if ( is_user_logged_in() && wc_customer_bought_product( $current_user->email, $current_user->ID, get_the_id() ) ) {
    // Do something
    echo '<p>' . __("You have already purchased this product before") . '</p>';
}


text:
Q: PHP search and merge array elements if they have an identical substring I have this php array:
Array (
     [0] =>
"BLABLABLA   08.09.15

 00.00.00  BBB  BBB  X3 0000  00:00   00:00
 00.00.00  BBB  BBB  TP 0000  00:00
 FNC015P blablablablablabla    blablabla
  1  blablabla     blablabla
 am blablabla blablabla
 blablabla blablabla blablabla
 blablabla
 blablabla
 bblablabla blablabla
 H999999  blablabla
blablabla
blablabla
blablabla
blablabla "

    [1] =>
"00.00.00  BBB  BBB  X3 0000  00:00   00:00
 00.00.00  BBB  BBB  TP 0000  00:00
 FNC015 blablablablablabla    blablabla
   blablablablablabla    blablabla
 blablablablablabla    blablabla
 blablablablablabla    blablabla
 blablablablablabla
 blablablablablabla    bla
  blablablablablabla    blablabla
 H999996   blablablablablabla    blablabla
 blablablablablabla    bla
 blablablablablabla
 blablablablablabla    blabla
 blablablablablabla    blablabla
 blablablablablabla    blablabla
 blablablablablabla    blablabla"

    [2] =>
"BLABLABLA   08.09.15
  00.00.00  BBB  BBB  X3 0000  00:00   00:00
 00.00.00  BBB  BBB  TP 0000  00:00
 FNC234  blablablablablabla    blablabla
 blablablablablabla    blablabla
blablablablablabla    blablabla
 blablab
 blablablablablabla    blablablablablablablablabla    blablabla
 blablab
H999999 blablablablablabla    blablabla
blablablablablabla    blablablablablablablablabla    blablabla"

[3] =>
"BLABLABLA   22.09.15
BLABLABLA
 22.09.15  STR  FNC  X3 2810  14:20   17:25
 29.09.15  FNC  STR  X3 2811  18:15
 FNC042  blablablablablabla    blablabla
 blablablablablabla    blablablablablablablablabla    blablabla
blablablablablabla    blablabla
blablab
 H999997  blablablablablabla    blablabla"
)

What I want to do is merge into one element the items that have the same H______. Like the folowing for the previous example:
 Array (
     [0] =>
"BLABLABLA   08.09.15

 00.00.00  BBB  BBB  X3 0000  00:00   00:00
 00.00.00  BBB  BBB  TP 0000  00:00
 FNC015P blablablablablabla    blablabla
  1  blablabla     blablabla
 am blablabla blablabla
 blablabla blablabla blablabla
 blablabla
 blablabla
 bblablabla blablabla
 H999999  blablabla
blablabla
blablabla
blablabla
blablabla

+

"BLABLABLA   08.09.15
  00.00.00  BBB  BBB  X3 0000  00:00   00:00
 00.00.00  BBB  BBB  TP 0000  00:00
 FNC234  blablablablablabla    blablabla
 blablablablablabla    blablabla
blablablablablabla    blablabla
 blablab
 blablablablablabla    blablablablablablablablabla    blablabla
 blablab
H999999 blablablablablabla    blablabla
blablablablablabla    blablablablablablablablabla    blablabla"

    [1] =>
"00.00.00  BBB  BBB  X3 0000  00:00   00:00
 00.00.00  BBB  BBB  TP 0000  00:00
 FNC015 blablablablablabla    blablabla
   blablablablablabla    blablabla
 blablablablablabla    blablabla
 blablablablablabla    blablabla
 blablablablablabla
 blablablablablabla    bla
  blablablablablabla    blablabla
 H999996   blablablablablabla    blablabla
 blablablablablabla    bla
 blablablablablabla
 blablablablablabla    blabla
 blablablablablabla    blablabla
 blablablablablabla    blablabla
 blablablablablabla    blablabla"

[2] =>
"BLABLABLA   22.09.15
BLABLABLA
 22.09.15  STR  FNC  X3 2810  14:20   17:25
 29.09.15  FNC  STR  X3 2811  18:15
 FNC042  blablablablablabla    blablabla
 blablablablablabla    blablablablablablablablabla    blablabla
blablablablablabla    blablabla
blablab
 H999997  blablablablablabla    blablabla"
)

I have to find the item of the array the substring H_____ and compare with other items and if equal merge. I found examples of removing duplicates and finding exactly same item, but this is not the case.
however unfortunately not always I have the same number of spaces, characters before and after the H______
I got the regex for the key: "#H\d+#" and I know that I need to use preg_match.
Can anyone help please?

A: See comments in code. The use of \b matches at a word boundary and prevents strings like XXH12345 from being matched.
$a = [
    "This is one with H11111",
    "This is one that has an H22222    in it",
    "Tricky one WITH22222 in it",
    "This is another H11111, like the first one",
    "Here's a line without any number at all",
    "Here goes H33333",
    "H22222, finally."
];

foreach ($a as $key => $element) {
    // Find any string matching H<digits> pattern
    if (preg_match('#\bH\d+\b#', $element, $numbers)) {
        $number = $numbers[0]; // Remember first found pattern

        if (!isset($keys[$number])) { // Do we know this from before?
            $keys[$number] = $key; // No, remember the index of this number
        }
        else {
            $a[$keys[$number]] .= " + " . $element; // Yes, append to existing value
            unset($a[$key]); // Then remove the appended element
        }
    }
}
print_r($a);

Output:
Array
(
    [0] => This is one with H11111 + This is another H11111, like the first one
    [1] => This is one that has an H22222    in it + H22222, finally.
    [2] => Tricky one WITH22222 in it
    [4] => Here's a line without any number at all
    [5] => Here goes H33333
)

A: I create some algorithm maybe is not perfect but is work.
$array = [
    'aaaaa aaa H999997 aaa
    aaaa aaaa',
    'bbbbb bbbb bbbb
    bbb H999997 b',
    'cccccccccc ccccccccccc H999993
    ccccccc cccc'
];

$mergeMap = [];
foreach ($array as $key => $value) {
    if (preg_match('/H[0-9]+/', $value, $matches)) {
        $searchId = $matches[0];
        $mergeMap[$searchId][] = $key;
    }
}
$result = [];
foreach ($mergeMap as $key => $indexes) {
    $result[$key] = '';
    foreach ($indexes as $index) {
        $result[$key] .= $array[$index];
    }
}
print_r($result);

And output:
Array
(
    [H999997] => aaaaa aaa H999997 aaa
            aaaa aaaabbbbb bbbb bbbb
            bbb H999997 b
    [H999993] => cccccccccc ccccccccccc H999993
            ccccccc cccc
)

PS. If is any other way (better?), I'll glad to see how this problem can be solved.


text:
Q: Backup to URL not working when using Ola Hallengrens Database Backup I am using Ola Hallengrens DB backup and am trying to get it working with the URL parameter.
I first set up a Shared Access Credential in SQL with the following sql
USE MASTER
CREATE CREDENTIAL [https://exampleblob.blob.core.windows.net/backups]
WITH IDENTITY='SHARED ACCESS SIGNATURE'
,SECRET = 'sv=2015-04-05&ss=bf&srt=sco&sp=rwd&se=2030-11-14T20:07:06Z&st=2016-11-13T12:07:06Z&spr=https&sig=KEY'
GO

Next I tried using the following in my log backup maintenance plan:
sqlcmd -E -S $(ESCAPE_SQUOTE(SRVR)) -d DBATools -Q \
"EXECUTE [dbo].[DatabaseBackup] \
@Databases = 'USER_DATABASES', \
@BackupType = 'LOG', \
@Verify = 'Y', \
@Compress = 'Y', \
@CheckSum = 'Y', \
@LogToTable = 'Y', \
@ChangeBackupType='Y', \
@url='https://exampleblob.blob.core.windows.net/backups', \
@Credential='https://exampleblob.blob.core.windows.net/backups'" -b

However when I run the job I get the following error

Use of WITH CREDENTIAL syntax is not valid for credentials containing
  a Shared Access Signature

A: I just ran into this issue as well creating a Maintenance Plan in SQL Server. The default backup maintenance plan creates a script that includes WITH CREDENTIAL, but I was able to get it working when I removed that default Task. So I ended up with this code in an Execute T-SQL Statement Task:
declare @backuptime as varchar(250);
set @backuptime = 'https://youraccountname.blob.core.windows.net/backups/mytestdb_' + CONVERT(VARCHAR(19), GETDATE(), 120) + '.bak';

BACKUP DATABASE yourdb
    TO URL = @backuptime

A: If you open Properties of 'Back Up Database Task' and set 'CredentialName' to empty, then saving the plan and running the job actually succeeds.
Tried with SSMS 13.0.16100.1


text:
Q: Set user as online in asp.net membership When a user sets the option (remember me) and closes the browser and then opens the site again he does not appear listed with the on-line members.
How can I set a user to on-line after the user reopens the site again?
I am using this code Membership.GetNumberOfUsersOnline(); but it returns 0 on-line

A: If by "sets the option" you mean sets the "remember me" flag.  The reason for this is that this just sets a persistent cookie on the users computer.  They are not "logged in" again afterwards.  Thus, the Membership login never occurs again.
You need to perform some membership activity that has a "userIsOnline" flag, such as calling Membership.GetUser(username, true) to set the userIsOnline.

A: As an alternative, if you want to track users online, you could look at SignalR, see some tutorials here.
There's a post with a similar question here SignalR for tracking online users and chat.
and here signalR tracking connected users


text:
Q: TXC not reading in project file I have been working on my thesis report and use TXC as my editor. Everything was fine until there was a BSOD on my computer for unknown reason. After restarting the computer I realised that the TXC is no longer able to read my project file. Here is the screenshot of the error.

Is there any reason why this happens and how can I possibly fix this issue ?

A: From the TeXnicCenter FAQ on project files:

What's the ressource overhead when working with projects?
There is nearly none. TeXnicCenter only creates two files for each project:
<project>.tcp: This is the project file. It is very small, because it contains only information about the main file of the project and whether the project requires BibTeX and/or MakeIndex. All the other information displayed in the structure view is generated by the TeXnicCenter parser from the main file.
<project>.tps: This is the project session file, which stores information about the files, that where opened in the editor, last time the user worked at the project.
Both files are in INI-file format, so that they a readable/editable with a text editor.
Both files together will require less than 2kB in most cases, so there is no reason, not to use the project support.

The format of <project>.tcp is very basic and has the following format/contents:
[FormatInfo]
Type=TeXnicCenterProjectInformation
Version=4

[ProjectInfo]
MainFile=Master.tex
UseBibTeX=0
UseMakeIndex=0
ActiveProfile=LaTeX > PDF
ProjectLanguage=en
ProjectDialect=US

It's clear that it contains a number of default flags associated with some master/main file. In contrast, the actual session is saved in <project>.tps, and have a more detailed view/format:
[FormatInfo]
Type=TeXnicCenterProjectSessionInformation
Version=2

[Frame0]
Flags=0
ShowCmd=1
MinPos.x=-1
MinPos.y=-1
MaxPos.x=-1
MaxPos.y=-1
NormalPos.left=4
NormalPos.top=26
NormalPos.right=1362
NormalPos.bottom=445
Class=LaTeXView
Document=ch01_introduction.tex

[Frame0_View0,0]
TopLine=1394
Cursor=117985

[Frame1]
Flags=0
ShowCmd=1
MinPos.x=-1
MinPos.y=-1
MaxPos.x=-1
MaxPos.y=-1
NormalPos.left=4
NormalPos.top=26
NormalPos.right=1362
NormalPos.bottom=445
Class=LaTeXView
Document=ch02_methodology.tex

[Frame1_View0,0]
TopLine=4
Cursor=1146

...

[SessionInfo]
FrameCount=18
ActiveFrame=0

[Bookmarks]
ch01_introduction.tex=437

So, for each tab that was open, it stores the filename, the location of the cursor, as well as some information on bookmarks using a [Frame0]...[Frame_View0,0]...[Frame1]...[Frame_View0,0]... layout.
You have the following choices, assuming that your <project>.tps file is intact:

*

*Try to recreate <project>.tcp from the above layout;

*Create a new, blank project and copy the contents of <project>.tps into the newly-created session file;

*Recreate the project from scratch.

Sadly enough it happens that these files become corrupted during crashes. It's happened to me once before. So I usually keep a backup.