text:
Q: Wrong values inside of array I am a new C-Language learner and faced 2 problems. (Written in the same page because I think it's the same root cause for both)
int mrr [2][3];

for (int r=0;r<2;r++)
{
    for (int c=0; c<3; c++)
        printf("[%d],[%d]:%d\n",r,c,mrr[r][c]);
}

I read that in case we don't provide a value to a newly created array it gets a default value of 0 inside all of its cells. But when I print the result it showed:
[0],[0]:0
[0],[1]:4201072
[0],[2]:6422224
[1],[0]:6422280
[1],[1]:6422476
[1],[2]:1977208000

Second, the following code returns a totally unexpected value (The Average) of 431374336.000000
double getAverage(int arr[], int size) {

   int i;
   double avg;
   double sum = 0;

   for (i = 0; i < size; ++i) {
      sum += arr[i];
   }
   avg = sum / size;

   return avg;
}

double balance[5] = {1000, 2, 7, 17, 50};
double avg = getAverage(balance, 5 );
printf( "Average value is: %f ", avg );

A: Objects defined inside functions without static or _Thread_local are not automatically initialized and have indeterminate values. To ensure the array mrr is initialized, define it with int mrr[2][3] = { 0 };, which will initialize it to all zeros.
The code in the second question is incomplete, but, presumably, the array is defined in the calling function and is not initialized, so its values are indeterminate.

A: By default, [the values of] an array defined inside a function (i.e. a local array) is indeterminate. Global (i.e. static) variables, on the other hand, are initialized to 0 by default. See this related post: initial value of int array in C
To address your issue, simply initialize your array manually, with something like
for (int r=0;r<2;r++)
{
    for (int c=0; c<3; c++) {
        mrr[r][c] = 0;
        printf("[%d],[%d]:%d\n",r,c,mrr[r][c]);
    }
}

A: Your question about uninitialized variables is well-covered by the comments and other answers; this answer is for your second question, about the unexpected output from getAverage().
You define balance as an array of double, but getAverage() is expecting an array of int.  When I change:
double getAverage(int arr[], int size) { ... }

to:
double getAverage(double arr[], int size) { ... }

I get the expected result: 215.2.  The implicit type-conversion [1] in your original code is causing the unexpected behavior.
Also, I don't know what compiler you are using, but when I compiled your original code [2], gcc threw this warning:
warning: incompatible pointer types passing 'double [5]' to parameter of type 'int *'

... which is a dead give-away that trouble is brewing.  If your compiler doesn't generate this warning, or if you have warnings suppressed, or if they are logged to a file or something that you aren't looking at, I recommend making them visible again; paying attention to compiler warnings has saved me untold hours of grief.
[1] "type conversion" isn't maybe the best term here; type conversion is generally benign, even though there are some gotchas; what's happening here is that the bytes that make up the double value are being read as an int, and the byte structure of those two data types is very different; that's why the output of your original code makes it seem like it's dealing with such crazy-large numbers : e.g., the bytes used to represent "17" as a double when read as an int become a very, very different number.  Worse, stepping through the bytes that make up an array of double values as if it were an array of int values, it probably isn't even looking at the array elements at the proper element boundaries.  In short, the type disparity is causing havoc.
[2] By "original code" I mean your code with enough overhead code to make it compile, like include pragmas and a main() body; I agree in general with the other comments about providing a complete, minimal example.

A: This supplemental answer is in response to the OP's comment on my earlier answer.  Defender asks:
"I have some questions left. If it's expecting an array of type int and i sent double why this would change the result in 360 degrees. I still didn't get an answer to that."
It'll be easier to illustrate this with a type clash between short int and int, but the same idea applies to int vs. double.
Take a look at this code:
#include <stdlib.h>
#include <stdio.h>

void functionA(short int[], int size);

int main(void) {

    printf("sizeof short int : %lu\n", sizeof(short int));
    printf("sizeof int       : %lu\n", sizeof(int));
    printf("\n\n");

    printf("====  sending short int to functionA() ====\n");
    short int shortdata[4] = {10, 20, 50, 100};
    functionA(shortdata, 4);

    printf("====  sending int to functionA() ====\n");
    int intdata[4] = {10, 20, 50, 100};
    functionA(intdata, 4);
}

void functionA(short int arr[], int size) {

   int i;

   char* ptr;

   for (i = 0; i < size; ++i) {
      ptr = &arr[i];
      printf("bytes of 'arr[%d]' : %x %x\n", i, *ptr, *(ptr+1));

      printf("value of 'arr[%d]' : %d\n", i, arr[i]);

      printf("\n");
   }
}

which produces this output:
sizeof short int : 2
sizeof int       : 4

====  sending short int to functionA() ====
bytes of 'arr[0]' : a 0
value of 'arr[0]' : 10

bytes of 'arr[1]' : 14 0
value of 'arr[1]' : 20

bytes of 'arr[2]' : 32 0
value of 'arr[2]' : 50

bytes of 'arr[3]' : 64 0
value of 'arr[3]' : 100

====  sending int to functionA() ====
bytes of 'arr[0]' : a 0
value of 'arr[0]' : 10

bytes of 'arr[1]' : 0 0
value of 'arr[1]' : 0

bytes of 'arr[2]' : 14 0
value of 'arr[2]' : 20

bytes of 'arr[3]' : 0 0
value of 'arr[3]' : 0

The first two lines of output show that on my machine, short int takes 2 bytes of memory and int takes 4 bytes.
functionA() is expecting a short int array, and when I send it a short int[], we see the expected output.  The bytes that make up the first element of the array are 0x0a 0x00, which in decimal is "10"; the bytes that make up the second element of the array are 0x14 0x00, which in decimal is "20"; and so on.
But when I send functionA() an int[], I'm sending 4 bytes per element, so when it iterates through the array, it doesn't see the elements correctly.  It does okay with the first element, but only because it's a small number; when it looks for the second element, it is actually looking at the last two bytes of the first element, so it sees 0x00 0x00, or "0"; when it looks for the third element it is looking at the first two bytes of the second element, and sees 0x14 0x00, or "20"; and so on.
Another way to show it is that the bytes of shortdata are this:
0a 00 14 00 32 00 64 00

and the bytes of intdata are this:
0a 00 00 00 14 00 00 00 32 00 00 00 64 00 00 00

Because functionA() is expecting a short int[], it treats intdata that way -- two bytes per element -- and sees as its elements:
arr[0] : 0a 00
arr[1] : 00 00
arr[2] : 14 00
arr[3] : 00 00

It's a similar story with your code.  Your getAverage() is expecting a int[], so when you send it a double[], it is not seeing the bytes the way you intend.
(The clash between int and double is even more drastic than between short int and int; this is because in addition to being different sizes (on most modern machines, int is 4 bytes and double is 8 bytes), floating-point numbers are stored as an exponent and a mantissa -- so the byte values have an entirely different meaning.)
I hope this explanation helps, and I encourage you to experiment with the code above, and read about the internals of C memory as it pertains to allocating and handling variables.  As a new C programmer, you will gain insight in to fundamentals that will help you for as long as you continue programming in C.


text:
Q: :after bug (chrome only) I am building a website for a school project and I experiment a weird bug.
I use ::after and transform/transitions on my menu items. It works on all browsers but the tags in the right div have an animation on it in chrome only.
You can see it here : http://mbrillaud.fr/gamejutsu/
On hover on the menu, the tags (action, adventure etc ...) of the right div are "clipping".
The css for the menu :
.left a::after{
    content: '';
    display: block;
    height: 2px;
    background-color: #282C34;
    -webkit-transform: scaleX(0);
    -moz-transform: scaleX(0);
    -ms-transform: scaleX(0);
    -o-transform: scaleX(0);
    transform: scaleX(0);
    transition: transform 0.1s;
}
.left a:hover::after{
    -webkit-transform: scaleX(1);
    -moz-transform: scaleX(1);
    -ms-transform: scaleX(1);
    -o-transform: scaleX(1);
    transform: scaleX(1);
}

Do someone have experienced this or have an idea ?
Thank you by advance for your help !

A: It actually isn't clipping on hover, it is always clipped and it is the backface-visibility showing. When you hover with css transitions chrome flickers the backface visibility. You can prevent the flicker by applying this:
*, *:before, *:after {
    -webkit-backface-visibility: hidden;
}

That won't prevent your tags from being clipped though. Change your line-height on .game-label-tags to be 1.6em and that will prevent the clipping and you will not need to apply the backface-visibility hack.

A: You may use a background (gradient or img) and background-size.

a {
  text-decoration:none;
  color:black;
  background:linear-gradient(to top, black , black) no-repeat bottom center;
  background-size:0 2px;
  transition:0.1s;
}
a:hover {
  background-size:100% 2px;
}

Home

About

Clients

Contact Us

redpajama_set_name: RedPajamaStackExchange


text:
Q: downloading files with goroutines? I'm new to Go and I'm learning how to work with goroutines.
I have a function that downloads images:
func imageDownloader(uri string, filename string) {
    fmt.Println("starting download for ", uri)

    outFile, err := os.Create(filename)
    defer outFile.Close()
    if err != nil {
        os.Exit(1)
    }

    client := &http.Client{}

    req, err := http.NewRequest("GET", uri, nil)

    resp, err := client.Do(req)
    defer resp.Body.Close()

    if err != nil {
        panic(err)
    }

    header := resp.ContentLength
    bar := pb.New(int(header))
    rd := bar.NewProxyReader(resp.Body)
    // and copy from reader
    io.Copy(outFile, rd)
}

When I call by itself as part of another function, it downloads images completely and there is no truncated data.
However, when I try to modify it to make it a goroutine, images are often truncated or zero length files.
func imageDownloader(uri string, filename string, wg *sync.WaitGroup) {
    ...
    io.Copy(outFile, rd)
    wg.Done()
}

func main() {
var wg sync.WaitGroup
wg.Add(1)
go imageDownloader(url, file, &wg)
wg.Wait()
}

Am I using WaitGroups incorrectly? What could cause this and how can I fix it?
Update:
Solved it. I had placed the wg.add() function outside of a loop. :(

A: While I'm not sure exactly what's causing your issue, here's two options for how to get it back into working order.
First, looking to the example of how to use waitgroups from the sync library, try calling defer wg.Done() at the beginning of your function to ensure that even if the goroutine ends unexpectedly, that the waitgroup is properly decremented.
Second, io.Copy returns an error that you're not checking. That's not great practice anyway, but in your particular case it's preventing you from seeing if there is indeed an error in the copying routine. Check it and deal with it appropriately. It also returns the number of bytes written, which might help you as well.

A: Your example doesn't have anything obviously wrong with its use of WaitGroups. As long as you are calling wg.Add() with the same number as the number of goroutines you launch, or incrementing it by 1 every time you start a new goroutine, that should be correct.
However you call os.Exit and panic for certain errors conditions in the goroutine, so if you have more than one of these running, a failure in any one of them will terminate all of them, regardless of the use of WaitGroups. If it's failing without a panic message, I would take a look at the os.Exit(1) line.
It would also, be good practice in go to use defer wg.Done() at the start of your function, so that even if an error occurs, the goroutine still decrements its counter. That way your main thread won't hang on completion if one of the goroutines returns an error.

A: One change I would make in your example is leverage defer when you are Done. I think this defer ws.Done() should be the first statement in your function.
I like WaitGroup's simplicity. However, I do not like that we need to pass the reference to the goroutine because that would mean that the concurrency logic would be mixed with your business logic.
So I came up with this generic function to solve this problem for me:
// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

So your example could be solved this way:
func imageDownloader(uri string, filename string) {
    ...
    io.Copy(outFile, rd)
}

func main() {
    functions := []func(){}
    list := make([]Object, 5)
    for _, object := range list {
        function := func(obj Object){
            imageDownloader(object.uri, object.filename)
        }(object)
        functions = append(functions, function)
    }

    Parallelize(functions...)

    fmt.Println("Done")
}

If you would like to use it, you can find it here https://github.com/shomali11/util


text:
Q: Speeding up ubuntu machine Does below command improved performance of the machine:
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
I know this is for freeing RAM. Please guide

A: No, it just dumps a load of stuff (slab objects and pagecache) from the system cache.
If your system is out of memory (and I mean: deep into swap usage, nothing free, hard disk churning) then yes, this might help... But not as much as:

*

*Buying more RAM, it isn't expensive or hard to fit.

*Closing something that's using lots of memory (or tabs from a browser).

*Using something faster for swap space (eg SSD)

*Compressing swap
So while it may work for a few seconds, if you have something rampaging all over your RAM, you'd do better just to close it, or buy it more RAM with which to rampage over. Freeing up inode and page cache isn't going to help you for long.

A: No, see How do I clean or disable the memory cache? for an indepth answer.
Cache is there to be used and to speed things up. So Linux makes full use of caching. If you do this it will takes seconds for  the cache to be filled up again.
Adding hardware to your system would be more efficient (depending on what triggered your question it  might be memory or a better hard disk).

A: You can also write command as:
echo 3 > /proc/sys/vm/drop_caches

The above command will free pagecache, dentries and inodes.
And
sudo sync

is used to  to make sure all cached objects are freed as dirty objects are not free-able and the echo operation is non-destructive.


text:
Q: How do I write a PowerShell alias that changes directory and lists all files and folders? I am trying to write a command like cs *directory* that will change directories and list all items immediately. How would I do this with PowerShell?

A: Use a function. Example:
function cs {
  [CmdletBinding()]
  param(
    [Parameter(Mandatory=$true)]
      [String] $path
  )
  Set-Location -LiteralPath $path -ErrorAction Stop
  Get-ChildItem
}


text:
Q: How the use decode option of protoc for decoding google::protobuf:any types I try to decode a binary file which inherits some serialized proto3 messages. I do this with protoc and the option --decode.
All work fine until one of the serialized messages contains a google::protobuf::Any field. This field contains another message which is defined in a extra .proto file. When i execute the --decode option of the protoc then the type_url is correct and a value with the raw bytes is shown.
Is it possible that the protoc is able to detect which message is included in the Any field and decode it corresponding to the .proto file of this message? If yes, how can i do this?
Thanks in advance!


text:
Q: C# array to MVC view for Google Map markers I am having such a rough time accomplishing this and all the research I'm doing is not turning out positive. In short, I need to send an array of markers from my code to my MVC view (through the model and setting it as a hidden field) so that the Google map can use this array to place markers on the map. I have tried building it as a List and then using JSON serialization to turn it to a string, but the format just won't turn out and won't be recognizable to the Google API. Has anyone done this before successfully??
Here is my updated code based on CodeMonkey's answer, but the markers still aren't placing. I think it's happening somewhere in the addMarker function...
    var lat = $("#Latitude").val();
    var lng = $("#Longitude").val();

    var myOptions = {};
    var map = null;
    var marker = null;
    var global_markers = [];
    var infowindow = new google.maps.InfoWindow({});
    var geodata;
    var markers = [];

    function map_initialize() {
        var myLatlng = new google.maps.LatLng(lat, lng);
        myOptions = {
            zoom: 14,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        @foreach (var item in Model.AllSearchResults)
        {

            <text>try
        {
            var lat = '@item.Latitude';
            var lng = '@item.Longitude';
            var name = '@item.Name';
            var url = '@Url.Action("GetMarker", "Base")';
            var model = { "Latitude": lat, "Longitude": lng, "Name": name };

                $.ajax({
                    type: "POST",
                    data: model,
                    dataType: "json",
                    url: url,
                    success: function (data) {
                        geodata = data;
                        JSONString = JSON.stringify(geodata);
                        var valuesToPush = new Array();
                        valuesToPush[0] = data.Latitude;
                        valuesToPush[1] = data.Longitude;
                        valuesToPush[2] = data.Name;
                        markers.push(valuesToPush);
                        addMarker();
                    },
                    error: function () {
                        alert("fail");
                    }
                });
            }
            catch (err) { }</text>
            }
        }

    function addMarker() {
        for (var i = 0; i < markers.length; i++) {
            var lat = parseFloat(markers[i][0]);
            var lng = parseFloat(markers[i][1]);
            var name = markers[i][2];
            var location = new google.maps.LatLng(lat, lng);
            var contentString = '

' + name + '

';
            var marker = new google.maps.Marker({
                position: location,
                map: map,
                title: name
            });
            marker['infowindow'] = contentString;
            global_markers[i] = marker;
            google.maps.event.addListener(global_markers[i], 'click', function () {
                infowindow.setContent(this['infowindow']);
                infowindow.open(map, this);
            });
        }
    }
    google.maps.event.addDomListener(window, 'load', map_initialize);

A: I was able to do a combo server side/client side approach using the following link as a guide: http://mikehadlow.blogspot.com/2008/10/using-google-maps-with-mvc-framework.html
Thanks for Code Monkey's input!!

A: You can reference my front-end JS code at this URL: http://www.wallodex.com/WallodexAdmin/Map/10
This is how I use it on the VIEW:

    <meta name="viewport" content="width=device-width" />
    <title>CloudClaims Administration - Site Visits</title>

    <form id="form1" runat="server">
    <asp:panel id="Panel1" runat="server" style="height: 600px;">
            <asp:Literal ID="js" runat="server"></asp:Literal>

                        CloudClaims™ - Site visitors - Last X days

                        <asp:Label runat="server" id="errors"/>

                            @{Html.RenderAction("Subscribers");}

                            DEBUGGING

                            <asp:Label runat="server" id="ajaxtest"/>

        </asp:panel>
    </form>

And this is my CONTROLLER (I convert IP ADDRESSES to gMap objects on the front-end but you get the idea...):
public ActionResult Map(int id)
        {
            try
            {
                using (var db = new CloudClaimsEntities())
                {

                    DateTime dateFrom = (id != null && id > 1) ? DateTime.Now.AddDays(-id) : DateTime.Now.AddDays(-1);
                    List<string> IPAddresses = new List<string>();
                    IPAddresses = db.IPLogs
                        .Where(i => i.timeStamp <= DateTime.Now)
                        .Where(i => i.timeStamp >= dateFrom)
                        .Select(i => i.IPAddress)
                        .ToList();
                    return View(IPAddresses);
                }
            }
            catch
            {
                return View();
            }
        }


text:
Q: Who knows the Doctor's name? Who, apart from from River Song knows the Doctor's true name? In The Time of the Doctor, the time lords want him to say his name to prove they have the right universe and it is safe to come through - would the doctor's name have been common knowledge amongst time lords, or was it a specific set of time lords asking?
I was under the impression the doctor's name was secret even from most Galifreyans - am I mistaken?

A: The Matrix would have contained The Doctor's name; however, access to The Matrix was at least somewhat limited. Given that the revelation of a Time Lord's name is a sacrament of marriage, one might assume that casual attempts to access such data are discouraged.

A: Well, in one episode – might be last one of Season 4 (if i am right) – where Donna becomes a Time Lord, she says she got the Doctor's mind. This seems to imply, since she got the Doctor's mind, that she would know the Doctor's name.


text:
Q: How to remove corner radius from TextInput in spark I'm creating a mobile app in Flex and AS3 and the design i recieved has no corner radius in TextInput fields.
In mobile projects in Flash Builder only Spark can be used for layout, and according to the documentation of Adobe the TextInput element has no attribute to set the corner radius.
Is there an other way for me to do this ?
Thanks.

A: Thanks for your responses, i found and standard skin of Spark that has no rounded corners.
This what was the skin i needed to get the result i wanted.
The skin that i found is located in spark.skins.spark.TextInputSkin, i leaves everything the same excepts that it has normal corners instead of rounded.
Again thanks for your help.


text:
Q: ArrayList of ArrayLists - clear function confusion Here is a particular method I have written:
class A {

    private static ArrayList<ArrayList<Integer>> inputTerms = new ArrayList<ArrayList<Integer>();

    public static void method1(ArrayList<Integer> terms) {
        ArrayList<Integer> clauses = new ArrayList<Integer>();
        int N = terms.size();
        for (int i = 0; i < N - 1; i++) {
            for (int j = i + 1; j < N; j++) {
                clauses.add(-terms.get(i));
                clauses.add(-terms.get(j));
                inputTerms.add(clauses);
                clauses.clear();
            }
        }
    }
}

This method is called multiple times from the main function.
In the end, i try to write the contents of the class variable into a file. However, when I do this, i get 0 as the contents of inputTerms. However, if i remove the clauses.clear() line, i am able to get approppriate values.
My program is such that it is vital for me to clear the clauses after adding to inputTerms. Is there any alternative to this?
**Hmmm.. I have done what you've suggested. However, I haven't quite overcome the problem. To give more background, in my main function, I have the following code:
for (int i=0; i<N-1; i++){
ArrayList<Integer> firstdiagonalTerms = new ArrayList<Integer>();
for (int j=0; j<N-i; j++){
firstdiagonalTerms.add(variable[j][i+j]);
}
method1(firstdiagonalTerms);
}

I have to call the method1 function 4 times for different combinations of 'i' and 'j'. However, I still get 0 when I use the above mentioned suggestions**

A: You are adding the same list and clearing it repeatedly. When you add an object to a list it copies a reference to it, not a copy of the object.
int N = terms.size();
for (int i = 0; i < N - 1; i++) {
    for (int j = i + 1; j < N; j++) {
        List<Integer> clauses = new ArrayList<Integer>();
        clauses.add(-terms.get(i));
        clauses.add(-terms.get(j));
        inputTerms.add(clauses);
    }
}

or
for (int i = 0, N = terms.size(); i < N - 1; i++)
    for (int j = i + 1; j < N; j++)
        inputTerms.add(Arrays.asList(-terms.get(i), -terms.get(j)));

A: When you call clear() on list, you are updating/removing same objects (because list contains reference to objects, not copy of object). That is what causing the issue.
I think you need to do something like below. Instead of using clear(), create a new list everytime.
public static void method1 (ArrayList<Integer> terms)
{

int N = terms.size();
        for (int i = 0; i<N-1; i++) {
            for (int j=i+1; j<N; j++) {
              ArrayList<Integer> clauses = new ArrayList<Integer>();
              clauses.add(-terms.get(i));
              clauses.add(-terms.get(j));
              inputTerms.add(clauses);

}
}

A: Not sure i understand what you are trying to achieve, but you keep reusing the same list, which is probably not what you meant to do.
You should probably move the ArrayList<Integer> clauses = new ArrayList<Integer>(); inside the inner loop, and not call clauses.clear() at all.

A: When you are adding "clauses" you are adding the actual object to the arrayList, not a copy. So when you clear them all the values in the list will be removed. To get arround this, add a clone of the list:
inputTerms.add((ArrayList<Integer>) clauses.clone());


text:
Q: Privilege and badge links are displayed on stackexchange.com When I click in stackexchange-button in http://stackexchange.com is displayed Privilege and Badge links form stackoverflow.com:

When I click in privileges link:

When I click in Badge link:

stackexchange-button in meta.stackexchange:


text:
Q: for loop not working correctly with json encode Php I am trying to fetch members ratings from the database using ajax. I passed a function to the JSON, even though it returned a value in the function but it doesn't execute the for loop condition.
Here is my code, the loop failed to execute. What am I doing wrong?
    function mrate($irate) {
        $class = "fa-star star-filled";
        for ($i = 0; $i < 5; $i++) {
            if ($irate <= $i) {
                $class = "fa-star-o empty";
            }
            return '';
        }
    }

    $perPage = 2;
    if (isset($_GET["page"]) && isset($_GET["page"])) {
        $page = $_GET["page"];
        $pid = $mysqli->real_string_escape($_GET["pid"]);
    } else {
        $page = 1;
        $pid = $mysqli->real_string_escape($_SESSION['pid']);
    };

    $startFrom = ($page - 1) * $perPage;
    $sqlQuery = "SELECT id, name,
        review, rating, added_date
        FROM review_rating
        where product_id = '$pid'
        ORDER BY id ASC LIMIT $startFrom, $perPage";
    $result = mysqli_query($mysqli, $sqlQuery);
    $paginationHtml = '';
    while ($row = mysqli_fetch_assoc($result)) {

        $img = '';
        $irate = $row['rating'];

        $paginationHtml .= '
';
        $paginationHtml .= '
';
        $paginationHtml .= '
' . $img;
        $paginationHtml .= '

' . $row["name"] . '
';
        $paginationHtml .= '' . $row['added_date'] . '

';
        $paginationHtml .= '

' . mrate($irate) . '

';
        $paginationHtml .= '
';
        $paginationHtml .= '
' . $row['review'] . '
';
        $paginationHtml .= '
';
    }
    $jsonData = array(
        "html" => $paginationHtml,
    );
    echo json_encode($jsonData);

A: Replace your function mrate($irate) with this and try. You needed to concatenate the stars code to display it more than once.
function mrate($irate){
    $stars = '';
    for($i=0; $i<5; $i++){
        if($irate <= $i){
            $class = "fa-star-o empty";
        }else{
            $class = "fa-star star-filled";
        }
        $stars .= '';
    }
    return $stars;
}

A: Assuming there's no fractional rating, you can do the following - Display all 5 stars but solid ones will represent the rating.
function mrate($irate){
    $class = '';
    for($i = 0; $i < 5; $i++){
        if ($irate <= $i) {
            $class .= '';
        } else {
            $class .= '';
        }
    }
    return $class;
}


text:
Q: Refer to same cell n times then next cell So I have a list of persons on sheet1 but then on sheet two i need to refer to a cell 4 times in a row then next cell 4 times, and son on
so on sheet 2 i want this
=Shee1(A1)
=Shee1(A1)
=Shee1(A1)
=Shee1(A1)
=Shee1(A2)
=Shee1(A2)
=Shee1(A2)
=Shee1(A2)

if i try to auto complete that it will go like
=Shee1(A1)
=Shee1(A1)
=Shee1(A1)
=Shee1(A1)
=Shee1(A2)
=Shee1(A2)
=Shee1(A2)
=Shee1(A2)
=Sheet1(A9)

(because im now 9 cells down from first cell)
Now i could just write all this for 400 cells - but there has to be a better way :)

A: Use the following formula:
=INDEX(A:A,FLOOR(((ROW(1:1)-1)/ 4)+1,1))

If you put formula in Sheet2 then just refer sheet2 in index array, like:-
=INDEX(Sheet1!A:A,FLOOR(((ROW(1:1)-1)/ 4)+1,1))

A: finaly figured it out - after 4 days for ARGHHH
=INDEX(Sheet1!$A$1:$A$999,INT((ROWS(A$1:A1)-1)/4)+1)


text: Q: What should be max sstable count to improve read latency on prod cluster? We are facing read latancy issue on our prod cassandra cluster. I am suspecting that sstables are the reasons. Can any one tell that what should be max sstable count on cassandra node? or any other reasons for read latency? acssandra version 2.0.11.


text:
Q: Proving a limit exists with probability $1$ and computing its value
Let $X_{1}, X_{2}, \ldots$ be a sequence of i.i.d. random variables
  with the uniform distribution on $[0, 1]$.
Prove that the limit
$$\lim_{n\to\infty} \sqrt[n]{X_{1} X_{2} \cdots X_{n}} $$
exists with probability one and find its value.

I'm studying for an exam and have been stuck on this problem for quite some time now. I've really got no clue how to prove the limit exists with probability one. I tried to use lots of inequalities like Markov's, Chebyshev's etc, with no look.
So assuming the limit exists for now, I looked at various ways to compute products of uniform random variables. It seems like there is some discussion on this site but all of it seems to be a lot of computation. I'm not sure if there's any one nice way to solve this problem, so I am searching your help.
Thanks

Taking the log of the limit we get
$$\lim_{n\to\infty} \sum_{k=1}^{n} \log(X_{k})$$
By law of large numbers, this goes to
$$E(\left(\log(X_1\right))= \int_{0}^{1} \log x\mathop{dx} = -1 $$
So the answer is $1/e?$
Does this prove that the limit exists w.p. $1?$ I'm not so sure how to do that.

A: Your edit is almost correct; note that
$$\log(X_1X_2\dots X_n)^{\frac{1}{n}}= \frac{1}{n}\sum_{i=1}^n \log(X_i)$$
Since the variables $Y_i=\log(X_i)$ are independent and identically distributed, the Strong Law of Large Numbers guarrante that
$$\frac{1}{n}\sum_{i=1}^n Y_i=\frac{1}{n}\sum_{i=1}^n \log(X_i)\longrightarrow E(\log(X_1))=-1$$
and the convergence is almost sure. So
$$(X_1X_2\dots X_n)^{\frac{1}{n}}\longrightarrow\frac{1}{e}$$
almost surely.


text:
Q: ADO.Net connection executing DB2 stored procedure returning pooled output parameter values using iSeries connection [EDIT - This issue is resolved.  The problem had to do with uninitialized out parameters on the stored procedure.]
Why would I need to turn connection pooling off to get this to work correctly???
[EDIT - connection pooling released a shared connection memory area on the AS400]
In my MVC web app I call a DB2 Stored Procedure (SP).
This SP has multiple in and out parameters similar to this pseudo code:
CreatePO(@REQNO[in], @PO[out], @Approver[out], @ErrorMsg[out])

My app writes data to tables used by this SP during its processing so when all the data is in place I call the SP and it tries to create a PO.
If the PO creation fails there will be an error message in the @ErrorMsg out parameter.  In these cases the @PO and @Approver parameters should be blank.
Here's what happens in sequence:
1)  I try to create my first PO but there is a problem...
   CreatePO(100, blank, blank, blank)
which results in...
   CreatePO(100, blank, blank, 'unable to determine approver')
2)  I successfully create the 2nd PO...
CreatePO(101, blank, blank, blank)
CreatePO(101, 'P1234', 'JJONES', blank)
3)  I try to re-create a PO for @REQNO 100
    CreatePO(100, blank, blank, blank)
    CreatePO(100, 'P1234', 'JJONES', 'unable to determine approver')
Step 3 has conflicting out parameters.  The app pool is returning the PO and Approver from Step 2 along with the appropriate an error message.
If I recycle my IIS app pool then the results are back to what happened in Step #1.
I am able to get expected results I add "pooling=false" to the connection string.  But why would output parameters be affected in this manner by connection pooling?  This seems more like a bug than some sort of desirable caching method.
If I don't paste my code someone will get bent out of shape so here it is...
(Look at the end of the top two lines)
    'Dim cs As String = "DataSource=mydb;UserID=myuser;Password=mypassword;Naming=System;ConnectionTimeout=180; DefaultIsolationLevel=ReadUncommitted;AllowUnsupportedChar=True;CharBitDataAsString=True; TransactionCompletionTimeout=0;pooling=false"
    Dim cs As String = "DataSource=mydb;UserID=myuser;Password=mypassword;Naming=System;ConnectionTimeout=180; DefaultIsolationLevel=ReadUncommitted;AllowUnsupportedChar=True;CharBitDataAsString=True; TransactionCompletionTimeout=0;"
    Using conn As New iDB2Connection(cs)
        conn.Open()
        Dim cmd As iDB2Command = New iDB2Command()
        cmd.Connection = conn

        cmd.CommandType = CommandType.StoredProcedure
        cmd.CommandText = "BF6360CL"

        ' Input parameters
        cmd.Parameters.Add(New iDB2Parameter With {.ParameterName = "@REQNO", .DbType = SqlDbType.Char, .Size = 7, .Value = model.RO})

        ' Output parameters
        Dim opo = New iDB2Parameter With {.ParameterName = "@POORDER", .DbType = SqlDbType.Char, .Size = 7, .Direction = ParameterDirection.Output}
        cmd.Parameters.Add(opo)

        Dim oApprover = New iDB2Parameter With {.ParameterName = "@APPROVER", .DbType = SqlDbType.Char, .Size = 10, .Direction = ParameterDirection.Output}
        cmd.Parameters.Add(oApprover)

        Dim oStatus = New iDB2Parameter With {.ParameterName = "@STATUS", .DbType = SqlDbType.Char, .Size = 3, .Direction = ParameterDirection.Output}
        cmd.Parameters.Add(oStatus)

        Dim oErr = New iDB2Parameter With {.ParameterName = "@ERROR", .DbType = SqlDbType.Char, .Size = 1, .Direction = ParameterDirection.Output}
        cmd.Parameters.Add(oErr)

        ' return value
        Dim oRetval = New iDB2Parameter With {.ParameterName = "@RETURN_VALUE", .DbType = SqlDbType.Char, .Size = 10, .Direction = ParameterDirection.ReturnValue}
        cmd.Parameters.Add(oRetval)

        cmd.ExecuteNonQuery()

        model.PO = opo.Value
        model.Approver = oApprover.Value
        model.Status = oStatus.Value
        model.Err = oErr.Value

    End Using
return model

So the big question is this:
Why on earth would connection pooling be responsible for out parameter values???
Could this be a bug in the IBM iSeries iDB2Connection implementation?

A: The IIS application pool is caching stored procedure output parameters by name and returning a cached value when nulls are detected. This happens with ODBC or iSeries connections. When I recycled the application pool this cached value went away. I added to the connection string "pooling=false;" and these cached values would no longer appear.

A: My boss asked me to try calling the stored procedure using iSeries Navigator just to see what the out parameters contain.  Boy was I surprised.
It turned out that the Stored Procedure (SP) was at fault after all.  I sat with the AS400 RPG developer this morning and watched them debug the SP.  The problem had to do with uninitialized memory.
Here's the definition of the SP:
BF6360CL(@REQNO, @USER, @ENVIRONMENT, @PO[out], @Approver[out], @Status[out], @Error[out])

I then reset my connection to the AS400 in iSeries Navigator and the output parameters reset back to
4 = S2.RETU
5 = RN_VAR0000
etc...
The AS400 developer is making changes now to initialize the variables.  When they're done I expect to be able to change my program back to use connection pooling.
When I reset the IIS App Pool it reset my connection to the database.  This seemed to release allocated memory on the AS400.
If anyone has more specifics about Connections and AS400 output parameter memory please share.


text:
Q: What does this c++ syntax means? `inline const Color (&EnumValuesColor())[3] {...}` What does the following c++ syntax means?
inline const Color (&EnumValuesColor())[3] {...}
Is it a function? I don't understand the syntax.
It is very different from the usual syntax type name(params){...}
It is generated from flatbuffers.
It is inside:
enum Color {
  Color_Red = 0,
  Color_Green = 1,
  Color_Blue = 2,
  Color_MIN = Color_Red,
  Color_MAX = Color_Blue
};

inline const Color (&EnumValuesColor())[3] { //<< here
  static const Color values[] = {
    Color_Red,
    Color_Green,
    Color_Blue
  };
  return values;
}

inline const char * const *EnumNamesColor() {
  static const char * const names[4] = {
    "Red",
    "Green",
    "Blue",
    nullptr
  };
  return names;
}

inline const char *EnumNameColor(Color e) {
  if (flatbuffers::IsOutRange(e, Color_Red, Color_Blue)) return "";
  const size_t index = static_cast<size_t>(e);
  return EnumNamesColor()[index];
}
//more codes...

It is just the basic example from https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html

A:
Is it a function?

Yes.
Arrays have a bit wonky syntax in the C syntax that C++ inherited. The square brackets go to the very end of the declaration. Here is a variable example:
element_type variable_name [array_size];

Pointers and references also have wonky syntax especially when combined with arrays. The following is simple:
// array of pointers
element_type * variable_name [array_size];
// array of references - this is not allowed
element_type & variable_name [array_size];

But what if we want a reference (or pointer) to an array? We add parentheses around the name and the punctuator to signify that the it applies to the variable rather than the array element:
// pointer to array
element_type (* variable_name) [array_size];
// reference to array
element_type (& variable_name) [array_size];

Now on to functions. Arrays cannot be returned, but you can return pointer or reference to an array. Just like in the case of variables, the square brackets go to the end of the declaration - all the way after the parameter list. And parentheses surround not only the punctuator and name but also the parameter list:
// function that returns pointer to array
element_type (* function_name (parameter_list)) [array_size];
// function that returns reference to array
element_type (& function_name (parameter_list)) [array_size];

I would recommend not writing functions like this, but instead to take advantage of type aliases to make it easier to read:
using Color3 = Color[3];
inline const Color3 & EnumValuesColor();

Or use the std::array template:
inline const std::array<Color, 3> & EnumValuesColor();

Or std::span:
inline std::span<const Color, 3> EnumValuesColor();

To actually understand how any C-like declaration works, you could teach yourself the Clockwise/Spiral Rule. Frankly, I wouldn't bother unless you intend to write a C or C++ parser. Not understanding unnecessarily complex declarations makes it easier to prevent yourself from writing unreadable declarations yourself.
If you encounter something that you don't understand, let a program parse it for your: https://github.com/ridiculousfish/cdecl-blocks


text:
Q: Can not resolve Symbol "ForSqliteHasDefaultValueSql" I want to define a Timestamp in my EF Core Project with SQLite and wanted to use this function:
Click
I know that this function seems to be in the classic EF and maybe it is not available anymore but 3 days ago I found the right package and the extension method that I was searching. Unfortunatelly I had another problem with the code and reverted everything and now I do not find the right package anymore. It was during a hackathon during the last hours, so i really do not remember how I got it to work :/
Does anybody know which nuget package has this method? The only thing that I am referencing is Microsoft.EntityFrameworkCore.Sqlite. I allready tried the .Core and the classic EF dependencies and some random third party sqlite/ef packages, but I still can not compile this extension method :(

A: As you can see from the link, this method applies to EF Core versions 1.0 and 1.1.
Starting from v2.0, most of the provider specific ForAbcXyz methods have been replaced with the generic Xyz methods.
So the method you are looking for is HasDefaultValueSql. If you support multiple databases, use it inside a block enclosed with
if (Database.IsSqlite())
{
    // ...
}


text:
Q: How can I save my table from truncate in SQL Server I need to restrict my table from update and delete.
For Update and Delete I'm Using an Instead of trigger, and its working fine.
But if I use the TRUNCATE Command, it erases my data.
I need to restrict truncate or any other table modification process.
Can anyone give your valuable suggestions.

A: To run a TRUNCATE statement you need to have the ALTER permissions on the object; as per the documentation: TRUNCATE TABLE (Transact-SQL) - Permissions.
If you want to stop a user/role from using the TRUNCATE statement on a table, you will need to use the following (Replacing the text in braces ({})):
USE {YourDatabase}
DENY ALTER ON {YourTable} TO {User/Role};

You can easily test if this works with a quick test script:
USE Sandbox;
GO

CREATE TABLE dbo.TestTable (Id int IDENTITY(1,1), String varchar(10));

INSERT INTO dbo.TestTable (String)
VALUES ('asdfhj'),('asdjkas'),('asdjkhsad');
GO

CREATE USER TestUser WITHOUT LOGIN;

ALTER ROLE db_ddladmin ADD MEMBER TestUser;
ALTER ROLE db_datareader ADD MEMBER TestUser;
ALTER ROLE db_datawriter ADD MEMBER TestUser;
GO

EXECUTE AS USER = 'TestUser';
GO
TRUNCATE TABLE dbo.TestTable; --This works
GO
REVERT;
GO

SELECT *
FROM dbo.TestTable;

INSERT INTO dbo.TestTable (String)
VALUES ('asdfhj'),('asdjkas'),('asdjkhsad');

DENY ALTER ON dbo.TestTable TO TestUser;
GO

EXECUTE AS USER = 'TestUser';
GO
TRUNCATE TABLE dbo.TestTable; --This fails
GO
REVERT;
GO

SELECT *
FROM dbo.TestTable;
GO
--Clean up
DROP TABLE dbo.TestTable;
DROP USER TestUser;


text:
Q: Interpolated DEM RMSE I'm trying to figure out the 'true' error associated with interpolated cells in a DEM, which itself is known to have a RMSE of 0.15m.

*

*DEM has RMSE of 0.15

*Interpolation model shown by cross-validation to have an RMSE of 0.1
What is the RMSE of any interpolated cells?
Is it:
0.15 + 0.1 or
0.15 * 0.1 or even,

A: I'm going to hazard the last of my suggestions was correct based on this extract from the following guidance.

See: enter link description here


text:
Q: Is there any way I can test the performance of XF and the ability of the phone to create new elements? I am trying to understand how my XF application performs with different models of phones. Specifically the time it take to draw new pages or change the structure of existing pages.
Does anyone know of any simple way to test the ability of the phone to draw out for example something like a text label 500 times so that I could then use C# stopwatch to measure the time it took to do that event?

A: you can add an element dynamically
myStackLayout.Add(new Label { Text = "test test" });

you can remove all the children
myStackLayout.Children.Clear();

or a single child, by reference or by index
myStackLayout.Children.Remove(element);
myStackLayout.Children.RemoveAt(index);


text:
Q: How to efficiently find documents by various criteria in MongoDB? I have a collection of books with documents laid out like
{
   "title": "The book",
   "author": "Joe Bob",
   "tags": ["dogs", "funny", "race"],
   "categories": ["fiction", "adventure"]
}

I would like to use one search bar to find a book by any of these criteria. I've got this down for the most part, but I don't understand now if it is a search or aggregation I should be using. I also wish I could have everything be case insensitive but I cannot figure out how to do something similar to $options: 'i' with an $in operator.
$or : [
    {'title': {$regex: search, $options: 'i'}},
    {'author': {$regex: search, $options: 'i'}},
    {'tags': {$in: [search]}},
    {'categories': {$in: [search]}},
]

Is this the best way for me to search through 100s of documents like this? Or should I prefer aggregate.

A: As you point out, you have this thing thing pretty much figured out, save for the case insensitivily for those arrays, which I will get to in a moment.
First off, I suggest that you follow this approach to searching all fields. However, if you want to stick to your method, which is also perfectly valid, here is how I would alter your query.
Since arrays are matched the same way strings are, you don't really need the $in operator there at all. So making those categories and tags searches case-insensitive is a trivial matter. Let's say we're looking for "Mark", so anything with "marketing" in the categories should get picked up. Here is how:
db.collection.find({
  $or: [
    {
      "title": {
        $regex: "Mark",
        $options: "i"
      }
    },
    {
      "author": {
        $regex: "Mark",
        $options: "i"
      }
    },
    {
      "tags": {
        $regex: "Mark",
        $options: "i"
      }
    },
    {
      "categories": {
        $regex: "Mark",
        $options: "i"
      }
    },

  ]
})

And here is a Playground example for you to test it.


text:
Q: Context menu in list HTML / CSS / JavaScript / jQuery What is the best way to implement a menu for web in a list mode?
What I have:

*

*a list view of some items on a client website that looks exactly like a finder (mac) window in list view.

What I need:

*

*a way to implement a menu like the menu that appears when you right-click an item in finder or windows explorer (the menu with "open | open with | rename | delete" etc)

image for reference:

requirements:

*

*the menu must work in a list view mode. I tried some implementation with popovers that didn't allow to select one of the menu items because when the mouse went down on the screen it activated another popover;

*the menu must allow for buttons inside as well as input text areas.

*the menu must be positioned in the right side of the screen or wherever the person right-clicks with a mouse. This is important because clicking the list has a specific function (other then displaying the menu). So, I have to allow the action to be performed or the menu to be displayed. My idea was left-click / right-click or left side of the item minus 20 pixels and 20 pixels in the right.
ideally, it would also be:

*

*accessed on hovering the right end of the item, and allowing the user to move the mouse down and access each menu until he finds the correct. Something like when there is a sidemenu with submenus in (just the same feel, as it is not the same context applied);

*not having the tooltip / arrow of a popover would be better. If impossible, it could at least be arranged correctly in direction with the object to hover. I learned that in object too much to the right or left the tooltip / arrow doesn't adjust itself, but remains centered to the menu width.

*better if less dependencies. I prefer just HTML, just HTML or CSS, just HTML, CSS and Javascript or, if impossible, just HTML, CSS, Javascript, jQuery and jQuery plugins. But, as usual, the simpler the better.
My list is based a lot of divs (for each item) inside another div (for the right side of the window). There is also, like a finder window, a left side menu based on a div with float left. (just saying that because better more info than less).
I do not have a working code yet for the menu. Actually, I'm not sure how to start. I tried some stackoverflow answers but none seems to fit my purpose. I'm unsure if I should dive in bootstrap, x-editable or anything else.

A: I've made a Mac OS X like content menu here:
Fiddle
You can't really make a context menu without JavaScript. There is an object called funcs if you scroll down in the JavaScript. Each item is HTML like:
<item action="">HTML Code for Menu Item</item>

There is also a state tag you can apply to gray something out:
<item state="gray">Grayed out item</item>

The attribute action will let the item run JavaScript when you click it:
<item action="run">Run Code!</item>

then you make a function run in funcs:
var funcs = {
    "run": function () {
        alert('Code!');
    }
};

Now when you click that item. It will alert Code!. In each item, you can put whatever HTML, and you can run whatever code.

This will allow you to right click anywhere to get the context menu. It will allow you to put whatever code you want, uses jQuery only without plugins, and is generally pretty simple. I modeled this after OS X Yosemite's popover, I even sampled colors directly.

JavaScript port with Element Detection support

With special noclick option and input
This version you can add exit='noclick' and that specific item won't make the thing disappear.


text:
Q: How to call a function from models.py to views or template I am a beginner in Django and Python. I am creating a Payroll project whose calculations are done using a function from models.py. The user must input the variables through templates and save it to sql. Then  search for the employee (through templates again) and output his payroll details. That is the time when I want to use the calculation function.
Data from the database is working and is outputted by the templates. As for the calculated data, it simply isn't showing.
I have been trying to use the function to no avail and I've searched for 3 days already. I am at lost at what to do now.
models.py
from django.db import models

#Class in model.py acts as a table in database
class Add_Employee(models.Model):
    name = models.CharField (max_length = 150, default = '', null = False)
    position = models.CharField (max_length = 150, default = '', null = False)
    email = models.EmailField (max_length = 150, default = '', null = False)
    address = models.CharField (max_length = 500, default = '', null = False)
    basic_pay = models.FloatField(default=None)
    overtime_hours = models.IntegerField(default=None)
    allowance = models.FloatField(default=None)
    days_leave = models.IntegerField(default=None)
    other_deductions = models.FloatField(default=None)

    #Django admin page; the table will show the name
    def __str__(self):
        return '{}{}'.format(self.name, self.position, self.email, self.address)

    def salary_calculation(self):

        #Earnings
        self.overtime_hours_pay = self.overtime_hours * 64

        self.gross_income = self.basic_pay + self.overtime_hours + self.allowance

        #Deductions
        self.days_leave = self.days_leave * 512
        self.pagibig = self.basic_pay * 0.01
        self.gsis = self.basic_pay * 0.09
        self.withholdingtax = self.basic_pay * 0.15
        self.philhealth = self.basic_pay * 0.0275 / 2

        self.total_deductions = self.days_leave + self.pagibig + self.gsis + self.withholdingtax + self.philhealth

        #Net Pay
        self.net_pay = self.gross_income - self.total_deductions

        print ("Calculated.") #this was never outputted from all the times i tried.
        return (self)

views.py
#Code for form submission and redirect back to employer page again
def add_employee_form_submit(request):
    print ("Form is successfully submitted.") #print can only be seen on the terminal, not the browser

    #create local variable for each variable entered using the form
    name = request.POST["name"]
    address = request.POST["address"]
    email = request.POST["email"]
    position = request.POST["position"]
    basic_pay = request.POST["basic_pay"]
    overtime_hours = request.POST["overtime_hours"]
    allowance = request.POST["allowance"]
    days_leave = request.POST["days_leave"]
    other_deductions = request.POST["other_deductions"]

    #assigning the local variable into the database fields
    employee_info = Add_Employee(name = name, address = address, email = email, position = position, basic_pay = basic_pay, overtime_hours = overtime_hours, allowance = allowance, days_leave = days_leave, other_deductions = other_deductions )

    #save the entire stuff
    employee_info.save()

    return render(request, 'employer.html')

def search_employee_form_submit(request):
    if request.method == "POST":
        search_id = request.POST['search_id']

        if search_id:
            employee_match = Add_Employee.objects.filter( pk = search_id ) #pk is primary key

            if employee_match:

                return render (request, 'employee.html', {'Search': employee_match})
            else:
                messages.error(request, 'No results found.')

        else:
            return HttpResponseRedirect('employee/')

    return render(request, 'employee.html')

employee.html (template for query and result viewing)

Employee Payroll

Enter your ID:

    <form action="/search_employee_form_submit/", method="post">

        {% csrf_token %}

        <input type = "text" name="search_id" placeholder="Enter employee id">

        <input type="submit" value="search employee">
    </form>

    {% if Search %}
        {% for k in Search %}
            Name:
            {{ k.name }}

            Position:
            {{ k.position }}

            Email:
            {{ k.email }}

          ..... etc (this part is working)

            Overtime Hour Pay:
            {{ k.overtime_hours_pay }}

            Gross Income:
            {{ k.gross_income }}

          ..... etc (calculated data = doesnt show result)
        {% endfor %}

Pardon me for the long post as I have no idea where I am missing something.

A: First of all, you are referencing fields that do not exist in the model, such as overtime_hours_pay and gross-income. If you do self.someFieldName on a model instance, that field should be defined or inherited in the model. So this is wrong:
self.overtime_hours_pay = self.overtime_hours * 64

You could either

*

*Add those fields in the model definition

*Remove the self part and make them normal variables. Which would look like:

def salary_calculation(self):
        overtime_hours_pay = self.overtime_hours * 64

        gross_income = self.basic_pay + self.overtime_hours + self.allowance

        self.days_leave = self.days_leave * 512
        pagibig = self.basic_pay * 0.01
        gsis = self.basic_pay * 0.09
        withholdingtax = self.basic_pay * 0.15
        philhealth = self.basic_pay * 0.0275 / 2

        total_deductions = self.days_leave + pagibig + gsis + withholdingtax + philhealth

        net_pay = gross_income - total_deductions

        return net_pay

After doing that, you could calculate net_pay in the view.
...
if employee_match:
    # calculation
    net_pay = employee_match.salary_calculation()
    # then pass this to the template
    return render (request, 'employee.html', {'Search': employee_match, 'net_pay': net_pay})
else:
    messages.error(request, 'No results found.')


text:
Q: Help in solving nonlinear system of equations I have a system of six non-linear equations in six unknowns, which I do not know how to solve.
$$\left( 1 + 4 \left( x_2^2 + x_3^2 \right) \right)x_4 - 4x_1x_2x_5 - 4x_1x_3x_6 = 0,$$
$$-4x_1x_2x_4 + \left( 1 + 4 \left( x_1^2 + x_3^2 \right) \right)x_5 - 4x_2x_3x_6 = 0,$$
$$-4x_1x_3x_4 - 4x_2x_3x_5 + \left( 1 + 4 \left( x_1^2 + x_2^2 \right) \right)x_6 = 0,$$
$$\left( 1 - 4 \left( x_5^2 + x_6^2 \right) \right)x_1 + 4x_4x_5x_2 + 4x_4x_6x_3 = 0,$$
$$4x_4x_5x_1 + \left( 1 - 4 \left( x_4^2 + x_6^2 \right) \right)x_2 + 4x_5x_6x_3 = 0,$$
$$4x_4x_6x_1 + 4x_5x_6x_2 + \left( 1 - 4 \left( x_4^2 + x_5^2 \right) \right)x_3 = 0.$$
As a start, I have added the first three equations and the last three equations to try and get a perfect square. In the process, I have:
$$\left( 1 + 2 \left( x_1 + x_2 + x_3 \right)^2 \right) \left( x_4 + x_5 + x_6 \right) - 2 \left( 2x_2x_3 + x_1^2 \right)x_4 - 2 \left( 2x_1x_3 + x_2^2 \right)x_5 - 2 \left( 2x_1x_2 + x_3^2 \right)x_6 = 0,$$
$$\left( 1 - 2 \left( x_4 + x_5 + x_6 \right)^2 \right) \left( x_1 + x_2 + x_3 \right) + 2 \left( 2x_5x_6 + x_4^2 \right)x_1 + 2 \left( 2x_4x_6 + x_5^2 \right)x_2 + 2 \left( 2x_4x_5 + x_6^2 \right)x_3 = 0.$$
From here, I have no idea how to proceed! Is there any general method to solve a system of nonlinear equations? Any help will be appreciated!

PS: The system is only a part of a system of $90$ equations in $36$ unknowns which I obtained when trying to find a Lie algebra isomorphism between $\mathfrak{so} \left( 3; 1 \right)_{\mathbb{C}}$ and $\mathfrak{sl} \left( 2, \mathbb{C} \right) \oplus \mathfrak{sl} \left( 2, \mathbb{C} \right)$. Most of the equations in the system are of this form, and if I can solve this system, I suppose the other $30$ variables can be known easily.

A: Using Maxima
load(grobner);
vars : [x1,x2,x3,x4,x5,x6];

eqns : [(1+4*(x2^2+x3^2))*x4−4*x1*x2*x5−4*x1*x3*x6,
−4*x1*x2*x4+(1+4*(x1^2+x3^2))*x5 −4*x2*x3*x6,
−4*x1*x3*x4 −4*x2*x3*x5+(1+4*(x1^2+x2^2))*x6,
(1−4*(x5^2+x6^2))*x1 + 4*x4*x5*x2 +4*x4*x6*x3,
4*x4*x5*x1+(1−4*(x4^2+x6^2))*x2 + 4*x5*x6*x3,
4*x4*x6*x1+4*x5*x6*x2+(1−4*(x4^2+x5^2))*x3];

eqns : expand(eqns);

gb : poly_reduced_grobner(eqns,vars);

$$\begin{pmatrix} -4\,x_{1}
 \,x_{3}\,x_{6}-4\,x_{1}\,x_{2}\,x_{5}+4\,x_{3}^2\,x_{4}+4\,x_{2}^2\,
 x_{4}+x_{4}\cr -4\,x_{1}\,x_{6}^2+4\,x_{3}\,x_{4}\,x_{6}-4\,x_{1}\,
 x_{5}^2+4\,x_{2}\,x_{4}\,x_{5}+x_{1}\cr x_{3}\,x_{6}+x_{2}\,x_{5}+
 x_{1}\,x_{4}\cr 4\,x_{1}\,x_{2}\,x_{6}^2-4\,x_{1}\,x_{3}\,x_{5}\,
 x_{6}-4\,x_{2}\,x_{3}\,x_{4}\,x_{6}+4\,x_{3}^2\,x_{4}\,x_{5}+x_{4}\,
 x_{5}-x_{1}\,x_{2}\cr -4\,x_{2}^2\,x_{6}^2+8\,x_{2}\,x_{3}\,x_{5}\,
 x_{6}-4\,x_{3}^2\,x_{5}^2+x_{4}^2+x_{3}^2+x_{2}^2\cr 4\,x_{4}\,x_{6}
 ^2+4\,x_{4}\,x_{5}^2+4\,x_{4}^3-x_{4}\cr -4\,x_{6}^3-4\,x_{5}^2\,
 x_{6}-4\,x_{4}^2\,x_{6}+x_{6}\cr -4\,x_{5}\,x_{6}^2-4\,x_{5}^3-4\,
 x_{4}^2\,x_{5}+x_{5}\cr -4\,x_{3}\,x_{6}^2-4\,x_{3}\,x_{5}^2-4\,
 x_{3}\,x_{4}^2+x_{3}\cr -4\,x_{2}\,x_{6}^2-4\,x_{2}\,x_{5}^2-4\,
 x_{2}\,x_{4}^2+x_{2}\cr -x_{6}^2-x_{5}^2-x_{4}^2-x_{3}^2-x_{2}^2-
 x_{1}^2\cr \end{pmatrix}$$
All these equations are equal to $0$.
The last equation gives $x_{6}^2+x_{5}^2+x_{4}^2+x_{3}^2+x_{2}^2+
 x_{1}^2 = 0$
Looking at the equations they seem to be very symmetric.
It implies that some more properties/equations are needed to differentiate the variables.


text:
Q: How do I enable scrolling in the integrated terminal in Visual Studio Code? I'm trying to scroll with the integrated terminal and I'm getting a series of weird text that's showing up, like ^[[<64;57;24M]] and it's not scrolling.
I'm on the most up to date mac with the most up to date vs code.
Where can I enable scrolling for VS code?


text:
Q: Is there an opencv or python api call that calculates the jaccard similarity of two bounding boxes? Is there an opencv or python api call that calculates the jaccard similarity of two bounding boxes?

A: Yes there is ,I used to work with SimpleCV library for doing tasks that were look like yours
see this page
http://simplecv-examples.readthedocs.org/en/latest/


text:
Q: How to create this Kakuro table? Hi I am trying to write Kakuro, but little bit different, If there is no only one possible
solution, It will count, how many solutions are able to achieve. My problem is to
create exact table of this shape

X     X     16\X  16\X  X     X     15\X  16\X  X     X     X     X
X     X\8   .     .     7\X   X\13  .     .     X     7\X   12\X  X
X     16\17 .     .     .     29\9  .     .     19\15 .     .     X
X\9   .     .     6\23  .     .     .     11\11 .     .     .     X
X\16  .     .     .     23\19 .     .     .     .     9\X   X     X
X     X     X\22  .     .     .     19\8  .     .     .     30\X  6\X
X     X     6\X   15\21 .     .     .     .     11\19 .     .     .
X     X\22  .     .     .     11\21 .     .     .     4\8   .     .
X     X\7   .     .     X\3   .     .     X\9   .     .     .     X
X     X     X     X     X\12  .     .     X     X\12  .     .     X

*

*X means there is no number

*X\number ; number defines sum of numbers on the right side of number

*number1\number2; number 1 is sum of numbers below it; number 2 is sum

*of numbers on the right side of number

*number\X; sum of numbers below it

*. empty space for [1-9]

*there cannot be 2 same numbers in sum of one number

*Max size of Table will be 32x32

*I have to use malloc, realloc and struct in C

*My Idea is to create struct CELL with char*[5], but it is no effective still to use retyping

A: Hint: a cell is either:

*

*free for containing any digit between 1 and 9

*non-free; then it is a pair of (optional) sums.


text:
Q: creating simple object in ts I have interface
export interface Vehicle {
    IdNumber: number;
    isNew: boolean;
    contact: {
        firstName: string;
        lastName: string;
        cellPhoneNumber: number;
    };
    color: string;
}

Inside component I'm importing this interface.
 let car: Vehicle = {
      IdNumber: 1,
      isNew: true,
      contact: {
        firstName: 'John',
        lastName: 'Doe',
        cellPhoneNumber: 123,
      },
      color: 'red',
    };

I cannot compile this code cause webpack reporting following error

Types of property 'contact' are incompatible.

A: You have a few errors:
Mismatched property names:
isExisting vs isNew // pick one...

Type error:
color: red // 'red' needs quote marks to be a string

Hope that clears it up...


text:
Q: Normalize json column and join with rest of dataframe
This is my first question here on stackoverflow so please don't roast me.
I was trying to find similar problems on the internet and actually there are several, but for me the solutions didn't work.
I have created this dataframe:
import pandas as pd
from ast import literal_eval
d = {'order_id': [1], 'email': ["hi@test.com"], 'line_items': ["[{'sku':'testproduct1', 'quantity':'2'},{'sku':'testproduct2','quantity':'2'}]"]}
orders = pd.DataFrame(data=d)

It looks like this:
order_id    email         line_items
1           hi@test.com   [{'sku':'testproduct1', 'quantity':'2'},{'sku':'testproduct2','quantity':'2'}]

I want the dataframe to look like this:
order_id    email               line_items.sku        line_items.quantity
1           hi@test.com         testproduct1           2
1           hi@test.com         testproduct2           2

I used the following code to change the type of line_items from string to dict:
orders.line_items = orders.line_items.apply(literal_eval)

Normally I would use json_normalize now to flatten the line_items column. But I also want to keep the id and don't know how to do that. I also want to avoid any loops.
Is there anyone who can help me with this issue?
Kind regards
joant95

A: If your dictionary really is that strange, then you could try:
d['line_items'] = eval(d['line_items'][0])
df = pd.json_normalize(d, record_path=['line_items'], meta=['order_id', 'email'])

To create d out of orders you could try:
d = orders.to_dict(orient='list')

Or you could try:
orders.line_items = orders.line_items.map(eval)
d = orders.to_dict(orient='records')
df = pd.json_normalize(d, record_path=['line_items'], meta=['order_id', 'email'])

But: I still don't have a clear picture of the situation :)


text:
Q: Laravel Schedule One-Off Events Users are able to set up a marketing email send time within my app for random dates as they need them.  It is crucial that the emails start to go out exactly when they are scheduled.  So, the app needs to create something that fires one time for a specific group of emails at a specific date and time down to the minute.  There will be many more dates for other sends in the future, but they are all distinct (so need something other than 'run every xxx date')
I could have a Scheduler task that runs every minute that looks at the dates of any pending tasks in the database and moves to the command that sends those that need sending.  But I'm running a multi-tenanted app -- likely not overlap, but seems like a huge hit to multiple databases every minute for every tenant to search through potentially thousands of records per tenant.
What I need (I think) is a way to programmatically set a schedule for each send date, and then remove it.  I liked this answer or perhaps using ->between($startMin, $endMin), without the every xxx instruction, or even using the cron function within Scheduler to set up one single time for each group that needs to be sent.  Not sure I'm using this the way it was intended though?
Would this even work?  I programmatically created a schedule from within a test method, and it was added to the schedule queue based on the dump of the $schedule I created, showing all schedules - but it did not show up via this method found from this answer:
$schedule = app()->make(\Illuminate\Console\Scheduling\Schedule::class);

$events = collect($schedule->events())->filter(function (\Illuminate\Console\Scheduling\Event $event) {
    return stripos($event->command, 'YourCommandHere');
});

It also did not output anything, so I'm wondering if programmatically creating a schedule outside of Kernel.php is not the way to go.
Is there another way?  I don't know scheduler well enough to know if these one-off schedules permanently remain somewhere, are they deleted after their intended single use, taking up memory, etc?
Really appreciate any help or guidance.


text:
Q: Cannot install firebase-tools I'm following this post to be able to schedule recurring notifications to my Android app via Firebase: enter link description here
The problem is that, at the end, when I have to deploy my functions at: firebase functions:log --project <FIREBASE_PROJECT_ID> My windows terminal says it doesn't recognize firebase command. So I tried to install firebase cli to have access to its commands. So, following enter link description here I installed Node.js but when I run npm install -g firebase-tools The following error shows up:
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: pinkie-promise@^2.0.0 (node_modules\firebase-tools\node_modules\globby\node_modules\pinkie-promise):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: No valid versions available for pinkie-promise
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: timed-out@^3.0.0 (node_modules\firebase-tools\node_modules\got\node_modules\timed-out):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: No valid versions available for timed-out

npm ERR! code ENOVERSIONS
npm ERR! No valid versions available for pinkie-promise

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Roaming\npm-cache\_logs\2018-01-06T20_45_10_832Z-debug.log


text:
Q: There's a drop down at the bottom of this moodle quiz page, how to remove? Still learning here, is it possible to remove the Jump To .... drop down bar by way of CSS?
If not, how can I find the place to change this in Moodle if anyone knows?
Thanks
Moodle Jump To:

A: Extend your css with this:
#jump-to-activity {
    display: none !important;
}

It will remove element which is selected on your image.


text:
Q: A sharp version of Scott core thorem for 3-manifolds Let $M$ be an open $3$-manifold with finitely generated fundamental group. Does $M$ contain a compact codimension zero submanifold whose inclusion into $M$ is a homotopy equivalence?
Somehow I thought this should follow from Scott core theorem, but after some searching I cannot find the statement anywhere. I do not want to assume anything else about $M$, e.g. $M$ may contain two-sided projective planes. In fact, in this generality I do not even see this stated anywhere.

A: As stated, no, because $M$ might be homeomorphic to this core but with an infinite discrete set removed.  You can also do more complicate things, e.g., remove Whitehead continua instead of removing isolated points.
However, $\pi_2$ is the only obstruction to homotopy equivalence.  I cannot think of anything else rigorous to say, but I could imagine that somehow every counterexample can be constructed as a combination of simply connected non-compact regions, and a manifold which is homotopy equivalent to the core.


text:
Q: Split strings in a list of lists I currently have a list of lists:
[['Hi my name is'],['What are you doing today'],['Would love some help']]

And I would like to split the strings in the lists, while remaining in their current location. For example
[['Hi','my','name','is']...]..

How can I do this?
Also, if I would like to use a specific of the lists after searching for it, say I search for "Doing", and then want to append something to that specific list.. how would I go about doing that?

A: You can use a list comprehension to create new list of lists with all the sentences split:
[lst[0].split() for lst in list_of_lists]

Now you can loop through this and find the list matching a condition:
for sublist in list_of_lists:
    if 'doing' in sublist:
        sublist.append('something')

or searching case insensitively, use any() and a generator expression; this will the minimum number of words to find a match:
for sublist in list_of_lists:
    if any(w.lower() == 'doing' for w in sublist):
        sublist.append('something')

A: list1 = [['Hi my name is'],['What are you doing today'],['Would love some help']]

use
[i[0].split() for i in list1]

then you will get the output like
[['Hi', 'my', 'name', 'is'], ['What', 'are', 'you', 'doing', 'today'], ['Would', 'love', 'some', 'help']]

A: l = [['Hi my name is'],['What are you doing today'],['Would love some help']]

for x in l:
    l[l.index(x)] = x[0].split(' ')

print l

Or simply:
l = [x[0].split(' ') for x in l]

Output
[['Hi', 'my', 'name', 'is'], ['What', 'are', 'you', 'doing', 'today'], ['Would', 'love', 'some', 'help']]


text:
Q: installed mediterraneandark theme, but doesn't look like example I have installed a theme in Ubuntu 12.10, and the preview image looks like
.
However, Nautilus file manager looks the same, it's just the window manager top part (title, close, minimise maximise) which has changed.
Am I missing a step?
To clarify: The colours have changed, but the layout and buttons remain the same. It looks like
.
Thanks in advance.

A: You have to install Nautilus 3.6. It is not included in Ubuntu 12.10 repositories, so run following commands:
$ sudo add-apt-repository ppa:gnome3-team/gnome3

and then:
$ sudo apt-get update

Now you just have to kill all Nautilus processes:
$ killall nautilus

and upgrade your software:
$ sudo apt-get upgrade

You should have Nautilus 3.6 now.


text:
Q: Using Spark to insert into Hive database with "." in database name I have the following code to select some data from a Hive table, do some simple transformations, then insert them back into the same table:
sqlContext.sql("USE `database.with.dot`");
val ds = sqlContext.sql("select * from Table where column = 'SomeValue'");
ds.withColumn("anotherColumn", lit("SomeOtherValue"))
  .write.insertInto("Table")

However, I'm getting:
org.apache.hadoop.hive.ql.parse.SemanticException: Invalid table database.with.dot.Table
  at org.apache.hadoop.hive.ql.exec.Utilities.getDbTableName(Utilities.java:2350)
  at org.apache.hadoop.hive.ql.exec.Utilities.getDbTableName(Utilities.java:2336)
  at org.apache.hadoop.hive.ql.metadata.Hive.getTable(Hive.java:1070)
  at org.apache.hadoop.hive.ql.metadata.Hive.getTable(Hive.java:1058)
  at org.apache.hadoop.hive.ql.metadata.Hive.loadDynamicPartitions(Hive.java:1581)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at org.apache.spark.sql.hive.client.Shim_v1_2.loadDynamicPartitions(HiveShim.scala:823)
  at org.apache.spark.sql.hive.client.HiveClientImpl$$anonfun$loadDynamicPartitions$1.apply$mcV$sp(HiveClientImpl.scala:689)
  at org.apache.spark.sql.hive.client.HiveClientImpl$$anonfun$loadDynamicPartitions$1.apply(HiveClientImpl.scala:687)
  at org.apache.spark.sql.hive.client.HiveClientImpl$$anonfun$loadDynamicPartitions$1.apply(HiveClientImpl.scala:687)
  at org.apache.spark.sql.hive.client.HiveClientImpl$$anonfun$withHiveState$1.apply(HiveClientImpl.scala:283)
  at org.apache.spark.sql.hive.client.HiveClientImpl.liftedTree1$1(HiveClientImpl.scala:230)
  at org.apache.spark.sql.hive.client.HiveClientImpl.retryLocked(HiveClientImpl.scala:229)
  at org.apache.spark.sql.hive.client.HiveClientImpl.withHiveState(HiveClientImpl.scala:272)
  at org.apache.spark.sql.hive.client.HiveClientImpl.loadDynamicPartitions(HiveClientImpl.scala:687)
  at org.apache.spark.sql.hive.HiveExternalCatalog$$anonfun$loadDynamicPartitions$1.apply$mcV$sp(HiveExternalCatalog.scala:796)
  at org.apache.spark.sql.hive.HiveExternalCatalog$$anonfun$loadDynamicPartitions$1.apply(HiveExternalCatalog.scala:784)
  at org.apache.spark.sql.hive.HiveExternalCatalog$$anonfun$loadDynamicPartitions$1.apply(HiveExternalCatalog.scala:784)
  at org.apache.spark.sql.hive.HiveExternalCatalog.withClient(HiveExternalCatalog.scala:95)
  at org.apache.spark.sql.hive.HiveExternalCatalog.loadDynamicPartitions(HiveExternalCatalog.scala:784)
  at org.apache.spark.sql.hive.execution.InsertIntoHiveTable.sideEffectResult$lzycompute(InsertIntoHiveTable.scala:268)
  at org.apache.spark.sql.hive.execution.InsertIntoHiveTable.sideEffectResult(InsertIntoHiveTable.scala:170)
  at org.apache.spark.sql.hive.execution.InsertIntoHiveTable.doExecute(InsertIntoHiveTable.scala:347)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:114)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:114)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:135)
  at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
  at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:132)
  at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:113)
  at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:87)
  at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:87)
  at org.apache.spark.sql.DataFrameWriter.insertInto(DataFrameWriter.scala:263)
  at org.apache.spark.sql.DataFrameWriter.insertInto(DataFrameWriter.scala:243)
  ... 46 elided

Are there any ways to use Spark to insert into a Hive table whose database name has dots in it?
Edit: I am able to query from the table using either Hive shell or Spark SQL, just not insert back into the table.


text:
Q: Problem with Navigation (Error: Range Error (index): Index out of range: no indicies are valid:0) When i am update some field then it updated successfully and redirect on detail Page but it give following error to me when redirect: Range Error index out of range:no indices are valid:0. I cannot get what is the problem in my code.Please guide me about it. I am attaching my code here,
AppointmentDetailEditPage
class AppointmentDetailsEditPage extends StatefulWidget {
      final int aptId;
      final int docID;
      final int staffId;
      final String dTitle;
      final int tNo;
      final String aptExecutive;

      AppointmentDetailsEditPage(
          this.aptId,
          this.docID,
          this.staffId,
          this.dTitle,
          this.tNo,
          // this.doctitle,
          //  this.docToken,
          this.aptExecutive);

      @override
      _AppointmentDetailsEditPageState createState() =>
          _AppointmentDetailsEditPageState(this.aptId, this.docID, this.staffId,
              this.dTitle, this.tNo, this.aptExecutive);
    }

    class _AppointmentDetailsEditPageState
        extends State<AppointmentDetailsEditPage> {
      var paymentMode = ["Online", "Cash", "Cheque"];

      String? selectedMode;
      var items = ["Owner", "Tenant", "Agent", "Both"];

      var status = ["Open", "Closed", "Cancel"];
      TextStyle style = const TextStyle(fontFamily: 'Montserrat', fontSize: 6.0);

      AppointmentController appointmentController =
          Get.put(AppointmentController());

      late Future<Appointment> futureAppointments;
      late final int aptId;
      late final int docID;
      late final int staffId;

      late final String dTitle;
      late final int tNo;
      final String aptExecutive;

      List<Appointment> aptmnt = [];

      _AppointmentDetailsEditPageState(
        this.aptId,
        this.docID,
        this.staffId,
        this.dTitle,
        this.tNo,
        this.aptExecutive,
      );

      @override
      void initState() {
        super.initState();
        futureAppointments =
            AppointmentController.fetchAppointmentsById(this.aptId);

        init();
      }

      Future init() async {
        print('apt ID $aptId');

        final aptmnt = await AppointmentController.fetchAppointments;
        setState(() {
          this.aptmnt = aptmnt as List<Appointment>;
          print(aptmnt);
        });
      }
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Color.fromARGB(255, 3, 87, 156),
            title: Text('Edit Appointment'),
            // flexibleSpace: LogOut(),
            leading: IconButton(
                icon: BackButtonIcon(),
                onPressed: () => Navigator.of(context).push(MaterialPageRoute(
                    builder: (BuildContext context) => AppointmentDetails(
                        aptId, docID, staffId, dTitle, tNo, aptExecutive)))),
          ),
          body:
              //SafeArea(
              Center(
            child: SafeArea(
              child: SingleChildScrollView(
                child: Container(
                  alignment: Alignment.center,
                  child: FutureBuilder<Appointment>(
                    future: futureAppointments,
                    builder: (context, snapshot) {
                      if (snapshot.connectionState == ConnectionState.done) {
                        if (snapshot.hasData) {
                          return Form(
                            key: _formKey,
                            child: Padding(
                                padding: const EdgeInsets.all(7),
                                child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: <Widget>[
 SizedBox(
                                        //   height: 80.0,
                                        width:
                                            MediaQuery.of(context).size.width *
                                                0.4,
                                        child: TypeAheadField<UserLogin>(
                                          hideSuggestionsOnKeyboardHide: true,
                                          textFieldConfiguration:
                                              TextFieldConfiguration(
                                            decoration: InputDecoration(
                                              errorStyle: const TextStyle(
                                                  fontSize: 0.05),

                                              fillColor: Color.fromARGB(
                                                  255, 233, 246, 252),
                                              //  prefixIcon: Icon(Icons.search),
                                              suffixIcon: GestureDetector(
                                                child: Icon(
                                                  Icons.close,
                                                  color: Color.fromARGB(
                                                      137, 221, 221, 221),
                                                  size: 20,
                                                ),
                                                onTap: () {
                                                  aptExecutiveController
                                                      .clear();
                                                  FocusScope.of(context)
                                                      .requestFocus(
                                                          FocusNode());
                                                },
                                              ),
                                              border: OutlineInputBorder(
                                                  // borderRadius: BorderRadius.circular(10.0),
                                                  ),
                                              hintText:
                                                  'Appointment Executive ',
                                              //  labelText: 'Appointment Executive',

                                              hintStyle:
                                                  TextStyle(fontSize: 12),
                                            ),
                                            controller: aptExecutiveController =
                                                TextEditingController(
                                                    text:
                                                        '${this.aptExecutive}'),
                                          ),
                                          suggestionsCallback: (pattern) async {
                                            return await LoginController
                                                .users();
                                          },
                                          itemBuilder:
                                              (context, UserLogin? allUsers) {
                                            final user = allUsers!;

                                            return ListTile(
                                              title: Text(user.userName),
                                            );
                                          },
                                          noItemsFoundBuilder: (context) =>
                                              Container(
                                            height: 50,
                                            child: Center(
                                              child: Text(
                                                'No Staff Found.',
                                                style: TextStyle(fontSize: 12),
                                              ),
                                            ),
                                          ),
                                          onSuggestionSelected:
                                              (UserLogin? AllUsers) {
                                            final user = AllUsers!;
                                            this.aptExecutiveController.text =
                                                user.userName;

                                            setState(() {
                                              this.staffid = user.userId;
                                              //  this.staffid = user.userId;
                                              // print('$staffid');
                                              print('$staffid');
                                              // aptExecutive;
                                            });
                                          },
                                        ),
                                      ),

Navigator.of(context).push(
                                                  MaterialPageRoute(
                                                      builder:
                                                          (BuildContext context) =>
                                                              AppointmentDetails(
                                                                  aptId,
                                                                  docID,
                                                                  staffId,

                                                                  dTitle,
                                                                  tNo,
                                                                  aptExecutive)));

AppointmentController
import 'dart:convert';
import 'dart:ui';
import 'package:AtDocHUB/Model/Appointment.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'package:http/http.dart' as http;

import 'dart:async';

class AppointmentController {
  // fetch list of appointment

static FutureOr<Iterable<Appointment>> fetchAppointments(String title) async {
    //  final url = Uri.parse('http://192.168.0.134:8080/AtdochubJ-3/appointment/');
    final url = Uri.parse(
        'http://3.108.194.111:8080/AtdochubJ-3/appointment/appointmentdetails'
        // 'http://3.108.194.111:8080/AtdochubJ-3/appointment/appointmentdetails'
        );
    final response = await http.get(url);

    if (response.statusCode == 200) {
      final List docs = json.decode(response.body);

      return docs.map((json) => Appointment.fromJson(json)).where((doc) {
        final titleLower = doc.docTitle.toLowerCase();
        final tokenLower = doc.tokenNo.toString();
        final searchLower = title.toLowerCase();

        return titleLower.contains(searchLower) ||
            tokenLower.contains(searchLower);
      }).toList();
    } else {
      throw Exception();
    }
  }
  //list of appointment

  static Future<List<Appointment>> fetchAppointmentList() async {
    final response = await http.get(Uri.parse(
        'http://3.108.194.111:8080/AtdochubJ-3/appointment/appointmentdetails'));
    //print(fromJson(json)).toList());
    if (response.statusCode == 200) {
      final parsed = json.decode(response.body).cast<Map<String, dynamic>>();

      return parsed
          .map<Appointment>((json) => Appointment.fromJson(json))
          .toList();

      //return Document.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Failed to load Appointment');
    }
  }
  //fetch list of appointment by id

  static Future<Appointment> fetchAppointmentsById(aptId) async {
    final response = await http.get(
      Uri.parse(
          'http://3.108.194.111:8080/AtdochubJ-3/appointment/find/${aptId}'),
    );

    if (response.statusCode == 200) {
      return Appointment.fromJson(jsonDecode(response.body)[0]);
    } else {
      throw Exception('Failed to load Appointment');
    }
  }

Future<Appointment> createAppointment(
  int? aptId,
  int? docId,
  int staffId,
  //String docTitle,
  // String tokenNo,
  String partyName,
  String contactNo,
  String partyType,
  String aptPlace,
  String city,
  int? feesCollected,
  int totalFees,
  String paymentMode,
  String aptDate,
  String aptTime,
  // String aptExecutive,
  String aptStatus,
  String comments,
  // String createdAt,
) async {
  final response = await http.put(
      // Uri.parse('http://192.168.0.134:8080/AtdochubJ-3/appointment/register'),
      Uri.parse('http://3.108.194.111:8080/AtdochubJ-3/appointment/register'

          // 'http://3.108.194.111:8080/AtdochubJ-3/appointment/register'
          ),
      headers: {
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(<String, dynamic>{
        'aptId': aptId,
        'docId': docId,
        'staffId': staffId,

        'partyName': partyName,
        'contactNo': contactNo,
        'partyType': partyType,
        'aptPlace': aptPlace,
        'city': city,
        'feesCollected': feesCollected!,
        'totalFees': totalFees,
        'paymentMode': paymentMode,
        'aptDate': aptDate,
        'aptTime': aptTime,
        //'aptExecutive': aptExecutive,
        'aptStatus': aptStatus,

        'comments': comments,
        //  'createdAt': createdAt,
      }));
  if (response.statusCode == 200 || response.statusCode == 201) {

    return Appointment.fromJson(jsonDecode(response.body)[0]);
else{
  throw Exception(' Failed To Create Appointment');
}

AppointmentDetailPage
class AppointmentDetails extends StatefulWidget {
  final int aptId;
  final int staff_Id;
  late final int docID;

  final String dTitle;
  final int tNo;
  final String aptExecutive;
  // final String doctitle;
  // final String docToken;

  AppointmentDetails(this.aptId, this.staff_Id, this.docID, this.dTitle,
      this.tNo, this.aptExecutive);

  @override
  _AppointmentDetailsState createState() => _AppointmentDetailsState(
        this.aptId,
        this.staff_Id,
        this.docID,
        this.dTitle,
        this.tNo,
        this.aptExecutive,
      );
}

class _AppointmentDetailsState extends State<AppointmentDetails> {
  AppointmentController appointmentController =
      Get.put(AppointmentController());

  late Future<Appointment> futureAppointments;
  final int aptId;
  final int staff_Id;
  final int docID;
  final String dTitle;
  final int tNo;
  final String aptExecutive;

  _AppointmentDetailsState(this.aptId, this.staff_Id, this.docID, this.dTitle,
      this.tNo, this.aptExecutive);

  @override
  void initState() {
    super.initState();
    //  print('detail staff ID $staff_Id');
    //  print('detail doc ID $docId');
    print('apt detail...... $aptId, $dTitle, $tNo, $aptExecutive');

    futureAppointments =
        AppointmentController.fetchAppointmentsById(this.aptId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color.fromARGB(255, 3, 87, 156),
        title: Text('Appointment Details'),
        leading: IconButton(
            icon: BackButtonIcon(),
            onPressed: () => Navigator.of(context).push(MaterialPageRoute(
                builder: (BuildContext context) => AppointmentPageFE()))),
      ),
      body: Center(
        child: FutureBuilder<Appointment>(
          future: futureAppointments,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return ListView(children: [
                SafeArea(
                  child: SingleChildScrollView(
                    child: Container(
                      padding: EdgeInsets.all(15),
                      height: 750,
                      child: SelectionArea(
                        child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
 Text('Document Title: ' + this.dTitle,
                                  style: const TextStyle(fontSize: 15.0)),
                              Text('Token No :' + this.tNo.toString(),
                                  style: const TextStyle(fontSize: 15.0)),
                              Text("Party Name : " + snapshot.data!.partyName,
                                  style: const TextStyle(fontSize: 15.0)),
                              Text(
                                  'Appointment Executive :' + this.aptExecutive,
                                  style: const TextStyle(fontSize: 15.0)),
                              Text("Contact No : " + snapshot.data!.contactNo,
                                  style: const TextStyle(fontSize: 15.0)),
                              Text("Party Type : " + snapshot.data!.partyType,
                                  style: const TextStyle(fontSize: 15.0)),
                              Text(
                                  "Appointment Place : " +
                                      snapshot.data!.aptPlace,
                                  style: const TextStyle(fontSize: 15.0)),
                              Text("Appointment City : " + snapshot.data!.city,
                                  style: const TextStyle(fontSize: 15.0)),
                              Text(
                                  "Appointment Date : " +
                                      snapshot.data!.aptDate,
                                  style: const TextStyle(fontSize: 15.0)),
                              Text(
                                  "Appointment Time : " +
                                      snapshot.data!.aptTime,
                                  style: const TextStyle(fontSize: 15.0)),
                              Text(
                                  "Appointment Status : " +
                                      snapshot.data!.aptStatus,
                                  style: const TextStyle(fontSize: 15.0)),
                              Text(
                                  "Fees : " +
                                      snapshot.data!.totalFees.toString(),
                                  style: const TextStyle(fontSize: 15.0)),
                              Text(
                                  "Fees Collected : " +
                                      snapshot.data!.feesCollected.toString(),
                                  style: const TextStyle(fontSize: 15.0)),
                              Text(
                                  "Payment Mode : " +
                                      snapshot.data!.paymentMode,
                                  style: const TextStyle(fontSize: 15.0)),
                              Text("Comments : " + snapshot.data!.comments,
                                  style: const TextStyle(fontSize: 15.0)),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Container(
                                    alignment: Alignment.center,
                                    height: 35,
                                    width: 200,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(10),
                                      color: Color.fromARGB(255, 3, 89, 168),
                                    ),
                                    child: TextButton(
                                      // style:
                                      //     TextButton.styleFrom(fixedSize: Size.fromHeight(300)),
                                      child: const Text(
                                        'Edit ',
                                        style: TextStyle(
                                          fontSize: 17.0,
                                          fontWeight: FontWeight.bold,
                                          color: Colors.white,
                                          backgroundColor:
                                              Color.fromARGB(255, 3, 89, 168),
                                        ),
                                      ),

                                      onPressed: () {
                                        print(
                                            'apt executive.......${aptExecutive}');
                                        Navigator.of(context)
                                            .pushAndRemoveUntil(
                                                MaterialPageRoute(
                                                    builder: (BuildContext
                                                            context) =>
                                                        AppointmentDetailsEditPage(
                                                          this.aptId,
                                                          this.staff_Id,
                                                          this.docID,
                                                          this.dTitle,
                                                          this.tNo,
                                                          this.aptExecutive,
                                                        )),
                                                (Route<dynamic> route) =>
                                                    false);
                                      },
                                    ),
                                  ),
                                ],
                              ),
                            ]),
                      ),
                    ),

                    // ),
                    padding: const EdgeInsets.all(10),
                  ),
                ),
              ]);
            } else if (snapshot.hasError) {
              return Text('${snapshot.error}');
            }

            // By default, show a loading spinner.
            return const CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}


text:
Q: vector of functions in c++ I have a vector:
std::vector<int> v;

I push back 10 elements to this vector so now it has 10 elements: v[0], v[1], ... ,v[9]
I have another vector:
std::vector<std::function<>()> v5;

I want to push_back() these formulas to v5: v[0]*v[1], v[0]*v[2], ...
How can I push_back() these formulas to v5 vector? Can you help me for the syntax?
I will use these formulas later in the program.
For example when I call v5[0], I want to extract v[0]*v[1] (the first pushed_back formula to v5).

A: This could be one way:
#include <functional>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{3,4,5};

    // a vector of std::functions capturing v by reference
    std::vector<std::function<int()>> v5{
        [&v]{ return v[0] * v[1]; },
        [&v]{ return v[0] * v[2]; },
    };

    for(auto&& func : v5) {
        std::cout << func() << '\n';
    }

    v[0] = 10; // changing v changes the output of the formula:

    std::cout << v5[0]() << '\n';
}

Output:
12
15
40