text:
Q: Sending intermittent response from ASP.NET Web API method to jquery ajax I am working on a task where I need to send intermittent status response from Web API method back to the jquery ajax call and display the progress in UI.

Initially, the jquery ajax will call the web Api method passing some parameters and the web Api method starts to perform long running actions. After each action is complete, I want to send a percentage (manually, some number) back to the calling jquery ajax method and show the progress in UI,
What I have tried so far,
HTML:

                <input type="file" id="FileInput" />

                <button type="button" class="btn btn-default btn-xs" id="UploadFileBtn">Upload</button>

Typescript:
        instance.importFile.on('change', function () {
            instance.selectedFile = this.files[0];
            // This code is only for demo ... (usage of FileAPI)
            console.log("name : " + instance.selectedFile.name);
            console.log("size : " + instance.selectedFile.size);
            console.log("type : " + instance.selectedFile.type);
            console.log("date : " + instance.selectedFile.lastModifiedDate);
        });

        $('#UploadFileBtn').on('click', function () {
            var formData = new FormData();
            formData.append('file', instance.selectedFile);

            $.when(FileUploadService.ProcessData(formData)).done(function () {
            }).fail(function () {
                }).progress(function () {
                    console.log("progressing...");
            });
        });

Web API:
public class FileUploadController : ApiController
    {
    [HttpPost]
    public HttpResponseMessage Upload()
    {

        if (HttpContext.Current.Request.Files.Count > 0)
        {
            var postedFile = HttpContext.Current.Request.Files[0];

            var fileNameParts = postedFile.FileName.Split('\\');
            var fileName = fileNameParts[fileNameParts.Length - 1];

            fileName = string.Format("{0}_{1}", DateTime.Now.Ticks.ToString(), fileName);
            string filePath = Path.Combine("c:\\temp", fileName);
            postedFile.SaveAs(filePath);
        }

        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StringContent("UPLOADED");

        System.Threading.Thread.Sleep(5000);

        return response;
    }
}

Question
Now, I have the web api method but, I am not sure how to send the intermittent responses back to UI. I am looking for simple solutions. Any suggestion / example is appreciated.

A: I followed the comments from Jason and able to do polling using a separate ajax call and get the intermittent response.
In the code below, I am trying to upload a file (using jquery.form plugin) to server and perform a long running tasks at the controller level. In order to show progress to the users, the polling concept is used to check the status of the long running tasks.
Here is the code,
ASP.NET HTML:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

This page uses jquery.form plugin to upload

</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="NoFormContentPlaceHolder" runat="server">

            <form id="ImportFileForm" method="post" action="api/FileUpload/Upload" enctype="multipart/form-data">

                    <input type="file" id="ImportFile" name="ImportFile" accept="*.xlsx" class="col-xs-12 file-selector" />

                    <button class="btn btn-danger btn-xs" id="ImportFileBtn" type="submit" title="Import">Import</button>

            </form>

                        0%

</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
     <%:Scripts.Render("~/Scripts/jQueryForm") %>
</asp:Content>

File Upload Controller CS
 public class FileUploadController : ApiController
    {
        [HttpPost] //this is demo, lets assume that user is uploading a file and in the same method, some long running operation is happening.
        public HttpResponseMessage Upload()
        {
            var requestId = HttpContext.Current.Request.Form["RequestTracker"];

            if (HttpContext.Current.Request.Files.Count > 0)
            {
                var postedFile = HttpContext.Current.Request.Files[0];

                var fileNameParts = postedFile.FileName.Split('\\');
                var fileName = fileNameParts[fileNameParts.Length - 1];

                fileName = string.Format("{0}_{1}", DateTime.Now.Ticks.ToString(), fileName);
                string filePath = Path.Combine("c:\\temp", fileName);
                postedFile.SaveAs(filePath);
            }

            //Note: usually, this will be some other operation (database insert/update, data validation etc)
            //Inorder to show the exact status / progress, the backend should store some indication which can be retrieved using another ajax call by polling

            ObjectCache cache = MemoryCache.Default;
            cache.Remove(requestId);//remove any previous for demo purpose

            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now.AddMinutes(10);

            List<int> taskStatus = new List<int>();

            //long running task 1

            for (int i = 0; i < 100; i++)
            {
                System.Threading.Thread.Sleep(100);
                taskStatus.Add(i);
            }

            cache.Set(requestId, taskStatus, policy);

            //long running task 2

            for (int i = 0; i < 100; i++)
            {
                System.Threading.Thread.Sleep(100);
                taskStatus.Add(i);
            }

            cache.Set(requestId, taskStatus, policy);

            //long running task 3

            for (int i = 0; i < 100; i++)
            {
                System.Threading.Thread.Sleep(100);
                taskStatus.Add(i);
            }

            cache.Set(requestId, taskStatus, policy);

            //long running task 4

            for (int i = 0; i < 100; i++)
            {
                System.Threading.Thread.Sleep(100);
                taskStatus.Add(i);
            }

            cache.Set(requestId, taskStatus, policy);

            return Request.CreateResponse(HttpStatusCode.OK, "All Operations Completed");
        }
    }

Polling Controller CS
public class PollingController : ApiController
    {
        [HttpPost]
        public HttpResponseMessage GetStatus(UploadStatusRequest request)
        {
            ObjectCache cache = MemoryCache.Default;
            var fileUploadStatus  = cache.Get(request.RequestId) as List<int>;

            var count = 0;

            if (fileUploadStatus != null)
            {
                count = fileUploadStatus.Count;
            }

            return Request.CreateResponse(HttpStatusCode.OK, "Processed data : " + count + ". Please wait...");
        }
    }

TypeScript file:
namespace jQueryForm {

    export class FileUploadComponent {

        progressBar: JQuery = $('.progress-bar');
        importFile: JQuery = $('#ImportFile');
        uploadStatusMessage: JQuery = $('#UploadStatusMessage');
        pollingStatusMessage: JQuery = $('#PollingStatusMessage');
        pollingInstance: any = null;

        public RegisterEvents() {

            var instance: FileUploadComponent = this;

            instance.importFile.on('change', function () {
                instance.ResetProgressBar();
            });

            var requestStatusTracker = null;

            $('#ImportFileForm').ajaxForm({
                beforeSubmit: function (arr, $form, options) {

                    requestStatusTracker = new Date().getMilliseconds();

                    arr.push({ name: 'RequestTracker', value: requestStatusTracker });

                    return true;
                },
                beforeSend: function (xhr, options) {

                    instance.ResetProgressBar();
                    instance.uploadStatusMessage.text('Uploading...');
                },
                //Note: The uploadProgress method displays the status of file transfer progress to web api method. Once the file is completely transferred to Web API method,
                //      the percentage will become 100. But, there could be other operations once the file is reached Web API and those are not counted.
                uploadProgress: function (event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';

                    instance.progressBar.css("width", percentVal).attr("aria-valuenow", percentComplete).text(percentVal);

                    if (percentComplete == 100) {

                        var uploadStatusRequest = new Entities.UploadStatusRequest();
                        uploadStatusRequest.RequestId = requestStatusTracker;

                        instance.Poll(uploadStatusRequest);
                        instance.uploadStatusMessage.text('File Upload Complete.');
                    }
                },
                success: function (data) {
                    //instance.ResetProgressBar();

                    //Note: all operations completed in the web api method and the success response is received from the controller
                    clearTimeout(instance.pollingInstance);
                    instance.pollingStatusMessage.html(data);

                },
                error: function (xhr) {

                },
                complete: function (xhr) {//controller has completed all the action

                }
            });
        }

        private ResetProgressBar() {
            this.progressBar.css("width", '0%').attr("aria-valuenow", 0).text('0%');
            this.uploadStatusMessage.empty();
        }

        private Poll(uploadStatusRequest) {

            var instance: FileUploadComponent = this;

            instance.pollingInstance = setTimeout(function () {
                $.ajax({
                    url: "api/Polling/GetStatus", data: uploadStatusRequest, dataType: "json", type: 'POST', success: function (data) {
                        //Update your status
                        instance.pollingStatusMessage.html(data);

                        //Setup the next poll recursively
                        instance.Poll(uploadStatusRequest);

                    }, error: function (xhr) {
                        instance.pollingStatusMessage.html(xhr.responseText);
                    }
                });
            }, 2000);
        }
    }
}
$(function () {

    var fileUploadComponent = new jQueryForm.FileUploadComponent();

    fileUploadComponent.RegisterEvents();
});

Output:
The progress is displayed to the user as shown below,


text:
Q: EFI Ubuntu not booting or shown in bios After having installed Ubuntu Server 20.04.2 LTS, when starting my laptop it throws an error stating "No bootable device". When I enter the boot options menu by spamming F12 on startup, I find the "EFI device: Ubuntu" which makes the OS boot. However, when I open the BIOS by spamming F2, in the boot order menu, I can't find it. Any idea how I can make it the default boot drive anyway?
Laptop: Acer Aspire V3-571G
Operating System: Ubuntu Server 20.04.2 LTS

A: Your laptop could be set to boot legacy instead of UEFI. In the boot options, see if you set it to only boot UEFI instead of Legacy (BIOS) or [CSM].(What is CSM option)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I avoid using eval on scripts from JSON? My web app (running jQuery) gets the following JSON response from the server:
{
    "script_0": "$('#objview_0_306').on('click', function(e){ getObjectResponse(96089, '306', 'display'); e.preventDefault();});",
    "verb_0": "display",
    "obid_0": "0_306",
    "body_0": "

",
    "icon_0": "icons/caseman16.png",
    "close_0": "previousTab();",
    "title_0": "Cases",
    "cmdCount": "1"
}

The script_0 element contains scripts that must be run, in this case adding an onClick event to a DOM element.
At the moment, I use eval() to run the scripts, since they are returned as strings. Is there a way to avoid using eval()?

A: Noop. The eval (and alias Function constructor etc.) is designed to do exactly this, parse strings into runnable javascript.
If you don't want to use eval, instead of return the complete javascript from the server, you can return values in json response that instruct your client app to do predefined tasks.
I'm going to plagiarize the comment made by @Esailija:
Why on earth would you have code in json? it's a data-interchange format...

A: I do not think that you can achieve what you want without eval or one of its derivates.
You could give a look to jQuery.globalEval() method, as described here: http://api.jquery.com/jQuery.globalEval/
And you could also give a look to the jQuery.getScript() method: http://api.jquery.com/jQuery.getScript/

A: I'll be the first to spout the usual eval == evil mantra, but im also a realist, and there are times when rules can be broken.
I'd say you might have one of them here.

A: You can try to append that string with code to DOM and then trigger the click event on needed element.


text:
Q: Property in Objective-C Line 1: First.h
Line 2: @property (nonatomic, retain) NSString *name;

Line  3: First.m
Line  4: @synthesize name;
Line  5: -(void)viewDidLoad()
Line  6: {
Line  7:     name = [NSString stringWithString:@"Hello"];
Line  8:                          OR
Line  9:     self.name = [[NSString alloc]initWithString:@"Hello"];
Line 10:                          OR
Line 11:  }
Line 12:-(void)dealloc()
Line 13: {
Line 14: [name release];
Line 14: }

Question 1:
If I follow line number 7 everything is fine and if I used line number 9 Memory leakage is there. As I know self is point to current object and if I used self.object or simply object no more difference.
Question 2: And if I used
@synthesize name = _name;

Then which one is for setting the value of name and which one is for get the value? Difference between:
name = [NSString stringWithString:@"Hello"];
            OR
self.name = [NSString stringWithString:@"Hello"];
            OR
_name = [NSString stringWithString:@"Hello"];

Question 3:
If I create any property is there any need to alloc in the memory as I allocated showing the memory leakage?

A: To respond the first question: you get the leak because initializing the string with the alloc method you are retaining the object created but you don't release the object after, so you get the leak, while creating the string with the stringWithString you get an autoreleased object that is released automatically by the autorelease pool. Note that in your example at line 9 you are initializing the object and passing it to the setter of the property, things would have been different if you have used the ivar ...
To respond your second question: you are synthesizing the property name and associating it to the internal variable(ivar) named _name, so internally in your class you can access the value of the property using the ivar _name.
I strongly suggest to read the Apple documentation about memory management.

A:
QUESTION 1: if I follow line number 7 everything is fine and if I used line number 9 Memory leakage is there. As I know self is point to current object and if I used self.object or simply object no more difference.

Line  7:     name = [NSString stringWithString:@"Hello"];
Line  8:                          OR
Line  9:     self.name = [[NSString alloc]initWithString:@"Hello"];

On line 7 you are using a convenience constructor which returns an autoreleased object and assigning the object directly to your name ivar; now, it is ok to assign an autoreleased object to a retain property, but it is incorrect to assign an autoreleased object directly to an ivar without also explicitly retaining it:
name = [[NSString stringWithString:@"Hello"] retain];

On line 9 you are using alloc/init which gives you a retained object: it is correct to assign such an object directly to an ivar, but you should autorelease it before assigning to a retain property, e.g.:
self.name = [[[NSString alloc]initWithString:@"Hello"] autorelease];

You can reason about this in terms of the object retain count:

*

*a convenience constructor will set the retain count to 1, but this will be later on automatically decreased by a release call done by the framework;

*alloc/init will give you a retain count of 1 that will not be decreased unless you explicitly call release;

*When an object retain count goes to 0, then it will be deallocated.
Reasoning in terms of retain count is just a way to look at this whole matter of memory management and to understand what is going on deep in the framework; in no case this is a proper way to analyze your objects lifecycle, though.

then which one is for setting the value of name and which one is for get the value? Difference between name = [NSString stringWithString:@"Hello"]; OR self.name = [NSString stringWithString:@"Hello"]; OR _name = [NSString stringWithString:@"Hello"];

name = [NSString stringWithString:@"Hello"];

and
_name = [NSString stringWithString:@"Hello"];

are just the same thing in the two cases given. This will bypass the property setter(/getter) method and assign directly to the ivar. In this case, your app would sooner or later crash because you are assigning an autoreleased object to the ivar directly. This would be correct:
_name = [[NSString stringWithString:@"Hello"] retain];

or
_name = [[NSString alloc] initWithString:@"Hello"];

Note that in a program where you declare your ivar as _name, you cannot use name to refer to it; you can use name to directly refer to the ivar if you declared only the property without explicitly specifying the ivar like you did for question 1 (in this case, name would be the ivar automatically generated by the compiler for you).
On the other hand:
self.name = [NSString stringWithString:@"Hello"];

will use the property accessor method (actually, the setter); since your property is declared as retain, it is ok to assign to it the autoreleased variable returned by the convenience constructor stringWithString:.

QUESTION 3: if I create any property is there any need to alloc in the memory as I allocated showing the memory leakage.

This is not really clear to me.
A good document where to read about the basic of memory management is: Memory Management Policy and also Practical Memory Management from Apple's Advanced Memory Management Programming Guide.

A: First some background, a summary only of the concepts for MRC:
Memory management is all about ownership; as long as you own an object it will exist, some time after you relinquish ownership the object will be destroyed. Any references you maintain to an object are effectively invalid and should not be used once you've relinquished ownership.
Ownership is not exclusive but follows a shared model, there can be more than one owner at any given time and only when an object has no owners does it become available to be destroyed.
If you only need to use an object temporarily, e.g. within a single block of code, you do not always need to take ownership. This is partly a consequence of how ownership and be relinquished; rather than immediately relinquishing ownership you can request ownership is relinquished later.
Later occurs at certain points in the execution of an application and unless any such points are manually added there is one such point after the execution of each cycle through the run loop.
Ownership is asserted through a retain call or calling a method which returns an object you own - most commonly alloc, but also copy and others. Ownership is relinquished using a call to release; and is relinquished later using a call to autorelease.
Question 1:
Line  7:     name = [NSString stringWithString:@"Hello"];
Line  8:                          OR
Line  9:     self.name = [[NSString alloc] initWithString:@"Hello"];

The right hand side (RHS) of line 7 returns a reference to an object you do not own. The left hand side (LHS) assigns this reference to the instance variable name. You have now stored a reference to something you do not own, this is bad as at any future time the owner(s) of the object may relinquish ownership, the object destroyed, and you have an invalid reference in name. Lesson: *Do not store references to objects you do not own in instance variables".
On the other hand the RHS of line 9 returns a reference to an object you do own. However the LHS uses a property invocation self.name to store the reference, and that also takes ownership as it is a retain property - you now own it twice, this is bad but if a different way; unless you also relinquish ownership twice, which you probably won't do, the object will always have an owner and will live forever, commonly called a leak.
If you swap the code around:
Line  7a:     name = [[NSString alloc] initWithString:@"Hello"];
Line  8a:                          OR
Line  9b:     self.name = [NSString stringWithString: @"Hello"];

then it will do what you expect. The RHS of line 7a returns an object reference you own and the LHS stores it in the instance variable name which is managed by the property name.
The RHS of line 9a returns an object reference you do not own, however the LHS uses a property invocation and as the property has the retain attribute ownership is taken and the reference stored in the instance variable name is to an owned object.
In either case when the current instance (self) is destroyed as the property name has the retain attribute ownership of any object reference by the instance variable name will be relinquished.
Question 2
What is the affect of using:
@synthesize name = _name;

This just means that the property name will use an instance variable _name rather than name. In your code snippets you never declare name or _name so both are automatically declared by the @synthesize; so there is only either a name or an _name instance variable depending on the @synthesize. So the answer to Question 2 is the answer to Question 1 with every reference to the instance variable name replaced by _name.
Question 3
If I understand this question, and I'm not sure I do, it is covered by the answer to Question 1.
HTH


text:
Q: Shared Django field across model instances I'm new to Django, and need help with something quite basic.
Suppose we created a model representing a worker, and we wanted to create a function to calculate how much each worker made after taxes. For simplicity, a worker has a take-home pay of their gross income times their tax rate, and the tax rate is a variable that all workers share.
class Worker(models.Model):
    gross_income = models.FloatField(null=True, blank=True)
    def take_home_pay(self):
        return self.gross_income*tax_rate

I know how to store each worker's gross income in the database. I did it using models.FloatField. Here's my question: how would I store the tax rate, which is shared across workers, in the database?

A: You can create a TaxRate model and attach a relation on your Worker model. Additionally, you can implement the __mul__ and __rmul__ methods so you can the TaxRate instance directly in your computation.
class TaxRate(models.Model):
    rate = models.FloatField(null=True, blank=True)

    def __mul__(self, other):
        return self.rate * other

    __rmul__ = __mul__

class Worker(models.Model):
    gross_income = models.FloatField(null=True, blank=True)
    tax_rate = models.ForeignKey(TaxRate)

    def take_home_pay(self):
        return self.gross_income * self.tax_rate


text:
Q: Restrict users from seeing the command line history I want to restrict the user to view the command line history of bash. I'm able to do this through the steps mentioned in this StackOverflow question.
Now, as an admin, I need to  know the list of commands/scripts a user executed. Is there any way I can achieve this task?

A: You will have to re-enable the history file, undoing what you did in the other article, then it will start logging again, you won't be able to "get back" ones that weren't saved.
By default permission users can only view their own history, but as root you could read them all.
If you want to ban a user from viewing their own history you could change the permission of the /home/username/.bash_history file, but I am not sure why you would want this,.


text:
Q: PowerShell Invoke-Command -AsJob The script I wrote is pretty long but works fine except for one problem. When I have more jobs for the same $Server it's only submitting one job and doesn't execute the second or third job for the same $Server.
The input comes from a CSV-file in this format:
\\domain\SHARE\Target3, 0
BELSFBRUS0131, E:\DEPARTMENTS\CBR\SHARE\Target2, 0
BELSFBRUS0131, E:\DEPARTMENTS\CBR\SHARE\Target4, 0

In the example above the script only starts 2 jobs, one for the UNC-path Target3 and one for Target2 on BELSFBRUS0131, these are executed fine. But there's no job launched for Target4to the same server... Is this maybe a restriction of Invoke-Command to only launch once to each server?
Thank you for your help guys.
Here is the important part of the script (due to max. 30.000 lines, I limited it):
Foreach ($_ in $File) {

# Starting jobs

    if (($Server -eq "UNC") -or ($Server -eq "$env:COMPUTERNAME")) {
        Write-Host "$(Get-TimeStamp) $env:COMPUTERNAME > Start job: local > $Server, $Target, $OlderThanDays, $LogFolder, $CleanFolders" -ForegroundColor Gray
        $arrayAllJobs += Start-Job -ScriptBlock $JobCall -ArgumentList ($Target, $OlderThanDays, $Server, $LogFolder, $CleanFolders) -Name DelFiles
    }
    else {
          Write-Host "$(Get-TimeStamp) $env:COMPUTERNAME > Start job: Remote > $Server, $Target, $OlderThanDays, $LogFolder, $CleanFolders" -ForegroundColor Gray
          $arrayAllJobs += Invoke-Command -ScriptBlock $JobCall -ArgumentList ($Target, $OlderThanDays, $Server, $LogFolder, $CleanFolders) -ComputerName "$Server.grouphc.net" -Authentication Credssp -Credential $Credentials -AsJob -JobName DelFiles
    }
}
#__________________________________________________________________________________________________________________________________
# Checking jobs

Write-Host "`n$(Get-TimeStamp) $env:COMPUTERNAME > Waiting for all jobs to finish.." -ForegroundColor Cyan; Wait-Job -Job $arrayAllJobs
Write-Host "`n$(Get-TimeStamp) $env:COMPUTERNAME > The targets were:" -ForegroundColor Cyan; $arrayAllPaths | Format-List

foreach ($Job in $arrayAllJobs) {
    if ($job.State -ne 'Completed') {
        # Write-Host ($Job.ChildJobs[0].JobStateInfo.Reason.Message) -ForegroundColor Red
        $arrayJobError += $Job.ChildJobs[0].JobStateInfo.Reason.Message
        $HTMLarrayJobError += $Job.ChildJobs[0].JobStateInfo.Reason.Message +"<br>"
    }
    #<# Reported success:
    else {
        Write-Host (Receive-Job $Job) -ForegroundColor Green
    } #>
}

A: I suspect it related to the fact that all of your jobs are being created with the same JobName:
 Invoke-Command -ScriptBlock $JobCall -ArgumentList ($Target, $OlderThanDays, $Server, $LogFolder, $CleanFolders) -ComputerName "$Server.grouphc.net" -Authentication Credssp -Credential $Credentials -AsJob -JobName DelFiles

so you're trying to create two jobs with the same name, on the same server.

A: I made a previous error in my script, that was the reason why the seconde server didn't arrive in the loop. I'm sorry everyone, my bad.


text:
Q: Types of Rules Don't Agree I'm trying to write a program in SML for the following problem:

A game is played with a card-list and a goal. The player has a list of held-cards, initially empty. The player
makes a move by either drawing, which means removing the first card in the card-list from the card-list and
adding it to the held-cards, or discarding, which means choosing one of the held-cards to remove. The game
ends either when the player chooses to make no more moves or when the sum of the values of the held-cards
is greater than the goal. Write a function officiate, which "runs a game." It takes a card list (the card-list) a move list
(what the player "does" at each point), and an int (the goal) and returns the score at the end of the
game after processing (some or all of) the moves in the move list in order. Use a locally defined recursive
helper function that takes several arguments that together represent the current state of the game. As
described above:

*

*The game starts with the held-cards being the empty list.

*The game ends if there are no more moves. (The player chose to stop since the move list is empty.)

*If the player discards some card c, play continues (i.e., make a recursive call) with the held-cards
not having c and the card-list unchanged. If c is not in the held-cards, raise the IllegalMove
exception.

*If the player draws and the card-list is (already) empty, the game is over. Else if drawing causes
the sum of the held-cards to exceed the goal, the game is over (after drawing). Else play continues
with a larger held-cards and a smaller card-list.

And this is my solution:
datatype suit = Clubs | Diamonds | Hearts | Spades
datatype rank = Jack | Queen | King | Ace | Num of int
type card = suit * rank

datatype move = Discard of card | Draw

exception IllegalMove

fun remove_card (cs, c, e) =
    let
       fun delete_it (cs, c, e, count, acs) =
           case cs of
           [] => if count = 0 then raise e else acs
         | cp::cs' => if cp = c andalso count = 0
                      then delete_it (cs', c, e, count + 1, acs)
                      else
                          if cp = c then delete_it (cs', c, e, count + 1, [cp] @ acs) else delete_it (cs', c, e, count, [cp] @ acs)
    in
       delete_it (cs, c, e, 0, [])
    end

fun sum_cards (loc) =
    let
        fun sum_it (loc, sum) =
           case loc of
           [] => sum
         | c::loc' => sum_it (loc', sum + card_value (c))
    in
        sum_it (loc, 0)
    end

fun score (loc, goal) =
    let
        val sum = sum_cards (loc)
        val all_same = all_same_color (loc)
    in
        let
           fun prem_score (sum, goal) =
               if sum > goal
               then 3 * (sum - goal)
               else goal - sum
        in
           let
              val pre_score = prem_score (sum, goal)
              fun final_score (all, pre) =
                  if all
                  then pre div 2
                  else pre
        in
           final_score (all_same, pre_score)
        end
    end
    end

fun officiate (loc, lom, goal) =
    let
    fun get_score (lcards, lohc, lmoves, goal, e) =
        case lmoves of
        [] => score (lcards, goal)
          | Draw::lmoves' => case lcards of
                   [] => score (lcards, goal)
                 | c::loc' => if sum_cards (c) > goal
                          then score (lcards, goal)
                          else get_score (loc', c::lohc, lmoves', goal, e)
          | d::lmoves' => case d of
                 Discard c => get_score (loc, remove_card (lohc, c, e), lmoves', goal, e)
    in
    get_score (loc, [], lom, goal, IllegalMove)
    end

Ihe function sum_cards returns the values sum of the given card lists. score function returns the score of the game, while remove_card returns a list of cards minus the card provided. All these functions are working perfectly, but the problem is in the officiate function as I tried to use another two helper functions but without luck. This is the error log:
hw2.sml:196.17-196.60 Error: operator and operand don't agree [tycon mismatch]
  operator domain: (suit * rank) list * (suit * rank) list list * 'Z * int *
                   'Y
  operand:         (suit * rank) list list * (suit * rank) list list *
                   move list * int * 'Y
  in expression:
    get_score (loc',c :: lohc,lmoves',goal,e)
hw2.sml:198.29-198.78 Error: operator and operand don't agree [tycon mismatch]
  operator domain: (suit * rank) list list * (suit * rank) list * exn
  operand:         (suit * rank) list list * card * 'Z
  in expression:
    remove_card (lohc,c,e)
hw2.sml:192.27-198.78 Error: types of rules don't agree [tycon mismatch]
  earlier rule(s): (suit * rank) list list -> int
  this rule: move list -> 'Z
  in rule:
    :: (d,lmoves') =>
      (case d
        of Discard c => get_score (<exp>,<exp>,<exp>,<exp>,<exp>))
hw2.sml:192.27-198.78 Error: case object and rules don't agree [tycon mismatch]
  rule domain: (suit * rank) list list
  object: (suit * rank) list
  in expression:
    (case lcards
      of nil => score (lcards,goal)
       | :: (c,loc') =>
           if sum_cards <exp> > goal
           then score (<exp>,<exp>)
           else get_score (<exp>,<exp>,<exp>,<exp>,<exp>)
       | :: (d,lmoves') =>
           (case d
             of Discard <pat> => get_score <exp>))
val it = () : unit

I think this is because I used multiple case expressions.
Any help will be appreciated!


text:
Q: Complex and multiple transform styles in angular 2+ How can I add multiple inline transform styles in angular 2+?
This works:
[style.transform]="'rotate(45deg)'"

But when I add more than 1 style it does not work:
[style.transform]="'rotate(45deg) translateX(10px)'"

Where can I find a reference of supported style.* directive?
Is something like this possible?
[style.transform.translateX.px] = "10"
[style.transform.rotate.deg] = "45"

A: Here are two methods that work:
Method 1 - Using ngStyle:
[ngStyle]="{'transform': 'rotate(45deg) translateX(10px)'}"

Method 2 - Sanitizing the value passed to [style.transform]:
[style.transform]="myTransform"

import { DomSanitizer, SafeStyle } from '@angular/platform-browser';

get myTransform(): SafeStyle {
  return this._sanitizer.bypassSecurityTrustStyle("rotate(45deg) translateX(10px)");
}

See this stackblitz.

As mentioned in the question, the following syntax does not work (see this demo):
[style.transform]="'rotate(45deg) translateX(10px)'"

The style attribute is removed from the HTML output and this warning is triggered:

WARNING: sanitizing unsafe style value rotate(45deg) translateX(10px)
  (see http://g.co/ng/security#xss).


text:
Q: Using R variables to construct table names and functions I work for a small nonprofit trying to look at census data for guiding our work. since I have to look at a bunch of different census tables looking for trends I would love to automate this since the task is the same I am just changing table names.
Here is what I have so far:
Variables block
 #table specific variables
importpath <-paste("C:/Users/DataNerd/OneDrive/",
                   "censusdata/",
                   sep = "")

#columns to keep from larger table
focuscolumns <- c("GEO.id2", "HC01_EST_VC01", "HC02_EST_VC01")

#years to focus on from the acs data
acsyear <- c("15", "14", "13", "12")

#Name of the ACS table
acstablename <- "S1701"

#data naming variables
datanames <- c("poverty", "rate", etc...)

So the variables block above is the only block of code I want to change when I go from examining a census table on Poverty Rate to one on substandard housing.
Using those variables I can get pretty far.
#create the table name
tablefile <- paste("ACS_", acsyear[1], "_5YR_", acstablename, sep = "")

#import data
tableA<-          read_csv(paste(importpath,
                                   tablefile,
                                   "/",
                                   tablefile,
                                   ".csv",
                                   sep = ""))

ACS15 <- subset(tableA, select = focuscolumns)

tablefile <- paste("ACS_", acsyear[2], "_5YR_", acstablename, sep = "")

tableA<-          read_csv(paste(importpath,
                                 tablefile,
                                 "/",
                                 tablefile,
                                 ".csv",
                                 sep = ""))

ACS14 <- subset(tableA, select = focuscolumns)

The issue I have concerns creating the names and functions using the variables block. To get poverty rate I need to divide one column by another column in my focuscolumns variable.
Here is what I thought would work.
paste0('ACS', acsyear[1], datanames[1]) <- mutate( paste0("ACS", acsyear[1],
paste0("ACS",acsyear[1],datanames[1],datanames[2]) = focuscolumns[3]/ focuscolumns[2]
    ))

Through the magic of R I thought that code should evaluate down to:
ACS15poverty <- mutate(ACS15,
                       ACS15povertyrate = HC02_EST_VC01/HC01_EST_VC01)

It does not and I am not sure how to R to evaluate it in the way I was hoping for.
Any help would be appreciated.


text:
Q: LS two folder side by side How do I paste the content of two folders side by side so that output looks like
some_command dir1 dir2

dir1_file1 dir2_file1
dir1_file2 dir2_file2
dir1_file3 dir2_file3
dir1_file4 dir2_file4

A: Have a look in gnu diff utility combined with process substitution:
$ diff -y <(ls ./tmp) <(ls ./tmp2)
20161201.csv                              <
20161202.csv                              <
aa.txt                              aa.txt
a.txt                               a.txt
bb.txt                              bb.txt
bsd.bsd                             bsd.bsd
b.txt                               b.txt

$ diff -y --suppress-common-lines <(ls ./tmp) <(ls ./tmp2)
20161201.csv                              <
20161202.csv                              <

See man diff for more options.

A: You can do it in 3 commands:
ls -1 dir1 > file1
ls -1 dir2 > file2
pr -m -t file1 file2

A: You could use sdiff and view the 2 directories side by side like so:
$ sdiff <(ls -1 dir1) <(ls -1 dir2)

Any differences between the 2 directories will be reflected with a < or > depending on which side of the comparison is missing a specific file/sub-directory.
Example
$ sdiff <(ls -1 dir1) <(ls -1 dir2)
alison_krauss                                                   alison_krauss
Bach - Brandenburg Concertos                                  <
band_of_horses                                                  band_of_horses
Barenaked Ladies                                              <
big_star                                                        big_star
bob_seger                                                       bob_seger

A: I don't understand the need for the hack of diffing / sdiffing this. This introduces useless processing. The same for pr.
If all you need is to print files from two folders side-by-side, all you need is paste. This command is precisely for not counting, not diffing, but simply printing multiple files side-by-side in (by default) tab-separated fields, one line per file.
Just do:
paste <(ls dir1) <(ls dir2)

You can easily make this into a script or a function.
6 Excellent Free Books to Learn Bash

*

*GNU Bash Reference Manual by Chet Ramey, Brian Fox

*Advanced Bash Scripting Guide by Mendel Cooper

*The Linux Command Line by William Shotts

*Bash Guide for Beginners by Machtelt Garrels

*The Bash Guide by Maarten Billemont

*Linux Shell Scripting Tutorial by Vivek Gite
#1 is authored by Chet Ramey, the author of bash.
I had at some point a book exclusively dedicated to shell filters, but that was in the early 90s, before bash, Linux, electricity...
EDIT
Here's the function:
function join_by {
  local d=${1-} f=${2-}
  if shift 2; then
    printf %s "$f" "${@/#/$d}"
  fi
}

sbs() {
  d="<(ls `join_by ') <(ls ' $*`)"
  echo $d
  eval paste $d
}

The auxiliary function join_by was contributed here in SO almost a decade ago, because bash, just like diamonds, is forever.


text:
Q: Ошибка авторизации VK Есть скрипт по отправке некоторых сообщений (не спам, не флуд, не реклама), работал с ним уже более полугода, все было отлично.
Сегодня при попытке авторизации выдало следующую ошибку: vk.exceptions.VkAuthError: OAuth2 authorization error
Пробовал логиниться через другое приложение - не помогло.
Вот код самой авторизации:
import vk
session = vk.AuthSession('idприложения', 'логин', 'пароль', scope='messages,users,friends')
vk_api = vk.API(session)

Если убрать из scope='messages,users,friends' флаг messages, то ошибка пропадает и авторизация проходит, в чем может быть проблема?

A: Проблема решена не была, но вот ее причина:

С 15 февраля 2019 года методы секции messages по умолчанию будут доступны для вызова только с ключом доступа сообщества.
Если Вы планируете начать разработку мессенджера, после 15 февраля 2019 года для этого потребуется получить в Поддержке тестовый доступ, подразумевающий работу методов секции Messages с ключами администраторов Вашего Standalone-приложения.
Для получения полного доступа к пользовательскому Messages API приложению будет необходимо пройти модерацию.

Источник:
https://vk.com/dev/messages_api


text:
Q: How to use read() to read data until the end of the file? I'm trying to read binary data in a C program with read() but EOF test doesn't work. Instead it keeps running forever reading the last bit of the file.
#include <stdio.h>
#include <fcntl.h>
int main() {

  // writing binary numbers to a file
  int fd = open("afile", O_WRONLY | O_CREAT, 0644);
  int i;
  for (i = 0; i < 10; i++) {
    write(fd, &i, sizeof(int));
  }
  close(fd);

  //trying to read them until EOF
  fd = open("afile", O_RDONLY, 0);
  while (read(fd, &i, sizeof(int)) != EOF) {
    printf("%d", i);
  }
  close(fd);
}

A: You must check for errors. On some (common) errors you want to call read again!
If read() returns -1 you have to check errno for the error code. If errno equals either EAGAIN or EINTR, you want to restart the read() call, without using its (incomplete) returned values. (On other errors, you maybe want to exit the program with the appropriate error message (from strerror))
Example: a wrapper called xread() from git's source code

A: read returns the number of characters it read. When it reaches the end of the file, it won't be able to read any more (at all) and it'll return 0, not EOF.

A: POSIX rasys return == 0 for end of file
http://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html

If no process has the pipe open for writing, read() shall return 0 to indicate end-of-file.

This confirms Jerry's answer.
EOF is returned by some ANSI functions, e.g. man getc says:

fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.
ungetc() returns c on success, or EOF on error.

so you still can't use it to distinguish error and end of file in that case, feof is needed.
See also: How to use EOF to run through a text file in C?


text:
Q: Unable to access bootstrap 'defines' within View I am in the process of upgrading from CakePHP 2.1 to 2.3, however I seem unable to reference bootstrap.php defines from within a view file.
bootstrap.php:
define('MODEL_VARIABLE_ID_YES', 1);

View File:
if($model['Model']['variable_id'] == MODEL_VARIABLE_ID_YES)
{
     show something...
}
else
{
    show something else...
}

Is this something that has been removed intentionally, or is there some other way to access these defines?

A: Well, I feel like a right idiot.
The issue was related to CakePHP caching, I use memcache and had broken my PHP installation of memcache (when updating PHP earlier). This was causing CakePHP to fire an error about the caching, then when it tried to display the error in my default.ctp file, it errored again because that file contains a define from bootstrap.php, which must not have loaded due to the cache engine issue.


text:
Q: Where can I find a Python 3-compatible library for Db2? I have been working with Python 2 and Db2. Changing to Python 3 the same library doesn't seem to work. What can I do?

A: IBM provides four (4) different type of Python-related libraries for Db2:

*

*ibm_db

*ibm_db_dbi (DBI API)

*ibm_db_sa (SQLAlchemy)

*ibm_db_django (Django adapter)

All libraries and more information can be accessed through the documentation link. In some cases a different library is needed depending on Python 2 or 3, or on 32 bit and 64 bit systems.
In your case you probably need a newer library.


text:
Q: Can the JS equality operators (like ===) work with embind types? Suppose I have some Emscripten bindings like so:
class_<MyNode>("MyNode")
    .constructor<>()
    .function("getParentNode", &MyNode::parentNode, allow_raw_pointers());

When I run the following code in JS, I get false, but I want it to be true:
node.getParentNode() === node.getParentNode()

I'm guessing this is because Emscripten is wrapping the result of each function call in a new JS object, even though the JS objects point to the same underlying C++ object.
That is, is there some trick in Emscripten for JS === or == to return true with bound types that have the same underlying raw pointer values?

A: Probably not. From the MDN docs on the strict equality operator:

If both operands are objects, return true only if they refer to the same object.

You might be interested in this SO thread asking on how to "overload" the equality operator


text:
Q: VB Auto populate datagridview from datatable Is it possible to have a datagrieview populate directly from a datable ? Below is what I am trying in the form load.  Basically I want it to show all the columns this query returns automatically
Dim con As New OleDbConnection
    con = New OleDbConnection(connStr)
    If con.State = ConnectionState.Closed Then
        con.Open()
    End If
    Dim titleSQLStr As String = "SELECT * FROM Titles ORDER BY YearPublished DESC"
    daYears = New OleDbDataAdapter(titleSQLStr, connStr)
    daYears.Fill(dtYears)
    cboYearsFillBy.DataSource = dtYears
    cboYearsFillBy.DisplayMember = "YearPublished"
    cboYearsFillBy.ValueMember = "YearPublished"
    DataGridView1.AutoGenerateColumns = True
    DataGridView1.DataSource = daYears
    con.Close()

A: Change it to:
DataGridView1.DataSource = dtYears


text:
Q: R list.files not showing all files (pathing issue maybe?) I am trying to make a list of files using list.files (Code below):
 raw.file.list <-"/Volumes/TempData/Heather Speckman/EC_Restored/NNTR EC/2014/Unpacked Data"
 setwd(raw.file.list)
 raw.file.list <- list.files(path = raw.data.dir, recursive = T, full.names = T)

I know that there are 4,000+ files in this raw.data.dir, this command is only listing the 1,200 of them-- and it's 1,200 I do NOT see when I look in Windows.
Can anyone help me out as to why?
Additional info:
The file path (raw.file.list) does exist, R moves there just fine.  The pathway is correct and identical when I look in Windows and R (besides / and \ ).  I also tried this on my Mac, and got the same non-functional result.
 raw.file.list <-"/Volumes/TempData/Heather Speckman/EC_Restored/NNTR EC/2014/Unpacked Data"

is a work server which works just like a hard drive.  It has never given me trouble before.  If I copy/paste the data to:
 raw.file.list <-"/Volumes/TempData/Heather Speckman/EC_Restored/NNTR EC/2014/Test Folder"

it works just fine.  For work flow reasons, I don't want copy/paste to be the solution here.
If I try:
 file.name = "Example_file_name.csv"; file.exists(file.name)

R says false.  My computer sees the file and opens it just fine.
Trying:
 setwd(raw.data.dir); list.files(path = ".", recursive = T, full.names = T)

Gives only the 1200 files, not the full 4,000.  Same if I try
     dir()

A: Found the error: file path malfunction.


text:
Q: Different durations for CSS properties in jQuery animate() I'm using jQuery to animate DOM element on the page and I hit an obstacle when using its native animate().
I'm trying to move my element to the right and change its opacity.
$element.animate({
    'left': '50%',
    'opacity': '1.0'
}, 1000);

It works very well, but I need to animate position in 1000ms and opacity in 300ms.
I found out that I can't write it like this:
$element.animate({
    'left': '50%'
}, 1000);

$element.animate({
    'opacity': '1.0'
}, 300);

This will result in queued animation, because it is the same element and jQuery apparently needs to wait for the first animation to finish. Or I'm doing something wrong here.
I tried using second argument notation (based on http://api.jquery.com/animate) and using queue: false but it didn't work. I must say I don't understand it thoroughly, so any corrections are welcome.
So my question is this – how to independently change duration interval for these CSS properties?

A: I think you were on the right track when trying to use queue. Here's an example of how this should be working, I hope it helps :
$('#element').animate({ left:'50%' }, { queue: false, duration: 1000 })
             .animate({ opacity : '1.0' }, { queue : false, duration: 300 });

Edit: Successfully Tested :)

A: Could you animate both in one call for 300 ms. up to 3/10 of the position change, and then animate the remainder of the position change for another 700ms?


text:
Q: bash script for replace text from two file in one I have two file xml; en.xml and it.xml
in the default file language en.xml I have this structure
<string key="City is not set">

 City is not set

in the file It.xml I have:
<string key="Città non è impostato">

In that way I can extract data from it.xml and put in to en.xml ?
from en.xml I need to get string key
<string key="City is not set">

in the second file it.xml I need to change:
<string key="Città non è impostato">

in to :

 Città non è impostato

my goal is to obtain a final result:
<string key="City is not set">

 Città non è impostato

I hope is clear.

A: I use this to parse my xml:
get_data () {
local tag=$1
local xml=$2

# Find tag in the xml, convert tabs to spaces, remove leading spaces, remove the tag.
grep $tag $xml | \
    tr '\011' '\040' | \
    sed -e 's/^[ ]*//' \
        -e 's/^<.*>\([^<].*\)<.*>$/\1/'
}
get_data \<tag_name\> filename.xml | tee output.txt
cat output.txt

and then add a bunch of extra if else commands relating to input, some prompts and stuff, and you've got yourself a functionable xml parser.
I use this with a curl command to parse xml feeds from newspapers, and my personal favourite rssmaker.
Also, here's the source.
Have fun!


text:
Q: Web Socket or XMPP ? Which is better for mobile application for making chat applications I want to create a chat application. My chat application is properly working as a real time chat at web server using continuous polling and pushing data. But, Polling is not a good solution for mobile application. Since, Our whole chat is already built as HTTP Rest API so, moving to XMPP is a great deal for us.
So,We just came to know about WebSocket. Can anyone suggest me which is better for real time chat in this situation. WebSocket is very fast and we didn't need continuous timer polling from server also.
Do suggest better option if any and thanks :)

A: One creation purpose of XMPP was instant messaging. It had a server on jabber.com, and also having possibility of setting up a server on your own due to its open source nature. But, XMPP is an XML based application protocol which will not allow you to do some specific customizations. Also possibly you will want to use websockets as transport protocol (except handshakes) for your XMPP for real-time messaging.
Since Websocket will make you to write your own app with some effort, you will get strength to design it as you wish.
You can use path decleration of websockets to declare different channels and broadcast incoming data to all connected users. Its up to you.


text:
Q: Why isn't SQLite giving me an error when I try to open a file with the wrong encryption key? I was unable to find any information about this behavior online, so any help will be much appreciated.
When using the following code:
//create file with encryption key "test1"
$tempDB = new \SQLite3("temp.db", SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, "test1");

//attempt to open the same file using key "test2"
$tempDB = new \SQLite3("temp.db", SQLITE3_OPEN_READWRITE, "test2");

var_dump($tempDB->lastErrorCode()); //int(0)  : no error?

Is this the expected behavior? If so, how can I check whether or not a key is correct for a given SQLite3 file?

A: Yeah, I'm an idiot. After skimming through the manual I assumed that encryption was a module that PHP+SQLite ships with or which you can just easily install and use.
Turns out that's not the case. You have to pay USD 2000 in order to use this module. Ugh.
My code was just ignoring the parameter as per this:

An optional encryption key used when encrypting and decrypting an SQLite database. If the SQLite encryption module is not installed, this parameter will have no effect.


text:
Q: Finding $\int _{-\infty }^{\infty }\frac{e^x\,dx}{1\:+\:e^{4x}}$ with residue integration This integral was given as part of an exam in complex analysis. Here we are first asked to take the contour integral of the rectangle below.

This is computed by finding the poles:
$$z\:=\:\frac{1}{4}\left(i\pi \:+\:i2\pi c_1\right),\:c_1\in \mathbb{Z}
$$
Only $iπ/4$ and $i3π/4$ are inside the contour and we proceed to find the solution of the contour integral:
$$\frac{\pi \sqrt{2}}{2}$$
This is fine, however, when asked to compute the real integral (task c) in the linked picture), I struggle to understand how we rigorously can be sure that
$$ \frac{\pi \sqrt{2}}{4}$$
is the correct answer. This leads to my question:
Q. Could I reach the same result by instead using the "standard" semicircle in the upper half-plane, and let the radius $R$ approach infinity. Or is this an integral where I need to choose a different geometric contour to reach the correct answer? If so, how do I proceed to find the correct contour in a similar situation where I am not given the shape beforehand?

I am puzzled because the integral has four poles in the unit circle, but if we instead look at the imaginary axis, it has an infinite number of poles when the radius approaches infinity.

A: The integral along the top horizontal side is
$$\int_M^{-M} \frac{e^{x+\pi i}}{1+e^{4(x+\pi i)}}dx=\int_{-M}^M\frac{e^x}{1+e^{4x}}dx$$
Therefore the result is exactly half of the contour integral.
It won't be easy to do it with the semi-circle contour. For one thing, it will enclose more and more singularities.

A: With the substitution $e^x=t$, $e^xdx=dt$, the integral, considering the integrand is now an even function, becomes:
$$\int_0^\infty \frac{dt}{1+t^4}=\frac{1}{2}\int_{-\infty}^\infty \frac{dx}{1+x^4}\;.$$
Now
$$f(z)\equiv \frac{1}{1+z^4}$$
has four poles, only two of which fall inside the upper semicircle, namely $z_1=e^{πi/4}$ and $z_2=e^{3πi/4}$. Therefore, you only need to evaluate the residues of $f(z)$ at those two poles.
By differentiation you will quickly find that
$$Res(f,z_1)+Res(f,z_2)=\frac{1}{4}\left(\frac{1}{z_1^3}+\frac{1}{z_2^3}\right)\;.$$
The integral on the upper semicircle can be easily shown to approach $0$ as $R\to \infty$, so if you put all the above results together and use the residue theorem you get the expected result of $\frac{π}{2\sqrt{2}}$.
I hope this answers your question.


text:
Q: ElasticSearch: Using output of one query as input to another I have a problem which requires to fetch a doc based on id from elasticsearch and use that to make another query. This works but I am forced to make two round trips to elasticsearch cluster. Can I somehow do this in one query something like query elasticsearch and use its output as an input to another query to avoid the round trip ?
Please let me know if you don't understand the issue.

A: I would like to use this opportunity to advertise different approach to the given problem. In fact, ElasticSearch: The Definitive Guide does pretty good job on its own, I just have to quote it:

Four common techniques are used to manage relational data in
  Elasticsearch:

*

*Application-side joins

*Data denormalization

*Nested objects

*Parent/child relationships

  Often the final solution will require a mixture of a few of these
  techniques.

Data denormalization in practice means that data gets stored in a way that one single query performs the trick that you would do before with 2 consecutive queries.
Here I will unfold the example from the aforementioned book. Suppose you have two following indices, and you wish to find all blog posts written by any person named John:
PUT /my_index/user/1
{
  "name":     "John Smith",
  "email":    "john@smith.com",
  "dob":      "1970/10/24"
}

PUT /my_index/blogpost/2
{
  "title":    "Relationships",
  "body":     "It's complicated...",
  "userID":     1
}

There is no other option but to first fetch the IDs of all Johns in the database. What you could do instead is to move some of the user information on the blogpost object:
PUT /my_index/user/1
{
  "name":     "John Smith",
  "email":    "john@smith.com",
  "dob":      "1970/10/24"
}

PUT /my_index/blogpost/2
{
  "title":    "Relationships",
  "body":     "It's complicated...",
  "user":     {
    "id":       1,
    "name":     "John Smith"
  }
}

Hence enabling search on user.name of the index blogpost.
Apart from traditional ElasticSearch methods you may also consider using third-party plugins like Siren Join:

This join is used to filter one document set based on a second
  document set, hence its name. It is equivalent to the EXISTS()
  operator in SQL.


text:
Q: Simple executable segfaults on launch when linking pthreads Spent all day investigating this bug, and my colleagues are saying it looks like a linker or library bug. I've never had anything like that before, so I am here to document it and ask for help!
My executable segfaults before main is called
Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
(gdb) bt
#0  0x0000000000000000 in ?? ()
#1  0x00007ffff7b47901 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#2  0x00007ffff7b47943 in std::locale::locale() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00007ffff7b44724 in std::ios_base::Init::Init() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x0000000000400c1c in __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535)
    at /usr/include/c++/4.8/iostream:74
#5  0x0000000000400c45 in _GLOBAL__sub_I__ZN9CrashTestC2Ev () at crash_test.cc:8
#6  0x0000000000400c9d in __libc_csu_init ()
#7  0x00007ffff7512e55 in __libc_start_main (main=0x400bea <main()>, argc=1, argv=0x7fffffffdca8,
    init=0x400c50 <__libc_csu_init>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fffffffdc98)
    at libc-start.c:246
#8  0x0000000000400ad9 in _start ()
(gdb)

The resulting crash seems similar to this question which leads to this bug report, but my code is different and very sensitive to changes. I narrowed down the issue to 5 requirements:

*

*Have an class implemented in a shared library.

*Declare an instance of that class in another, immediately following  a std::string member declaration.

*Include iostream

*Link with pthreads

*Use g++-4.8 (or 4.9) and the gold linker
That's it. Change or omit any requirement, and the segfault does not occur.
I've created a minimal test case. Here is the executable header
// crash_test.h
#pragma once
#include <string>
#include "crash.h"

class CrashTest {
  CrashTest();  // must have a constructor

  std::string first_;  // must be a string declared before Crash object
  Crash crash_;  // must be a value, not pointer
};

And the main function is empty. I don't even construct the class I defined!
#include "crash_test.h"
#include <iostream>  // required

CrashTest::CrashTest() { }  // must be here, not header

int main() {
  return 0;
}

The Crash class can't get much simpler
// crash.h
#pragma once
struct Crash {
  Crash();
};

But it does require an implementation to create a shared library.
#include "crash.h"
Crash::Crash() {}  // must be here, not header

I've also tested this in a Docker container on a fresh install of Ubuntu 14.04, with g++-4.8 installed via apt-get.
Here is the build script.
#! /bin/sh
COMPILE="/usr/bin/x86_64-linux-gnu-g++-4.8 -Wall -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-missing-field-initializers -Werror -std=c++11 -O0 -g "

# Segfault only occurs using the gold linker.
LINKER="-fuse-ld=gold"

# Compile a shared library and then an executable.
# If the latter is linked with pthread, it segfaults when run.
# If the shared library is removed, there is no segfault.
$COMPILE -fPIC -o crash.o -c crash.cc \
&& $COMPILE -o crash_test.o -c crash_test.cc \
&& $COMPILE -fPIC $LINKER -shared -Wl,-soname,libcrash.so -o libcrash.so crash.o -Wl,-rpath=. \
&& $COMPILE $LINKER crash_test.o -o crash_test -rdynamic libcrash.so -pthread -Wl,-rpath=. \
&& echo "Compiled and linked..." \
&& ./crash_test \
&& echo "Did not crash!"

I've put all the code in a github repo: crash_test
Advice appreciated!

A: It seems you're running into the problem described in this gold ticket.  Based on the comments to that ticket, the following workaround solved the problem for me: Change your linker command line to include the parameter -Wl,--no-as-needed.  For your build script, that would be:
$COMPILE -fPIC -o crash.o -c crash.cc \
&& $COMPILE -o crash_test.o -c crash_test.cc \
&& $COMPILE -fPIC $LINKER -shared -Wl,-soname,libcrash.so \
   -o libcrash.so crash.o -Wl,-rpath=. \
&& $COMPILE $LINKER crash_test.o -o crash_test \
   -rdynamic libcrash.so -pthread -Wl,-rpath=. -Wl,--no-as-needed

But as I said, that's just a workaround, and I'm not sure if that is an acceptable solution for you.  If you need a proper solution, you should probably revive that ticket and post your findings there.


text:
Q: function name with on+Verb in UI5 I noticed in UI5 there are a lot of functions named with on+verb.
for example:
sap.Panel.prototype.onPressButton = function (oEvent) {
   //.....
};

does it imply the function is related to the Event bus. where I could find the reference for this type of function in UI5

A: Its only a convention to distinguish 'event callbacks' function from 'other functions'.
Same as set / get for setters & getters


text:
Q: React useState - State not updating I am trying to change the state of my map. My code is quite simple. But i can't figure out why it's not working.
const [mapCenter, setMapCenter] = useState({ lat: 34.80746, lng: -40.4796 });

 const onCountryChange = async (e) => {
    const countryCode = e.target.value

    const url = countryCode === 'Worldwide' ? 'https://disease.sh/v3/covid-19/all' : `https://disease.sh/v3/covid-19/countries/${countryCode}`

    await fetch(url).then(response => response.json()).then((data) => {
      setCountry(countryCode);
      setCountryInfo(data);

      console.log(data.countryInfo.lat, data.countryInfo.lng)

      setMapCenter([data.countryInfo.lat, data.countryInfo.lng]);
      setMapZoom(6)
      console.log(mapCenter, mapZoom)
    })
  }

In my onCountryChange function, I am calling data from an API and setting the data in the UI, which is working fine, but the setMapCenter data fails to update. When I log the response I get from the API, I get the correct response in the console, but when I log the state of mapCenter, it still returns the initial state... what am I doing wrong please?


text:
Q: How to find the url where login credentials are send to? Using PHP/cURL I'm trying to login to www.teliatv.dk with my credentials and return some json from a file on the domain, while keeping the session alive by storing the session cookie in a txt file.
<?php
// Login to www.teliatv.dk
$username = "xxxxxxx";
$password = "xxxxxxxx";
$file = dirname(__FILE__) . "cookie.txt";

$ch = curl_init("http://www.teliatv.dk/");
curl_setopt($ch, CURLOPT_COOKIEFILE, $file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $file);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
echo curl_exec ($ch);
curl_close($ch);

// Display content of cookie.txt
echo file_get_contents($file);

// Retrieve json content
$ch = curl_init("https://www.teliatv.dk/rest/secure/livechannels/2087/decryptionticket_postasget?deviceType=WEB&callback=jQuery161003904806077480316_1421055449439&_=1421055849886");
curl_setopt($ch, CURLOPT_COOKIEFILE, $file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $file);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
echo curl_exec ($ch);
curl_close($ch);
?>

However, my script doesn't seem to be able to login to the site in the first place.
The action attribute in the login form on the site is empty and the HTTPheader doesn't reveal a URL when submitting the form.
Apparently the site uses Embedded JavaScript (EJS) so generate the HTML content of the site (which I'm unfamiliar with). I don't know if somehow this is the reason why I'm unable to find the URL where username and password is sent?
I hope somebody's able to help me out.

A: Looks like you're sending a GET request. Login stuff use POST requests most of the time.
You may also have a look at the answer from the server after your first request: it may contain an message or an error that could help you.
Good luck!


text:
Q: C# Getting the src from a iframe html tag? Basically I have a string which the user creates and it may or may not have a iframe link for youtube in. Since this is a client application it doesn't use html tags and I have a special form that shows things like youtube videos. However, I need to get the src from the tag and replace all the data around it with nothing.
It may also have multiple links so this needs to be something like regex to do it globally..
Example:
User string:

What I want to be outputted:
I want the users to just see: http://www.youtube-nocookie.com/embed/4FhG-UYRHJ0 then I can handle the rest.
Any help is much appreciated as I have no idea how to even start with this. Thankyou all.

A: you can also use this
string iframe = "";

            Match matchdec = Regex.Match(iframe, @"\ssrc='\b(\S*)\b", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
            if (matchdec.Success)
            {
                if (matchdec.Groups.Count > 1)
                {
                    string retval = matchdec.Groups[1].Value;
                }
            }

for all match you can use:-
string iframe = "";
                iframe += "";

                Match matchdec = Regex.Match(iframe, @"\ssrc='\b(\S*)\b", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
                while (matchdec.Success)
                {
                    if (matchdec.Groups.Count > 1)
                    {
                        string retval = matchdec.Groups[1].Value;
                    }
                    matchdec = matchdec.NextMatch();
                }

To Replace add this line
iframe = Regex.Replace(iframe, retval, "yournewurl");

Hope this helps.

A: Here is a regular expression to get you started:
(?<=src=')[^']+

Note: May be some edge cases that aren't accounted for. I'll leave that as an exercise for the OP :)

A: you can use bellow code;
var source = Regex.Match(iframeStr, "", RegexOptions.IgnoreCase).Groups[1].Value;


text:
Q: Tensorflow - Getting a shape error on feed_dict() even though the shape appears to be ok from sklearn.datasets import fetch_california_housing
import numpy as np
from sklearn.preprocessing import StandardScaler

n_epochs = 1000
learning_rate = 0.01

housing = fetch_california_housing()

# m is length of dataset, n is # of atts
m, n = housing.data.shape

# Scale Data with StandardScalar()
scaler = StandardScaler()
scaled_housing_data = scaler.fit_transform(housing.data)

# m is length of dataset, n is # of atts
m, n = housing.data.shape

batch_size = 100
num_batches = int(np.ceil(m/batch_size))

# Just appends a a column of '1.'s to beginnging of table
scaled_housing_data_plus_bias = np.c_[np.ones((m, 1)), scaled_housing_data]

X = tf.placeholder(tf.float32, shape=(None, n+1), name="X")
y = tf.placeholder(tf.float32, shape=(None, 1), name="y")
theta = tf.Variable(tf.random_uniform([n+1, 1], -1, 1), name="theta")

# Formulas for preducing predictions and error metrics
y_pred = tf.matmul(X, theta)
error = y_pred - y
mse = tf.reduce_mean(tf.square(error), name="mse")

# gradients = 2/m * tf.matmul(tf.transpose(X), error)
gradients = tf.gradients(mse, [theta])[0]       # Calculate gradients with built in function for efficiency

# Operation that adjusts theta values based on gradients & learning rate
# training_op = theta.assign(theta - learning_rate * gradients)
# optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=0.9)
training_op = optimizer.minimize(mse)

def fetch_batch(epoch, batch_index, batch_size):
    np.random.seed(epoch * num_batches + batch_index)
    indices = np.random.randint(m, size=batch_size)
    X_batch = scaled_housing_data_plus_bias[indices]
    y_batch = housing.target.reshape(-1, 1)[indices]

    return X_batch, y_batch

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for epoch in range(n_epochs):
        print("Epoch: " + str(epoch))

        for batch_index in range(num_batches):
            X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size)
            print(X_batch.shape)
            print(y_batch.shape)
            sess.run(training_op, feed_dict={X: X_batch, y: y_batch})
            if epoch % 100 == 0:
                print("Mean Squared Error: " + str(mse.eval()))

    print(theta.eval())

Output: Epoch: 0, (100, 9), (100, 1)
Error Message:
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'y' with dtype float and shape [?,1]
     [[Node: y = Placeholder[dtype=DT_FLOAT, shape=[?,1], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

(I get something similar for 'X' as well)
Thanks in advance for any suggestions or help!!!

A: I figured it out. Attempting to evaluate 'mse' caused an error with the placeholder values.
# Correct Code
with tf.Session() as sess:
    sess.run(init)
    best_theta = None
    best_mse = None
        for epoch in range(n_epochs):

        for batch_index in range(num_batches):
            X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size)
            _, best_mse = sess.run([training_op,mse], feed_dict={X: X_batch, y: y_batch})

        if epoch % 100 == 0:
            print("Epoch: " + str(epoch))
            print("MSE " + str(best_mse))

     print(theta.eval())


text:
Q: Driver for RTL-8139 required for Enter E-100E Ethernet Card - Can't compile source file I purchased an Enter E-100E Ethernet Card (http://www.entermultimedia.com/pci_ethernet_10_100_lancard.html) today..
I found that ubuntu can't detect the device. So, I checked out the device driver documentation, which said :

This document contains instructions on installing Linux driver and adjusting speed for the series of RTL8139(A/B/C/8130) Network Adapter Installing Driver:
(1.) Kernel Had Supported Driver: Check the directory " /lib/modules/¡K./net " if you could find "rtl8139.o" Your kernel had supported RTL8139 series. You could easy use "linuxconf" to setup your card. If you don't like linuxconf, you also could use "modprobe rtl8139" and "ifconfig up eth0" to load module. If your driver load properly, your "/etc/conf.modules" should include line of "alias eth0 rtl8139".
(2.) Kernel Don't Support Driver: If your kernel doesn't support RTL8139 series, you should compiler driver by yourself. Please contact "www.scyld.com/network/rtl8139.html" to get source code. The compiler command is located on the end of source code. Maybe like "gcc -DMODULE -Wall -Wstrict-prototypes -O6 -c rtl8139.c". If you couldn't compiler success, maybe you should refer to error message and copy library or head file to Linux.

Now, (1) didn't work for me, as I did not find the said directory (after replacing the ¡K with linux-headers-3.0.8-19).
So, I tried to do (2)..
But, the website is down.. So, I got the source file, rtl8139.c from some site online.. However, when I tried to compile it with the included command, the compiler showed an error that the /usr/src/linux (or library, as the case may be) directory didn't exist..
However, I noticed from this site that the Realtek RTL8139 driver is quite famous.. So, I was wondering, am i missing something? Plese Help.. I'm at an dead end..
I'm new to linux and Ubuntu.. So, can someone please tell me what to do... Thanks for taking the time to read this..

A: Recent Linux kernels support Real-Tek RTL8139 based cards using the 8139too module.
The 8139too module is base on the code by Donald Becker you linked.
Do
modprobe 8139too

or
insmod /<path to module>/8139too.ko

and then use ifconfig as per your posting.


text:
Q: How to do a proper LEFT OUTER JOIN in N1QL I have created an index in order to perform the following left outer join in N1ql:
CREATE INDEX idx_test ON bucket("User::" || userId) WHERE docType="Order";

SELECT u.*, ARRAY_AGG(o) as orders
FROM bucket AS u
LEFT OUTER JOIN bucket AS o ON KEY "User::" || o.userId FOR u
WHERE u.docType="User"
AND o.docType="Order"
GROUP BY u;

This works fine when I have orders for that particular user. The problem is when I don't have any orders, then I get no results at all.
I have noticed that if I remove the AND o.docType="Order" statement from the query I get some results, but what happens if there are documents that also have a userId property? How can I get this to work correctly?

A: @a_horse_with_no_name is essentially correct. Use IS MISSING instead of IS NULL:
AND (o.docType="Order" OR o.docType IS MISSING)


text:
Q: Local notification, applicationIconBadgeNumber remains when app is in foreground When app is in foreground, even if I set the applicationBadgeNumber to 0, when I quit the app, there's still a "1" badge on my app, even whem I kill it, any ideas? When I open the notification when the app is in background, no problem at all!
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
    {
        NSLog(@"%i", notification.applicationIconBadgeNumber); // Return 1
        notification.applicationIconBadgeNumber = 0;
        NSLog(@"%i", notification.applicationIconBadgeNumber); // Return 0

        UIApplicationState state = [application applicationState];

        if (state == UIApplicationStateInactive)
        {
            // Application was in the background when notification
            // was delivered.
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"An item is asking your attention" message:nil delegate:nil
                                  cancelButtonTitle:@"Cancel" otherButtonTitles:@"Show me", nil];
            [alert show];
        }
    }

A: In my app, clicking on the icon acknowledges any outstanding notifications. So when I close the app, it always resets the application icon badge number. In the app delegate, add a method to reset the badge number in the applicationWillResignActive method, like so:
- (void) applicationWillResignActive:(UIApplication *)application
{
    [application setApplicationIconBadgeNumber:0];
}

A: Where are you setting the applicationBadgeNumber?  I think you are setting the notification badge number.
Try this:
 application.applicationIconBadgeNumber = 0;


text:
Q: Any function that can add rownames and colnames into excel file? I am using write.xlsx function from "xlsx" package.
for (i in 1:noctry) {
    for (l in 1:3) {
        write.xlsx(tab110rev[i,,], file=paste(title[l],l,".xlsx"), sheetName = country_code[i],
           col.names=FALSE, row.names=FALSE, append=TRUE)
    }
}

noctry stands for number of countries and its 53
countrylist is a list of countries with country codes which are numbers.
tab110rev is an array that has the structure of array(value, c(country, industry, year))
The result is each sheet by each country, rows representing ISIC code, columns representing years.
I want to add column names and row names to the excel file, but as you can see, "col.names" and "row.names" option is a logical.
Is there any option or function I can add a row name and column when writing an xlsx file?
I can add the name by loading the xlsx file I have just wrote and add row name and column name and save it back but I just want to know if there is a function that can write xlsx and add row names and column names at the same time.
I have tried the following code and the rownames just appear as numbers and colnames and X1, X2, X3...
for (i in 1:noctry) {
for (l in 1:3) {
rownames(tab110rev[i,l,,]) <- c(isic_code)
colnames(tab110rev[i,l,,]) <- c(year)
write.xlsx(tab110rev[i,l,,], file=paste(title[l],l,".xlsx"), sheetName = country_code[i],
           col.names=TRUE, row.names=TRUE, append=TRUE)
}
}

A: Simply define the row names and column names as strings and use col.names=TRUE and row.names=TRUE:
library(WriteXLS)
x = as.data.frame(replicate(2, rnorm(2))
colnames(x) = c("test", "test1")
rownames(x) = c("test", "test1")

WriteXLS(x, ExcelFileName="temp.xls", col.names=TRUE, row.names=TRUE)


text:
Q: Clientside Caching C# My wpf client is loading a lot of standing data at startup from the server. So, I want to implement a caching strategy at client side.
I know about the new System.Runtime.Caching namespace in the .NET framework 4. Unfortunately, there is only a memory caching. I don't want to load the huge amount of data at each startup of the client. So I'm searching for a persistent client caching.
What do you think about it?
Another idea was I use an OODB (like db4o or VelocityDB) for client caching. Is this a bad idea? I haven't any experience in client caching.
Thanks for your answers and suggestions.
Kind regards, pro

A: How you store the data on the client side doesn't matter very much. I'd look into IsolatedStorage for your purposes, though. What might be more difficult is to tell when the cache turns stale. This is actually what System.Runtime.Caching is good at. Does the server data change at all, or only after a new release of the application? If the data changes only after a new release, you might want to include it as resources into the application setup. If not, you'd have to have some timeout or signal which tells the client that it is time to check for changed data on the server. Have you already considered lazy loading of the data? That way, the delay would probably not occur all at application startup and would be less noticable, and probably you wouldn't even have to load the complete data into the client.
Regarding Timeouts: in our application, we have a fixed timeout which is set to each reference list when it is first loaded, and every time it is requested from the cache, that timeout is checked. If it has expired, the cache is transparently refreshed before the list is returned. This is a tradeoff, because the data on the client side could be stale for some time. We accept this, because it isn't critical in our case, and that way every list is responsible for itself and we don't need a central registry keeping track of each list's state in order to set the timeout from outside.


text:
Q: как покрасить ввод? Как покрасить input в python? (при помощи colorama либо termcolor)
print краситься отлично
from colorama import Fore, Back, Style, init
init()

print(Fore.RED + 'test')

но если провернуть такое с input он не покрасится
from colorama import Fore, Back, Style, init
init()

input(Fore.RED + 'test')

Заранее спасибо

A: print(Fore.RED + 'test')
input()


text:
Q: Cannot drop a table because of foreign keys I've been trying to fix this problem for hours now and I have no idea what causes it. I'm trying to drop tables in MSSQL Server (I need to start from scratch) and whenever I'm using the statement
DROP TABLE dbo.Manages;

I get this message:

Could not drop object 'dbo.Manages' because it is referenced by a
  FOREIGN KEY constraint.

Problem is, I have three tables left and all of them contain foreign keys(they're linked with eachother). It turned out that I can't delete either and I'm stuck. I tried dropping foreign keys first, but
ALTER TABLE dbo.Manages DROP FOREIGN KEY Mgr_start_date;

wouldn't work. I know there's also a way to write it like this:
ALTER TABLE dbo.Manages
DROP FOREIGN KEY fk_(...)

Yet when I created the foreign keys, I didn't use fk_, I just simply stated
ALTER TABLE dbo.Department
    ADD FOREIGN KEY (Mgr_start_date)
    REFERENCES dbo.Manages(Mgr_start_date);

Any help would be highly appreciated. I'm fairly new to SQL, but I really want to make this work. I tried some solutions from this forum like using FOREIGN_KEY_CHECKS = 0 and then setting it to 1, but it wouldn't work either.

A: You can use the GUI to delete the foreign keys.
In Management studio on the table folders you find your foreign keys in the Key folder.
Or use EXEC sp_fkeys 'Your Table' to find the names of your foreign keys.

A: Actually, I think I finally succeeded. I right-clicked on my specific database and chose 'design', then found the names of the foreign keys in drop down menu under properties. That way I was able to find the names of foreign keys that the program has set, and drop them normally. Works just fine, database was cleaned up. Thank you very much for your suggestions!


text:
Q: Testing nodejs with mocha and supertest. How to get the app? I am trying to test a nodejs app with supertest, and I cannot get a single route to run.  I've narrowed the problem down.  In my test file, I start with this:
var app = express();  // this is the problem, this isn't really the app, right?

// testing this dummy works fine, but I want the real one
app.get('/user', function(req, res){
  res.status(200).json({ name: 'tobi' });
});

describe('GET /user', function(){
  it('respond with json', function(done){
    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  })
})

...and this test passes.  But of course, that dummy /user route is not the one I want to test.  I want to test routes defined in my "real" app, defined at ./server.js.
Even if I simply move the dummy app.get('/user', function... definition to my "real" server.js file, the one that I launch with nodemon, this simple test fails with a 404.
So what does this line really do: var app = express();, and how do I get hold of the app configured in my server.js file so I can test it?

A: You need to export your app from server.js. Once you do this, you can require the app in your test files.
server.js
var express = require('express')

var app = express();

// Your routes here...

// At end of file
module.exports = app;

test.js (in a test directory)
var api = require('../server.js'),
    request = require('supertest')(api);

describe('noshers', function() {

    it('doesn\'t allow GET requests', function(done) {
        request
            .get('/foo')
            .expect(405, done);
    });

});


text:
Q: Problem with file iris_dri.so I need help, delete the file iris_dri.so because I confused it and now certain programs are much slower than usual. What I can do?
It should be clarified, I have Ubuntu 20.04

A: That library appears to be part of the libgl1-mesa-dri package, so you will need to re-install it to ensure you have all of your files.
You can do so from the Terminal like this:
sudo apt --reinstall install libgl1-mesa-dri

Try to be a bit more careful with the rm command, as there is not always a simple fix


text:
Q: getstatuscode is not working with phantomJS I am testing a web app with loads and loads of web pages and I would like to verify that none of the URLs are broken on every commit. Here is a code snippet.
$page = $this->getSession()->getPage();
$page_URLs = $page->findAll('css', 'header nav ul a');
assertEquals(16, count($page_URLs));

foreach($page_URLs as $pageUrl){
    try{
        $pageUrl->click();
        $statusCode = $this->getSession()->getStatusCode();
        echo $pageUrl->getText();
        assertEquals(200, $statusCode, "The webpage is not available");
        } catch (Exception $ex) {
        echo 'Caught exception: ',  $ex->getMessage(), "\n";
        }
        $this->getSession()->back();
}

I was using the Behat, MINK with Goutte driver (as a headless browser) for CI integration (and getStatusCode() was working fine). But most of the functionality on the web app is java script driven therefore I have to move on to PhantomJS which support javascript. But I didn't realise that getStatusCode() doesn't work with PhantomJS.
Has anyone got any idea if I can replace this with something and get the similar result.

A: PhantomJS support in Behat is realised via the WebDriver protocol (selenium). WebDriver doesn't support inspecting status codes on purpose, as it falls out of scope of emulating user actions.


text:
Q: Recursion without overun I've been looking for real world examples of recursion. Remember, programming Wizards, I'm and artist and in Photoshop scripting (scriptus modus operandi) it's normally used to loop over all layers and sub layers.
I'm working on a (simple) recursion script to solve a four digit combination lock. You know, start with 1, then try 2, then 3 etc until the solution is found. To make things easy in the example the second digit is correct so we know that we don't have to change that. Also the initial state the numbers start zero, but we know there are no zeroes in the final solution.

*

*The attempt must match the solution AND also add up to 10 in order to
be solved.

This may seem a bit stoppid, but I want to put in a two part condition of the solution, mainly because I can then apply what I've learned and write a brute force suduko solver. But you must crawl before you can ice skate...
var puzzle = [0,2,0,0]; // source
var solution = [1,2,3,4];
var s = superCopy(puzzle); // working array

drawPuzzle(s);
solvePuzzle(s, puzzle);

var total = checkTotal(s, solution);
var solution = checkSolution(s, solution);

function checkTotal(arr, source)
{
  var c = 0;

  // count the total
  for (var i = 0; i < arr.length; i++)
  {
    c += arr[i];
  }
  if (c == 10)
  {
    alert("Total OK")
    return true;
  }
}

function checkSolution(arr, source)
{
  // check the solution
  for (var i in arr)
  {
    if (arr[i] != source[i]) return false
    return true;
  }
}

function solvePuzzle(arr, source)
{
  for (var i = 0; i < arr.length; i++)
  {
    // check the source
    var sourceCell = source[i];
    //alert("checking source " + sourceCell)
    //if it's a zero we can change it
    if (arr[i] == 0)
    {
      cell = arr[i];

      cell+=1;
      if (cell > 4) cell = 0;
      arr[i] = cell;
    }
  }

  // check the solution
  for (var i in arr)
  {
    // overflow time!
    if (arr[i] != source[i]) solvePuzzle(arr, source)
    else
    {
      alert("All done!")
    }
  }
}

function drawPuzzle(arr)
{
  var p = "";
  var c = 0;
  for (var i = 0; i < arr.length; i++)
  {
    if (arr[i] == 0) p += "-"
    else p += arr[i];
  c+=1;
  }
  alert(p);
}

function superCopy(arr)
{
  // returns a true copy of an array
  tempArr = new Array();
  for (var i = 0; i < arr.length; i++)
  {
    if (arr[i] == 0) tempArr[i] = 1 // changed, thanks Nostradamnit!
    else tempArr[i] = arr[i]
  }
  return tempArr
}

The script is incomplete. This what I have so far, it falls over with an overflow error. Note solvePuzzle and checkTotal functions are not called because I realised that solvePuzzle needs to call itself and work out the solution...which is when I ran into overflow problems and got a bit confused.
I realise that this type of question runs dangerously close to a "fix my code" venture, so I'm prepared to put a bounty out for it. Thanks.

A: There are a couple of problems with your code. First up, your checkSolution function stops at the very first number that matches. You probably want it to check every number before returning true, so you should move return true outside the for loop. It only gets there if all numbers match up.
Another flaw is the superCopy function, which as Nostradamnit pointed out has a flawed condition.
Your next problem is in solvePuzzle, where you have this:
if (arr[i] == 0)
{
  cell = arr[i];

  cell+=1;
  if (cell > 4) cell = 0;
  arr[i] = cell;
}

The thing is, because arr[i] is 0 and you only add 1, cell will never be 4. So your if is never going to fire. This is where your infinite loop is: it only increments values that are zero with one, so after all zeros became one, it never goes further and you keep checking if "1111" is the solution.
Now the overflow: you shouldn't be calling solvePuzzle for every cell, this grows exponentially:
for (var i in arr)
{
  // overflow time!
  if (arr[i] != source[i]) solvePuzzle(arr, source)
  else
  {
    alert("All done!")
  }
}

Also, you never check the result again, so the looping never ends. You would probably want to change this to this:
if(checkTotal(arr) && checkSolution(arr, source))
{
  alert("All done!");
  return;
}
solvePuzzle(arr, source);

As a side note (not a bug causing thing): your checkTotal function isn't using the source parameter, so you can probably leave that out. Also, there is a rogue variable called cell in solvePuzzle, which isn't a big deal in this case, but it would be better to put var in front of it so it doesn't become global. Also, there is a sourceCell variable that never gets used.

A: At first glance, it seems that your superCopy function is flawed. You create an empty array, then compare its 0 index (which doesn't exist) to the input array. Is that where you are getting your "overflow"?

A: The problem seems to be that you call solvePuzzle(arr, source) multiple times in the same iteration:
  for (var i in arr)
  {
    // overflow time!
    if (arr[i] != source[i]) solvePuzzle(arr, source)
    else
    {
      alert("All done!")
    }
  }

So you iterate over every item in the array, and if it is not equal to the source item, you call solvePuzzle again. But if you have several items that don't match, solvePuzzle will get called multiple times on the same array. And for each call, it gets called again multiple times. Therefore your function calls grow exponentially and result finally in a stack overflow.
What you probably intended to do, is the following:
  var areArraysEqual = true;
  for (var i in arr)
  {
    if (arr[i] != source[i]) {
        areArraysEqual = false;
        break;
    }
  }

  if (areArraysEqual) {
      alert("All done!");
  } else {
      solvePuzzle(arr, source);
  }

A: I haven't looked over your solution yet, but i did write a recursive one for myself to solve the problem. Perhaps it can be of help as a guideline?
var solution = [1,2,3,4];

function checkSolution(arr) {
  return solution.every(function(item, index){ return item === arr[index]; });
}

function increment(arr) {
  for (var i=0; arr[i] === 9; i++) {
    arr[i] = 0;
  }
  arr[i]++;
  return arr;
}

function solvePuzzle(arr) {
  if (isNaN(arr[arr.length-1])) {
      return null;
  }
  if (checkSolution(arr)) {
    return arr;
  }

  return solvePuzzle(increment(arr));
}

var solution = solvePuzzle([1,1,1,1]);
console.log(solution); // [1,2,3,4]

A: Maybe little bit off topic but I have created the easiest recursion example possible in my opinion.
http://jsfiddle.net/33yfS/
var str = "9785";
function rec(a, b)
{
    var c=0;
    if(b==-1)
        return "";
       if(a!=str.charAt(b))
           return rec(a+1, b);
        else
        {
            return rec(0,b-1)+""+a;
        }
}
var ans = rec(0,str.length-1)


text:
Q: Alert if input is empty I have a form that I would like all fields to be filled in. If a field is not filled out, I would like to display a red background of the field and an message.
    \$('#id_form').blur(function()
    {
        if( $(this).val().length == 0 ) {
            $(this).parents('p').addClass('warning');
        }

print $q->start_form (-method => 'post', -action => "add.pl", -id => 'id_form');
print $q->legend({-class => "ui-widget-header ui-corner-all"},"");
print $q->input ({-id => 'name', -name => 'name',-type => 'text' , -size => 20, -style => ' margin-left:300 px' },"<br>");

I am not sure this is the right way!

A: You have to bind your element to the DOM. You can use the $(document).ready(), or use jQuery's anonymous function like this:
$(function () {
    $('#id_form').blur(function () {
        if ($(this).val().length == 0) {
            $(this).parents('p').addClass('warning');
        };
    });
});

A: try this http://jsfiddle.net/tYhpw/
$('#id_form input').on('blur', function () {
    if( $(this).val() == '' ) {
        $(this).css('border','1px solid #f00');
    }else{
        $(this).css('border','1px solid #000');
    }
});

A: I used this Jquery function with a button to check if all fields had been filled in:
    function check(){

    var ok = 1;

    $('input').each(function(){

    if($(this).val().length == 0){
        ok = 0; $(this).css('background-color','red');
        alert("Error message");
    }

    else{ $(this).css('background-color',''); }
});

if(ok != 1){ alert("Error message"); }

else{ $('#form').submit(); }

}

Maybe this helps?


text:
Q: Could Gödel's incompleteness theorems be false? I'm fascinated by Gödel's incompleteness theorems for a while now. The fact that a mathematical system can't be proven to be consistent or complete is amazing. But can that be false?
Could we construct/discover a mathematical system that is both complete and consistent and prove that within the same system? And in that system to prove that the current one that we are using (the Zermelo Fraenkel set theory or whatever)  is inconsistent. And the inconsistent part of our current system to be the very proof of Gödel's theorems?
Can the following statement (or its proof) "No system can be proven consistent within itself" be the actual inconsistency in our system used today?
This is just a thought experiment that i need other opinions on.
Thanks!

A: Turning my comments into an answer:

First off, it's important to state the incompleteness theorem carefully (to be precise, I'm giving Rosser's improvement of Gödel's first incompleteness theorem):

There is no first-order theory $T$ which is computably axiomatizable, consistent, complete, and interprets Robinson arithmetic.

Of particular note are the phrases "computably axiomatizable" and "interprets Robinson arithmetic." These are technical terms which I won't define here, but I will very briefly motivate them:

*

*Computable axiomatizability is basically a "simplicity" condition, demanding that the theory in question not be so complicated that we can't even write down a set of axioms for it in a reasonable way.

*The interpretability criterion is a "strength" condition. Our theory needs to be able to implement basic arithmetical calculations.
Basically, both too complicated theories (such as the set of all true sentences about $(\mathbb{N};+,\times)$) and too weak theories (such as Presburger arithmetic) are beyond the scope of applicability of the incompleteness theorem.
This isn't really related to your specific question, but I think being careful about what the theorem actually says will demystify it substantially.

OK, now on to the actual question.
There are two ways a theorem (including Gödel's) can be wrong: either the argument used is faulty, or the axioms used are not all correct. Here for simplicity I'm adopting a "naive Platonist" position, that there is a "true mathematics" out there even if we don't know what it is.
There isn't much to say about the first possibility; the incompleteness theorem's proof has been checked ad nauseam, including implemented on computers, and additional proofs have been discovered as well (see e.g. here). The interesting issue is the second possibility. Because of the rhetoric around the incompleteness theorem, it's quite reasonable to assume that some rather subtle axioms must be at work in its proof (note that I'm speaking of the axioms used in the proof of the incompleteness theorem itself, not the axioms of a system it applies to). This, however, is false: in fact extremely little is needed to run the proof! In order to doubt the incompleteness theorem, we have to be skeptical of rather basic principles of arithmetic itself - specifically, a very weak form of proof by induction. The logical structure of the proof of the incompleteness theorem is quite subtle, but the basic assumptions that argument begins with are just simple properties of arithmetic which we use all the time.


text:
Q: Change a html element from a separate file I am trying to acheive having 2 open html files open and be able to manipulate on with the other.
not sure where to start. I am attempting to create a cricket scoreboard layout and have the first html file which will be displayed on an electronic scoreboard while a game is being played and want to be able to have buttons in another file which will be used on another computer or tablet to change the wickets and runs.
Any guidance would be appreciated.

A: Flow
Having a webserver to handle this would be ideal but if that is not the case.

*

*You may need a database to store the score which can be accessed by both the pages. While one page would write/update the score other page (scoreboard) would primarily be fetching the data to show it. Check this to find how to access and updpate sqlite. Is it possible to access an SQLite database from JavaScript?

you can access SQLite database with client-side JavaScript by using
  SQL.js.

*

*For the scoreboard page, access data from sqlite db and auto-refresh so that the latest scores are shown. Add below html tag to refresh every 5 seconds.

<meta http-equiv="refresh" content="5" >


text:
Q: Scroll speed slows down after a long period This has seemed to happen after I updated from Ubuntu 18.10 to 19.04, so I am not sure if it is because of the update or not.
But the issue that I am having, is that if I leave my computer running for a few days the scroll speed when scrolling the mouse wheel in all my applications (Chrome, Spotify, vscode, Nautilus, etc.) drastically decreases until I restart my computer then the scroll speed works as it did before.

A:
Looks like the answer is to power off the mouse and turn it back on instead of the computer.

You are my hero for the day and I can't believe that actually worked. I guess the old "have you tried turning it off and back on" still applies.