text:
Q: How does the SUMPRODUCT command works in this example? The following code allows me to determine distinct values in a pivot table in Excel:
=SUMPRODUCT(($A$A:$A2=A2)*($B$2:$B2=B2))

See also: Simple Pivot Table to Count Unique Values
The code runs perfectly fine. However, can somebody help me understand how this code actually works?

A: Firts, i think you made a type here, as the formula should be :
=SUMPRODUCT(($A$2:$A2=A2)*($B$2:$B2=B2))
Let's decompose it in 2 parts:

*

*First, we check the cells between A2 and A2, so only one cell, and we check the number of cells wich are equals to A2. In this case, the output should be 1, as you're comparing A2 with A2. However, you're not limited to compare A2 with A2. If you had chosen 2 cells equals to A2, the results would have been 2.You can compare as many cells as you want with A2 (replace the characters after the $ to modulate).
We do the same for the second bracket, except the pivot value is B2.

*After that, you need to understand what the function SUMPRODUCT does. It sum the value of the product for a range of array. For example, say you have the value 1 on A1, 1 on A2, 2 on B1 and 3 on B2, if you make SUMPRODUCT((A1:A2)*(B1:B2)) , you will obtain (1*2) + (1*3) = 5. So, in the example you gave us, it will give the sum of (A2=A2)*(B2=B2) = 1.

So, it will output the number of pair (Ax,Bx) which is equals to (A2,B2). With the link, you can see that, if you select the first line only, the function will output 1 (and so the IF will output 1), but if you select the first 2 lines, the function will output 2, (and so the IF will output 0).
I hope this made sense to you, as i hoped i didn't make any mistakes along the explanation.

A: You write: the following code allows me to determine distinct values in a pivot table in Excel
No. That formula alone does not do that. Read on for the explanation of what does.
There's a typo in the formula. It should be
=SUMPRODUCT(($A$2:$A2=A2)*($B$2:$B2=B2))

See the difference?
The formula starts in row 2 and is copied down. In each row, the $A$2 reference and the $B$2 reference will stay the same. The $ signs make them absolute references. The relative references $A2 and A2 will change their row numbers when copied down, so in row 3 the A2 will change to A3 and B2 will change to B3. In the next row it will be A4 and B4, and so on.
You may want to create a sample scenario with data similar to that in the thread you link to. Then use the "Evaluate Formula" tool on the Formulas ribbon to see step by step what is calculated. The formula evaluates from the inside out. Let's assume the formula has been copied down to row 5 and we are now looking at
=SUMPRODUCT(($A$2:$A5=A5)*($B$2:$B5=B5))

($A$2:$A5=A5) this bit compares all the cells from A2 to A5 with the value in A5. The result is an array of four values, either true or false. The next bit ($B$2:$B5=B5) also returns an array of true or false values.

These two arrays are multiplied and the result is an array of 1 or 0 values. Each array has the same number of values.
The first value of the first array will be multiplied with the first value of the second array. (see the red arrows)
The second value of the first array will be multiplied with the second value of the second array. (see the blue arrows)
and so on.
True * True will return 1, everything else will return 0. The result of the multiplication is:

The nature of the SumProduct function is to sum the result of the multiplications (the product), so that is what it does.
This function alone does not do anything at all to establish distinct values in Excel. In the thread you link to, the Sumproduct is wrapped in an IF statement and THAT is where the distinct values are identified.
=IF(SUMPRODUCT(($A$2:$A2=A2)*($B$2:$B2=B2))>1,0,1)
In plain words: If the combination of the value in column A of the current row and column B of the current row has already appeared above, return a zero, otherwise, return a 1.
This marks distinct values of the combined columns A and B.


text:
Q: Convert array of objects post splitting them in half: Javascript I have an array of array of objects similar to this:
arr = [{ val: 1, ts : 123},{val: 2, ts : 125},{val: 3,ts : 120}, {val: 4, ts : 113} , {val:5, ts : 117},{ val: 6, ts : 143},{val: 7, ts : 193},{val: 8, ts : 187}, {val: 9, ts : 115} , {val:10,ts : 116}]

The length of the array is always an even number. Now basically I'd like to split them in 2 halves.
split1 = [{ val: 1, ts : 123},{val: 2, ts : 125},........,{val:5, ts : 117}]
split2 = [{ val: 6, ts : 143},{val: 7, ts : 193},........,{val:10,ts : 116}]

I have to map over these arrays and transform their fields(first item of array1 with first item of array2 and so on). Say the first array is called "old" array with objects having(keys val and ts) and second array is called "new" array with objects having(keys val and ts) . So I have map them and the final should look like this
final = [
          { oldVal:1, oldts: 123 , newVal:6, newts: 143},
          { oldVal:2, oldts: 125 , newVal:7, newts: 193},
          { oldVal:3, oldts: 120 , newVal:8, newts: 187},
          { oldVal:4, oldts: 113 , newVal:9, newts: 115},
          { oldVal:5, oldts: 117 , newVal:10, newts: 116},
        ]

What I have tried is:
var res= a.splice(0, arr.length/2);
var c = a.map((val, ind) => { {val, res[ind]} })

Can someone guide here?

A: You can simply iterate over half of the array, and take the ith element and i + halfth as its pair:

const arr = [{ val: 1, ts : 123},{val: 2, ts : 125},{val: 3,ts : 120}, {val: 4, ts : 113} , {val:5, ts : 117},{ val: 6, ts : 143},{val: 7, ts : 193},{val: 8, ts : 187}, {val: 9, ts : 115} , {val:10,ts : 116}];

const final = [];
const half = arr.length / 2;
for (let i = 0; i < half; i++) {

  final.push({
    oldVal: arr[i].val,
    oldTs: arr[i].ts,
    newVal: arr[i + half].val,
    newTs: arr[i + half].ts,
  });
}

console.log(final);

A: I'm not sure if you have to slice the array or not, but that's my approach :

arr = [{ val: 1, ts : 123},{val: 2, ts : 125},{val: 3,ts : 120}, {val: 4, ts : 113} , {val:5, ts : 117},{ val1: 6, ts : 143},{val1: 7, ts : 193},{val1: 8, ts : 187}, {val1: 9, ts : 115} , {val1:10,ts : 116}];
let final = [];
arr.forEach(function(v, i) {
    if (i >= arr.length / 2) return false;
    final[i] = {oldVal: v.val, oldTs: v.ts, newVal: arr[i + arr.length / 2].val, newTs: arr[i + arr.length / 2].ts}
});
console.log(final)

A: You could take a single loop approach and change the value as the array loops.

var data = [{ val: 1, ts: 123 }, { val: 2, ts: 125 }, { val: 3, ts: 120 }, { val: 4, ts: 113 }, { val: 5, ts: 117 }, { val: 6, ts: 143 }, { val: 7, ts: 193 }, { val: 8, ts: 187 }, { val: 9, ts: 115 }, { val: 10, ts: 116 }],
    result = data.reduce((r, { val, ts }, i, { length }) => {
        const index = i % (length >> 1);
        if (r[index]) {
            r[index].newVal = val;
            r[index].newts = ts;
        } else {
            r[index] = { oldVal: val, oldts: ts };
        }
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: var newArr = [];
var half = Math.floor(arr.length / 2);

for (var i = 0; i < half; i++){
    newArr.push({oldVal: arr[i].val, oldTs: arr[i].ts, newVal: arr[i + half].val, newTs: arr[i + half].ts})
}

**P.S If your original array has even length you will have leftover item

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting started with Cassandra Solr Search I have an existing Datastax Cassandra cluster that I am just experimenting with currently. Cassandra itself was very easy to get going and is working very well. However, I honestly can't seem to figure out how to get Solr Searching working.
I am supposed to have a solrconfig.xml file however I don't seem to have that anywhere on the machine. Solr and cassandra certainly appear to be installed correctly.
I tried a solr_query request which does not work. I tried it connected to a normal node and a Solr node with the same results.
test.user@cqlsh:Datafyer> select "Title" from "Table" where solr_query = 'title:test*';
InvalidRequest: Error from server: code=2200 [Invalid query] message="Undefined name solr_query in where clause ('solr_query = 'title:test*'')"

I have indeed verified that on the search node SOLR_ENABLED=1.
And the node itself is part of the system as you can see below.
administrator@dse-search-qa01:/usr/share/dse$ nodetool ring

Datacenter: Analytics
==========
Address     Rack        Status State   Load            Owns                Token

10.10.98.7  rack1       Up     Normal  325.86 KB       ?                   -7438423332917368512

Datacenter: Cassandra
==========
Address     Rack        Status State   Load            Owns                Token
                                                                           6175281243369380764
10.10.98.3  rack1       Up     Normal  441.55 KB       ?                   4412916390327649050
10.10.98.5  rack1       Up     Normal  442.44 KB       ?                   4563214312080485226
10.10.98.1  rack1       Up     Normal  451.64 KB       ?                   6175281243369380764

Datacenter: Solr
==========
Address     Rack        Status State   Load            Owns                Token

10.10.98.9  rack1       Up     Normal  447.89 KB       ?                   -8974470140210234803

A: It looks like you didn't create the indices for 'solr_query' to work. If you're just experimenting, you can simply run:
dsetool create_core <keyspace>.<table> generateResources=true reindex=true

(for more options, see: https://docs.datastax.com/en/datastax_enterprise/5.0/datastax_enterprise/tools/dsetool.html )
This will create the Solr config and schema XML files for you, as well as index the data already at rest. By default, this will index all columns and do auto-type detection to create the respective indices.
When you're ready to get more in depth with DSE Search, I recommend checking out this course: https://academy.datastax.com/resources/ds310-datastax-enterprise-search
Best,
Marc


text:
Q: Move audio stream from OpenAL application to different audio device I have two different audio output devices: an internal sound card and an external DAC/amp.
When starting an OpenAL application (I first observed the issue with Minecraft, but I suspect it affects all applications that use OpenAL for audio playback), the internal sound card is selected for output, and I cannot change the device using pavucontrol (or KMixer on Kubuntu). The option to select an alternate device is present, but choosing the device has no effect.
How can I select an alternate audio playback device for OpenAL applications?

A: The solution is to add the option allow-moves = true to the OpenAL configuration file (the per-user file is located at ~/.alsoftrc).
If you don't already have this file (it doesn't exist by default), you can copy it from /etc/openal/alsoft.conf or use this sample default configuration.


text:
Q: problem with a text view I'm reading some data like speed and curent location using a single ton class....I'm reading them using an AsyncTask thread in a loop....:)....each time I'm reading a new speed and location I'm setting them in a text view above a map.
This is how a part of my code looks like:
while (true) {
    speed = ServerManager.getInstance().getLastSpeed();
    loc1 = ServerManager.getInstance().getLastLocation();
    speed = ServerManager.getInstance().getLastSpeed();
    speed_1.setText(Integer.toString(speed));
    location.setText(loc1);
}

where:

*

*speed-is float and

*loc1-is String.

This is how my xml looks like:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"

    >

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

 android:orientation="horizontal"

 android:layout_width="fill_parent"
  android:id="@+id/bar"
   android:background="#FFFFFF"
 android:layout_height="wrap_content"

>

<TextView
    android:id="@+id/prod1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="3dip"
    android:textSize="12px"
    android:text="Current Location"
                        />
   <TextView
    android:id="@+id/location"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="3dip"
     android:textColor="#013220"
    android:textSize="12px"

                        />

<TextView
 android:id="@+id/prod2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:gravity="center_horizontal"
 android:paddingLeft="90dip"
 android:textSize="12px"
 android:text="Speed"
            />

<TextView
    android:id="@+id/speed"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="3dip"
    android:textColor="#013220"
    android:textSize="12px"

                        />

</LinearLayout>

<com.google.android.maps.MapView
        android:id="@+id/mapview1"
        android:layout_width="fill_parent"
        android:layout_below="@id/bar"
        android:layout_height="wrap_content"
        android:enabled="true"
        android:clickable="true"
 android:apiKey="0egkyrbiooKAfYyj43YB6wW1cmlG-TiIILXjpBg"
/>

</RelativeLayout>

And this is the error I get posted in my logcat:
   at android.view.ViewRoot.checkThread(ViewRoot.java:2683)

 at android.view.ViewRoot.requestLayout(ViewRoot.java:557)

 at android.view.View.requestLayout(View.java:7918)

 at android.view.View.requestLayout(View.java:7918)

 at android.view.View.requestLayout(View.java:7918)

at android.view.View.requestLayout(View.java:7918)

android.widget.RelativeLayout.requestLayout(RelativeLayout.java:255)

   at android.view.View.requestLayout(View.java:7918

 at android.view.View.requestLayout(View.java:7918)

 at android.widget.TextView.checkForRelayout(TextView.java:5380)

  at android.widget.TextView.setText(TextView.java:2684)

  at android.widget.TextView.setText(TextView.java:2552)

  at
android.widget.TextView.setText(TextView.java:2527)

 at com.Server_1.Server4$InitTask.doInBackground(Server4.java:86)

 at com.Server_1.Server4$InitTask.doInBackground(Server4.java:1)

The line at which I get thie error is:
speed_1.setText(Integer.toString(speed));

A: You should always post UI updates on the UIThread.
runOnUiThread(new Runnable() {
        public void run() {
             speed_1.setText(Integer.toString(speed));
             location.setText(loc1);

        }
}

A: THelper is right, you cannot do any UI operations from a different thread than the main / UI one. You can either use his solution (which works great) or, since you are already using an AsyncTask you can use the methods provided by it:

*

*publishProgress

*onProgressUpdate

Basically, from inside your doInBackground method you call publishProgress() and the AsyncTask class handles all thread-related headaches and calls your onProgressUpdate as soon as possible, on the UI thread, ensuring that you can modify the UI (for example call setText) without any problems.


text:
Q: jQuery AJAX .load() only hitting controller method once So I've read through some of the other similar questions and can't find one that exactly fits my scenario. I have script tag as follows:

$(document).ready(function() {
  $(document).on("change", '[id*="SomeId]', function() {
    SomeFunction();
  });
});

function SomeFunction() {
  $("SomeOtherId").load('@(Url.Action("ControllerMethod", "Controller", null, Request.Url.Scheme))?numberExample=' + 7);
});

  @Html.DropDownListFor(model => model.SomeProperty, (SelectList)Model.SomeOtherProperty, htmlAttributes: new { @id="SomeId", @class="form-control" })

  @Html.DropDownListFor(model => model.SomeEvenOtherProperty, (SelectList)Model.SomeEvenOtherOtherProperty, htmlAttributes: new { @class="form-control" })

So my goal is when the user selects a different option from the first dropdown list, the second dropdown list will dynamically change. This happens when the .load() function is called.
Here is what is happening. I place a breakpoint at the beginning of the method in my controller. When I start the application, I go to this page and select an option from the first dropdown list. SomeFunction() is invoked and the .load() on the SomeOtherId div is run, which results in the breakpoint being hit. The controller method renders a partial view containing another list like this @Html.DropDownListFor(model => model.SomeEvenOtherProperty, (SelectList)Model.SomeEvenOtherOtherProperty, htmlAttributes: new { @class = "form-control" }) in place of the old one. Now if I select a different option from the first dropdown list, again, the breakpoint will be hit and the second dropdown list will be updated.
The issue arises when I go back to select my first option, the breakpoint is not hit, however the list is still updated. I need to hit that breakpoint EVERYTIME, however it seems that it only actually calls the controller method once. I have debugged through the Javascript and can confirm that the SomeFunction() is called everytime. I have also tried putting a callback with an alert to confirm the .load() function is executing successfully. This problem persists even after the page is reloaded. The only way I can hit that breakpoint twice for the one option is if I:

*

*Restart the application.

*Inspect Element -> Console.

Oddly enough, when I inspect element on the page, it will hit the breakpoint more than once for a specific option.
Extra Details:
So in simpler terms, the second dropdown is supposed to contain a different set of options depending on what option is chosen in the first list. However, if the user chooses to save a new entity containing a combination of Option 2 from List 1 and Option 2 from List 2, they should not be able to save another entity with that same combination.
So because this issue persists until the application is restarted, it allows a user to create the same combination TWICE, because the old list is being rendered in place of the second dropdown list. The purpose of the controller method is to render a filtered list by making a quick call to the DB to find out what combinations exist. If the user has saved Option 2 from List 1 and Option 2 from List 2 to the DB, when they go back to create another combination they should not be displayed Option 2 in List 2 if they choose Option 2 from List 1. However because the controller method is only being called the first time they create the combination, when they decide to create a another combination for Option 2 from List 1, it will render the old list, displaying Option 2 from List 2.

A: Add an 'onchange' to the first drop down which calls a javascript function and passes 'this.value'
@Html.DropDownListFor(m => m.ResultId, new SelectList(The list of objects, "fieldid", "value"), new { @class = "form-control HomePageDropDown", @onchange = "javascript:GetValues(this.value);" })

In your javascript function post data you want to the controller (id of the dropdown possibly). In your controller function get the list of objects you want for your next drop down and return it as a Json.
In your ajax result create the markup for a dropdown and pass it to an id in your page.
            var markup = "<option Value='0'>Select option</option>";

            for (var i = 0; i < result.length; i++)
            {
                markup += "<option Value=" + result[i].Value + ">" + result[i].Text + "</option>";
            }

            $("#YOUR ID").html(markup).show();

<select class="form-control HomePageDropDown" data-val="true" id="ID" name="NAME"></select>

A: After looking into the issue more, I found the solution here: Stop jQuery .load response from being cached
Turns out it was a caching issue after all.


text:
Q: DotNetZip save self-extractor directly to Response.OutputStream I'm creating a REST endpoint which should return a sfx (Self Extracting Archive). I'm using Ionic.Zip to do the heavy lifting as far as creating the actual archive, but I'm having some trouble understanding how I should write the finished sfx archive back to the client.
From what I can tell, ZipFile.Save(Response.OutputStream) works fine in order to write a zip file back, and I was rather surprised that I could not do the same using something like ZipFile.SaveSelfExtractor(Response.OutputStream, options). According to the docs, there is no overload for SaveSelfExtractor which takes in a stream.
The examples I'm able to dig up on the web explains either

*

*how I can create my own stub and write that back to the stream first, and then write the zip archive on top of the same stream.

*how I can temporarily store the sfx on the server, and then write it back to the client using a FileStream.

But I do not need nor want to temporarily store the sfx executable on the server, and I do not want to create my own sfx stub. I'm quite happy to use the stub already provided in the Ionic package.
Is there any way for me to just let the Ionic.Zip.ZipFile create the sfx and write it back to Response.OutputStream in one go?
This is what I have now:
using System.IO;
using Ionic.Zip;
using System.Web.Http;
using Context = System.Web.HttpContext;

namespace MyCompany.web.Controllers
{
    [HttpGet]
    public void Export()
    {
        var response = Context.Current.Response;
        var stream = response.OutputStream;

        // Create the zip archive in memory
        using (var archive = new ZipFile())
        {
            archive.Comment = "Self extracting export";
            archive.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;

            using (var memoryStream = new MemoryStream())
            using (var streamWriter = new StreamWriter(memoryStream))
            {
                streamWriter.WriteLine("Hello World");
                archive.AddEntry("testfile.txt", memoryStream.ToArray());
            }

            // What I want is to write this to outputstream
            archive.SaveSelfExtractor(/*stream*/ "export.exe", new SelfExtractorSaveOptions
            {
                Flavor = SelfExtractorFlavor.ConsoleApplication,
                Quiet = true,
                ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently,
                RemoveUnpackedFilesAfterExecute = false
            });
            /*archive.Save(stream); // This will write to outputstream */
        }

        response.AddHeader("Content-Disposition", "attachment; filename=export.exe");
        response.AddHeader("Content-Description", "File Transfer");
        response.AddHeader("Content-Transfer-Encoding", "binary");
        response.ContentType = "application/exe";

        response.Flush();
        response.Close();
        response.End();
    }
}

A: I'm posting this for posterity. It was the best solution I could come up with. Others are welcome to provide a better solution.
    [HttpGet]
    public void Export()
    {
        var response = Context.Current.Response;
        var writeStream = response.OutputStream;

        var name      = "export.exe";

        // Create the zip archive in memory
        using (var archive = new Ionic.Zip.ZipFile())
        {
            archive.Comment = "Self extracting export";
            archive.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;

            using (var memoryStream = new MemoryStream())
            using (var streamWriter = new StreamWriter(memoryStream))
            {
                streamWriter.WriteLine("Hello World");
                streamWriter.Flush();
                archive.AddEntry("testfile.txt", memoryStream.ToArray());
            }

            // Write sfx file to temp folder on server
            archive.SaveSelfExtractor(name, new Ionic.Zip.SelfExtractorSaveOptions
            {
                Flavor = Ionic.Zip.SelfExtractorFlavor.ConsoleApplication,
                Quiet = true,
                DefaultExtractDirectory = "\\temp",
                SfxExeWindowTitle = "Export",
                ExtractExistingFile = Ionic.Zip.ExtractExistingFileAction.OverwriteSilently,
                RemoveUnpackedFilesAfterExecute = false
            });

            // Read file back and output to response
            using (var fileStream = new FileStream(name, FileMode.Open))
            {
                byte[] buffer = new byte[4000];
                int n = 1;
                while (n != 0)
                {
                    n = fileStream.Read(buffer, 0, buffer.Length);
                    if (n != 0)
                        writeStream.Write(buffer, 0, n);
                }
            }

            // Delete the temporary file
            if (File.Exists(name))
            {
                try { File.Delete(name); }
                catch (System.IO.IOException exc1)
                {
                    Debug.WriteLine("Warning: Could not delete file: {0} {1}", name, exc1);
                }
            }
        }

        response.AddHeader("Content-Disposition", "attachment; filename=" + name);
        response.AddHeader("Content-Description", "File Transfer");
        response.AddHeader("Content-Transfer-Encoding", "binary");
        response.ContentType = "application/exe";

        response.Flush();
        response.Close();
        response.End();
    }

A: using (ZipFile zip = new ZipFile())
{
    //string DirPath = Application.StartupPath + @"\CSVfile\files" + DateTime.Now.ToString("yyMMdd");
    string DirPath = Server.MapPath("DoneCSV//" + ViewState["Filepath"]);
    string savepath = DirPath + "/" + ViewState["Filepath"] + "_" + DateTime.Now.ToString("yyMMdd") + ".zip";
    zip.AddDirectory(DirPath);
    zip.Save(savepath);
    //sendmail(savepath);
}


text:
Q: Permutation as a product of transposition I'm trying to figure out how the proof of the following theorem works:
THEOREM: Every permutation is a product of transpositions.
The proof is based on noetherian induction. I don't understand how it goes: proof for the number $m$ of the numbers $i$ from {$1,2,...,n$} for which $\sigma(i) \neq i$. How does this suffice? Why exactly this connection with fixed points? Thank you very much!

A: For a permutation $j_1 j_2 \cdots, j_n$
Imagine people from 1 to $n$ sitting on seats with the same numbers, when one person moves, he changes his seat with one person beside him.
Then person $j_n$ moves to seat $n$ by crossing all the persons in front of him, then person $j_{n-1}$ moves to seat $n-1$ in the same way, etc.
A move is a transposition, and at the end we have the permutation $j_1 j_2 \cdots, j_n$


text:
Q: How do I make values stay in chekbox? How do I make the values stay in checkboxes?
my problem is when I submit the form the values do not stay (in the form).
Below is my code :
Mca<input type="checkbox" name="qual[]" id="Mca" value="Mca"
           <?php if($qual == "Mca") { echo ' checked="checked"' ; } ?>>
 Mtech<input type="checkbox" name="qual[]" id="Mtech" value="Mtech"
          <?php if($qual == "Mtech") { echo "checked"; } ?>>
 Btech<input type="checkbox" name="qual[]" id="Btech" value="Btech"
          <?php if($qual == "Btech") { echo "checked"; } ?>>

A: Try this because $qual is an array.
/* Your $qual should be */ <?php $qual = $GET['qual']; ?>

<?php if($qual == "Mca")

must be changed to :
<?php if(in_array("Mca",$qual)

A: Try using better code for your form:
<?php

$checkboxes = array('Mca', 'Mtech', 'Btech');

foreach($checkboxes as $k => $v){

echo '<input '.($v==$qual[$k]? 'checked="checked" ': '').'type="checkbox" name="qual[]" id="'.$v.'" value="'.$v.'">';

}
?>


text:
Q: behaviour of accessibiility service on events help in understanding the concept of accessibility service in android in its behaviour when the events is stopped also can the accessibility service can be stopped or killed. What are the cases when the accessibility service is killed by the user.

A: No, accessibility service can't be killed by the user.
It can only be turned off from the accessibility settings or via other provided stopping ways.
Android developer site says:
"
The lifecycle of an accessibility service is managed exclusively by the system and follows the established service life cycle. Starting an accessibility service is triggered exclusively by the user explicitly turning the service on in device settings. After the system binds to a service, it calls AccessibilityService#onServiceConnected(). This method can be overridden by clients that want to perform post binding setup.
An accessibility service stops either when the user turns it off in device settings or when it calls AccessibilityService#disableSelf().
"
Please let me know if you have more queries on this


text:
Q: Model works but graph is empty So, my teammate posted this already and got no response.

We built a model.
Our model and numbers work. We have the title and the axis as well. But the graph is empty. Originally, when the RMSE wasn't as good, we had a graph.
So, I assume that I must have changed something without realizing. We probably ran the notebook with the fix and I somehow didn't realize it and deleted the fix.
For context for the current dilemma, the graph looks like this right now : https://gyazo.com/8448d327c952446e661c2411eb4a1405
As for function for making the graph it is the following :
from matplotlib.patches import Rectangle

def run_model(_matrix, _target, label):
  """
  Take features_matrix and target_df and run it through whatever the current model is.
  Plot results.
  """

  # Run model and calculate error
  model.fit(_matrix.loc[_matrix.index.year<2019], _target.loc[_target.index.year<2019])
  error = mean_squared_error(model.predict(_matrix.loc[_matrix.index.year == 2019]), _target.loc[_target.index.year == 2019])

  # Draw plot
  plt.figure(figsize=[21,12], dpi=300)
  plt.plot(_matrix.index, _target, _matrix.index, model.predict(_matrix), linewidth=1)
  plt.xlim(left=mdate.datestr2num("2018-04-15"), right=mdate.datestr2num("2019-10-31"))
  top=200
  plt.ylim(bottom=0, top=top)

  # Add info
  try:
    text_str = "Intercept: {:.1f}".format(model.intercept_)
    for i, row in enumerate(pd.Series(model.coef_, index=_matrix.columns).iteritems()):
      text_str += "\n{}: {:.1f}".format(row[0], row[1])
  except:
    text_str = ""

  plt.text(
    x=mdate.datestr2num("2019-10-31"),
    y=top-6,
    s=text_str,
    bbox=dict(facecolor='gray', alpha=0.2),
    verticalalignment='top',
    horizontalalignment='right'
  )
  plt.annotate(
    label,
    xy=(mdate.datestr2num("2018-04-15"), top-10),
    fontsize=18,
    fontweight='heavy'
  )
  plt.annotate(
    "RMSE = {:.2f}".format(math.sqrt(error)),
    xy=(mdate.datestr2num("2019-04-05"), top-10),
    fontsize=14,
  )
  plt.annotate(
    "Training",
    xy=(mdate.datestr2num("2018-04-15"), 3),
    fontsize=10,
  )
  plt.annotate(
    "Testing",
    xy=(mdate.datestr2num("2019-04-15"), 3),
    fontsize=10,
  )

  rect = Rectangle((mdate.datestr2num("2018-04-15"), 0), 365, 200, facecolor="black", alpha=0.05)
  plt.gca().add_patch(rect)

  plt.show()

One fix that I tried is to remove the  plt.xlim & plt.ylim parts to see if it plotted something. It did plot something but all the text/annotations was/were needed got removed : https://gyazo.com/bbe9d515367bb0873ba4c537cb95ed81
So, we're lost as to what to do to get something plotted. We know it should work, since it did at some point.

Furthermore, what is especially weird is that earlier in the notebook, this graphs perfect :
from matplotlib import dates as mdate
plt.figure(figsize=[21,9], dpi=300)
plt.plot(feature_matrix.index, target_df, feature_matrix.index, model.predict(feature_matrix))
plt.xlim(left=mdate.datestr2num("2019-04-15"), right=mdate.datestr2num("2019-10-31"))
plt.show()

It's the same syntax or am I wrong?


text:
Q: Incorrect reshape of vtk->numpy array? I am reading VTK uniform grid into python. When I visualize a slice through the data in Paraview, I get the following (correct) image:

Then I visualize the slice using via numpy & pylab using the following script:
import vtk
from vtk.util.numpy_support import vtk_to_numpy
import pylab

imr=vtk.vtkXMLImageDataReader()
imr.SetFileName('flow.vti')
imr.Update()
im=imr.GetOutput()

nx,ny,nz=im.GetDimensions()
orig=im.GetOrigin()
extent=im.GetExtent()
spacing=im.GetSpacing()

flowVtk=im.GetPointData().GetArray("|flow|")
flow=vtk_to_numpy(flowVtk).reshape(nx,ny,nz)
# bottom z-slice
flowZ0=flow[:,:,0]
# set extent so that axes units are physical
img=pylab.imshow(flowZ0,extent=[orig[0],orig[0]+extent[1]*spacing[0],orig[1],orig[1]+extent[3]*spacing[1]],cmap=pylab.gray())
img.set_clim(vmin=0,vmax=1000)
pylab.show()

which seems to be out-of-phase. I tried reordering dimensions in reshape(...), it did something, but it has never shown the data it is actually supposed to show.
Is there something obviously wrong?
EDIT: I also tried reshape((nx,ny,nz),order="F") (fortran ordering) and now I get a much better image (with jet colormap for better clarity)  which is almost correct, but the data is suspiciously rotated by 90°, plus I would like some authoritative explanation which ordering to use and why (which one is used by VTK internally?).
EDIT2: to get the same view as in Paraview, I had to do pylab.imshow(np.rot90(flowZ0)); not sure why, so the question is still open:


text:
Q: Using a SQL database and a NoSQL database How do I connect Postgres and MongoDB at the same time in my Django project? I'm just clueless, and the MongoEngine documentation wasn't exactly helpful. Like what would I do in the settings, models, and views.py? Absolutely clueless.
I mean, would I use a db_alias?


text:
Q: Mouse to world position without gluUnProject? I'm trying to implement an editor like placing mod with opengl.
When you click somewhere on the screen an object get placed in that position.
So far this is my code
void RayCastMouse(double posx, double posy)
{
    glm::fvec2 NDCCoords = glm::fvec2( (2.0*posx)/ float(SCR_WIDTH)-1.f, ((-2.0*posy) / float(SCR_HEIGHT)+1.f) );
    glm::mat4 viewProjectionInverse = glm::inverse(projection * camera.GetViewMatrix());
    glm::vec4 worldSpacePosition(NDCCoords.x, NDCCoords.y, 0.0f, 1.0f);
    glm::vec4 worldRay = viewProjectionInverse*worldSpacePosition;
    printf("X=%f / y=%f / z=%f\n", worldRay.x, worldRay.y, worldRay.z);
    m_Boxes.emplace_back(worldRay.x, 0, worldRay.z);
}

The problem is the object isn't placed at the correct position, worldRay vec3 is used to translate the model matrix.
Can anyone one please help with this i will really appreciate it.
By the way division the worldRay xyz component by worldRay.w is setting the object at the camera position.


text:
Q: How can I order by more than one element with an angular ng-repeat? I know how to do a simple orderBy like this:
ng-repeat="test in tes.tests orderBy: 'modifiedDate'">

but how can I orderBy: title (Ascending) and then modifiedBy (most recent first?

A: You should use:
ng-repeat="test in tes.tests | orderBy:['+title','-modifiedDate']

A: Yes.  You can.
<div ng-repeat="test in tes.tests | orderBy: ['title','-modifiedDate']"> {{title}} - {{modifiedDate}}  </div>


text:
Q: resize div width down based on the amount of data contained within repeater and up to a max-width I have a repeater wrapped in a div which displays results as horizontal text. The div is set to a maximum width of 450px which causes the results to wrap onto the next line which is perfect, but the width remains 450px when there are less than 450px width's worth of results. I would like the div to resize down to the width of the results.
This is the data wrapping ok in the div:

This is what happens when there are a small number of results:

This is what I would like to happen:

Here is my css for the div:
        div.SelectedStudents {
            background-color: lightyellow;
            font-family: verdana, tahoma, Helvetica, sans-serif;
            font-size: 11px;
            border:solid 1px black;
            max-width:450px;
            text-align: left;
            margin-left: auto;
            margin-right: auto;
            padding: 5px;
            line-height:1.5em;
        {

Here is my div and repeater:
           <div class="SelectedStudents">
               <asp:Repeater ID="Repeater1" runat="server" DataSourceID="dsProgressCohorts" onitemdatabound="Repeater1_ItemDataBound">
                   <ItemTemplate>
                       <asp:Label ID="Column1Label" runat="server" Text='<%# Eval("Column1") %>' />
                    </ItemTemplate>
                    <AlternatingItemTemplate>
                        <asp:Label ID="Column1Label" runat="server" Text='<%# Eval("Column1") %>' Font-Bold="True" />
                    </AlternatingItemTemplate>
                    <FooterTemplate>
                        <asp:Label ID="lblEmptyData" Text="No Data To Display" runat="server" Visible="false" />
                    </FooterTemplate>
                </asp:Repeater>
           </div>

EDIT:
After applying display:table; to css I lose the spaces between each result:

Got around this by adding a space + ' ' to my select statement inside the SQL stored procedure I am calling to retrieve the results.

A: All you need to add is display: table.  It acts similar to inline-block in that it shrinks to fit the content, but without having the element appear inline.
http://cssdeck.com/labs/12tg3bge
div.SelectedStudents {
    background-color: lightyellow;
    font-family: verdana, tahoma, Helvetica, sans-serif;
    font-size: 11px;
    border:solid 1px black;
    max-width:450px;
    text-align: left;
    margin-left: auto;
    margin-right: auto;
    padding: 5px;
    line-height:1.5em;
    display: table;
}

A: Try setting the width to auto in the css:
div.SelectedStudents {
        background-color: lightyellow;
        font-family: verdana, tahoma, Helvetica, sans-serif;
        font-size: 11px;
        border:solid 1px black;
        max-width:450px;
        text-align: left;
        margin-left: auto;
        margin-right: auto;
        padding: 5px;
        line-height:1.5em;
        width: auto;
    }

if it does not work set the width of all the other containers inside the div to auto as well.


text:
Q: Copy a specific part of a string and addit to the start of each line based on a regex, pass on if not matched in Python2 I have a group of hashes that im looking to copy the USERNAME to the start of each line followed by a ':' symbol and rewrite over the file with the changes.
for example:
$krb5tgs$23$*USERNAME$realm$test/spn*$12345
Would become:
USERNAME:$krb5tgs$23$*USERNAME$realm$test/spn*$12345
The input will be given from a file. So far i have come up with this but as yet haven't got it working.
Any suggestions of the right way of doing this would be appreciated.
This regex works as expected so looking to incorporate that.
'\*(.*?)\$'

L=file.txt
file_object = open(L, 'a+')
while True:
        lines = file_object.readline()
        match = re.search(r'\*(.*?)\$', lines)
        if match:
                for line in fileinput.input([L], inplace=1):
                        sys.stdout.write('TEST'.format(l=lin))
        else:
            pass
        if not lines:
            break
file_object.close()

Second attempt: I can get every line to have "TEST:" at the start but cant quite get an ifstatement or similar working based on the match above.
with open(L, 'r') as f:
    lines = f.readlines()
lines = ['TEST:' + line for line in lines]
with open(L, 'w') as f:
    f.writelines(lines)

A: Usernames seem to be introduced by the sequence $*, and end at $. You should make that part of the regex. There are other things in the string that start with a *, so looking for that alone is probably not sufficient. I think \$\*([^$]+)\$ might be better.
re.search() returns a match object, or None, so it's easy to see when to modify a line, and when to leave it alone.
Also, get into the habit of using context managers (with blocks) to work with files, instead of calling .close() manually.
username_re = re.compile(r'\$\*([^$]+)\$')

with open('file.txt', 'r') as f:
    lines = list(f)

with open('file.txt', 'w') as f:
    for line in lines:
        match = username_re.search(line)
        if match:
            line = match.group(1) + ':' + line
        f.write(line)

Writing to a different file for the output eliminates the risk of destroying input file if something goes wrong.


text:
Q: Shortern code with AutoFilter My code works perfectly to return filtered data to three columns of TextBoxes on a form. When I step through it in debug I can see it takes a very long time to execute my newbie (but working) code. I've recorded macros to try to understand how I might do the same thing with an AutoFilter script & therefore have a quicker script but I'm beaten I'm afraid. Could anyone advise me how I could do this, or if I should bother to do this ?
Private Sub CommandButton1_Click()
Dim i As Integer, c As Integer, d As Integer
Dim e As Integer, f As Integer, g As Integer
Dim lstrw As Integer, ws As Worksheet
Dim MySerNum As String, MyLocation As String
Dim MySearchValue As String, MyStatus As String

    MySearchValue = "x" 'search column for cells that contain only the letter "x"
    Set ws = Sheets(2)
                       'The user will type an "x" in column N at the rows...
                       'he wishes to return data from to the form TextBoxes
    lstrw = ws.Range("N" & Rows.Count).End(xlUp).Row
                       'find how many cells contain string "x"
    For f = 1 To lstrw
        If ws.Cells(f, 14).Value = MySearchValue Then
            e = e + 1
        End If
    Next f
                       ' loop to find occurrence of "x" and load variables
    For i = 1 To lstrw
                      'the adjacent textbox on the form to TextBox1...
                      'is TextBox16 hence the +15 below
        If ws.Cells(i, 14).Value = MySearchValue Then
            MySerNum = ws.Cells(i, 2).Value
        End If
        If ws.Cells(i, 14).Value = MySearchValue Then
            MyLocation = ws.Cells(i, 4).Value
        End If
        If ws.Cells(i, 14).Value = MySearchValue Then
            MyStatus = ws.Cells(i, 5).Value
        End If
        d = c + 15
        g = d + 15
        Me.Controls("TextBox" & c).Value = MySerNum
        Me.Controls("TextBox" & d).Value = MyLocation
        Me.Controls("TextBox" & g).Value = MyStatus
        If ws.Cells(i, 14).Value = MySearchValue Then
            c = c + 1
        End If
    Next i
End Sub

A: That said - here are a couple of tips:
Change:
For i = 1 To lstrw
                  'the adjacent textbox on the form to TextBox1...
                  'is TextBox16 hence the +15 below
    If ws.Cells(i, 14).Value = MySearchValue Then
        MySerNum = ws.Cells(i, 2).Value
    End If
    If ws.Cells(i, 14).Value = MySearchValue Then
        MyLocation = ws.Cells(i, 4).Value
    End If
    If ws.Cells(i, 14).Value = MySearchValue Then
        MyStatus = ws.Cells(i, 5).Value
    End If
    d = c + 15
    g = d + 15
    Me.Controls("TextBox" & c).Value = MySerNum
    Me.Controls("TextBox" & d).Value = MyLocation
    Me.Controls("TextBox" & g).Value = MyStatus
    If ws.Cells(i, 14).Value = MySearchValue Then
        c = c + 1
    End If
Next i

To:
For i = 1 To lstrw
                  'the adjacent textbox on the form to TextBox1...
                  'is TextBox16 hence the +15 below
    If ws.Cells(i, 14).Value = MySearchValue Then
        Me.Controls("TextBox" & c).Value = ws.Cells(i, 2).Value
        d = c + 15
        Me.Controls("TextBox" & d).Value = ws.Cells(i, 4).Value
        g = d + 15
        Me.Controls("TextBox" & g).Value = ws.Cells(i, 5).Value
        c = c + 1
    End If
Next i

Doing so removes all the intermediate My... variables, so you can delete the Dim statements for them. If you need them later, you can set them once at the end of the loop. That will speed things up a bit.


text:
Q: Search a value in associative array and return key Given this associative array:
$currencies = [
    'foo' => [
        'name' => 'EUR',
        'symbol' => '€'
    ],
    'bar' => [
        'name' => 'USD',
        'symbol' => '$'
    ],
    'baz' => [
        'name' => 'GBP',
        'symbol' => '£'
    ],
];

How can I search for a name and retrieve key in a concise manner? I.e. searching for EUR returns foo.
I could loop, but I'd prefer a shorter way, if it exists...
Thanks

A: function searchCurrencies($currencies, $name) {
  foreach($currencies as $k => $v) {
    if($v->name==$name)
      return $k;
  };
};


text:
Q: Add one more Abstract I need to add one more abstract page in my thesis. I'm using this model.
I need it to be in Portuguese, so instead of being an "Abstract" is "Resumo". I already tried to copy the definition of the abstract on the Thesis.cls file and change it but it keeps me giving an error.
How can I solve this problem? The idea is to have an abstract in english and another in portuguese.

A: The relevant command in \abstract is a \textit{Abstract}, i.e. it's hardcoded into the abstract.
This can be changed by patching \textit{Abstract} to \textit{\abstractname}, which is translated into the relevant language representation if babel is used.
I've added the lines
   \usepackage[portuguese,english]{babel}
    \usepackage{xpatch}
    \xpatchcmd{\abstract}{\textit{Abstract}}{\textit{\abstractname}}{}{}

to the preamble of main.tex (being shipped together with Thesis.cls as an example file)
and \selectlanguage{portuguese} just before \abstract and after it switched back to \selectlanguage{english}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Masters/Doctoral Thesis
% LaTeX Template
% Version 1.43 (17/5/14)
%
% This template has been downloaded from:
% http://www.LaTeXTemplates.com
%
% Original authors:
% Steven Gunn
% http://users.ecs.soton.ac.uk/srg/softwaretools/document/templates/
% and
% Sunil Patel
% http://www.sunilpatel.co.uk/thesis-template/
%
% License:
% CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/)
%
% Note:
% Make sure to edit document variables in the Thesis.cls file
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%----------------------------------------------------------------------------------------
%   PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
%----------------------------------------------------------------------------------------

\documentclass[11pt, oneside]{Thesis} % The default font size and one-sided printing (no margin offsets)

\graphicspath{{Pictures/}} % Specifies the directory where pictures are stored

\usepackage[square, numbers, comma, sort&compress]{natbib} % Use the natbib reference package - read up on this to edit the reference style; if you want text (e.g. Smith et al., 2012) for the in-text references (instead of numbers), remove 'numbers'
\hypersetup{urlcolor=blue, colorlinks=true} % Colors hyperlinks in blue - change to black if annoying
\title{\ttitle} % Defines the thesis title - don't touch this

%%%%%%%%%%%%% My additions

\usepackage[portuguese,english]{babel}
\usepackage{xpatch}
\xpatchcmd{\abstract}{\textit{Abstract}}{\textit{\abstractname}}{}{}
%%%%%%%%%%%%% My additions end here for the preamble

\begin{document}

\frontmatter % Use roman page numbering style (i, ii, iii, iv...) for the pre-content pages

\setstretch{1.3} % Line spacing of 1.3

% Define the page headers using the FancyHdr package and set up for one-sided printing
\fancyhead{} % Clears all page headers and footers
\rhead{\thepage} % Sets the right side header to show the page number
\lhead{} % Clears the left side page header

\pagestyle{fancy} % Finally, use the "fancy" page style to implement the FancyHdr headers

\newcommand{\HRule}{\rule{\linewidth}{0.5mm}} % New command to make the lines in the title page

% PDF meta-data
\hypersetup{pdftitle={\ttitle}}
\hypersetup{pdfsubject=\subjectname}
\hypersetup{pdfauthor=\authornames}
\hypersetup{pdfkeywords=\keywordnames}

%----------------------------------------------------------------------------------------
%   TITLE PAGE
%----------------------------------------------------------------------------------------

\begin{titlepage}
\begin{center}

\textsc{\LARGE \univname}\\[1.5cm] % University name
\textsc{\Large Doctoral Thesis}\\[0.5cm] % Thesis type

\HRule \\[0.4cm] % Horizontal line
{\huge \bfseries \ttitle}\\[0.4cm] % Thesis title
\HRule \\[1.5cm] % Horizontal line

\begin{minipage}{0.4\textwidth}
\begin{flushleft} \large
\emph{Author:}\\
\href{http://www.johnsmith.com}{\authornames} % Author name - remove the \href bracket to remove the link
\end{flushleft}
\end{minipage}
\begin{minipage}{0.4\textwidth}
\begin{flushright} \large
\emph{Supervisor:} \\
\href{http://www.jamessmith.com}{\supname} % Supervisor name - remove the \href bracket to remove the link
\end{flushright}
\end{minipage}\\[3cm]

\large \textit{A thesis submitted in fulfilment of the requirements\\ for the degree of \degreename}\\[0.3cm] % University requirement text
\textit{in the}\\[0.4cm]
\groupname\\\deptname\\[2cm] % Research group name and department name

{\large \today}\\[4cm] % Date
%\includegraphics{Logo} % University/department logo - uncomment to place it

\vfill
\end{center}

\end{titlepage}

%----------------------------------------------------------------------------------------
%   DECLARATION PAGE
%   Your institution may give you a different text to place here
%----------------------------------------------------------------------------------------

\Declaration{

\addtocontents{toc}{\vspace{1em}} % Add a gap in the Contents, for aesthetics

I, \authornames, declare that this thesis titled, '\ttitle' and the work presented in it are my own. I confirm that:

\begin{itemize}
\item[\tiny{$\blacksquare$}] This work was done wholly or mainly while in candidature for a research degree at this University.
\item[\tiny{$\blacksquare$}] Where any part of this thesis has previously been submitted for a degree or any other qualification at this University or any other institution, this has been clearly stated.
\item[\tiny{$\blacksquare$}] Where I have consulted the published work of others, this is always clearly attributed.
\item[\tiny{$\blacksquare$}] Where I have quoted from the work of others, the source is always given. With the exception of such quotations, this thesis is entirely my own work.
\item[\tiny{$\blacksquare$}] I have acknowledged all main sources of help.
\item[\tiny{$\blacksquare$}] Where the thesis is based on work done by myself jointly with others, I have made clear exactly what was done by others and what I have contributed myself.\\
\end{itemize}

Signed:\\
\rule[1em]{25em}{0.5pt} % This prints a line for the signature

Date:\\
\rule[1em]{25em}{0.5pt} % This prints a line to write the date
}

\clearpage % Start a new page

%----------------------------------------------------------------------------------------
%   QUOTATION PAGE
%----------------------------------------------------------------------------------------

\pagestyle{empty} % No headers or footers for the following pages

\null\vfill % Add some space to move the quote down the page a bit

\textit{``Thanks to my solid academic training, today I can write hundreds of words on virtually any topic without possessing a shred of information, which is how I got a good job in journalism."}

\begin{flushright}
Dave Barry
\end{flushright}

\vfill\vfill\vfill\vfill\vfill\vfill\null % Add some space at the bottom to position the quote just right

\clearpage % Start a new page

%----------------------------------------------------------------------------------------
%   ABSTRACT PAGE
%----------------------------------------------------------------------------------------

\addtotoc{Abstract} % Add the "Abstract" page entry to the Contents

%%%%% Another addition --> switch to Portuguese
\selectlanguage{portuguese}
\abstract{\addtocontents{toc}{\vspace{1em}} % Add a gap in the Contents, for aesthetics

The Thesis Abstract is written here (and usually kept to just this page). The page is kept centered vertically so can expand into the blank space above the title too\ldots
}
%%%%%%%%%%% Switch back to English

\selectlanguage{english}

\clearpage % Start a new page

%----------------------------------------------------------------------------------------
%   ACKNOWLEDGEMENTS
%----------------------------------------------------------------------------------------

\setstretch{1.3} % Reset the line-spacing to 1.3 for body text (if it has changed)

\acknowledgements{\addtocontents{toc}{\vspace{1em}} % Add a gap in the Contents, for aesthetics

The acknowledgements and the people to thank go here, don't forget to include your project advisor\ldots
}
\clearpage % Start a new page

%----------------------------------------------------------------------------------------
%   LIST OF CONTENTS/FIGURES/TABLES PAGES
%----------------------------------------------------------------------------------------

\pagestyle{fancy} % The page style headers have been "empty" all this time, now use the "fancy" headers as defined before to bring them back

\lhead{\emph{Contents}} % Set the left side page header to "Contents"
\tableofcontents % Write out the Table of Contents

\lhead{\emph{List of Figures}} % Set the left side page header to "List of Figures"
\listoffigures % Write out the List of Figures

\lhead{\emph{List of Tables}} % Set the left side page header to "List of Tables"
\listoftables % Write out the List of Tables

%----------------------------------------------------------------------------------------
%   ABBREVIATIONS
%----------------------------------------------------------------------------------------

\clearpage % Start a new page

\setstretch{1.5} % Set the line spacing to 1.5, this makes the following tables easier to read

\lhead{\emph{Abbreviations}} % Set the left side page header to "Abbreviations"
\listofsymbols{ll} % Include a list of Abbreviations (a table of two columns)
{
\textbf{LAH} & \textbf{L}ist \textbf{A}bbreviations \textbf{H}ere \\
%\textbf{Acronym} & \textbf{W}hat (it) \textbf{S}tands \textbf{F}or \\
}

%----------------------------------------------------------------------------------------
%   PHYSICAL CONSTANTS/OTHER DEFINITIONS
%----------------------------------------------------------------------------------------

\clearpage % Start a new page

\lhead{\emph{Physical Constants}} % Set the left side page header to "Physical Constants"

\listofconstants{lrcl} % Include a list of Physical Constants (a four column table)
{
Speed of Light & $c$ & $=$ & $2.997\ 924\ 58\times10^{8}\ \mbox{ms}^{-\mbox{s}}$ (exact)\\
% Constant Name & Symbol & = & Constant Value (with units) \\
}

%----------------------------------------------------------------------------------------
%   SYMBOLS
%----------------------------------------------------------------------------------------

\clearpage % Start a new page

\lhead{\emph{Symbols}} % Set the left side page header to "Symbols"

\listofnomenclature{lll} % Include a list of Symbols (a three column table)
{
$a$ & distance & m \\
$P$ & power & W (Js$^{-1}$) \\
% Symbol & Name & Unit \\

& & \\ % Gap to separate the Roman symbols from the Greek

$\omega$ & angular frequency & rads$^{-1}$ \\
% Symbol & Name & Unit \\
}

%----------------------------------------------------------------------------------------
%   DEDICATION
%----------------------------------------------------------------------------------------

\setstretch{1.3} % Return the line spacing back to 1.3

\pagestyle{empty} % Page style needs to be empty for this page

\dedicatory{For/Dedicated to/To my\ldots} % Dedication text

\addtocontents{toc}{\vspace{2em}} % Add a gap in the Contents, for aesthetics

%----------------------------------------------------------------------------------------
%   THESIS CONTENT - CHAPTERS
%----------------------------------------------------------------------------------------

\mainmatter % Begin numeric (1,2,3...) page numbering

\pagestyle{fancy} % Return the page headers back to the "fancy" style

% Include the chapters of the thesis as separate files from the Chapters folder
% Uncomment the lines as you write the chapters

\input{Chapters/Chapter1}
%\input{Chapters/Chapter2}
%\input{Chapters/Chapter3}
%\input{Chapters/Chapter4}
%\input{Chapters/Chapter5}
%\input{Chapters/Chapter6}
%\input{Chapters/Chapter7}

%----------------------------------------------------------------------------------------
%   THESIS CONTENT - APPENDICES
%----------------------------------------------------------------------------------------

\addtocontents{toc}{\vspace{2em}} % Add a gap in the Contents, for aesthetics

\appendix % Cue to tell LaTeX that the following 'chapters' are Appendices

% Include the appendices of the thesis as separate files from the Appendices folder
% Uncomment the lines as you write the Appendices

\input{Appendices/AppendixA}
%\input{Appendices/AppendixB}
%\input{Appendices/AppendixC}

\addtocontents{toc}{\vspace{2em}} % Add a gap in the Contents, for aesthetics

\backmatter

%----------------------------------------------------------------------------------------
%   BIBLIOGRAPHY
%----------------------------------------------------------------------------------------

\label{Bibliography}

\lhead{\emph{Bibliography}} % Change the page header to say "Bibliography"

\bibliographystyle{unsrtnat} % Use the "unsrtnat" BibTeX style for formatting the Bibliography

\bibliography{Bibliography} % The references (bibliography) information are stored in the file named "Bibliography.bib"

\end{document}

A: Using an updated version of the template, this is much easier:

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Masters/Doctoral Thesis
% LaTeX Template
% Version 2.1 (2/9/15)
%
% This template has been downloaded from:
% http://www.LaTeXTemplates.com
%
% Version 2.0 major modifications by:
% Vel (vel@latextemplates.com)
%
% Original authors:
% Steven Gunn  (http://users.ecs.soton.ac.uk/srg/softwaretools/document/templates/)
% Sunil Patel (http://www.sunilpatel.co.uk/thesis-template/)
%
% License:
% CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass[
11pt, % The default document font size, options: 10pt, 11pt, 12pt
%oneside, % Two side (alternating margins) for binding by default, uncomment to switch to one side
portuguese,
english, % ngerman for German
singlespacing, % Single line spacing, alternatives: onehalfspacing or doublespacing
%draft, % Uncomment to enable draft mode (no pictures, no links, overfull hboxes indicated)
%nolistspacing, % If the document is onehalfspacing or doublespacing, uncomment this to set spacing in lists to single
%liststotoc, % Uncomment to add the list of figures/tables/etc to the table of contents
%toctotoc, % Uncomment to add the main table of contents to the table of contents
%parskip, % Uncomment to add space between paragraphs
headsepline,
nohyperref
]{MastersDoctoralThesis}
\usepackage{blindtext}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{palatino}

\usepackage[backend=bibtex,style=authoryear,natbib=true]{biblatex}

\addbibresource{example.bib} % The filename of the bibliography

\usepackage[autostyle=true]{csquotes} % Required to generate language-dependent quotes in the bibliography

\thesistitle{Thesis Title}
\supervisor{Dr. James \textsc{Smith}}
\examiner{}
\degree{Doctor of Philosophy}
\author{John \textsc{Smith}}

\university{University of Duckburg}
\department{Department of applied Dancing}
\group{A nice group}
\faculty{Jazz dance}

\newcaptionname{portuguese}{\byname}{por}

\begin{document}
\begin{abstract}
    \blindtext
\end{abstract}
{\selectlanguage{portuguese}
\begin{abstract}
    \blindtext
\end{abstract}
}
\end{document}

Note: That abstract page might not even make any sense in portuguese.


text:
Q: How to get the first value to be default in select option How to get the first value to be default value. In the select option values I have taken a loop for the multiple values. Now I want to select the first values by default but in a way that the last value is always selected by default. How do I do this?

A: try <option value="1" selected="selected">xyz</option>

A: Try this, add the selected attribute to the option u want to be selected
<select>
<option selected="selected"  value="1">selected option1</option>
<option  value="2">option2</option>
<option value="3">option3</option>
</select>

A: use selected attribute for your first option


text:
Q: inner join ambiguous column name: id I want to search in my db, but the error
ambiguous column name: id (code 1): , while compiling: SELECT placa, modelo, fabricante, cor FROM carros INNER JOIN carroCliente ON id = carro WHERE cliente = ?
shows up, what am I doing wrong? I've been searching all day and did not find anything here.
My method:
public void buscarDados(){
        cursor = getDatabase().rawQuery("SELECT " + DatabaseHelper.Carros.PLACA + ", " + DatabaseHelper.Carros.MODELO + ", "
                + DatabaseHelper.Carros.FABRICANTE + ", " + DatabaseHelper.Carros.COR +  " FROM " + DatabaseHelper.Carros.TABELA_CARROS
                + " INNER JOIN " + DatabaseHelper.CarroCliente.TABELA_CARROCLIENTE +
                " ON " + DatabaseHelper.Carros.ID + " = " + DatabaseHelper.CarroCliente.ID_CARRO
                + " WHERE " + DatabaseHelper.CarroCliente.ID_CLIENTE + " = ?", new String[] {Integer.toString(buscarIdCliente())});

        if(cursor!=null){
            cursor.moveToFirst();
        }
    }

A: As @Akhilesh mentioned in his comment, your error is probably being caused due to both tables having an id column defined.  You can get around this by using explicit aliases to limit the scope of each column:
SELECT
    t1.placa,
    t1.modelo,
    t1.fabricante,
    t1.cor
FROM carros t1               -- explicitly specify which 'id' column you are referring to
INNER JOIN carroCliente t2
    ON t1.id = t2.carro
WHERE t2.cliente = ?

The other answers gave Java code, but I think a raw query is actually more appropriate here because it shows how you can use aliases to fix your problem.  Actually, it is always a good idea to use aliases in your query, because it makes the query less terse and easier to read and understand.

A: Use Reference for both the tables, both tables have id columns ambiguous column name: id (code 1) error
public void buscarDados(){
        cursor = getDatabase().rawQuery("SELECT A." + DatabaseHelper.Carros.PLACA + ", A." + DatabaseHelper.Carros.MODELO + ", A."
                + DatabaseHelper.Carros.FABRICANTE + ", A." + DatabaseHelper.Carros.COR +  " FROM " + DatabaseHelper.Carros.TABELA_CARROS
                + " as A INNER JOIN " + DatabaseHelper.CarroCliente.TABELA_CARROCLIENTE +
                " as B ON A." + DatabaseHelper.Carros.ID + " = B." + DatabaseHelper.CarroCliente.ID_CARRO
                + " WHERE B." + DatabaseHelper.CarroCliente.ID_CLIENTE + " = ?", new String[] {Integer.toString(buscarIdCliente())});

        if(cursor!=null){
            cursor.moveToFirst();
        }
    }

A: You have to use syntax as gicen below;
SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;

In your example ;
public void buscarDados(){
        cursor = getDatabase().rawQuery(
        "SELECT DatabaseHelper.Carros.PLACA, DatabaseHelper.Carros.MODELO, "
                + "DatabaseHelper.Carros.FABRICANTE , DatabaseHelper.Carros.COR FROM DatabaseHelper.Carros.TABELA_CARROS "
                + " INNER JOIN  DatabaseHelper.CarroCliente.TABELA_CARROCLIENTE  ON "
        + " DatabaseHelper.Carros.ID = '" + DatabaseHelper.CarroCliente.ID_CARRO + "' "
                + " WHERE DatabaseHelper.CarroCliente.ID_CLIENTE  = '", new String[] {Integer.toString(buscarIdCliente())} + "'" );
       if(cursor!=null){
            cursor.moveToFirst();
        }
    }

A: Try to give each table a name like
SELECT st.id FROM student st INNER JOIN attendance at ON at.id = st.id;

Something like this. So, it can be identified that which table's id you are trying to access.
If you get confused, than try preparing query in and DBMS tool first, than write code for that query.


text:
Q: Can't export to .p12 apple developer account I'm trying to make a .pkpass file using this guide
However I can't export inside of my dev account the .p12 pass. I tried to trouble shoot it using this other guide
But I don't have these options inside of my account
screenshot 1
screenshot 2
I tried every single step of the guides to no avail. For those with an apple dev account, are you presenting the same issues? Do you believe that perhaps the guides are outdated?
I would really appreciate any light on this matter.


text:
Q: Finding the number of basic/zero variables at an optimal corner point in linear programming
Draw a graph of the following problem
  $$\begin{align}4x+3y &\leq 180 \\
7x+4y &\leq 280 \\
y &\leq 40 \\
x &\geq 0 \\ y &\geq 0\end{align}$$
a) If the problem is to maximize the objective function $z= 5x+6y$ subject to above constrains, what would be the optimal solution? Find it graphically.

So I found it and the optimal solution is at $x=15$, $y=40$ where $z=315$.

b) How many basic and zero variables are there at an optimal corner point?

Well yeah, I don't know how to answer part b.

A: Writing your LP in standard form gives:
$$
\begin{aligned}
\max z=5x+6y\\
4x+3y+s_1&=180\\
7x+4y+s_2&=280\\
y+s_3&=40\\
x,y&\geq0
\end{aligned}
$$
The optimal solution, as you have shown is $x=14,y=40, z=315$. Substituting the values for $x$ and $y$ into the constraints above, we can see that $s_1=0,\,s_2=15,\,s_3=0$.
Thus, the basic variables are $x,y,s_2$ and the non-basic variables are $s_1,s_3$.
In response to my comments, each constraint corresponds to one basic variable. With $m$ constraints and $n$ variables ($m<n$), at each feasible solution, we are solving a linear system of $m$ equations in $m$ variables, having set $n-m$ variables to be zero. The set of variables we are solving for are called basic variables and the set of variables which we assign the value zero are non-basic variables.


text:
Q: I need help understanding a simple concept that I can't seem to get with a certain type of inequality I've got this inequality:
$$\dfrac{1}{x}-\dfrac{x}{2x-1}\geq1$$
And the solutions are supposed to be $(0,1/2)$. But why? Whenever I make my inequality table, it ends up telling me the solution is $(-∞,0) \cup (1/2,+∞)$
Can someone help me understand what is going on? I really need to know this to study for a test.
EDIT: Alright, to make it clearer this is what I've got after simplifying everything:
$$\dfrac{\left(-3x^2+3x-1\right)}{x\left(2x-1\right)}>=0$$
After that I just put all the values on a table, in which I look for the numbers that make 2x-1 and x equal 0. The polynomial in the numerator can never be zero since its discriminant is less than 0. That's basically where I'm stuck at. I would post the table, but I've no clue where I could create one, I'm doing this on paper.

A: $\dfrac{1}{x} - \dfrac{x}{2x-1} \geq 1 \iff \dfrac{1}{x} - \dfrac{x}{2x-1} - 1 \geq 0 \iff \dfrac{2x-1 - x^2 - x(2x - 1)}{x(2x - 1)} \geq 0 \iff \dfrac{-3x^2 + 3x - 1}{x(2x - 1)} \geq 0$.
Observe that: $-3x^2 + 3x  - 1 < 0$, $\forall x$ because $\triangle = 3^2 - 4(-3)(-1) = 9 - 12 = -3 < 0$, and $-3 < 0$. Thus the inequality is equivalent to:
$x(2x - 1) < 0$, and this gives: $0 < x < \dfrac{1}{2}$

A: The inequality is equivalent to
$$
\begin{array}{rclr}
  \frac{2x-1 - x^2}{x(2x-1)} -1       &\geq& 0  & \iff \\
  \frac{2x-1 - x^2-2x^2 + x}{x(2x-1)} &\geq& 0  & \iff \\
  \frac{-3x^2 + 3x -1 }{x(2x-1)}      &\geq& 0. & \ \\
\end{array}
$$
The numerator is a negative term (the polynomial opens downwards and has no real roots) thus the quotient is non-negative precisely when $x(2x-1) < 0$, i.e.
when $x \in (0,1/2)$.

A: Combine the fractions on the LHS of the inequality by finding the common denominator and note that the numerator is then the square of $x-1$:
$$\frac{1}{x}-\frac{x}{2x-1}=\frac{2x-1-x^2}{x(2x-1)}=-\frac{(x-1)^2}{x(2x-1)}=\frac{(x-1)^2}{x(1-2x)}.$$
Assuming $x\neq 1$, we divide both sides by $(x-1)^2$:
$$1\leq \frac{(x-1)^2}{x(1-2x)} \implies \frac{1}{(x-1)^2}\leq \frac{1}{x(1-2x)}$$
This tells us that $1/x$ and $1/(1-2x)$ must either be both positive or both negative, and hence that $x$ and $1-2x$ must either be both positive or negative as well. All that's left now is some very simple case work.


text:
Q: Printing authors in descending order per sold copies per year I have two tables
create table AUTHORS
(
    id integer primary key,
    name varchar(30)
)

create table BOOKS
(
    id integer primary key,
    name varchar(30),
    year integer,
    sold_copies integer,
    author_id integer references AUTHORS (id)
)

How would I create a table with authors in descending order per sold copies of books per year in pgAdmin4 (PostgreSQL) ?
im a beginner and I am not sure how to go about this

A: I don't see why you would need to create a new table. A simple SELECT will do (maybe stored inside a view)
select a.id, a.name, b.year, sum(b.sold_copies) as total_copies
from author a
  join books b on b.author_id = a.id
group by a.id, a.name, b.year
order by sum(b.sold_copies) desc;


text:
Q: Session Handling in Angular JS, with Spring MVC I am creating a project in AngularJs at frontend and Spring MVC in backend.
Now assume when a used logged in and if he wants to update his information, for this i have created an api which request for emailid and update the rest object in database of that email id
Now i have some questions,
1.) I dont want to use CookieStore or others sessionStorage or localstorage (because of my personal vulnerability experience and also i want to use session only) in Angular, how can i do it in angular with Spring MVC.
2.) How can i retrieve the email id from session to update data?
3.)If a user goes to another page how can i maintain that session in another page, how can i check that session is there and user is authentic to see the page
Read a lot about it but unable to find the exact solution with session. Answer over there is manage it by cookieStore.or localstorage, Please help

A: Let's try and see what is happening here using cookies is the right way to this, you may think it is not safe but is the safest way to do it. With cookies you will be sharing the same session in all tabs, so you can handle in all tabs and share it.
There is also an alternative option and is using URL rewriting, quoting @vanje in this question in stackoverflow

the session is only identified via a URL parameter containing the session ID. So every internal URL of your web application has to be enhanced with this parameter using the method HttpServletResponse.encodeURL(). If you are using a web framework like Wicket, chances are good that this is already done for you.

Lets go now with the Angular JS - Spring MVC approach:
There is no need to access the session within the Angular JS front-end, if you need to use it and you are using JSP you may use scriplet to retrieve the information openening a <%= session.getAttribute("user") %> , but as I said there is no need to do this. You may call your function, and retrieve this information in your controller in Spring.
You have a controller in angular JS that calls with http to your REST controller in Spring such like this. assuming that you save your user first in session:
$scope.getUserInfo= function () {
        $http.get(appContextPath +'/rest/getuser/').success(function (data) {
            $scope.user= data;
        });
    };

You may have a request mapping for the URL above:
@RequestMapping(value = "/rest/getuser", method = RequestMethod.GET)
@ResponseBody
public User getUserInfo (HttpSession session) {
    User nUser = session.getAttribute("user");
    return nUser;
}

A: I think the best way is to create a method in your AngularJS controller and then call it.
Java code:
@RequestMapping(value = "/menu/get", method = RequestMethod.GET, headers="Accept=*/*")
public @ResponseBody Empleado showMenu(HttpSession session) {
    Empleado empleado = (Empleado) session.getAttribute("empleado");

    return empleado;
}

AngularJS code:
angular.module('myModule')
    .controller('myMenuController', ['$scope', '$http'
        function($scope, $http){

        getEmpleadoInfo = function () {
            $http.get(myContextPage + '/menu/get')
                .then(function(data) {
                    $scope.empleado = data;
                })
        }

        getEmpleadoInfo();

    }]);

This way, when you load the page, the object will be loaded on the scope.


text:
Q: Sigma Algebra Measurable R.V I am trying to figure out what random variables are measurable with respect to sigma algebra given by $[1-4^{-n}, 1]$ where $n= 0, 1, 2, ....$ if $[0,1]$ is the sample space. I believe I can do with with indicator functions but I'm not sure how to write this.
Thanks!

A: The collection of intervals $[1-4^{-n}]$, $n\geqslant 0$ does not form a $\sigma$-algebra, but if we define $I_n:=[1-4^{-n},1-4^{-n-1})$, then the collection of sets of the form $\bigcup_{n\in J}I_n$, $J\subset\mathbb N$, plus singleton $\{1\}$,  is a $\sigma$-algebra.
If a $\sigma$-algebra is generated by a countable partition $(A_n)_{n\in\mathbb N}$, we can find an explicit characterization of measurable functions, namely, functions of the form $x\mapsto \sum_{n=0}^{+\infty}c_n\chi_{A_n}$, where $c_n$'s are real numbers.

A: Well, any indicator function won't do. You can see that there is no way to write $(0,25,0.5)$ as an element of the $\sigma$-algebra generated by those sets, and so the indicator of that set won't be measurable. But the set of simple functions which are measurable in that space is most likely dense with respect to any measure that is absolutely continuous with respect Lebesgue measure.

A: If $\mathcal{P}$ is a countable partition of the space then $\mathcal{F}=\left\{ \cup\mathcal{P}'\mid\mathcal{P}'\subset\mathcal{P}\right\} $
is the $\sigma$-algebra generated by the elements of $\mathcal{P}$.
A function $f$ is $\mathcal{F}$-measurable iff it is constant on
elements of $\mathcal{P}$.
So such functions take the form: $$\sum_{P\in\mathcal{P}}c_{P}1_{P}$$
where the $c_{P}$ are constants and the $1_{P}$ are characteristic
functions.
You are in such a position. The sets $I_{n}=\left[1-4^{-n},1-4^{-n-1}\right)$
together with singleton $\left\{ 1\right\} $ form such a partition of
$\left[0,1\right]$.


text:
Q: Multiple Unexpected Request: GET I have an angular app, that on initialisation, make a number of http requests.
I have set up a test, to expect the first request, and the second,
describe("MyController--", function () {

    var controller, scope, $httpBackend, myFactory;

    var iResponse = {
        table: 'red',
        price: '1.99'
    };

    beforeEach(angular.mock.module('myApp'));

    beforeEach(inject(function (_$controller_, _$rootScope_, _$httpBackend_, _myFactory_) {
        scope = _$rootScope_.$new();
        $httpBackend = _$httpBackend_;

        $httpBackend.expectGET("/app/shopping/cart/layout.html").respond({});
        $httpBackend.expectGET("/app/rest/products").respond(iResponse);

        myFactory = _myFactory_;
        spyOn(myFactory, 'getData').and.callThrough();

        controller = _$controller_('MainController', {$scope: scope});
        scope.$apply();
        $httpBackend.flush();
    }));

    it('should verify that the controller exists ', function() {
        expect(controller).toBeDefined();
    });

With the above, i keep seeing the error:
Error: Unexpected request: GET /app/rest/products
Information:    Expected GET /app/shopping/cart/layout.html

Any ideas what i am missing?

A: Firstly I would preload HTML in karma conf so u don't have to expect HTML
Secondly does your controller make a call to the unexpected url? If so u shud expect the request
All the best


text:
Q: @XmlElementWrapper for web method using JAX-WS I have a web service like below, it contains a web method which will return a list of objects:
@WebService(name = "ClubMembershipPortType", serviceName = "ClubMembershipService", portName = "ClubMembershipSoapPort", targetNamespace = "http://club.com/api/ws")
public class ClubMembershipWS {
  @WebMethod(operationName = "findClubMembershipsByClubId", action = "urn:findClubMembershipsByClubId")
  @WebResult(name = "club_membership")
  public List<ClubMembership> findClubMembershipsByClubId(@XmlElement(required=true)
                                                        @WebParam(name = "club_id") String clubId,
                                                        @WebParam(name = "status") StatusEnum status)
  ...
  ...
  }
}

The response I got for the api request is like below:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:findClubMembersByClubIdResponse xmlns:ns2="http://club.com/api/ws">
         <club_membership>
            ...
         </club_membership>
         <club_membership>
            ...
         </club_membership>
      </ns2:findClubMembersByClubIdResponse>
   </S:Body>
</S:Envelope>

The question is how to use @XmlElementWrapper (or other way?) to make the response like below?
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:findClubMembersByClubIdResponse xmlns:ns2="http://club.com/api/ws">
         <club_membership_list>
             <club_membership>
               ...
            </club_membership>
            <club_membership>
               ...
            </club_membership>
         </club_membership_list>
      </ns2:findClubMembersByClubIdResponse>
   </S:Body>
</S:Envelope>

A: Did you try this?
@XmlElementWrapper(name="club_membership_list", required=true)
@XmlElement(name="club_membership", required=true)
public List<ClubMembership> findClubMembershipsByClubId(@WebParam(name = "club_id") String clubId,
@WebParam(name = "status") StatusEnum status)

A: Annotate your method with:
@WebResult(name="club_membership_list", targetNamespace = "http://club.com/api/ws")


text:
Q: Cannot use self-starting models when manually defining maxiter for nls()? Data:
structure(list(ID = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L,
24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L,
37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L,
50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 59L, 60L, 61L,
62L, 63L, 64L, 65L, 66L, 67L, 68L, 69L, 70L), Stage = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 3L, 3L, 5L, 5L, 5L, 1L, 1L, 6L, 6L,
4L, 4L, 2L, 2L, 7L, 7L), .Label = c("milpa", "robir", "jurup che",
"pak che kor", "mehen che", "nu kux che", "tam che"), class = "factor"),
    Time.Since.Burn = c(4, 2, 0.21, 2, 0.42, 4, 0.33, 0.33, 3,
    6, 2.5, 5, 4, 5, 1.5, 6, 4, 6, 3, 6.5, 6.5, 6, 4, 2.5, 12,
    10, 8, 18, 5, 10, 8, 16, 28, 22, 22, 21, 20, 18, 30, 27,
    30, 36, 36, 40, 32, 28, 50, 32, 60, 60, 60, 60, 60, 60, 60,
    60, 6, 6, 24, 26, 22, 2, 1, 50, 45, 10, 10, 4, 4, 60, 60),
    meandec = c(0.3625, 0.3025, 0.275, 0.1075, 0.26, 0.395, 0.265,
    0.4075, 0.9, 0.9275, 0.7075, 0.9625, 0.7725, 0.9325, 0.9875,
    0.81, 0.575, 0.3075, 0.4675, 0.6975, 0.33, 0.8725, 0.46,
    0.19, 0.495, 0.3825, 0.58, 0.2275, 0.45, 0.3925, 0.605, 0.515,
    0.425, 0.34, 0.2475, 0.1375, 0.4225, 0.505, 0.36, 0.4325,
    0.26, 0.1575, 0.125, 0.3125, 0.1725, 0.3175, 0.43, 0.3475,
    0.2025, 0.395, 0.12, 0.1625, 0.3175, 0.1975, 0.1525, 0.2775,
    0.4975, 0.725, 0.04, 0.326666666666667, 0.1425, 0.445, 0.4725,
    0.3775, 0.27, 0.2225, 0.23, 0.3275, 0.9725, 0.215, 0.2325
    )), row.names = c(NA, -71L), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), vars = c("ID", "Stage"), drop = TRUE)

Problem:
I'm trying to run an exponential decay model on these data.  I've done it with similar data, but when I try to do it on this particular dataset, it says that the number of max iterations has been exceeded without convergence.
nonlinmod6<-nls(meandec~SSasymp(Time.Since.Burn, Asym,R0,lrc),data=averaged_perherb)

Error in nls(y ~ cbind(1 - exp(-exp(lrc) * x), exp(-exp(lrc) * x)), data = xy,  :   number of iterations exceeded maximum of 50

So, I tried to manually increase the maximum number of iterations using the code below:
nonlinmod6<-nls(meandec~SSasymp(Time.Since.Burn, Asym,R0,lrc),data=averaged_perherb,nls.control(maxiter=500))

but it then gives me an error saying that :
Error in nls(meandec ~ SSasymp(Time.Since.Burn, Asym, R0, lrc), data =
averaged_perherb,: parameters without starting value in 'data': Asym, R0, lrc

which I don't think should be the case given that I'm using a self-starting function to identify the starting parameters.  Is there any way to resolve this?

A: The problem is that the SSaymp intialization routine itself uses nls and it is that hidden invocation of nls that is the problem.
You are going to have to hack the intialization routine.  Make a new copy of SSasymp called SSasymp2, grab its initialization routine and call it SSasymp2Init, say.  Then use trace to insert into the initialization a new version of nls having the required control argument.  To do that we use the partial function in the pryr package. Replace the initialization routine with the hacked one and then run nls.
library(pryr)

SSasymp2 <- SSasymp
SSasymp2Init <- attr(SSasymp2, "initial")
trace(SSasymp2Init,
  quote(nls <- partial(stats::nls, control = nls.control(maxiter = 500))))
attr(SSasymp2, "initial") <- SSasymp2Init

nls(meandec ~ SSasymp2(Time.Since.Burn, Asym, R0, lrc), data = averaged_perherb)

giving:
Tracing (attr(object, "initial"))(mCall = mCall, data = data, LHS = LHS) on entry
Nonlinear regression model
  model: meandec ~ SSasymp2(Time.Since.Burn, Asym, R0, lrc)
   data: averaged_perherb
   Asym      R0     lrc
 0.1641  0.5695 -3.4237
 residual sum-of-squares: 2.977

Number of iterations to convergence: 15
Achieved convergence tolerance: 5.875e-06


text:
Q: Video Tutorial for Kohana3? Is there any Video Tutorial for the Kohana3 ? or some easy way to study Kohana3.
some one to tell me RTFM  , but I'm so stupid indeed .
I 'm searching the video tutorial for a while but gain nothing.
who can help me...

A: Not really for Kohana, I've looked around quite a bit but haven't found anything.
Best thing is really just to start using it and try to use the docs there is (and doin't forget the api docs which usually is better).
Once you get to know the available docs you don't really need the video.
If you get stuck, shoot out a question about that instead and you'll get help fast.
Good luck!


text:
Q: How does successCallback really work? I am so baffled by callback, as in I don't understand it at all. The API I am using has an ajax function like so:
"ajax": function ( method, url, data, successCallback, errorCallback ) {
$.ajax( {
        "type": method,
        "url":  url,
        "data": data,
        "dataType": "json",
        "success": function (json) {
            successCallback( json );
        },
        "error": function (xhr, error, thrown) {
            errorCallback( xhr, error, thrown );
        }
    } );

From the API doc:

method  - string
The HTTP method to use for the AJAX request
url - string
The URL to submit the data to
data    - object
The data submitted to the server
successCallback - function
Callback function on data retrieval success
errorCallback   - function
Callback function on data retrieval error

What I don't understand is when I remove successCallback, the event does not complete. Why is this so? I have hit the "success" parameter, as in I've succsesfully run the ajax request, so what does the callback here do? I would think that anything in "success" is basically saying, "do this stuff after the ajax request is complete".
Thanks

A: I'm not sure what API you are referring to, but successCallback is just a function.  That means it can do anything.  A callback is an executable block of code that you can pass as an argument.
api.ajax(method, url, data, function (json) {
    console.log(json);
}, function (err) {
    console.err(err);
});

The function will be called when the success method fires after the ajax request is successful.  The API is providing a way for you to pass your own custom code that is called when the ajax completes.

A: In the API documentation, successCallback refers to the function set as the success property. The success handler is optional and if omitted, the ajax will still execute and complete.
You seem to think that you have to call something called successFunction from within the success handler. This is not the case. You can put anything you want in the success handler, or nothing it all, or just omitt it.
To illustrate, all of the following are valid usage of $.ajax:
$.ajax({
     "type": method,
     "url": url,
     "success": function (json) {

      }
});

$.ajax({
     "type": method,
     "url": url,
     "success": function (json) {
          someFunction(); // providing this exists obviously
      }
});

$.ajax({
     "type": method,
     "url": url
});


text:
Q: Directory tree listing Hi i am looking for script witch lists directory's from ftp and read's all files from the listed folder..Is there something that can help me?

*

*>   //open the dir

                $sub = ($_GET['dir']);
                $path = 'store/'.$diro.'/';
                $path = $path . "$sub";
                $dh = opendir($path);
                $i=1;
                while (($file = readdir($dh)) !== false) {
                    if($file != "." && $file != "..") {
                            if (substr($file, -4, -3) =="."){
                            echo "$i. $file ";
                            }else{
                        echo "$i. $file";
                          }
                        $i++;
                    }
                }
                closedir($dh);

A: I did a quick Google, and there a MILLIONS of responses to this question.
The fourth result is a complete code sample.
http://www.phpreg.com/index.php?option=com_content&task=view&id=158&Itemid=28
Something like....
<?php
     $connect = ftp_connect("ftp.hostname.com");
     $result = ftp_login($connect, "username", "password");
     $a = ftp_nlist($connect, "code22");
     foreach($a as $value){
         echo $value, "<BR>";
     }
?>


text:
Q: AngularJS Application not booting I am trying to start an angularjs project, however for some reason I can't seem to get it started correctly. It probably is some kind of mistake that I am to blind for to see. Here is the code:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>WebUX</title>
    <link rel="stylesheet" href="css/index.css">

And the javascript:
var app = angular.module('webux', ['ngRoute']);

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);

    $routeProvider.when('/', {
        templateUrl: 'partials/home.html',
        controller: 'HomeCtrl'
    });
}]);

app.controller('HomeCtrl', function($scope) {
    console.log($scope);
});

Also the console log in the HomeCtrl does not get fired.
Update
Just to add some info:

*

*Console is empty

*All script files are correctly referenced

A: Ok, thank you all a lot for helping me out, however I found the solution. As you can see in my code example, I use

 to specify where the views should be rendered. After I inspected the element for a few times, I found that chrome stripped that empty property.
<div class="slide" data-ng-view does work (notice the 'data-').


text:
Q: Rate of change of stock price in pandas I have a pandas dataframe containing columns describing the following entities:
I) Stock Symbol,
II) Timestamp,
III) Price.
For each stock symbol, I'd like to find the discrete change in price defined by the current price minus the price from the closest but previous entry, divided by the current time minus the previous entries time.
For example, let's say I have:
…
(AAPL, 10, 100)
(AAPL, 12, 101)
…
Here, we have two rows for AAPL. At time 10, the price is 100, and at time 12, the price is 101. Suppose these are the only entries for AAPL in the data frame. I would like to add a fourth column that would be
…
(AAPL, 10, 100, NaN)
(AAPL, 12, 101, (101-100)/(12-10))
…
The first rows entry is NaN because there's no AAPL before it. The second is the rate of change of the price based on the closest previous entry we have.
If all of the stock symbols were the same, I could just sort by timestamp and compute the discrete changes by looking at successive rows. However, it's possible that there are different symbols. I wouldn't want AAPL to get matched to anything but AAPL.
Can someone please help me achieve this behavior? I did some research, and the merge_as of function seems relevant. I can't quite get the parameters right though, and I'm not even sure if it's the correct approach.

A: If you start out with this data for example:
   stock  time       price
0      A     7  101.666400
1      A    15  101.577825
2      A    20  102.686615
3      A    21  101.869665
4      A    24  100.941477
5      A    25  101.777495
6      A    30  102.926569
7      A    33   99.433201
8      A    42  102.197779
9      A    44   99.671157
10     B     2   49.742638
11     B     7   48.775407
12     B    14   47.568738
13     B    16   50.237352
14     B    23   47.766212
15     B    28   47.838829
16     B    29   47.431216
17     B    32   46.286115
18     B    36   43.962685
19     B    41   44.047109

Then you could do the following:
df_roc = df.assign(
    roc=df.groupby('stock').apply(lambda x: x['price'].diff()/x['time'].diff()).droplevel(0)
)

print(df_roc)

Result with rate-of-change
   stock  time       price       roc
0      A     7  101.666400       NaN
1      A    15  101.577825 -0.011072
2      A    20  102.686615  0.221758
3      A    21  101.869665 -0.816950
4      A    24  100.941477 -0.309396
5      A    25  101.777495  0.836018
6      A    30  102.926569  0.229815
7      A    33   99.433201 -1.164456
8      A    42  102.197779  0.307175
9      A    44   99.671157 -1.263311
10     B     2   49.742638       NaN
11     B     7   48.775407 -0.193446
12     B    14   47.568738 -0.172381
13     B    16   50.237352  1.334307
14     B    23   47.766212 -0.353020
15     B    28   47.838829  0.014523
16     B    29   47.431216 -0.407613
17     B    32   46.286115 -0.381700
18     B    36   43.962685 -0.580857
19     B    41   44.047109  0.016885

A: Maybe this is not the perfect and fast way to do it , but it will work with you
Suppose this is your df
df = pd.DataFrame([['AAPL', 10, 100],
                   ['AAPL', 12, 101],
                   ['AAPL', 14, 106]])

so it will look like this
df
       0    1   2
0   AAPL    10  100
1   AAPL    12  101
2   AAPL    14  106

your fourth column will be
col4 = (df[2][1:].values - df[2][:-1].values)

col4 = col4 / (df[1][1:].values - df[1][:-1].values)

col4 = pd.Series([np.nan]).append(pd.Series(col4))
col4 = col4.reset_index(drop=True)

so it will apear like
col4
0    NaN
1    0.5
2    2.5
dtype: float64

now you can do
df[3] = col4

so your data frame will be
df
       0    1   2   3
0   AAPL    10  100 NaN
1   AAPL    12  101 0.5
2   AAPL    14  106 2.5

and that what we want, I think!

A: Have a look at the .diff() method which you can use on series objects.
You can probably do something like:
price.diff() / timestamp.diff()

A: Here's a way without apply()
given time series data
import pandas as pd
import numpy as np
df
###
              Datetime Symbol       Price
0  2022-07-12 12:00:00   AAPL  147.795700
1  2022-07-12 12:02:00   AAPL  147.705002
2  2022-07-12 12:02:00   NVDA  152.940002
3  2022-07-12 12:03:00   AAPL  147.694595
4  2022-07-12 12:03:00   NVDA  153.009995
5  2022-07-12 12:08:00   NVDA  152.763504
6  2022-07-12 12:09:00   AAPL  147.419998
7  2022-07-12 12:11:00   AAPL  147.419998
8  2022-07-12 12:20:00   NVDA  152.869995
9  2022-07-13 11:24:00   NVDA  152.294998
10 2022-07-13 11:25:00   NVDA  151.910095

price delta
price_d = df.groupby('Symbol')['Price'].diff()

time delta in minute
time_d = df.groupby('Symbol')['Datetime'].diff()/ np.timedelta64(1,'m')

/ np.timedelta64(1,'m') turns the time delta unit into minute
Result
df['diff'] = price_d/time_d
df
###
              Datetime Symbol       Price      diff
0  2022-07-12 12:00:00   AAPL  147.795700       NaN
1  2022-07-12 12:02:00   AAPL  147.705002 -0.045349
2  2022-07-12 12:02:00   NVDA  152.940002       NaN
3  2022-07-12 12:03:00   AAPL  147.694595 -0.010406
4  2022-07-12 12:03:00   NVDA  153.009995  0.069992
5  2022-07-12 12:08:00   NVDA  152.763504 -0.049298
6  2022-07-12 12:09:00   AAPL  147.419998 -0.045766
7  2022-07-12 12:11:00   AAPL  147.419998  0.000000
8  2022-07-12 12:20:00   NVDA  152.869995  0.008874
9  2022-07-13 11:24:00   NVDA  152.294998 -0.000415
10 2022-07-13 11:25:00   NVDA  151.910095 -0.384903