text:
Q: UNIX: running processes in a loop with fork() and dup2() ends loop early I am beginning to code a shell in UNIX to practice with API calls such as fork() dup2(), read(), and wait(). Currently, my shell opens and runs fine. When I type a command to run, such as ls -a, it parses this command properly, and executes it. The problem is, the main loop terminates early, exiting the shell after a single command. I need the loop to continue to run until 'exit' is read from stdin. Here is my current code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <unistd.h>
static const char prompt[] = "myshell> ";
static const char sep[] = " \t\n\r";
int main()
{
    int ac; // arg count
    char *av[10]; //argument vector
    int tty = open("/dev/tty", O_RDWR); // open tty for read/write
    int pid; // process id
    int status; // child process exit status
    int w;
    void (*istat)(int), (*qstat)(int);

    if (tty == -1)
    {
        fprintf(stderr, "can't open /dev/tty\n");
        exit(EXIT_FAILURE);
    }
    while (1)
    {
        char *arg, line[256]; // buffer to hold line of input
        int i;
        // prompt and read
        write(tty, prompt, sizeof(prompt) - 1);
        i = read(tty, line, sizeof(line));
        if (i <= 0)
            break;
        line[i] = '\0';
        // tokenize the line into av[]
        ac = 0;
        for (arg = strtok(line, sep); arg && ac < 10; arg = strtok(NULL, sep))
            av[ac++] = arg;

        if (ac > 0 && strcmp(av[0], "exit") == 0)
            break;

        if ((pid = fork()) == 0)
        {
            // this is the forked child process that is a copy of the running program
            dup2(tty, 0); // stdin from tty
            dup2(tty, 1); // stdout to tty
            dup2(tty, 2); // stderr to tty
            close(tty);
            // last argument must be NULL for execvp()
            av[ac] = NULL;
            // execute program av[0] with arguments av[0]... replacing this program
            execvp(av[0], av);
            fprintf(stderr, "can't execute %s\n", av[0]);
            exit(EXIT_FAILURE);
        }
        close(tty);
        // disable interrupt (^C and kill -TERM) and kill -QUIT
        istat = signal(SIGINT, SIG_IGN);
        qstat = signal(SIGQUIT, SIG_IGN);
        // wait until forked child process terminated, get its exit status
        while ((w = wait(&status)) != pid && w != -1)
            continue;
        if (w == -1)
            status = -1;

    }

    // restore interrupt and quit signals
    signal(SIGINT, istat);
    signal(SIGQUIT, qstat);
    exit(EXIT_SUCCESS);
}

I tried moving these lines right above exit success (so they're outside of the loop and inside main)
    close(tty);
    // disable interrupt (^C and kill -TERM) and kill -QUIT
    istat = signal(SIGINT, SIG_IGN);
    qstat = signal(SIGQUIT, SIG_IGN);
    // wait until forked child process terminated, get its exit status
    while ((w = wait(&status)) != pid && w != -1)
        continue;
    if (w == -1)
        status = -1;

}

// restore interrupt and quit signals
    signal(SIGINT, istat);
    signal(SIGQUIT, qstat);
    exit(EXIT_SUCCESS);
}

What this did is loop the shell properly, but printed the prompt over top the last line of the output from the executed command, because the program wasn't waiting for the child process to end before printing the prompt and waiting for input. I tried moving some of the lines around, but every time it just ends up terminating the shell after one command is executed

A: You do not want to call close(tty) within your main loop. Doing so causes your next read(tty,... to fail, exiting the shell.
Additionally, if you really want to disable SIGQUIT/SIGQUIT, you should symmetrically restore them within the loop.

A: the following posted code:

*

*skips the handling of the signals, you may want to add that back in.

*cleanly compiles

*properly checks for and documents any errors

*performs the desired functionality, except for the disabling of certain signals

*continues to execute the loop until the user enters 'exit'

and now, the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

// added next statement for 'wait()' and 'waitpid()'
#include <sys/types.h>

#include <sys/wait.h>
#include <unistd.h>
//#include <signal.h>
#include <unistd.h>

static const char prompt[] = "myshell> ";
static const char sep[] = " \t\n\r";

int main( void )
{
    int ac; // arg count
    char *av[10]; //argument vector

    pid_t pid; // process id
    int status; // child process exit status

    int tty = open("/dev/tty", O_RDWR); // open tty for read/write
    if (tty == -1)
    {
        perror( "open for /dev/tty failed");
        exit(EXIT_FAILURE);
    }

    while (1)
    {
        char *arg;
        char line[256]; // buffer to hold line of input

        // prompt and read
        write(tty, prompt, sizeof(prompt) - 1);
        ssize_t i = read(tty, line, sizeof(line));

        if (i == 0)
            break;

        if (i < 0)
        {
            perror( "read failed" );
            exit( EXIT_FAILURE );
        }

        line[i] = '\0';

        // tokenize the line into av[]
        ac = 0;
        for (arg = strtok(line, sep); arg && ac < 10; arg = strtok(NULL, sep))
            av[ac++] = arg;

        // last argument must be NULL for execvp()
        av[ac] = NULL

        if (ac > 0 && strcmp( av[0], "exit" ) == 0)
            break;

        pid = fork();
        switch( pid )
        {
        case -1:
            perror( "fork failed" );
            exit( EXIT_FAILURE );
            break;

        case 0:  // child process
            // this is the forked child process that is a copy of the running program
            dup2(tty, 0); // stdin from tty
            dup2(tty, 1); // stdout to tty
            dup2(tty, 2); // stderr to tty
            close(tty);
            ;

            // execute program av[0] with arguments av[0]... replacing this program
            execvp(av[0], av);
            perror( "execvp failed" );
            exit(EXIT_FAILURE);
            break;

        default: // parent process
            // wait until forked child process terminated, get its exit status
            waitpid( pid, &status, 0 );
            break;
        }
    }

    return 0;
}


text:
Q: Resetting an Angular Reactive Form without triggering error rendering? In this demo the login form username field renders in red after login is clicked, even though the form is reset like this:
  submit() {
    if (this.form.valid) {
      this.onLogin.emit(this.form.value);
      this.form.reset();
      this.form.markAsPristine();
      this.form.markAsUntouched();
      this.form.setErrors(null);
    }
  }

How do we keep the username field from painting red?

A: You have to add the required validator to your form in order to check the validation otherwise it will always return true for this.form.valid. It should be as follows :
 form: FormGroup = new FormGroup({
    username: new FormControl('',[Validators.required]),
    password: new FormControl('',[Validators.required]),
  });

Note : be sure you imported Validators from @angular/forms
import { Validators } from '@angular/forms';

and the error message should not be send from parent element because your are checking for errors when submitting the form so the submit() method should be as follows :
submit() {
if (this.form.valid && this.form.touched) {
    this.error = ''
    this.submitEM.emit(this.form.value);
}else{
    this.error = 'Username or password invalid'
}

}
Note : remove Input decorator for error message because the validation check is done in child component.
error: string | null;

Click here for demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# WPF How to Pass an object of an observable collection from the property of the object thank you for reading my question.
Situation:
I have an observable collection
CheckableTags = new ObservableCollection<CheckableListItem<Item>>();

The wrapper class CheckableListItem<Item> adds a bool per object Item.
public class CheckableListItem<T> : INotifyPropertyChanged
{
    private bool mIsChecked;
    private T mItem;

    public event PropertyChangedEventHandler PropertyChanged;

    public CheckableListItem(T item)
    {
        mItem = item;
    }

    public bool IsChecked
    {
        get
        {
            return mIsChecked;
        }
        set
        {
            mIsChecked = value;
            OnPropertyChanged("IsChecked");
            MeasConSettings.Current.CheckableTags_CheckedChanged("ENTIRE OBJECT HERE");
        }
    }

    public T Item
    {
        get
        {
            return mItem;
        }
        set
        {
            mItem = value;
            OnPropertyChanged("Item");
        }
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

When the user checks the checkbox, the bool variable is changed, this is why I fire the function MeasConSettings.Current.CheckableTags_CheckedChanged("ENTIRE OBJECT HERE"); in the property of the bool variable.
The function is as following:
public void CheckableTags_CheckedChanged(object sender)
{}

My question is:
How can I send the entire object from the property of the bool to the function in my viewmodel, what should I send in the field "ENTIRE OBJECT HERE" in order to receive an object of CheckableListItem class with 2 elements the bool variable and the Item.
If possible get a reference to the object so I can copy it in the receiving function.
Alternatives:
If this is not possible, what else can I do?
Thanks in advance.

A: You can send the entire object using this keyword:
MeasConSettings.Current.CheckableTags_CheckedChanged(this);

Also you can change your method and class to use generics and accept a typed generic parameter like:
public void CheckableTags_CheckedChanged(CheckableListItem<T> sender)
{}


text:
Q: Javascript strange behavior in function (constructor) return types Assume we have two functions like the followings :
function a(){ this.x = 5; return {z:20};}
function b(){ this.x = 5; return 30;}

now if you run these lines everything seems to be reasonable:
a(); //output : {z:20}
b(); //output : 30;

but if you run them as object constructor :
new a() //output : Object {z:20}
new b() //output : b {x:5}

I don't understand if the new constructor should always return an object, why is the behavior different? Does JavaScript watch the return type? If the return type is an object so returns it directly and if not it returns the initiated instance?
I think if it is a constructor, so it should ignore the return type always and returs the initiated object. I think this behavior makes JavaScript too complex. Is there something else here that I don't get?

A:
I don't understand if the new constructor should always return an object, why is the behavior different? Does JavaScript watch the return type? If the return type is an object so returns it directly and if not it returns the initiated instance?

Basically yes. If the return value of the function is not an object, the new operator returns this (the new object) instead (actually it's the internal [[Construct]] method which does that).

I think if it is a constructor, so it should ignore the return type always and returs the initiated object. I think this behavior makes JavaScript too complex. Is there something else here that I don't get?

That's really more a subjective opinion. The advantage is that the constructor can decide to return a different value, which makes it more flexible. On the other side I'd argue that it's more common to not return a value than the other way round.


text:
Q: How does Python referencing work? I am confused with Python referencing. Consider the following example:
My task : To edit each element in the list
d = { 'm': [1,2,3] }
m = d['m']
m = m[1:]   # m changes its reference to the new sliced list, edits m but not d (I wanted to change d)

Similarly:
d = { 'm': [1,2,3] }
m = d['m']
m = m[0]    # As per python referencing, m should be pointing to d['m'] and should have edited d

In python everything goes by reference, then when is a new object created?
Do we always need copy and deepcopy from copy module to make object copies?
Please clarify.

A: Ethan Furman did an excellent job of explaining how Python internals work, I won't repeat it.
Since m really does represent the list inside the dictionary, you can modify it. You just can't reassign it to something new, which is what happens when you use = to equate it to a new slice.
To slice off the first element of the list for example:
>>> m[0:1] = []
>>> d
{'m': [2, 3]}

A:
In python everything goes by reference

In Python, everything is a reference, and the references get passed around by value.
If you want to use those terms. But those terms make things harder to understand.
Much simpler: in Python, a variable is a name for an object. = is used to change what object a name refers to. The left-hand side can refer to part of an existing object, in which case the whole object is changed by replacing that part. This is because the object, in turn, doesn't really contain its parts, but instead contains more names, which can be caused to start referring to different things.

then when is a new object created ?

Objects are created when they are created (by using the class constructor, or in the case of built-in types that have a literal representation, by typing out a literal). I don't understand how this is relevant to the rest of your question.
m = m[1:]   # m changes its reference to the new sliced list

Yes, of course. Now m refers to the result of evaluating m[1:].
edits m but not d (I wanted to change d)

Yes, of course. Why would it change d? It wasn't some kind of magic, it was simply the result of evaluating d['m']. Exactly the same thing happens on both lines.
Let's look at a simpler example.
m = 1
m = 2

Does this cause 1 to become 2? No, of course not. Integers are immutable. But the same thing is happening: m is caused to name one thing, and then to name another thing.
Or, another way: if "references" were to work the way you expect, then the line m = m[1:] would be recursive. You're expecting it to mean "anywhere that you see m, treat it as if it meant m[1:]". Well, in that case, m[1:] would actually mean m[1:][1:], which would then mean m[1:][1:][1:], etc.

A: In Python a variable is not a box that holds things, it is a name that points to an object.  In your code:

*

*d = { 'm': [1,2,3] }  --> binds the name d to a dictionary

*m = d['m'] --> binds the name m to a list

*m = m[1:] --> binds the name m to another list

Your third line is not changing m itself, but what m is pointing to.
To edit the elements in the list what you can do is:
m = d['m']
for i, item in enumerate(m):
    result = do_something_with(item)
    m[i] = result


text:
Q: Do slow detectives lose points? As the city is so well designed, I would like to wander around a little bit, discover the monuments, etc...
The issue is that the story goes from one case to another, without a break, whereas, in GTA:IV, you had to go to a given spot to start a new mission.
So the question is simple: in a middle of a case, will I get a penalty for doing something else for days or will I be marked as a detective taking days and days to go from crime scene to suspect's house? Will the final appreciation of the case (in term of number of stars) be affected by this behavior?
I perhaps have to wait to finish the game to be able to do the side missions and tourism...?

A: You can just wander around forever between objectives. Or, after you complete each station, you unlock them for freeplay, where you can just wander around and find all the collectables.

A: L.A. Noire doesn't seem to invite sightseeing trips. Because you're doing important police work, it doesn't feel right to stop the car and look around or even to drive slowly (or even to obey the traffic signs!).
The following discussion sheds some light on this aspect of the game. I'm copying it in case of link rot.

Bearing in mind that I've only played L. A. Noire for a few hours, I'm
  getting a strange feeling from its city. As we all know, L.A. is a
  "driving city", but it feels as though all the driving you do in the
  game serves to somehow negate the city around you. In some ways, I
  guess, this feels like the real L.A.: epic drives in which you just
  want to get where you're going. For a game with attention lavished on
  a virtual environment, though, it just feels off.
The major reason for the awkwardness of the virtual L.A. is that, so
  far, the structure of the game has revolved relentlessly around cases.
  Specifically, you're always in the middle of investigating something,
  and that means driving from place to place. Because you're doing
  important police work, it doesn't make sense (or, to me, feel right)
  to stop the car and look around or even to drive slowly (or even to
  obey the traffic signs!). What dawdling there is in the game is
  reserved for very local environments in which the pace of the game,
  quite pleasingly, slows to a crawl and you find yourself scouring an
  alleyway for clues.
In this setup, L. A. Noire reminds me of the original Police Quest. In
  that game driving was extremely functional – irrelevant locations in
  space barely existed. If you pulled over to somewhere that wasn't a
  part of the narrative, you'd just see a generic parking lot or
  suburban street. Move along. L. A. Noire has the same impatience with
  the majority of its city, except that in this case the "irrelevant"
  parts are lovingly modeled and detailed.
As such, this ostensibly beautiful city is generally just whipping
  past my windshield as I drive on and on, listening to my monotonous
  partner's directions for where to go. Technically I could stop and
  experience the sublimity of the general environment, but I don't. It
  would be rude and unprofessional and, frankly, kind of boring.
  Although the city is there, it's also not there: it's irrelevant. This
  doesn't have to be the case, either: consider how consistently ripe
  with meaning Fallout 3's wasteland manages to be.
In a way, it might be that L. A. Noire falls "victim" to its devotedly
  cinematic style: you're always trying to get to the next scene in both
  a crime-busting and a movie-making sense. The rest of it is all chaff
  in the wind. Which is actually pretty ironic. Consider that in
  watching a movie you're transported from scene to scene without the
  intervening space being required, just in some sense implied. Because
  it doesn't contribute to the story it's literally not there. In video
  games, of course, in this age of large scale virtual environments, the
  intervening space generally has to be there – game design simply
  demands it. Thus, in this extreme cinematic mode of play, we have the
  worst of both worlds: the intervening space is both irrelevant and
  frustratingly present.
In fact, as I've played, I've found myself wishing more and more that
  the rest of the city wasn't there. As I walk toward my virtual car
  with my partner I pause for a moment, and then I say:
"You drive."

A: With a couple of obvious exceptions you can take as long as you like to go from one case point to the next, it is even encouraged that you detour to do things like street crimes.  You will not be penalized in any way for taking too long to get to the next objective (unless the story states it).
However you do lose points for causing accidents and damaging property, as this is more likely the longer you drive around it will have an impact on your case.  This is why at the end of each desk you can open free roam and go mop up street crimes, go site seeing etc.  This way there is no chance of it impacting the case you are in.  It is one per desk as street crimes are locked to a certain desk and open during a certain case, but stay open from then on as long as you in the right time slot.


text:
Q: Run a custom script extension from Visual Studio ARM Template I have a project in Visual Studio for my ARM templates. One of the templates is for a VM and I am deploying a Custom Script Extension for the VM as well.
The script is in a .ps1 file that is part of the project (in the projects, I have a scripts folder). The whole project, including the script is under TFS for versioning.
How do I point the template to use the .ps1 file in my VS Project?
At the moment, I am simply uploading the file to a storage and pointing the template there, i.e:
           "settings": {
          "fileUris": [ "https://mystorageaccount.blob.core.windows.net/scripts/myPowerShelScriptFile.ps1" ],
          "commandToExecute": "[variables('commandToExecute')]"
        },

Thanks!

A: Well, according to this, you just need to do:
powershell "powershell.exe . . . -File './myPowerShelScriptFile.ps1'"

edit: arm templates don't work like that, you don't upload a file, you upload a template and that file get's downloaded only by the resource that is actually working with the file.


text:
Q: How to implement Miracast in my android app I am trying to find details on how to implement screencasting via Miracast in my application.  The only details I can find are part of the AllshareCast SDK from Samsung, which is not the same standard as (although very similar to) Miracast.
Can someone please point me in the direction of how I could achieve a simple in application Miracast button (like the YouTube app for example)?
EDIT:  Improved question:
How can I share the application display to and external monitor or projector using wireless protocol such as Miracast.
Thanks;
Andy

A: If you are asking "how do I arrange to show something different on an external display, like one connected via Miracast, than what is shown on the device's own screen", you will want to use the Presentation class, along with either DisplayManager or MediaRouter.


text:
Q: Accessing Text File in a different Directory My File Structure
-Final_CS_Project (Root Folder)
    -UserCredentials.txt
-src
    -main
        -java
            -com
                -aking
                    -java
                       -Create.java

How can I access the text file? My current code does not work.
Scanner fileScanner = new Scanner(new File("UserCredentials.txt"));

This error pops up:
java.io.FileNotFoundException: UserCredentials.txt (The system cannot find the file specified)


text:
Q: Ajax update content in yii I have an issue with the ajax, which doesn't update the content which is saved. The data are saving fine in the database. It only shows when I refresh the page.
The code for echo the comments
<?php
echo '

Comments

';
$commentList = Comments::model()->findAllByAttributes(array('offereventid'=>$id));
foreach($commentList as $Listdata2)
{
    $usercomment = $Listdata2['comment'];
    $usercommentid = $Listdata2['id'];
    $usercomtname = $Listdata2['name'];
    $usercommentmail = $Listdata2['email'];
    echo '
';
    echo '
'.$usercomtname.': '.''.'['.$usercommentmail.']'.''.'
';
    echo '
'.'"'.$usercomment.'"'.'
';
    if (Yii::app()->user->id!='' && Yii::app()->user->id!=1){
        if(Yii::app()->user->email==$usercommentmail){
           echo CHtml::ajaxButton('Delete',CHtml::normalizeUrl(array('Comments/del/id/'.$usercommentid,'render'=>true)),
                array(
                  'dataType'=>'json',
                  'type'=>'post',
                  'success'=>'function(data){
                     alert("Are You Sure?");
                     $("#name_"+data).hide();
                   }',
                ),array('id'=>$usercommentid,'class'=>'btn btn-danger'));

          }
      }
     echo '

';

}
?>

here you can see I  used ajax delete button which works fine.
Below the code is used to save the comment into the database
<?php
    echo CHtml::ajaxSubmitButton('Save',CHtml::normalizeUrl(array('Comments/create','render'=>true)),
        array(
            'dataType'=>'json',
            'type'=>'post',
            'success'=>'function(data){
                $("#AjaxLoader").hide();
                if(data.status == "success"){
                  $("#formResult").html("Comment Submitted");
                  $("#formResult").css({"color":"red"});
                  $("#comments-form")[0].reset();
                 }else{
                   $.each(data, function(key, val){
                   $("#comments-form #"+key+"_em_").text(val);
                   $("#comments-form #"+key+"_em_").show();
             });
                }
            }',
            'beforeSend'=>'function(){
            $("#AjaxLoader").show();
            }'
            ),array('id'=>'submit'.uniqid(),'class'=>'btn btn-success'));

?>

And the actioncreate is
public function actionCreate()
{
    $model=new Comments;

    // Uncomment the following line if AJAX validation is needed
    $this->performAjaxValidation($model);

    if(isset($_POST['Comments']))
    {
        $model->attributes=$_POST['Comments'];
        // echo '
';print_r($model->attributes);die();
        $valid = $model->validate();

        if($valid){
            if($model->save()){
            echo CJSON::encode(array(
                'status'=>'success'
                ));
        }
        }else{
            $error =CActiveForm::validate($model);
            if($error != '[]')
                echo $error;
            Yii::app()->end();
        }
    }
    // $this->render('create',array(
    //  'model'=>$model,
    // ));
}


text:
Q: Einstein Trailhead - Impossible to find the Assisted Setup It's been about one hour and a half that I tried, with three different account made for the trailhead, and nothing's working for me ;
I am at this step of this trailhead (one of the first steps !!)

It really is impossible for me to find in the Setup  the 'Assisted Setup' button...
It's part of this :
Assign Permission Sets
Great, you're all set with your brand-new special org. Before you can set up Einstein Lead Scoring, you must give yourself and your sales rep access to Sales Cloud Einstein.

From Setup, enter Permission Sets in the Quick Find box, then select Permission Sets.
Click the Sales Cloud Einstein Permission Set.
Click Manage Assignments to assign the permission set to users.
Click Add Assignments.
Select the checkbox next to Pepper, Belle and your name, then click Assign.
Click Done.

If you know what I'm doing wrong, thanks a lot for your help, I'm desperate.
Nb : tried those steps ... Nothing for me.
EDIT 19 July, 10:18 :
Yes, it's an account made using the specific trailhead form, and I've add permission set :

EDIT 19 JULY 11:14 :
My first issue is solved (don't know how tho)
But now, can't find why my process builder is not working.
Did the steps rigorously 3 times. Trailhead sometimes really is a time killing
-_-


text:
Q: How do you reference a file on an external drive on a mac from a script command? If this is what I want in PC land
 F:\new\home\dir
What is the equivalent on a Mac?  I just see the external drive called untitled.  What is its path for a script command please?

A: The mount points are under /Volumes. This includes the startup disk, which is a link back to /. Therefore if the removable disk shows up in Finder as "Untitled", you'll probably find it at
/Volumes/Untitled

Here's what the contents of my /Volumes looks like when I have an unnamed flash drive connected.
$ ls -la /Volumes
total 40
drwxr-xr-x@  6 root       wheel   204 27 Mar 23:34 .
drwxr-xr-x  41 root       wheel  1462 22 Mar 22:17 ..
drwxrwxrwx@  1 grgarside  staff  8192 22 Aug  2016 Untitled
lrwxr-xr-x   1 root       wheel     1 21 Mar 14:17 Mac SSD -> /
drwxrwxrwx   0 root       wheel     0 27 Mar 23:34 MobileBackups


text:
Q: Getting a string representation of a template parameter I want to be able to create a method in a templated class that returns the name of the type subsituted in the template parameter.
eg:
template <typename T>
class CPropertyValueT
{
  std::string GetTypeName()
  {
    return #T;
  }
}

This is possible with a preprocessor macro using #, I figured there must be a way with templates.
Is this possible?

A: You can use typeid(T).name(), though it will return decorated name of the type.
If you're using GCC, then you can use GCC API, declared incxxabi.h header, to demangle the names.
Here is an example (source):
#include <exception>
#include <iostream>
#include <cxxabi.h>

struct empty { };

template <typename T, int N>
  struct bar { };

int main()
{
  int     status;
  char   *realname;

  // exception classes not in <stdexcept>, thrown by the implementation
  // instead of the user
  std::bad_exception  e;
  realname = abi::__cxa_demangle(e.what(), 0, 0, &status);
  std::cout << e.what() << "\t=> " << realname << "\t: " << status << '\n';
  free(realname);

  // typeid
  bar<empty,17>          u;
  const std::type_info  &ti = typeid(u);

  realname = abi::__cxa_demangle(ti.name(), 0, 0, &status);
  std::cout << ti.name() << "\t=> " << realname << "\t: " << status << '\n';
  free(realname);

  return 0;
}

Output:
  St13bad_exception       => std::bad_exception   : 0
  3barI5emptyLi17EE       => bar<empty, 17>       : 0

Another interesting link that describe demangling in GCC and Microsoft VC++:

*

*C++ Name Mangling/Demangling


text:
Q: I have installed nodejs on windows how should i use it in WSL? I am having problem using libraries installed on windows to WSL and vice versa. I don't want to install not just nodejs but other things twice just to use it in WSL and also in normal text editors like VS code, atom, etc.

A: The complete instruction can be found here set-up-on-wsl
If you are too busy to follow the link, follow these steps in the WSL:

*

*Use curl to install nvm

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

*For installing NodeJs (lts)

nvm install node --lts

*You can also install specific node version. Check all commands uses by typing nvm in your terminal.

*Done Node has been successfully installed in your WSL,  nvm ls will list all the installations.

You can use the Node installed in your WSL for developing. Point to your working directory and use code . to open VSCode. Also, if you want to access your windows directories you can mount them by using /mnt/<dir>
If you face any issues during installation it is better to use the link I have provided above.
Also note that, the Node installed in the WSL can only be used, iff your working directory is in the WSL or is linked with your WSL(by using mnt).


text:
Q: Suspending a PC I'm fairly new to C#, I am trying to write my own UWP app to suspend the PC after a user entered interval.
I have managed to get my timer working but I am struggling to understand how to call the method to suspend the computer. I tried using the code suggested here
Application.SetSuspendState(PowerState.Suspend, true, true);

But I get the following error when I try to build the project:

CS0117    'Application' does not contain a definition for 'SetSuspendState'   SystemTimer C:\Users\xxxxx\Source\Workspaces\Workspace\SystemTimer\SystemTimer\MainPage.xaml.cs 52

I found an MSDN entry on PowerState which suggest I use the System.Windows.Form library. I tried adding it to the namespaces but get an error saying that Form is not an available namespace in System.Windows.
I feel I am probably missing something fundamental but I am not entirely sure what it is.

A:
I feel I am probably missing something fundamental but I am not entirely what it is.

The world of (UWP) apps is a different world. An app is not supposed to interfere (i.e. to mess around) with its underlying system. You basically run in a sandboxed environment and you only get what is provided by the API. Shutting down or suspending the system is not part of this API.
What options do you have? You probably are better off if you create a desktop app. Then you will be able to use all the available desktop APIs including System.Windows.Form.

A: Have you tried implementing this using Interop Services?
[DllImport("Powrprof.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern bool SetSuspendState(bool hiberate, bool forceCritical, bool disableWakeEvent);

// Hibernate
SetSuspendState(true, true, true);
// Standby
SetSuspendState(false, true, true);


text:
Q: PHP structure of a comment database At the moment I create a blog system with php. The admin can create x posts, and under every post should be a comment function. How can I realize something like that?  I dont know the structure of the databse, because it must be many tables (for each post(?)). Maybe someone of you have a good link. I searched already but have found nothing for my problem.

A: You don't need many tables. You could have a table for the posts like this:
id       INT(10)
title    TEXT
content  TEXT

And a table for the comments, like this:
id       INT(10)
postId   INT(10) // this links to the column post.id
content  TEXT

Of course, you can add more columns to both tables if necessary, for example to add timestamps, etc.
Now, when you have a post with id 7, you make sure that all the comments to that post get postId 7. That way, when you display post 7 on your website, you can search for all the rows in the comment table with postId=7, and display exactly those comments that are linked to that post.
I've simplified this example. To optimise the tables you could add indices, primary keys, etc.

A: @Skeptar, there quite a number of ways you can achieve this. Let me suggest one to you.
Users table: (very obvious)
Columns: user_id (INTEGER(n) PRIMARY KEY), username (VARCHAR(n)), password (VARCHAR(32) for md5), level (INTEGER Example: 1 for admin, 3 for regular user)

Posts:
Columns: post_id (INTEGER(n) PRIMARY KEY), post_title (VARCHAR(n)), post (TEXT), user_id (INTEGER(n))

Comments:
Columns: comment_id (INTEGER(n)), comment(TEXT), post_id,(INTEGER FOREIGN KEY REFERENCES post(post_ID)) user_id(INTEGER(n) FOREIGN KEY REFERENCES users(user_id))

Now, I believe you have a means of allowing both levels (admin and regular) of users to register into your system.
When inserting, you take the post title and the actual post and with the help of some user identification mechanism like SESSIONS, you get the user_id and insert them into to post table.
Then for each comment, when inserting, you fetch the post_id of the post on which the user is commenting and insert that into the comment table along with the comment and the user_id.
When you want to fetch all posts, that's fairly easy.
When you want to fetch all comments for a particular post, you take the post_id of that post to the comments table as such:
SELECT * FROM comments C, posts P WHERE C.post_id = C.post_id;

Since you inserted the user_id against each post and comment, similarly, you can fetch the corresponding user information for each comment as such:
SELECT U.username FROM comments C, users U Where C.user_id = U.user_id

Remember, this is only to give you and idea and not to be taken as a complete working solution. I wrote this off head and could have some errors.
Also, where I indicated in bracket n (INTEGER(n)), it means you need to replace n with the desired columns size. Hope it helps.


text:
Q: HIde load more button when all items are from array displayed in react This should be easy but of course I can't figure it out :)
Basically I've implemented a "load more" button when there are more items to display from array but when it reaches the end, I'd like to hide it. The code below doesn't work and I have a feeling it's because it need to check the index of the array and if it's at the end, then hide the button but I am unsure of how to go about the syntax. Thanks
import { useState } from 'react'
import releases from "../data/releases.json";
import styled from 'styled-components';
import { Link } from 'react-router-dom';
import '../main.css'

const Release = () => {
  // get first 12 items in array & load next 12 with "see more button"
  const STEP = 12;
  const [items, setItems] = useState(releases.slice(0, STEP));

  const loadMore = () => {
    setItems([...items, ...releases.slice(items.length, items.length + STEP)]);
  };

  return (
    <Wrapper>

        {items.map((item, i) => (

            <Link to={`/release/${item.id}`}>

            </Link>

        ))}
{/* code that isn't working here */}
        {items ? <button onClick={loadMore} className="btn" > show more </button> : <button className="btn hidden" ></button>}

    </Wrapper >
  )
}

A: when the items are less  than 12 the button will not be displayed
 {items%12 ===0 ? <button onClick={loadMore} className="btn" > show more </button> : nul}


text:
Q: Listen to DTMF tones during Sip/VoIP or regular calls i've read some articles about DTMF in Android. I guess that it's not possible to make an automatic phone call streaming a .wav file (or other format) and detect the input of the other person (receiver of the call).
I'm want to make an app that calls me/or someone else and is waiting for input to do some action.
Is this scenario possible with VoIP in Android? Any ideas?
Thx

A: You could use a cloud based telephony service like Tropo and Prophecy to achieve this requirement.  These services allow you to make outbound calls and listen for either DTMF or voice input.  They also stream .wav file for the person on the phone to listen to.  You can trigger these calls from any application by just making an HTTP request to the services API, so it could be an Android app that initiates the call.  This solution is independent of the phone device (any mobile, VoIP phone, or land line) and it works on VoIP as well as PSTN.


text:
Q: Ecto - how to get `has_many` with specific query I have an ecto model with has_many association. I want to define this association with some query by default.
Like
defmodule MyApp.User do
  use MyApp.Web, :model

  schema "users" do
    has_many :comments, MyApp.Comment
  end
end

I want to fetch comments which aren't deleted (deleted is a boolean field of MyApp.Comment schema, it should be equal to false). What is the way to achieve that?
My try #1
I tried to do
has_many :comments, Ecto.Query.from(c in MyApp.Comment, where: v.deleted == false)

But I got
(ArgumentError) association queryable must be a schema or {source, schema}, got: #Ecto.Query

A: Provided that you have Post and Comment models, you can find the non-deleted comments with the help of Ecto.Query and then Ecto.Repo.
query = from c in Comment,
        where c.deleted == false,
        select: c

comments = MyApp.Repo.all(query) # This will give you all the non-deleted comments

Also, You may want the following query in you application.
alias MyApp.{Post,Comment}

query = from p in Post,
        join: c in assoc(p, :comments),
        where: c.deleted == false,
        select: {p, c} # for comments only - just select: c.

Blog.Repo.all(query)


text:
Q: Git Bash for Windows showing/expecting file paths with forward-slashes, no drive colon I installed Git Extensions which automatically downloaded and installed Git for Windows, and when I use Git Bash, it shows the file path as /c/whatever/folder rather than C:\whatever\folder, and if I paste in a path from Windows Explorer, it chokes on it because it's expecting forward-slashes and no colon after the drive letter.
When I installed Git for Windows by itself previously, it showed the slashes/colon properly, but was much more limiting and harder to use (especially with copy/paste).
Why is it showing/expecting file paths with slashes and no colon, and how do I fix it?!
http://imgur.com/vMc7fU6

A: You could also try adding single quotes in the directory path copied from Windows Explorer and pasted in the Terminal prompt (e.g. cd 'D:\Documents\Developer Tools & Docs'). It worked for me. Check out the solution posted in the following link:
Escaping backslash in windows paths passed to unix programs

A: It's getting tripped up because the \ is an escape character in the Unix/Linux world.  If the path you paste is like c:\\somefolder\\anotherfolder, it would be ok, because \\ says "I want a literal \.  That said, my git bash understands a single \ as long as the path does not end with it.  So cd c:\folder works, but cd c:\folder\ does not work.
BTW what error message is it giving you when it chokes, and can you give an example of a pasted path it chokes on.

A: This is caused by the Git Bash (Ming) shell, not because of anything git itself is doing.
If you run the mount command inside this shell, you will find that /c/ is the folder where your hard drive is mounted. If you want Git Bash to use a different folder name for your hard disk, you can map your disk to a different folder.
By the way, you shouldn't have to care about this when using git. Repos typically don't (and typically shouldn't) contain files in the root directory of a volume. Even if they did, git references files relative to the repository root. Since any folder that is the root level of a volume will also be the root level of any repo it's in, it will be called / in git, regardless of how the underlying operating system or shell labels it.
For your convenience, here is the output of mount from inside Git Bash on my laptop. You should get similar results. You can see that it indicates that C:\ is mounted on the /c folder.
chris@caerdydd MINGW64 ~
$ mount
C:/Program Files/Git on / type ntfs (binary,noacl,auto)
C:/Program Files/Git/usr/bin on /bin type ntfs (binary,noacl,auto)
C:/Users/chris/AppData/Local/Temp on /tmp type ntfs (binary,noacl,posix=0,usertemp)
C: on /c type ntfs (binary,noacl,posix=0,user,noumount,auto)


text:
Q: Date Increment Issue -> irb
>> (Date.today +3).to_s
=> "2009-10-22"
>> (Date.today + 3).to_s
=> "2009-10-25"

between "+3" and "+ 3", there is a difference?

A: "+3" with no space means positive 3, which gets passed to the today method as an argument, while "+ 3" means plus three, so the return value of the today method gets added to 3.
In case you're curious, the optional parameter to the today method "specifies the Day of Calendar Reform", for conversions to other date formats.

A: I realize this must have been a frustrating bug to discover. When using a language where method invocation has optional parentheses, whitespace is a delicate matter. Consider the following:
square(2+2)*2   # square(4)*2 = 16*2 = 32
square (2+2)*2  # square(4*2) = square(8) = 64

Your case is trickier because the +3 with no space is actually a unary operator.  ! ~ and + unary operators have the highest precedence.
Also interesting the - unary operator has a lower precedence than the exponentiation   operator.   Therefor
-4**2  # -(4**2) = -16

A: It seems to me that the + binds to the 3 in the first case. That is the interpreter sees Date.today(+3). If there's a space after the plus the interpreter instead sees (Date.today) + (3).
Using + to denote positive numbers isn't very common since numbers are positive to begin with, but consider the case of negative numbers: it's easier to see that Date.today -3 means something else than Date.today - 3.


text:
Q: Java Remote API and the (Experimental) Federated Login I've been successfully using the Remote API for Java in a standalone client and some time ago switched my app to use the experimental Federated Login. Now I am getting the can't get appId from remote api; status code = 302 exceptions every time my standalone client connects to the app.
I am looking for a confirmation of whether (or not) the Remote API for Java works with the Federated Login, to know whether the problem is on my side or a current limitation of GAE.

A: After some additional searching it appears that there's indeed an acknowledged problem with the use of Federated Login and Remote API, accepted as the issue 5165 by the App Engine team.


text:
Q: Execute ENTRYPOINT from base image in build stage I'm using a code generator tool which is provided as a Docker image with an ENTRYPOINT. I.e. for the manual use case I execute the following command line:
$ docker run --rm -v ${PWD}:/local some/codegen-image:latest \
    generate  ... parameters for code generator tool ...

So far, so good.
But I want to integrate the code generator image into my own multi-stage image build. I.e. the first stage should call the ENTRYPOINT of the base image to generate the code that will be consumed by the second stage:
# stage 1
FROM some/codegen-image:latest as codegen

... build set up steps for stage 1 ...

# now run ENTRYPOINT from base image, copy & pasted from the output of
#
#  docker inspect -f '{{json .Config.Entrypoint}}' some/codegen-image:latest
#
RUN ["some_command", "option1", ..., "optionN",    \
        "generate",                                \
        ... parameters for code generator tool ... \
    ]

# stage 2
FROM some/other-image as stage2

... build set up steps for stage 2 ...

# copy-in generated code from stage 1
COPY --from=codegen /tmp/build/ .

This works but it violates the DRY principle, i.e. I need to update my Dockerfile every time the upstream project makes an incompatible change to its ENTRYPOINT.
Can I avoid the copy & paste from docker inspect output? My own research has turned up nothing so far...

A: Multi-Stage Dockerfile was introduced to optimize the overall size of the container docs.
The FROM directive just brings the content of the image specified, but you have to explicitly tell the container what command should be executed.
The feature you are expecting is not yet supported by docker.
Eg.
FROM some/codegen-image:latest as codegen
ARGS_ENTRYPOINT_OF_CODEGEN ["generate","parameters"]
.
.
.
FROM some/other-image as stage2
COPY --from=codegen /tmp/build/ .

It seems your approach is correct at this moment and the only way around.


text:
Q: Samsung Internet not working with App Links? Are other browsers/devices also incompatible? In my app when I try to use my app link from Google Chrome it works perfectly, but when I use Samsung Internet I find that the deep links don't work, and the URLs open in the browser instead.
Is there a list of compatible/incompatible internet browsers and/or phones that do not support Android App Links?
Or is there something potentially wrong with my app links implementation?

A: Unlike iOS that pushes hard to the use of Universal Links, Google doesn't do that and therefore any browser on Android can decide if they want to use App Links or not.
Most of the browsers usually blocks the use of App Links so there is a need for URI scheme as a fallback to make sure users will get to your app correctly.

A: I know there is already correct answer for the question. But I had this same issue with Samsung Internet and was able to solve it by enabling
Settings > Internet Settings > Open links in other apps

Hope this tip might help someone who see the question in the future.


text:
Q: Pytest @patch return different values like @parametrize I'm currently writing some tests for my python program and I have a scenario where I need to patch a method but want to run the test multiple times with different return values.
For example. Below is the basic use case. There is a method that is called in the class_to_patch class that makes a call to an external API and for this test case I want to mock the return value (below I have mocked the return value as "x").
@patch(
    "class_to_patch.method_to_patch",
    return_value="x"
    autospec=True,
)
def test_method(mock_method_to_patch):
    val = class_to_patch()
    assert val == 1

Is it possible to be able to run the test multiple times with different return values for method_to_patch, ie if I want to run the test with it returning "x" and then one where it returns "y"?
@pytest.mark.parametrize("param", ["x", "y"])

Something like parametrize but for the return value.
Any help would be greatly appreciated and if I need to provide any further details please let me know.

A: You can assign the return_value (unittest.mock.Mock.return_value) in the test (while using parametrize). Something like:
@pytest.mark.parametrize("param", ["x", "y"])
@patch(
    "class_to_patch.method_to_patch",
    autospec=True,
)
def test_method(mock_method_to_patch, param):
    mock_method_to_patch.return_value = param
    val = class_to_patch()
    assert val == 1


text:
Q: c++ Force implicit conversion on pass as argument I have problem with implicit conversions in C++.
I'm trying to create some Expression template for vector arithmetics (I know that same libraries already exists. I'm just learning C++ so I wanted to try something with templates).
I would like to create class Vector, that is able to compute like this:
simd::test::Vector<char, 5> a;
simd::test::Vector<short, 5> b;

auto ret = a + b + a + b;

, where on output would be Vector of shorts becouse short is bigger type than char.
Right now, I have class that is able to adds vectors of same data types. For different types I have to call explicit conversion:
//simd::test::Vector<short, 5>(a)
auto ret = simd::test::Vector<short, 5>(a) + b + simd::test::Vector<short, 5>(a) + b;

Is possible to implicit convert Vector before pass into function "operator+()"? Here is my code of Vector:
#pragma once

#include <type_traits>

namespace simd {
  namespace test {

  template<typename R, std::size_t Dim,
      typename std::enable_if<std::is_arithmetic<R>::value>::type* = nullptr
  >
  class Vector_expression {
    public:
      static constexpr std::size_t size = Dim;

      virtual const R operator[] (std::size_t index) const = 0;

      virtual ~Vector_expression() = default;

  };

  template<typename T, std::size_t Dim>
  class Vector final : public Vector_expression<T, Dim> {
    private:
      T data[Dim];
    public:
      Vector() = default;

      template<typename R>
      Vector(const Vector_expression<R, Dim> &obj) {
        for(std::size_t index = 0; index < Dim; ++index) {
          data[index] = obj[index];
        }
      }

      template<typename R>
      Vector(Vector_expression<R, Dim> &&obj) {
        for(std::size_t index = 0; index < Dim; ++index) {
          data[index] = obj[index];
        }
      }

      template<typename R>
      Vector<T, Dim> & operator=(const Vector_expression<R, Dim> &obj) {
        for(std::size_t index = 0; index < Dim; ++index) {
          data[index] = obj[index];
        }
        return (*this);
      }

      template<typename R>
      Vector<T, Dim> & operator=(Vector_expression<R, Dim> && obj) {
        for(std::size_t index = 0; index < Dim; ++index) {
          data[index] = obj[index];
        }
        return (*this);
      }

      virtual const T operator[] (std::size_t index) const override {
        return data[index];
      }

      T & operator[] (std::size_t index) {
        return data[index];
      }

      virtual ~Vector() = default;
    };

    template<typename E1, typename E2, typename R, std::size_t Dim>
    class Vector_sum final : public Vector_expression<R, Dim> {
      private:
        const E1 & _lhs;
        const E2 & _rhs;
      public:
        Vector_sum() = delete;

        Vector_sum(const E1 & lhs, const E2 & rhs) :
            _lhs(lhs),
            _rhs(rhs)
        {}

        virtual const R operator[] (std::size_t index) const override {
          return _lhs[index] + _rhs[index];
        }

        virtual ~Vector_sum() = default;
    };

    template<typename R, std::size_t Dim>
    Vector_sum<Vector_expression<R, Dim>, Vector_expression<R, Dim>, R, Dim> operator+ (const Vector_expression<R, Dim> & lhs, const Vector_expression<R, Dim> & rhs) {
      return {lhs, rhs};
    }

  }
}

A: Just define an operator+ that allows different argument types.  The one catch is determining the element type of the resulting sum.  Probably the best option is to use whatever the result of adding two elements is.  One way to write this type is:
decltype(std::declval<const R1>() + std::declval<const R2>())

Or if you know the types are built-in arithmetic types, that would be the same as
std::common_type_t<R1, R2>

Or using a trailing return type, we can take advantage of the function parameters to shorten the std::declval expressions:
template<typename R1, typename R2, std::size_t Dim>
auto operator+ (const Vector_expression<R1, Dim> & lhs,
                const Vector_expression<R2, Dim> & rhs)
-> Vector_sum<Vector_expression<R1, Dim>, Vector_expression<R2, Dim>,
              decltype(lhs[0] + rhs[0]), Dim>
{
  return {lhs, rhs};
}

A: It could be done using templates and std::common_type, something like this:
template<typename T1, typename T2, size_t S>
simd::test::Vector<typename std::common_type<T1, T2>::type, S>
operator+(simd::test::Vector<T1, S> const& v1,
          simd::test::Vector<T2, S> const& v2)
{
    // TODO: Implementation...
}


text:
Q: Panda Index Datetime Switching Months and Days I have a panda df.index in the format below.
It's a string of day/month/year, so the first item is 05Sep2017 etc:

*

*05/09/17  #05Sep2017

*07/09/17  #07Sep2017

*...

*18/10/17  #18Oct2017

Applying
df.index = pd.to_datetime(df.index)

to the above, transforms it to:

*

*2017-05-09 #09May2017

*2017-07-09 #09Jul2017

*...

*2017-10-18 #18Oct2017

What seems to be happening is that the first entries are having the Day and Month switched. The last entry instead, where the day is greater than 12, is converted correctly.
I tried to switch month days by converting the index to a column and applying:
df['date'] = df.index
df['date'].apply(lambda x: dt.datetime.strftime(x, '%Y-%d-%m'))

as well as:
df['date'].apply(lambda x: dt.datetime.strftime(x, '%Y-%m-%d'))

but to no avail.
How can i convert the index to datetime, where all entries are day/month/year please?

A: In pandas is default format of dates YY-MM-DD.
df = df.set_index('date_col')
df.index = pd.to_datetime(df.index)
print (df)
            val
2017-05-09    4
2017-07-09    8
2017-10-18    2

print (df.index)
DatetimeIndex(['2017-05-09', '2017-07-09', '2017-10-18'], dtype='datetime64[ns]', freq=None)

You need strftime, but lost datetimes, because get strings:
df.index = pd.to_datetime(df.index).strftime('%Y-%d-%m')
print (df.index)
Index(['2017-09-05', '2017-09-07', '2017-18-10'], dtype='object')

df.index = pd.to_datetime(df.index).strftime('%d-%b-%Y')
print (df)
             val
09-May-2017    4
09-Jul-2017    8
18-Oct-2017    2


text:
Q: For which $n, k$ is $S_{n,k}$ a basis? Fun algebra problem Here it is a nice algebra problem I had some fun with
Let $V$ be a vector space over $\mathbb R$ of finite dimension $\dim V = n$. Let $v = \{ v_1, \dots, v_n\}$ be a basis for $V$. Let $$S_{n,k} = \{ v_1 + v_2 + \dots + v_k, v_2 + \dots + v_{k+1}, \dots, v_n + v_1 + \dots + v_{k-1}\}$$
For which $n, k$ we have that $S_{n,k}$ is still a basis for $V$?

A: I guess the answer is that they are a basis iff $k$ and $n$ are coprime. Here's one half of the proof.
For the sake of clarity, I'll assume that $V = \mathbb R^n$ and $(v_i)$ is the canonical basis
If $d$ divides both $n$ and $k$, let's $\zeta = \exp(2i\pi/d)$ and $f : \mathbb C^n \to \mathbb C$ the complex linear form defined by $f(x_1, \ldots, x_n) = \sum_{k=1}^n x_i \zeta^i$. Seen as vectors of $\mathbb C^n$, the elements of $S_{k,n}$ all belong to $\ker f$, so the determinant of this system of vectors is 0 and they are not a basis of $\mathbb R^n$. (That's one of the superpowers of the determinant: when you compute the determinant of a system of vectors, the formulas are the same in every field, so even a complex linear relation prevents real vectors to form a basis).
Added later: the other half of the proof.
If $n$ and $k$ are coprime, $k$ has an inverse modulo $n$. So you can find $p > 0$ and $q$ such that $pk = qn + 1$.
Now, let's $V$ be the (real) vector space generate by our vectors. In particular $V$ contains the sum of all the vectors of $S_{n,k}$, which is just $k\cdot(1,1, \ldots, 1)$. So $(1, 1, \ldots, 1) \in V$. Now, add $p$ vectors of $S_{n,k}$: the one beginning with $v_1$, the one beginning with $v_{k+1}$, the one beginning with $v_{2k+1}$ and so on (the indices are to be understood modulo n). Simply put, you take the first vector in $S_{n,k}$, then the one which begins just after the last one stops, and so on. It's just like tiling a floor! (except that the room is something like a 1-dimensional analogue of the world of Snake and that you don't stop when the floor is entirely tiled.)
The sum of this $p$ vectors has all its components equal to $q$, except for one which is $q+1$. So if you take the difference with $q\cdot(1,1, \ldots, 1)$, you get one of the vectors $(v_i)$.
It's now easy to get the other vectors $(v_i)$: either you copy this "tiling" procedure with another first vector or you argue that $V$ is stable under cyclical permutation of the coordinates.
P.S.: actually, it's not to hard to use this tiling procedure to prove the necessary condition as well. Indeed if you start to make sums of vectors in the same way, with $d = \mathrm{gcd}(n,k) > 1$, the sum of the $n/d$ first vectors will be the constant vector $(k/d, \ldots, k/d)$. It's a novel way to prove that $(1,1, \ldots, 1)$ is in $V$, and together, these two ways give a (real) linear relation between the vectors. But I like my complex proof more, so I will not delete it.

A: Hint:  The set $S_{n,k}$  is a basis if  the  corresponding  determinant is not zero. But  this determinant is the Circulant.
The  rank of the circulant matrix equals $n-d$ where $d$ is degree of the polynomial $(1+x+\cdots+x^{k-1},x^n-1).$ Thus the cirulant is not zero iff the polinomials are coprime. Since  $1+x+\cdots+x^{k-1}=\dfrac{x^k-1}{x-1}$ we get that $(n,k)=1.$
So $S_{n,k}$  is a basis if $n$  and $k$ are coprime.


text:
Q: How can generate views in asp.net-mvc unit tests? Im trying to generate views in unit tests but i can't get around the missing VirtualPathProvider. Most viewengines use the VirtualPathProviderViewEngine base class that gets the provider from the current HostingEnvironment.
protected VirtualPathProvider VirtualPathProvider {
    get {
        if (_vpp == null) {
            _vpp = HostingEnvironment.VirtualPathProvider;
        }
        return _vpp;
    }
    set {
        _vpp = value;
    }
}

In unit tests there is no HostingEnvironment, even if i create one there is no current VirtualPathProvider.
How can i workaround this problem? Do i have to create a custom FakeWebFormViewEngine?

A: There are features coming in VS Team System 2010 for the Acceptance Testing which would be appropriate for what you are trying to do.  As mentioned by Gregory A Beamer Unit tests for MVC are done to the controller.  You can also test the Model depending on how you implement your model.
This is where there is a lot of controversy.  Some people look at the model as business entities where I look at them as representations of the model specific to the View.  More of a View Model.  Since there is no real functionality in my model I do not have to test it.  I test my DAL, Business Logic Layer outside of the MVC.  MVC really is all part of the presentation layer.  It is layering of your Presentation not your application.  You still layer your application.
As far as Unit testing goes the controller is where you test.  You can test your model if there are methods that require testing.  As for the views they are acceptance tested by users or through automation like Watin.

A: I tried to do this as well.  Unfortunately, it is not just the VirtualPathProvider (VPP) that is the problem.  The VPP is used to map the view or partial view to a physical path to determine the existance of the file.  Unfortunately, the ViewContext ends up with the virtualpath, not the physical path, so when the view is rendered the Builder uses properties of the HostingEvnironment which does not exist.
If you are using a version of Visual Studio with Testing, then you could use a Web Unit Test.  This will allow you to use the browser to call the URL and then parse the response to check for values.

A: Pardon me if this sounds ignorant, but what is the purpose of generating views? I may be missing something, but the primary focus of unit tests is "testing the unit". In a properly set up ASP.NET MVC application, the code that needs to be tested is in the controller and below. In fact, I would say, if properly developed, it is below.
The test of the view is a user acceptance test. I see nothing wrong with automating this, by any means, but I am not sure this is something that has to be done with a unit test.
Am I missing something?

A: You can try Ivonna for integration (and, to some extent, unit) testing your Views.


text:
Q: Wrap a VB Windows Form Project in a C# Project's Window I have a bit of a weird question. I'm not entirely sure how to phrase the question, but the general gist of the situation is that I am currently developing a plugin for a program in C# for some software called SDL Trados Studio. However, a lot of our code is currently in VB and I don't see that changing in the foreseeable future. There are plenty of tools out there that will let me convert the project from VB to C# that will take care of most of the syntax, but there is the occasional thing here and there that just cannot translate well from VB to C#.
I was wondering, if I have access to the source of both the C# project and the VB project, would it be possible to wrap the UI of the VB project and feed it input from the C# project?
I ask this because it would be much easier to just wrap the UI into my plugin as the VB code is still actively developed and it would become a tedious task to convert the VB project into C# before cleaning it up every time a new update is pushed to the code.
Thanks for the help!

A: You can always reference a DLL no matter what language it's written in, even unmanaged DLLs, but especially managed assemblies.
If your existing VB code is not already in its own DLL, but it in one, compile it, and reference it from your new project.


text:
Q: Get Latest Artifact from JFrog - Artifactory OSS I'm using JFrog Artifactory OSS in a docker container.
I want to download the latest version of an artifact. But it seems that it is not possible in OSS version.
Does anybody know a way to download the latest version of the artifact?

A: You are right, the Latest Version API endpoint works only in Artifactory Pro.
Working with Maven repositories, you can use the SNAPSHOT support to get Artifactory to return you the latest artifact.
Setting the Maven Snapshot behavior in repo settings to Unique, deploy the artifacts with -SNAPSHOT suffix. Artifactory will assign a unique version to those files internally, but you will always be able to retrieve the latest one using the -SNAPSHOT suffix.

A: Thanks a lot for your fast answer. I forgot you tell my hole workflow.
I have a jenkins server, building, testing and deploying my stuff.
I want build a spring boot jar file with maven and deploy it to my repository(i use jfrog). This works perfect. In a next step i will create a docker image containing this jar file. So the in the image file ther must be a command to download the execuatbel jar from jfrog. So for this reason i have to know the latest version of the jar file.
I hope you could understand it, this is my first english question.
Thanks a lot for helping me !


text:
Q: How to run aiosmtpd via Docker My Dockerfile
FROM python:3.10-alpine

LABEL Description="test smtp server"
EXPOSE 8025
COPY ./requirements.txt /app/requirements.txt
WORKDIR /app
RUN python -m pip install --upgrade pip && pip install -r requirements.txt
CMD python3 -m aiosmtpd --nosetuid --debug --debug --listen 127.0.0.1:8025

When i run this container with command
docker build -t test-smtp-image . && docker run -p 8025:8025 --name skad-test-smtp test-smtp-image

And tying to send email to it from host where container running i got next Exception
    raise SMTPConnectError(
aiosmtplib.errors.SMTPConnectError: Error connecting to 127.0.0.1 on port 8025: Unexpected EOF received

But it works great when i send email with same script and aiosmtpd running command on host
Sending mail script:
from email.message import EmailMessage
import aiosmtplib
import asyncio

m = EmailMessage()
m['From'] = "test@test.com"
m["To"] = 'test@test.com'
m["Subject"] = "Test subject"
m.set_content("Test msg")

loop = asyncio.get_event_loop()
r = loop.run_until_complete(aiosmtplib.send(m, hostname="127.0.0.1", port=8025))

A: Thanks to David Maze.
Correct Dockerfile:
FROM python:3.10-alpine

LABEL Description="test smtp server"
EXPOSE 8025
COPY ./requirements.txt /app/requirements.txt
WORKDIR /app
RUN python -m pip install --upgrade pip && pip install -r requirements.txt
CMD python3 -m aiosmtpd --nosetuid --debug --debug --listen 0.0.0.0:8025


text:
Q: Enable php to execute .php files that start with just  I bought a php script on Code canyon, and it was running ok on my localhosts (Xampp), but when i uploaded the files to my server, I noticed that the .php files where not being executed, after some investigation I discovered that my server does not recognise the php files, because they start with just <?, instead of <?php.
Is it possible to change PHP to execute .php files that start with just <?
I running ubuntu 14.04, with php 5.5.9

A: You need to change PHP's .ini file to include this (or change existing definition):
short_open_tag=1


text:
Q: Function for converting to base b, taking derivative with respect to b and evaluating at b I am relatively new to Mathematica and I would like to program a function taking 2 variables in and giving 1 output. I think the best way to describe the function is like so: Given a base 10 number x and a second number b, convert x to a "polynomial base b", if you will and take the derivative of the polynomial. Then evaluate it at b.
I will illustrate what I mean with 2 examples: F(37,5) would be calculated as 121 (base 5) then d(1*5^2+2*5+1)/d(5) if you excuse the notation for "derivative with respect to 5" using power rule. The "derivative with respect to 5" would be 2*5+2 which is 12. Therefore F(37,5)=12.
Example 2: F(988,4): 988 is 33130 in base 4, d(3*4^4+3*4^3+4^2+3*4)/d(4) = 12*4^3+9*4^2+2*4+3 = 923.

A: For your particular problem:
D[IntegerDigits[37, 5] {b^2, b, 1}, b] /. {b -> 5} // Total
12

In general you can create a function:
f[num_, base_] := Module[{}, dig = IntegerDigits[num, base]; len = Length[dig];
        D[dig Reverse[b^Range[0, len - 1] ], b] /. {b -> base} // Total]

So that f[37,5] returns 12 and f[988,4] is 923.

A: db[n_Integer, b_Integer] :=
 FromDigits[(# Range[Length@#, 1, -1]) &@ Most@IntegerDigits[n, b], b]

or
db[n_Integer, b_Integer] :=
 Total@MapIndexed[ ( #2[[1]] - 1 )   #   b^(#2[[1]] - 2) & ,
   Reverse@IntegerDigits[n, b]]

db[37, 5]
db[988, 4]

12
923

A: f[n_, b_] := Module[{dig},
  dig = IntegerDigits[n, b];
  D[dig.Table[x^i, {i, Length@dig - 1, 0, -1}], x] /. x -> b
  ]

Maybe a different example for illustration:
f[2016, 28]

128


text:
Q: Flutter - How can I retrieve a bool from an external function? I'm trying to find whether the logged in user is an admin or a normal user.
I have already created a global function (then called it in initState) to check whether the role is admin or not by setting a bool to true or false as follows:
bool isAdmin;
  _checkRole() async {
    var firebaseUser = FirebaseAuth.instance.currentUser;
    await FirebaseFirestore.instance
        .collection("users")
        .doc(firebaseUser.uid)
        .get()
        .then((value) {
      if ((value.data()['role']) == 'admin') {
        isAdmin = true;
      } else {
        isAdmin = false;
      }
      return isAdmin;
    });
  }

And here in the drawer I did the following:
          isAdmin
              ? buildListTile(
                  'Admin Panel', Icons.admin_panel_settings_sharp, () {
                  Navigator.of(context).pushNamed(AdminScreen.routeName);
                })
              : buildListTile('User dashboard', Icons.person, () {}),

But when I open the drawer, I receive Failed assertion: boolean expression must not be null
Any idea on how to fix this issue?
and thank you.

A: Short answer:
isAdmin isn't initialized when you are building your ListTile because the async function hasn't had a chance to finish running.
Longer answer:
Your build method happens synchronously with the rest of the code, meaning it happens one line after another. Your _checkRole() method happens asynchronously, meaning it will get around to it whenever it gets around to it. So when you try initializing isAdmin in your initState method it is running a network call (which takes a long time in terms of program time) and waiting till the network call finishes to set isAdmin. Meanwhile, your build is running and trying to build without knowing that it is supposed to wait for isAdmin to be set.
A Solution:
(note, there are many ways to solve this, this is just one)
Use a FutureBuilder or StreamBuilder to load the variable and set the variable type to Future or the equivalent for streams and listen to the state change and build your UI accordingly.
Here's a basic example. Careful copy/pasting. I didn't run the code. This is just the general idea.
Future<bool> isAdmin;

FutureBuilder<String>(
  future: Globals.isAdmin,
  builder: (BuildContext context, AsyncSnapshot<Bool> snapshot) {
    if (snapshot.hasData) { //
      var isAdmin = snapshot.data;
      // use the value for isAdmin
      if (isAdmin == true) {
        return Container();
      } else {
        return Container();
      }
    } else if (snapshot.hasError) {
      //handle your error
      return Container();
    } else {
      // handle your loading
      return CircularProgressIndicator();
    }
  },
),

A: Try to change your _checkRole() method the next way:
Future<bool> _checkRole() async {
  var firebaseUser = FirebaseAuth.instance.currentUser;
  return await FirebaseFirestore.instance
    .collection("users")
    .doc(firebaseUser.uid)
    .get()
    // we create the new Future with bool value, depending on
    // the Firebase response and throw it away as a result of
    // the _checkRole method
    .then((value) => Future.value(value.data()['role']) == 'admin'));
}

And then use a FutureBuilder inside your component. So your layout should look like:
child: FutureBuilder<bool>(
  future: _checkRole,
  builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
    if (snapshot.hasData) { // check whether we have any data in our Future object
      final isAdmin = snapshot.data; // bool type
      return isAdmin
          ? buildListTile(
              'Admin Panel', Icons.admin_panel_settings_sharp, () {
              Navigator.of(context).pushNamed(AdminScreen.routeName);
            })
          : buildListTile('User dashboard', Icons.person, () {}),
    }

    // if snapshot doesn't have data return a widget with an error message
    return Center(
      child: Text('Error!'),
    );
  },
),

A: put a default value for isAdmin variable
bool isAdmin = false;

or If you have a model for members, I mean you created a class called Member
class Member {
  // create a method for deteriming if the the member is an admin or not
  bool isAdmin() async {
    var firebaseUser = FirebaseAuth.instance.currentUser;
    await FirebaseFirestore.instance
    .collection("users")
    .doc(firebaseUser.uid)
    .get()
    .then((value) {
      return ((value.data()['role']) == 'admin');
    });
  }
}

Now, you can use this method to check if the member is an admin or not


text:
Q: Problem with Symbolic links in PHP\Laravel
I am using Laravel 7 on Direct admin. I don't actually have access to Command Line/Terminal, and I need a Symbolic link of Storage.
I have Tried:
Route::get('/foo', function () {
    Artisan::call('storage:link');
});

and also:
symlink('/domains/MyProject.com/LaravelFolder/storage/app/public', '/domains/MyProject.com/public_html');

But I am receiving this Error:
symlink() has been disabled for security reasons

My LaravelFolder is Placed before public_html.
UPDATE: I realized that the Hosting company disabled this function; I asked them to enable it, But They say: it is impossible. Do you know an alternative way to do that?

A: Old Solution
But I finally Solved This, It seems little bit stupid but it works:
In Ubuntu Linux I tried to create a symlink like the storage symbolic link in Laravel, with the following Command:
ln -s ../laravelFolder/storage/app/public storage

and then I compressed this symbolic link and uploaded to my public_html Folder and it works.
I hope it will be Helpful..
2022 UPDATE (New Solution)
In such cases that your projects production environment is a Linux server and you are developing your project on Windows I offer you to set up a WSL (Windows Subsystem for Linux) development environment.
This way you can simply use Linux terminal to creating a symbolic link with the following command:
// change laravelFolder with your laravel folder name
ln -s ../laravelFolder/storage/app/public storage

Here is Microsoft's quick guide to install and use WSL.

A: You can modify the public disk's root path to point directly public folder. Consider the below snippet;
/** /config/filesystems.php */

'disks' => [
    // ...
    'public' => [
        'driver' => 'local',
        'root' => public_path('storage'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],
    // ...
],

Note that this is not a best practice.


text:
Q: Keyboard and touch screen not working at all on MS Surface laptop I've just downloaded Ubuntu 18.04 on a flash drive and have gone to install it alongside Windows but my keyboard is not responsive at all. Every time I try to type something in it doesn't work and my touch screen isn't working either.
My computer is a Microsoft surface laptop (1st gen, Intel core i5.) The keyboard is built in.


text:
Q: vscode transforms  to  When typing
 vscode transforms it to

.
Not sure if it is a plugin that causes the issue or not. Vue3 does not support

 and throws an error.
Is it a way to disable this?

A: It is built-in extension for VS Code called Emmet.
You most definitely can customize it's settings in the settings.json file. If you don't know how to open settings.json, go here.


text:
Q: maven multi-module project not running I have developed a multi-module project with Java spring boot on IntelliJ.
This is runnable in the IDE without any problem via 'run Application' where 'Application' is my SpringBootApplication and located in a submodule of the parent module.
Now I want to run this system on a server and I am unable to get it running. I tried

mvn spring-boot:run

and I get following error:

Error: Could not find or load main class com.example.application.Application
Caused by: java.lang.ClassNotFoundException: com.example.application.Application

I also tried other commands like

mvn clean package

where I get errors saying that packages from the 'shared_model' (succesfully compiled - because no dependencies of other modules) do not exist (although they exist), while trying to compile 'aggregate'-package (depending on 'shared_model'), e.g.:

[ERROR] /.../aggregates/src/main/java/com/example/aggregates/.../.java:[3,52] package com.example.shared_model.... does not exist

[ERROR] /.../aggregates/src/main/java/com/example/aggregates/.../.java:[13,12] cannot find symbol

The file structure looks like this:
main
├── adapters-input
├── adapters-output
├── aggregates
├── application
├── application-services
└── shared_model

Where every package has its own pom-file.
The pom of the parent module looks as follows:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>main</artifactId>
    <packaging>pom</packaging>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <java-version>11</java-version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <modules>
        <module>adapters-output</module>
        <module>adapters-input</module>
        <module>application-services</module>
        <module>aggregates</module>
        <module>application</module> <!-- location of main class -->
        <module>shared_model</module>
    </modules>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.example.application.Application</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

The pom of the 'application'-package looks as follows:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>application</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>application</name>
    <description>Application endpoint</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.example</groupId>
            <artifactId>adapters-input</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>shared_model</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>adapters-output</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>application-services</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>aggregates</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>

I tried a lot of things and became a little desperate. It seems like there is an issue with seeing sibling-modules and child-modules, but I don't see why. Also, I don't understand why it is working smoothly from when ran from IntelliJ.
I greatly appreciate any help. Thanks!


text:
Q: Confidence interval of probability prediction from logistic regression statsmodels I'm trying to recreate a plot from An Introduction to Statistical Learning and I'm having trouble figuring out how to calculate the confidence interval for a probability prediction. Specifically, I'm trying to recreate the right-hand panel of this figure (figure 7.1) which is predicting the probability that wage>250 based on a degree 4 polynomial of age with associated 95% confidence intervals. The wage data is here if anyone cares.
I can predict and plot the predicted probabilities fine with the following code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
from sklearn.preprocessing import PolynomialFeatures

wage = pd.read_csv('../../data/Wage.csv', index_col=0)
wage['wage250'] = 0
wage.loc[wage['wage'] > 250, 'wage250'] = 1

poly = Polynomialfeatures(degree=4)
age = poly.fit_transform(wage['age'].values.reshape(-1, 1))

logit = sm.Logit(wage['wage250'], age).fit()

age_range_poly = poly.fit_transform(np.arange(18, 81).reshape(-1, 1))

y_proba = logit.predict(age_range_poly)

plt.plot(age_range_poly[:, 1], y_proba)

But I'm at a loss as to how the confidence intervals of the predicted probabilities are calculated. I have thought about bootstrapping the data many times to get the distribution of probabilities for each age but I know there is an easier way which is just beyond my grasp.
I have the estimated coefficient covariance matrix and the standard errors associated with each estimated coefficient. How would I go about calculating the confidence intervals as shown in the right-hand panel of the figure above given this information?
Thanks!

A: You can use delta method to find approximate variance for predicted probability. Namely,
var(proba) = np.dot(np.dot(gradient.T, cov), gradient)

where gradient is the vector of derivatives of predicted probability by model coefficients, and cov is the covariance matrix of coefficients.
Delta method is proven to work asymptotically for all maximum likelihood estimates. However, if you have a small training sample, asymptotic methods may not work well, and you should consider bootstrapping.
Here is a toy example of applying delta method to logistic regression:
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt

# generate data
np.random.seed(1)
x = np.arange(100)
y = (x * 0.5 + np.random.normal(size=100,scale=10)>30)
# estimate the model
X = sm.add_constant(x)
model = sm.Logit(y, X).fit()
proba = model.predict(X) # predicted probability

# estimate confidence interval for predicted probabilities
cov = model.cov_params()
gradient = (proba * (1 - proba) * X.T).T # matrix of gradients for each observation
std_errors = np.array([np.sqrt(np.dot(np.dot(g, cov), g)) for g in gradient])
c = 1.96 # multiplier for confidence interval
upper = np.maximum(0, np.minimum(1, proba + std_errors * c))
lower = np.maximum(0, np.minimum(1, proba - std_errors * c))

plt.plot(x, proba)
plt.plot(x, lower, color='g')
plt.plot(x, upper, color='g')
plt.show()

It draws the following nice picture:

For your example the code would be
proba = logit.predict(age_range_poly)
cov = logit.cov_params()
gradient = (proba * (1 - proba) * age_range_poly.T).T
std_errors = np.array([np.sqrt(np.dot(np.dot(g, cov), g)) for g in gradient])
c = 1.96
upper = np.maximum(0, np.minimum(1, proba + std_errors * c))
lower = np.maximum(0, np.minimum(1, proba - std_errors * c))

plt.plot(age_range_poly[:, 1], proba)
plt.plot(age_range_poly[:, 1], lower, color='g')
plt.plot(age_range_poly[:, 1], upper, color='g')
plt.show()

and it would give the following picture

Looks pretty much like a boa-constrictor with an elephant inside.
You could compare it with the bootstrap estimates:
preds = []
for i in range(1000):
    boot_idx = np.random.choice(len(age), replace=True, size=len(age))
    model = sm.Logit(wage['wage250'].iloc[boot_idx], age[boot_idx]).fit(disp=0)
    preds.append(model.predict(age_range_poly))
p = np.array(preds)
plt.plot(age_range_poly[:, 1], np.percentile(p, 97.5, axis=0))
plt.plot(age_range_poly[:, 1], np.percentile(p, 2.5, axis=0))
plt.show()

Results of delta method and bootstrap look pretty much the same.
Authors of the book, however, go the third way. They use the fact that
proba = np.exp(np.dot(x, params)) / (1  + np.exp(np.dot(x, params)))
and calculate confidence interval for the linear part, and then transform with the logit function
xb = np.dot(age_range_poly, logit.params)
std_errors = np.array([np.sqrt(np.dot(np.dot(g, cov), g)) for g in age_range_poly])
upper_xb = xb + c * std_errors
lower_xb = xb - c * std_errors
upper = np.exp(upper_xb) / (1 + np.exp(upper_xb))
lower = np.exp(lower_xb) / (1 + np.exp(lower_xb))
plt.plot(age_range_poly[:, 1], upper)
plt.plot(age_range_poly[:, 1], lower)
plt.show()

So they get the diverging interval:

These methods produce so different results because they assume different things (predicted probability and log-odds) being distributed normally. Namely, delta method assumes predicted probabilites are normal, and in the book, log-odds are normal. In fact, none of them are normal in finite samples, and they all converge to normal in infinite samples, but their variances converge to zero at the same time. Maximum likelihood estimates are insensitive to reparametrization, but their estimated distribution is, and that's the problem.

A: Here is an instructive and efficient method to calculate the standard errors ('se') of the fit ('mean_se') and single observations ('obs_se') on top of a statsmodels Logit().fit() object ('fit'), identical to the method in the book ISLR and the last method from the answer by David Dale:
fit_mean = fit.model.exog.dot(fit.params)
fit_mean_se = ((fit.model.exog*fit.model.exog.dot(fit.cov_params())).sum(axis=1))**0.5
fit_obs_se = ( ((fit.model.endog-fit_mean).std(ddof=fit.params.shape[0]))**2 + \
                fit_mean_se**2 )**0.5

A figure similar to the one in the book ISLR
The shaded regions represent the 95% confidence intervals for the fit and single observations.
Ideas for improvement are most welcome.


text:
Q: Could not find the task 'tsc: build - tsconfig.json'
Hello I am following this tutorial
https://code.visualstudio.com/docs/typescript/typescript-tutorial
to debug typescript but I have encountered error as shown in the screenshot.
If I choose debug anyway, the debugger works but I cant set any breakpoint. I suspect it has something to do with failing to set up the task file.
Any advise guys?

A: I had a similar problem. In my case, the tsconfig.json file was not in the main folder, but in a subfolder. In my case, the working configuration looked like this

{
      "type": "node",
      "request": "launch",
      "name": "Launch server",
      "program": "${workspaceFolder}/server/index.ts",
      "preLaunchTask": "tsc: build - server/tsconfig.json",
      "outFiles": ["${workspaceFolder}/out/**/*.js"]
}

A: Task tsc: build - tsconfig.json by default comes from VSCode when it detects the existence of tsconfig.json. Based on your screenshot, I can tell that you already have the file. So, it is odd if it can't be detected.
Please make sure the file content of tsconfig.json is valid.
tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "out",
    "sourceMap": true
  }
}

Also to check whether the tasks are exist, you can choose menu Terminal -> Run Build Task or press Shift + Command + B on MacOS. If correct, you can see two tasks available there as the image below.

Otherwise, there must be something wrong with the steps. Perhaps, there is an extra space in preLaunchTask. For reference, I also copy paste my launch.json here.
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "program": "${workspaceFolder}/helloworld.ts",
      "preLaunchTask": "tsc: build - tsconfig.json",
      "outFiles": [
        "${workspaceFolder}/out/**/*.js"
      ]
    }
  ]
}

A: For other language users, the tsc: build command maybe be another command, such as  tsc: 构建 in Chinese.
my launch.json:
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "pwa-node",
      "request": "launch",
      "name": "Launch Program",
      "skipFiles": [
        "<node_internals>/**"
      ],
      "program": "${workspaceFolder}/index.ts",
      "preLaunchTask": "tsc: 构建 - tsconfig.json",
      "outFiles": [
        "${workspaceFolder}/out/**/*.js"
      ]
    }
  ]
}

A: When you Ctrl+Shift+B terminal will run Run Build Task.. You'll see in the terminal
">Executing task: tsc -p c:....
Terminal will be reused by tasks, press any key to close it."
Then after that double click a ts file and press F5 you will have to select at which environment do you want your ts file to run and then you will see the output in the debug console.

A: because it does not find path of tsconfig file....
see your folder structure whether the structure contains multiple same folder with same name...so y debugger confused to find path....so make sure the devlopement folder which you work on has proper path with unique name no same name with its parent folder and contains tsconfig files...

A: This happens also if the Extension Host crashed. This prevents the task engine from finding the requested task. Usually, you should see a message in the toaster where you can immediately restart the Extension Host. After that the debugger and tasks work.

A: For Ubuntu Linux 20.04 LTS (but may well be the same on other OS's) what got preLaunchTask working for me, was using both a local tasks.json and launch.json
So my folder structure (pre-build) is:
.vscode/launch.json
.vscode/tasks.json
dist
src/index.ts
package.json
tsconfig.json

My launch.json contains:
{
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "TS preLaunchTask-build",
            "program": "${file}",
            "preLaunchTask": "tsc: build",
            "outFiles": ["${workspaceFolder}/dist/**/*.js"],
            "skipFiles": [
                "<node_internals>/**", "node_modules",
              ]
        },
    ]
}

My tasks.json contains:
{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "command": "echo hello yes working!",
            "problemMatcher": [],
            "label": "myTask"
        },
        {
            "type": "typescript",
            "tsconfig": "tsconfig.json",
            "problemMatcher": ["$tsc"],
            "group": "build",
            "label": "tsc: build"
        },
    ]
}

And my tsconfig.json contains:
{
  "compilerOptions": {
      "outDir": "./dist",
      "sourceMap": true,
      "target": "es5",
      "module": "commonjs"
  },
  "include": [
      "src/**/*"
  ]
}

Usage: whilst within the index.ts just hit F5 with a breakpoint set
I have also included another task, "myTask" you can change the preLaunchTask line in your launch.json to: "preLaunchTask": "myTask", (where it will output some text to console to verify preLaunchTask is now working)
That way, if you still have issues, you can see if the issue is in your tsconfig setup, or if it's a preTaskLaunch setup issue.
(I would have thought it should have resolved this itself, but apparently not at the current time of writing anyway - but does force the advantage (for me) of committing debug config to the repo on project basis rather than global config)

A: Be sure to check the exact structure/spelling of Task by pressing Ctrl+Shift+B (on Windows) and Cmd+Shift+B(on Mac).

In my case, it was tsc: build - projectName/tsconfig.json

A: Create launch.json inside .vscode in your workspace and set in there, instead of using vscode user profile settings.
I don't know why :(