问:
Issue with displaying randomly generated code
So i have a section of code that creates a random code and sends it in a private message (on another website) to them, however id like to update it to also display the code in the success message

Models

```<code>public function createDepositRequest()
    {
        // Generate unique code
        $code = Codes::generateCode();

        $deposit = Deposits::create([
            "accountID" => $this->id,
            "code" => $code,
        ]);
        echo $code;
        dispatch(new CreateDepositRequest($deposit));
    }
</code>```

UserController

```<code>/**
     * Creates a deposit request for an account
     *
     * @param int $accountID
     * @throws UserErrorException
     */
    protected function deposit(int $accountID)
    {
        // Get the account
        $account = Accounts::find($accountID);

        if ($account === null || $account->count() === 0)
            throw new UserErrorException("That account doesn't exist");

        // Verify that the submitting user owns this account
        if (Auth::user()->nID != $account->nID)
            throw new UserErrorException("You don't own that account, silly billy");

        // Now call to create the deposit request
        $account->createDepositRequest();

        $this->output->addSuccess("Deposit request added successfully. Please check your inbox in-game for instructions");
    }
</code>```

Job (the thing that has it sent to the other site) ```

```namespace App\Jobs;

use App\Classes\Nation;
use App\Classes\PWClient;
use App\Models\Accounts;
use App\Models\Deposits;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class CreateDepositRequest implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Holds the deposit request
     *
     * @var Deposits
     */
    protected $deposit;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Deposits $deposit)
    {
        $this->deposit = $deposit;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $client = new PWClient();
        $client->login();

        // Get nation info
        $nation = new Nation($this->deposit->account->nID);

        // Setup message
        $message = "Hi {$nation->leader},\n\n You've submitted a deposit request for the account named: {$this->deposit->account->name}.\n\nThe code for your deposit is: {$this->deposit->code}\n\nPlease send whatever money and resources you want to deposit into your account into the bank using the code above as the transaction, just like how you make a payment towards a loan.\n\nPlease note that the system checks for deposits at five past the hour, so if you make a deposit during that time, your deposit [b]will not count[/b]. So please try to avoid that. Additionally, this means that your deposit will not show up in your account until then. You will receive a confirmation email when your deposit is processed. If you not get a message within two hours, please contact us.";

        // Now send them a message
        $client->sendMessage($nation->leader, "Deposit Request", $message);
        echo "{$this->deposit->code}";
    }
}
```

So ive tried a dozen things but im reaching a level where im above my knowlage it would appear. You can see that in the models i have it just echo the code, and since the user controller actually sends the success message, im not sure how to return the code generated in models for use in the usercontroller.

So to clarify i made a screenshot https://prnt.sc/r42p0v

Attempts tried: to add
-return $code;  error was "undefined variable"

答:
I can't say absolutely for sure without seeing more of the code, but it looks like you should be able to do this...

In your model, after

dispatch(new CreateDepositRequest($deposit));

add

return $code;

Then in your controller, replace

$account->createDepositRequest();

with

$code = $account->createDepositRequest();

Having done that, you should be able to access the returned $code value in the next line as something like

```<code>$this->output->addSuccess("Deposit request added successfully.  Your code is $code. Please check your inbox in-game for instructions");
</code>```

The only thing that would throw a wrench in this would be if there's something going on in dispatch(new CreateDepositRequest($deposit)); that isn't fully shown in your code above.

Body:
So i have a section of code that creates a random code and sends it in a private message (on another website) to them, however id like to update it to also display the code in the success message

Models

public function createDepositRequest()
    {
        // Generate unique code
        $code = Codes::generateCode();

        $deposit = Deposits::create([
            "accountID" => $this->id,
            "code" => $code,
        ]);
        echo $code;
        dispatch(new CreateDepositRequest($deposit));
    }

UserController

/**
     * Creates a deposit request for an account
     *
     * @param int $accountID
     * @throws UserErrorException
     */
    protected function deposit(int $accountID)
    {
        // Get the account
        $account = Accounts::find($accountID);

        if ($account === null || $account->count() === 0)
            throw new UserErrorException("That account doesn't exist");

        // Verify that the submitting user owns this account
        if (Auth::user()->nID != $account->nID)
            throw new UserErrorException("You don't own that account, silly billy");

        // Now call to create the deposit request
        $account->createDepositRequest();

        $this->output->addSuccess("Deposit request added successfully. Please check your inbox in-game for instructions");
    }

Job (the thing that has it sent to the other site) ```

namespace App\Jobs;

use App\Classes\Nation;
use App\Classes\PWClient;
use App\Models\Accounts;
use App\Models\Deposits;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class CreateDepositRequest implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Holds the deposit request
     *
     * @var Deposits
     */
    protected $deposit;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Deposits $deposit)
    {
        $this->deposit = $deposit;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $client = new PWClient();
        $client->login();

        // Get nation info
        $nation = new Nation($this->deposit->account->nID);

        // Setup message
        $message = "Hi {$nation->leader},\n\n You've submitted a deposit request for the account named: {$this->deposit->account->name}.\n\nThe code for your deposit is: {$this->deposit->code}\n\nPlease send whatever money and resources you want to deposit into your account into the bank using the code above as the transaction, just like how you make a payment towards a loan.\n\nPlease note that the system checks for deposits at five past the hour, so if you make a deposit during that time, your deposit [b]will not count[/b]. So please try to avoid that. Additionally, this means that your deposit will not show up in your account until then. You will receive a confirmation email when your deposit is processed. If you not get a message within two hours, please contact us.";

        // Now send them a message
        $client->sendMessage($nation->leader, "Deposit Request", $message);
        echo "{$this->deposit->code}";
    }
}

So ive tried a dozen things but im reaching a level where im above my knowlage it would appear. You can see that in the models i have it just echo the code, and since the user controller actually sends the success message, im not sure how to return the code generated in models for use in the usercontroller.

So to clarify i made a screenshot https://prnt.sc/r42p0v

Attempts tried: to add
-return $code;  error was "undefined variable"

Body:
I can't say absolutely for sure without seeing more of the code, but it looks like you should be able to do this...

In your model, after

dispatch(new CreateDepositRequest($deposit));

add

return $code;

Then in your controller, replace

$account->createDepositRequest();

with

$code = $account->createDepositRequest();

Having done that, you should be able to access the returned $code value in the next line as something like

$this->output->addSuccess("Deposit request added successfully.  Your code is $code. Please check your inbox in-game for instructions");

The only thing that would throw a wrench in this would be if there's something going on in dispatch(new CreateDepositRequest($deposit)); that isn't fully shown in your code above.


来源: stackexchange

问:
Ajax functionality seems to fail when on adding a div tag to my .js.erb file
I am doing some styling in my code where I want to display the time a message is posted on a groups forum in my app. Currenlty posting of every message in this forum works with AJAX functionality implemented via Jquery 1.4.

On including the div tag in my post_message.js.erb file, i find that the message doesn't post on the groups home page( the place where I have all the group specific discussions - a functionality similar to what one would get to see in FB groups ).

The message gets saved in my DB and on refereshing the page I get to see the latest message posted.

The code in post_message.js.erb looks like this:-

```<code>$("#new_post").before('<div id ="new_post"><%= escape_javascript(flash.delete(:notice)) %></div>');<!--TO-DO the flash messages aren't yet enabled/working-->
$("#latest_post").prepend("<%= @group_post.message %> by <%=  Investor.find(@group_post.post_by).first_name %>  <%=  distance_of_time_in_words(@group_post.created_at,Time.now) %> ago <br/><br/><hr/>");
$("#new_post")[0].reset();
</code>```

The above code stops functioning properly when I change the second line to:-

```<code>$("#latest_post").prepend("<%= @group_post.message %> by <%=  Investor.find(@group_post.post_by).first_name %> <div class ="contentdispgrp"> <%=  distance_of_time_in_words(@group_post.created_at,Time.now) %> ago </div><br/><br/><hr/>");
</code>```

The part of the code corresponding the above in _common.html.erb file( this is a partial view where I have all the html tags and id's which I am eventually using in my .js.erb file) looks like this:-

```<code><table>
<tr>

<%if @current_user.is_an_existing_member_of_group(@investor_group)%>
<%form_for  :group_post, @group_post, :url => {:action => :post_message, :id => params[:id]},:html => {:multipart => 'true', :id => 'new_post'} do |f| -%>
    Start Discussion:<br><%=f.text_field :message%>
   <!--<%=f.file_field :photo%> -->
   <%=submit_tag "Post"%></p>
  <%end%>

   <div id = "latest_post"> </div>

<%for a in @group_all_posts %>
<%= a.message %> by <%=  Investor.find(a.post_by).first_name %> <div class ="contentdispgrp" id="style_chck"> <%=  distance_of_time_in_words(a.created_at,Time.now) %> ago </div><br/><br/> <hr/>

        <%end%>

</tr>
<%end%>
</table>
</code>```

My post_message method in my groups controller looks like this:-

```<code> def post_message
      @investor_group = InvestorGroup.find(params[:id])

      unless @current_user.is_an_existing_member_of_group(@investor_group)
        flash[:notice] = "Please join this group to participate in discussions"
        redirect_to :action => :show, :id => @investor_group and return # try to find out what exactly does this command do with return stmnt
      else
        @group_post = GroupPost.new(params[:group_post])
      end
      #@group_post = GroupPost.new(params[:group_post])

      investor_id = session['investor_id']
      @group_post.investor_group_id = @investor_group.id
      @group_post.post_by = investor_id
      if @group_post.save
        flash[:notice] = 'Post was successfully created.'
       # redirect_to :action => :show, :id => params[:id] - removed after trying to implement ajax via jquery
      else
        flash[:notice] = 'Post was not successfully created.'
      end

      respond_to do |format|
        format.html {redirect_to :action => "show", :id => params[:id]}
        format.js
      end

  end
</code>```

How can I fix this without refreshing the page? I am not sure of what I am doing wrong. Kindly help.

Thanks.

[EDIT]

group.js file code:-

```<code>jQuery.ajaxSetup({
    'beforeSend' : function(xhr) {
        xhr.setRequestHeader("Accept","text/javascript")
        }
})

$(document).ready(function(){
    $("#new_post").submit(function(){
        $.post($(this).attr("action"),$(this).serialize(),null,"script");
        return false;
    })
})
</code>```

答: The bug was fixed by removing the extra quotes(") made use while defining the class wrt the stylesheet, there were already a pair of quotes with the prepend method.. in post_message.js.erb.

ContentLicense: CC BY-SA 3.0

Body:
I am doing some styling in my code where I want to display the time a message is posted on a groups forum in my app. Currenlty posting of every message in this forum works with AJAX functionality implemented via Jquery 1.4.

On including the div tag in my post_message.js.erb file, i find that the message doesn't post on the groups home page( the place where I have all the group specific discussions - a functionality similar to what one would get to see in FB groups ).

The message gets saved in my DB and on refereshing the page I get to see the latest message posted.

The code in post_message.js.erb looks like this:-

$("#new_post").before('
<%= escape_javascript(flash.delete(:notice)) %>
');
$("#latest_post").prepend("<%= @group_post.message %> by <%=  Investor.find(@group_post.post_by).first_name %>  <%=  distance_of_time_in_words(@group_post.created_at,Time.now) %> ago

");
$("#new_post")[0].reset();

The above code stops functioning properly when I change the second line to:-

$("#latest_post").prepend("<%= @group_post.message %> by <%=  Investor.find(@group_post.post_by).first_name %>
 <%=  distance_of_time_in_words(@group_post.created_at,Time.now) %> ago

");

The part of the code corresponding the above in _common.html.erb file( this is a partial view where I have all the html tags and id's which I am eventually using in my .js.erb file) looks like this:-

<%if @current_user.is_an_existing_member_of_group(@investor_group)%>
<%form_for  :group_post, @group_post, :url => {:action => :post_message, :id => params[:id]},:html => {:multipart => 'true', :id => 'new_post'} do |f| -%>
    Start Discussion:
<%=f.text_field :message%>

   <%=submit_tag "Post"%>

  <%end%>

<%for a in @group_all_posts %>
<%= a.message %> by <%=  Investor.find(a.post_by).first_name %>
 <%=  distance_of_time_in_words(a.created_at,Time.now) %> ago

        <%end%>

<%end%>

My post_message method in my groups controller looks like this:-

 def post_message
      @investor_group = InvestorGroup.find(params[:id])

      unless @current_user.is_an_existing_member_of_group(@investor_group)
        flash[:notice] = "Please join this group to participate in discussions"
        redirect_to :action => :show, :id => @investor_group and return # try to find out what exactly does this command do with return stmnt
      else
        @group_post = GroupPost.new(params[:group_post])
      end
      #@group_post = GroupPost.new(params[:group_post])

      investor_id = session['investor_id']
      @group_post.investor_group_id = @investor_group.id
      @group_post.post_by = investor_id
      if @group_post.save
        flash[:notice] = 'Post was successfully created.'
       # redirect_to :action => :show, :id => params[:id] - removed after trying to implement ajax via jquery
      else
        flash[:notice] = 'Post was not successfully created.'
      end

      respond_to do |format|
        format.html {redirect_to :action => "show", :id => params[:id]}
        format.js
      end

  end

How can I fix this without refreshing the page? I am not sure of what I am doing wrong. Kindly help.

Thanks.

[EDIT]

group.js file code:-

jQuery.ajaxSetup({
    'beforeSend' : function(xhr) {
        xhr.setRequestHeader("Accept","text/javascript")
        }
})

$(document).ready(function(){
    $("#new_post").submit(function(){
        $.post($(this).attr("action"),$(this).serialize(),null,"script");
        return false;
    })
})


问:
How to allow only a specific user to push commits to master branch
I'm trying to setup a git server and I want to allow only a specific user to push commits to master branch.

I have tried to use the Linux group permission setting to meet the requirement above but it seems not a correct way.

And I even don't know what are the key words for searching the answer for this.

Any help would be appreciated.

答:
Git does not allow you to have private branches, but you can achieve this functionality by implementing your own server-side pre-receive hook. Github enterprise specific pre-receive hook example is here, as a reference.

However, if you are using Git hosting services (like Github) they might have an option for this. Github, in particular, has an option called branch restrictions, but it requires you to have a paid subscription, unless your project is public.

ContentLicense: CC BY-SA 4.0


问:
Zooming in / out on images - QT c++
I am currently using QT to load images into a graphicsview scene. Essentially, I am looking for a way to be able to zoom in and out on the loaded image using a slider. The image loads successfully into the pane, but whatever I try to implement to zoom in / out, the image would disappear.

This is how it looks:

This is my implemented function, but the image disappears:

```<code>    void MainWindow::on_horizontalSlider_valueChanged(int value)
{
    float pool ;
        if(value==0 )
            pool=0.1;
        else
            pool  = value*0.01;

        scene->update();
        ui->graphicsView->transform();
        ui->graphicsView->scale(pool,pool);

}
</code>```

This is how I'm loading the images:

```<code>    void MainWindow::on_BrowseImages_clicked()
{
    QString imagePath = QFileDialog::getOpenFileName(
                this,
                tr("Open File"),
                "",
                tr("Images (*.jpg *.jpeg *.png)" )
                );

    imageObject = new QImage();
    imageObject->load(imagePath);

    image = QPixmap::fromImage(*imageObject);

    scene = new QGraphicsScene(this);
    scene->addPixmap(image);
    scene->setSceneRect(image.rect());
    ui->graphicsView->setScene(scene);
    //ui->graphicsView->fitInView(scene->sceneRect(),Qt::KeepAspectRatio);

}
</code>```

答:
When scaling is applied to transformation it always scales around origin.

Scaling with a certain center (that is not the origin) means that the center has been translated to the origin before scaling.

This could be

v' = translateO→C(scale(translateC→O(v)))

or with matrix operations

v' = MtranslateO→C • Mscale • MtranslateC→O • v

However, the Grahics View Framework provides something where combining transformations is actually built-in by default:

Every item provides its own local transformation.

The transformation of a group item is applied to the child items as well forming something which can be imagined as a local coordinate system.

This in mind, I came up with the following MCVE where
- translation to center is applied to the pixmap item
- scaling is applied to a group item which becomes parent of the pixmap item.

testQGraphicsViewScaleItem.cc:

// Qt header:
#include <QtWidgets>

// main application
int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup data
  QGraphicsScene qGScene;
  QGraphicsItemGroup qGItemGrp;
  QImage qImgCat("cat.jpg");
  QGraphicsPixmapItem qGItemImg(QPixmap::fromImage(qImgCat));
  qGItemImg.setTransform(
    QTransform().translate(-0.5 * qImgCat.width(), -0.5 * qImgCat.height()));
  qGItemGrp.addToGroup(&qGItemImg);
  qGScene.addItem(&qGItemGrp);
  // setup GUI
  QWidget qWinMain;
  qWinMain.setWindowTitle("QGraphicsView - Scale Image");
  QVBoxLayout qVBox;
  QGraphicsView qGView;
  qGView.setScene(&qGScene);
  qVBox.addWidget(&qGView, 1);
  QSlider qSlider(Qt::Horizontal);
  qSlider.setRange(-100, 100);
  qVBox.addWidget(&qSlider);
  qWinMain.setLayout(&qVBox);
  qWinMain.show();
  // install signal handlers
  auto scaleImg = [&](int value) {
    const double exp = value * 0.01;
    const double scl = pow(10.0, exp);
    qGItemGrp.setTransform(QTransform().scale(scl, scl));
  };
  QObject::connect(&qSlider, &QSlider::valueChanged,
    scaleImg);
  // runtime loop
  return app.exec();
}
```

<p>and a qmake project file <code>testQGraphicsViewScaleItem.pro</code>:</p>

<pre class="lang-none prettyprint-override"><code>SOURCES = testQGraphicsViewScaleItem.cc

QT += widgets
</code>```

Output:

<img src="https://i.stack.imgur.com/lrTxZ.png" alt="Snapshot of testQGraphicsViewScaleItem (0.1 < scaling < 1)">

Title: Zooming in / out on images - QT c++

Body:
I am currently using QT to load images into a graphicsview scene. Essentially, I am looking for a way to be able to zoom in and out on the loaded image using a slider. The image loads successfully into the pane, but whatever I try to implement to zoom in / out, the image would disappear.

This is how it looks:

This is my implemented function, but the image disappears:

    void MainWindow::on_horizontalSlider_valueChanged(int value)
{
    float pool ;
        if(value==0 )
            pool=0.1;
        else
            pool  = value*0.01;

        scene->update();
        ui->graphicsView->transform();
        ui->graphicsView->scale(pool,pool);

}

This is how I'm loading the images:

    void MainWindow::on_BrowseImages_clicked()
{
    QString imagePath = QFileDialog::getOpenFileName(
                this,
                tr("Open File"),
                "",
                tr("Images (*.jpg *.jpeg *.png)" )
                );

    imageObject = new QImage();
    imageObject->load(imagePath);

    image = QPixmap::fromImage(*imageObject);

    scene = new QGraphicsScene(this);
    scene->addPixmap(image);
    scene->setSceneRect(image.rect());
    ui->graphicsView->setScene(scene);
    //ui->graphicsView->fitInView(scene->sceneRect(),Qt::KeepAspectRatio);

}

Body:
When scaling is applied to transformation it always scales around origin.

Scaling with a certain center (that is not the origin) means that the center has been translated to the origin before scaling.

This could be

v' = translateO→C(scale(translateC→O(v)))

or with matrix operations

v' = MtranslateO→C • Mscale • MtranslateC→O • v

However, the Grahics View Framework provides something where combining transformations is actually built-in by default:

Every item provides its own local transformation.

The transformation of a group item is applied to the child items as well forming something which can be imagined as a local coordinate system.

This in mind, I came up with the following MCVE where
- translation to center is applied to the pixmap item
- scaling is applied to a group item which becomes parent of the pixmap item.

testQGraphicsViewScaleItem.cc:

// Qt header:
#include <QtWidgets>

// main application
int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup data
  QGraphicsScene qGScene;
  QGraphicsItemGroup qGItemGrp;
  QImage qImgCat("cat.jpg");
  QGraphicsPixmapItem qGItemImg(QPixmap::fromImage(qImgCat));
  qGItemImg.setTransform(
    QTransform().translate(-0.5 * qImgCat.width(), -0.5 * qImgCat.height()));
  qGItemGrp.addToGroup(&qGItemImg);
  qGScene.addItem(&qGItemGrp);
  // setup GUI
  QWidget qWinMain;
  qWinMain.setWindowTitle("QGraphicsView - Scale Image");
  QVBoxLayout qVBox;
  QGraphicsView qGView;
  qGView.setScene(&qGScene);
  qVBox.addWidget(&qGView, 1);
  QSlider qSlider(Qt::Horizontal);
  qSlider.setRange(-100, 100);
  qVBox.addWidget(&qSlider);
  qWinMain.setLayout(&qVBox);
  qWinMain.show();
  // install signal handlers
  auto scaleImg = [&](int value) {
    const double exp = value * 0.01;
    const double scl = pow(10.0, exp);
    qGItemGrp.setTransform(QTransform().scale(scl, scl));
  };
  QObject::connect(&qSlider, &QSlider::valueChanged,
    scaleImg);
  // runtime loop
  return app.exec();
}

and a qmake project file testQGraphicsViewScaleItem.pro:

SOURCES = testQGraphicsViewScaleItem.cc

QT += widgets

Output:


问:
Renaming object properties in an array of objects
I have the following structure:

```<code>const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        }
    ]
};
</code>```

I am wanting to re-name all instances of InvoiceNumber to CreditNoteNumber to give me the following:

```<code>const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        }
    ]
};
</code>```

I have tried various things like the following for example:

```<code>var changed = data.invoices.map(function(item) {
    return {
        ...data.invoices,
        CreditNoteNumber: item.InvoiceNumber
    };
});
</code>```

However the spread pushes CreditNoteNumber outside the object.

答:
Just use destructure and rename

const data = {
  invoices: [
    {
      Date: "2018-12-18T00:00:00.000Z",
      InvoiceNumber: "59"
    },
    {
      Date: "2018-12-18T00:00:00.000Z",
      InvoiceNumber: "59"
    }
  ]
};

var changed = data.invoices.map(
  ({ Date, InvoiceNumber: CreditNoteNumber }) => ({ Date, CreditNoteNumber })
);

console.log(changed);```

Body:
I have the following structure:

const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            InvoiceNumber: "59"
        }
    ]
};

I am wanting to re-name all instances of InvoiceNumber to CreditNoteNumber to give me the following:

const data = {
    invoices: [
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        },
        {
            Date: "2018-12-18T00:00:00.000Z",
            CreditNoteNumber: "59"
        }
    ]
};

I have tried various things like the following for example:

var changed = data.invoices.map(function(item) {
    return {
        ...data.invoices,
        CreditNoteNumber: item.InvoiceNumber
    };
});

However the spread pushes CreditNoteNumber outside the object.


问:
Scraping all comments under an Instagram post
my previous questions was closed, but the suggested answer doesn't help me. Instagram comments has a very specific behaviour! I know how to programatically scroll a website down, but with the comments on Instagram is a bit different! I would appreciate if my question was not closed immediately because it really doesn't help. Woule ba grateful for help and not shutting me down! Thank you.

Here it is again:
I am trying to build a scraper that is saving the comments under an Instagram post. I manage to log in to the instagram through my code so I can access all comments under a post, but I seem to cannot scroll down enough times to view all comments in order to scrape all of them. I only get around 20 comments everytime.

Can anyone please help me? I am using selenium webdriver.

Thank you for your help in advance! Will be greatfull.

This is my function for saving the comments:

```<code>import time
from selenium.webdriver.firefox.options import Options
from selenium.webdriver import Firefox
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

class Instagram_comments():
    def __init__(self):
        self.firefox_options = Options()
        self.browser = Firefox(options=self.firefox_options)

    def get_comments(self, url):
        self.browser.get(url)
        time.sleep(3)

        while True:
        try:
            self.load_more_comments = self.browser.find_element_by_class_name(
                    'glyphsSpriteCircle_add__outline__24__grey_9')
            self.action = ActionChains(self.browser)
            self.action.move_to_element(self.load_more_comments)
            self.load_more_comments.click()
            time.sleep(4)
            self.body_elem = self.browser.find_element_by_class_name('Mr508')
            for _ in range(100):
                self.body_elem.send_keys(Keys.END)
                time.sleep(3)
        except Exception as e:
            pass

        time.sleep(5)
        self.comment = self.browser.find_elements_by_class_name('gElp9 ')
        for c in self.comment:
            self.container = c.find_element_by_class_name('C4VMK')
            self.name = self.container.find_element_by_class_name('_6lAjh').text
            self.content = self.container.find_element_by_tag_name('span').text
            self.content = self.content.replace('\n', ' ').strip().rstrip()
            self.time_of_post = self.browser.find_element_by_xpath('//a/time').get_attribute("datetime")
            self.comment_details = {'profile name': self.name, 'comment': self.content, 'time': self.time_of_post}
            print(self.comment_details)
            time.sleep(5)

    return self.comment_details
</code>```

答:
This chunk worked multiple times for me:

```<code>def scroll():

SCROLL_PAUSE_TIME = 1

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)
    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
        print('page height:', new_height)
    last_height = new_height
scroll()
</code>```

and for some sites you will need to scrape as you scroll as not all elements will appear when you get to the bottom(such as twitter).

This is what my code looked like for twitter:

```<code>account_names = []
account_tags = []
account_link = []

def scroll():

SCROLL_PAUSE_TIME = 1
global account_name

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)
    account_name = driver.find_elements_by_xpath('//*[@id="react-root"]/div/div/div/main/div/div/div/div/div/div[2]/div/div/section/div/div/div/div/div/div/div/div[2]/div[1]/div[1]/a/div/div[1]/div[1]/span/span')
    for act_name in account_name:
        global acctname
        acctname = act_name.text
        account_names.append(acctname)

    account_handle = driver.find_elements_by_xpath('//*[@id="react-root"]/div/div/div/main/div/div/div/div/div/div[2]/div/div/section/div/div/div/div/div/div/div/div[2]/div[1]/div[1]/a/div/div[2]/div/span')
    for act_handle in account_handle:
        global account_tags
        acct_handles = act_handle.text
        account_tags.append(acct_handles)

    soup = BeautifulSoup(driver.page_source, 'lxml')
    account_links = soup.find_all('a', href=True, class_='css-4rbku5 css-18t94o4 css-1dbjc4n r-1loqt21 r-1wbh5a2 r-dnmrzs r-1ny4l3l')
    for acct_links in account_links:
        global act_link
        act_link = acct_links['href']
        account_link.append(act_link)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

scroll()
</code>```

Just a note: as another user commented, Instagram is very difficult to scrape because of the dynamic html variables, so they would be correct to say no one, myself included is too interested in writing that for instagram.

Body:
my previous questions was closed, but the suggested answer doesn't help me. Instagram comments has a very specific behaviour! I know how to programatically scroll a website down, but with the comments on Instagram is a bit different! I would appreciate if my question was not closed immediately because it really doesn't help. Woule ba grateful for help and not shutting me down! Thank you.

Here it is again:
I am trying to build a scraper that is saving the comments under an Instagram post. I manage to log in to the instagram through my code so I can access all comments under a post, but I seem to cannot scroll down enough times to view all comments in order to scrape all of them. I only get around 20 comments everytime.

Can anyone please help me? I am using selenium webdriver.

Thank you for your help in advance! Will be greatfull.

This is my function for saving the comments:

import time
from selenium.webdriver.firefox.options import Options
from selenium.webdriver import Firefox
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

class Instagram_comments():
    def __init__(self):
        self.firefox_options = Options()
        self.browser = Firefox(options=self.firefox_options)

    def get_comments(self, url):
        self.browser.get(url)
        time.sleep(3)

        while True:
        try:
            self.load_more_comments = self.browser.find_element_by_class_name(
                    'glyphsSpriteCircle_add__outline__24__grey_9')
            self.action = ActionChains(self.browser)
            self.action.move_to_element(self.load_more_comments)
            self.load_more_comments.click()
            time.sleep(4)
            self.body_elem = self.browser.find_element_by_class_name('Mr508')
            for _ in range(100):
                self.body_elem.send_keys(Keys.END)
                time.sleep(3)
        except Exception as e:
            pass

        time.sleep(5)
        self.comment = self.browser.find_elements_by_class_name('gElp9 ')
        for c in self.comment:
            self.container = c.find_element_by_class_name('C4VMK')
            self.name = self.container.find_element_by_class_name('_6lAjh').text
            self.content = self.container.find_element_by_tag_name('span').text
            self.content = self.content.replace('\n', ' ').strip().rstrip()
            self.time_of_post = self.browser.find_element_by_xpath('//a/time').get_attribute("datetime")
            self.comment_details = {'profile name': self.name, 'comment': self.content, 'time': self.time_of_post}
            print(self.comment_details)
            time.sleep(5)

    return self.comment_details

Body:
This chunk worked multiple times for me:

def scroll():

SCROLL_PAUSE_TIME = 1

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)
    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
        print('page height:', new_height)
    last_height = new_height
scroll()

and for some sites you will need to scrape as you scroll as not all elements will appear when you get to the bottom(such as twitter).

This is what my code looked like for twitter:

account_names = []
account_tags = []
account_link = []

def scroll():

SCROLL_PAUSE_TIME = 1
global account_name

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)
    account_name = driver.find_elements_by_xpath('//*[@id="react-root"]/div/div/div/main/div/div/div/div/div/div[2]/div/div/section/div/div/div/div/div/div/div/div[2]/div[1]/div[1]/a/div/div[1]/div[1]/span/span')
    for act_name in account_name:
        global acctname
        acctname = act_name.text
        account_names.append(acctname)

    account_handle = driver.find_elements_by_xpath('//*[@id="react-root"]/div/div/div/main/div/div/div/div/div/div[2]/div/div/section/div/div/div/div/div/div/div/div[2]/div[1]/div[1]/a/div/div[2]/div/span')
    for act_handle in account_handle:
        global account_tags
        acct_handles = act_handle.text
        account_tags.append(acct_handles)

    soup = BeautifulSoup(driver.page_source, 'lxml')
    account_links = soup.find_all('a', href=True, class_='css-4rbku5 css-18t94o4 css-1dbjc4n r-1loqt21 r-1wbh5a2 r-dnmrzs r-1ny4l3l')
    for acct_links in account_links:
        global act_link
        act_link = acct_links['href']
        account_link.append(act_link)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

scroll()

Just a note: as another user commented, Instagram is very difficult to scrape because of the dynamic html variables, so they would be correct to say no one, myself included is too interested in writing that for instagram.


问:
Logic with classes in jenkins pipeline doesn't work
I'm trying to create a jenkins pipeline that takes the latest version of a project and use it's artifacts (like docker images) for end-to-end tests.

The pipeline might look complicated but it's rather simple. The ProjectVersion class is there for sorting the versions. The most complex part is in compareTo method which is meant to be used when selecting the greatest versions (there was going to be more complex logic with regex matching later on)

There is commented out part with sorting because it fails with it when is used.

The pipeline:

```<code>class ProjectVersion implements Comparable<ProjectVersion>, Serializable {

    private String version;

    public final String get() {
        return this.version;
    }

    public ProjectVersion(String version) {
        this.version = version;
    }

    public int compareTo(ProjectVersion that) {
        if(that == null)
            return 1;
        String[] thisParts = this.get().split("\\.");
        String[] thatParts = that.get().split("\\.");
        int length = Math.max(thisParts.length, thatParts.length);
        for(int i = 0; i < length; i++) {
            int thisPart = i < thisParts.length ?
                    tryToParse(thisParts[i]) : 0;
            int thatPart = i < thatParts.length ?
                    tryToParse(thatParts[i]) : 0;
            if(thisPart < thatPart)
                return -1;
            if(thisPart > thatPart)
                return 1;
        }
        return 0;
    }

    private int tryToParse(String part) {
        try {
            return Integer.parseInt(part)
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    boolean equals(Object that) {
        if(this == that)
            return true;
        if(that == null)
            return false;
        if(this.getClass() != that.getClass())
            return false;
        return this.compareTo((ProjectVersion) that) == 0;
    }

    @Override
    public String toString() {
        return "ProjectVersion{" +
                "version='" + version + '\'' +
                '}';
    }
}

def getJSON(url) {
    sh(returnStdout: true, script: "curl -s ${url} 2>&1 | tee result.json")
    readFile('result.json').trim()
}

def getVersions(String url) {
    def json =   readJSON text: getJSON(url)
    def allVersions = json.children.findAll { child -> child.folder }
            .collect { it.uri.substring(1).trim() }
    return sort(allVersions)
}

@NonCPS
def sort(allVersions) {
    return allVersions
            .collect { it-> new ProjectVersion(it) }
//            .sort{it1, it2 -> it1.compareTo(it2)}
//            .reverse()

}

def getVersions() {
    def versions = getVersions(MVN_ARTIFACTORY)
    println(versions.toString())
    def lastVersion = versions.iterator().next()
    println(lastVersion.toString())
    versions
}

pipeline {
    agent {
        label JENKINS_NODES
    }
    stages {
        stage('Get the right version') {
            steps {
                getVersions()
            }
        }
    }
</code>```

The result:

```<code>// not important stuff here

+ curl -s ************************ // not important
+ tee result.json
[Pipeline] readFile
[Pipeline] readJSON
[Pipeline] echo
ProjectVersion{version='1.5.10'}
[Pipeline] echo
ProjectVersion{version='1.5.10'}
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
</code>```

The first echo should print all versions in collection - yet the variable is obviously instance of the ProjectVersion class not a list. How is it even possible?

I was trying to play around with @NonCPS annotation but with no luck.

I'm quite sure that the groovy code part is working. When I try to run it from groovy console (and replace json parsing to new groovy.json.JsonSlurper().parseText(new URL(url).getText())) it works. The expected result (without sorting) is:

```<code>[ProjectVersion{version='1.5.10'}, ProjectVersion{version='1.5.11'}, ProjectVersion{version='1.6.0.31'}, ProjectVersion{version='1.6.0.32'}, ProjectVersion{version='1.6.0.33'}, ProjectVersion{version='1.6.0.34'}, ProjectVersion{version='1.6.0.35'}, ProjectVersion{version='1.6.0.36'}, ProjectVersion{version='2.0.0'}, ProjectVersion{version='2.0.10'}]
</code>```

Thank you for you help.

Frank

答:
There is a @NonCPS annotation missing for your toString method:

```<code>@Override @NonCPS
public String toString() {
    return "ProjectVersion{" +
            "version='" + version + '\'' +
            '}';
}
</code>```

Body:
I'm trying to create a jenkins pipeline that takes the latest version of a project and use it's artifacts (like docker images) for end-to-end tests.

The pipeline might look complicated but it's rather simple. The ProjectVersion class is there for sorting the versions. The most complex part is in compareTo method which is meant to be used when selecting the greatest versions (there was going to be more complex logic with regex matching later on)

There is commented out part with sorting because it fails with it when is used.

The pipeline:

class ProjectVersion implements Comparable<ProjectVersion>, Serializable {

    private String version;

    public final String get() {
        return this.version;
    }

    public ProjectVersion(String version) {
        this.version = version;
    }

    public int compareTo(ProjectVersion that) {
        if(that == null)
            return 1;
        String[] thisParts = this.get().split("\\.");
        String[] thatParts = that.get().split("\\.");
        int length = Math.max(thisParts.length, thatParts.length);
        for(int i = 0; i < length; i++) {
            int thisPart = i < thisParts.length ?
                    tryToParse(thisParts[i]) : 0;
            int thatPart = i < thatParts.length ?
                    tryToParse(thatParts[i]) : 0;
            if(thisPart < thatPart)
                return -1;
            if(thisPart > thatPart)
                return 1;
        }
        return 0;
    }

    private int tryToParse(String part) {
        try {
            return Integer.parseInt(part)
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    boolean equals(Object that) {
        if(this == that)
            return true;
        if(that == null)
            return false;
        if(this.getClass() != that.getClass())
            return false;
        return this.compareTo((ProjectVersion) that) == 0;
    }

    @Override
    public String toString() {
        return "ProjectVersion{" +
                "version='" + version + '\'' +
                '}';
    }
}

def getJSON(url) {
    sh(returnStdout: true, script: "curl -s ${url} 2>&1 | tee result.json")
    readFile('result.json').trim()
}

def getVersions(String url) {
    def json =   readJSON text: getJSON(url)
    def allVersions = json.children.findAll { child -> child.folder }
            .collect { it.uri.substring(1).trim() }
    return sort(allVersions)
}

@NonCPS
def sort(allVersions) {
    return allVersions
            .collect { it-> new ProjectVersion(it) }
//            .sort{it1, it2 -> it1.compareTo(it2)}
//            .reverse()

}

def getVersions() {
    def versions = getVersions(MVN_ARTIFACTORY)
    println(versions.toString())
    def lastVersion = versions.iterator().next()
    println(lastVersion.toString())
    versions
}

pipeline {
    agent {
        label JENKINS_NODES
    }
    stages {
        stage('Get the right version') {
            steps {
                getVersions()
            }
        }
    }

The result:

// not important stuff here

+ curl -s ************************ // not important
+ tee result.json
[Pipeline] readFile
[Pipeline] readJSON
[Pipeline] echo
ProjectVersion{version='1.5.10'}
[Pipeline] echo
ProjectVersion{version='1.5.10'}
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline

The first echo should print all versions in collection - yet the variable is obviously instance of the ProjectVersion class not a list. How is it even possible?

I was trying to play around with @NonCPS annotation but with no luck.

I'm quite sure that the groovy code part is working. When I try to run it from groovy console (and replace json parsing to new groovy.json.JsonSlurper().parseText(new URL(url).getText())) it works. The expected result (without sorting) is:

[ProjectVersion{version='1.5.10'}, ProjectVersion{version='1.5.11'}, ProjectVersion{version='1.6.0.31'}, ProjectVersion{version='1.6.0.32'}, ProjectVersion{version='1.6.0.33'}, ProjectVersion{version='1.6.0.34'}, ProjectVersion{version='1.6.0.35'}, ProjectVersion{version='1.6.0.36'}, ProjectVersion{version='2.0.0'}, ProjectVersion{version='2.0.10'}]

Thank you for you help.

Frank

Body:
There is a @NonCPS annotation missing for your toString method:

@Override @NonCPS
public String toString() {
    return "ProjectVersion{" +
            "version='" + version + '\'' +
            '}';
}


问:
Handling paper documentation
After every new program written a lot of paper documentation remains.

Apart from the usual scribble notes from the programmers there usually is a nice heap of papers containing physical model explanations, calculations and so on (equations, tables, graphs, little pictures describing variables ...)

We usually do numerically intensive calculations in console applications, which are not released to the public (remain in the house, only results go out). Before each project is finished all those papers have to be packed somehow with the application, so that one day, when someone will be reusing parts of it, has some idea what is what in there.
So far, we've been using the 'dirty' solution of just scanning all of it, and packing it up on the disc with the application.

So I was wondering ... for all science guys here in a similar situation ... how do you handle project documentation which is needed, but not released to the public ?
(the one that does, goes to the dtp laddies, and they make it nice and shiny - not our problem anymore :)

答:
I use one of three options:

Keep everything in my lab notebooks, which I archive myself, for low-level stuff

Scan the paper document, and add to source control in pdf. It's ugly, but if someone needs it, it's there

Transcribe the equations, results, etc... in a clean format (usually Latex) for future reference, and again, add to source control. Official paper copy gets signed (I work in a highly regulated domain) and filed in a binder.

ContentLicense: CC BY-SA 2.5

Title: Handling paper documentation

OwnerDisplayName: Kena


问:
Play! framework CRUD module: adding default values and change date format?
I'm using Play! frameworks CRUD module but I can't figure something out: my database table has a created field which is basically the time that a row was created. I don't want my user to set this, I want to do it in the backend, simply add the current time. I can't figure out how to do this though.

I have made the field invisible using @Hidden but obviously now I can't create new rows because it's value simply isn't set. So where do I do this?

And another question I have: my table also has a column called publish which is another timestamp. The current format for this field in the CRUD form is yyyy-MM-dd. I would like the specify a date as well, and can't figure out how..

Can someone help?

答:
you can use custom field rendering in CRUD templates to display the values formatted or using any control you want (i.e.: a jquery date picker for dates).

To hide a value and assign a default value, first of all remove the value from the edit/blank forms of CRUD by removing the field. Then override the _save() method from the entity (be careful with the initial _, you want the _save(), not save()) and set in the code the values you want before calling super._save(). Like this:

```<code>/* Return value may differ */
public void _save() {
   current = new Date();
   super._save();
}
</code>```

Body:
you can use custom field rendering in CRUD templates to display the values formatted or using any control you want (i.e.: a jquery date picker for dates).

To hide a value and assign a default value, first of all remove the value from the edit/blank forms of CRUD by removing the field. Then override the _save() method from the entity (be careful with the initial _, you want the _save(), not save()) and set in the code the values you want before calling super._save(). Like this:

/* Return value may differ */
public void _save() {
   current = new Date();
   super._save();
}


问:
"Please upgrade your dependency to build_web_compilers: ">=2.0.0", but it already is
I have an AngularDart-based web project. When I'm try webdev serve, I get this:

```<code>[SEVERE] Support for dartdevc in build_web_compilers < 2.0.0 has been removed.

Please upgrade your dependency to:

dev_dependencies:
  build_web_compilers: ">=2.0.0"

[SEVERE] Exception: dartdevc is no longer supported by this version
</code>```

However, I already have the dependency set to "2.0.0 and newer". Here is my pubspec.yaml file:

```<code>name: myproject
description: My Description

environment:
  sdk: '>=2.3.3 <3.0.0'

dependencies:
  angular: ^5.2.0
  angular_components: ^0.13.0

dev_dependencies:
  angular_test: ^2.2.0
  build_runner: ^1.5.0
  build_test: ^0.10.3
  build_web_compilers: ^2.0.0
  pedantic: ^1.0.0
  test: ^1.5.1
</code>```

I tried pub get, pub upgrade, pub activate global webdev, even pub cache repair.
In general, I seem to have problems with dependencies when creating AngularDart projects, even when I use versions from the Dart docs. Is there a magic way to know exactly which version numbers to use?

答:
Try deleting your .dart_tool directory, rerun pub get and try again.

That directory is where dart stores all of the dependencies and artifacts of the build process.  Sometimes it can get in an odd state.

Whenever your Dart build is misbehaving in ways that defy explanation, it is good practice to delete the .dart_tool directory first and build clean to see if that fixes it.

Body:
I have an AngularDart-based web project. When I'm try webdev serve, I get this:

[SEVERE] Support for dartdevc in build_web_compilers < 2.0.0 has been removed.

Please upgrade your dependency to:

dev_dependencies:
  build_web_compilers: ">=2.0.0"

[SEVERE] Exception: dartdevc is no longer supported by this version

However, I already have the dependency set to "2.0.0 and newer". Here is my pubspec.yaml file:

name: myproject
description: My Description

environment:
  sdk: '>=2.3.3 <3.0.0'

dependencies:
  angular: ^5.2.0
  angular_components: ^0.13.0

dev_dependencies:
  angular_test: ^2.2.0
  build_runner: ^1.5.0
  build_test: ^0.10.3
  build_web_compilers: ^2.0.0
  pedantic: ^1.0.0
  test: ^1.5.1

I tried pub get, pub upgrade, pub activate global webdev, even pub cache repair.
In general, I seem to have problems with dependencies when creating AngularDart projects, even when I use versions from the Dart docs. Is there a magic way to know exactly which version numbers to use?


问:
Replace dot in a specific column
I have the DF:

```<code>KEY <- c(12,55,889)
FOOD <- c("RICE","TOMATO","MANGO")
CAR <- c("BMW.3","FERRARI.12","TOYOTA.58")
DF <- data.frame(KEY,FOOD,CAR)
</code>```

How do I replace the dot in the "CAR" column?

I expect this result

```<code>    KEY <- c(12,55,889)
    FOOD <- c("RICE","TOMATO","MANGO")
    CAR <- c("BMW3","FERRARI12","TOYOTA58")
    DF <- data.frame(KEY,FOOD,CAR)
</code>```

Title: Replace dot in a specific column

Body:
I have the DF:

KEY <- c(12,55,889)
FOOD <- c("RICE","TOMATO","MANGO")
CAR <- c("BMW.3","FERRARI.12","TOYOTA.58")
DF <- data.frame(KEY,FOOD,CAR)

How do I replace the dot in the "CAR" column?

I expect this result

    KEY <- c(12,55,889)
    FOOD <- c("RICE","TOMATO","MANGO")
    CAR <- c("BMW3","FERRARI12","TOYOTA58")
    DF <- data.frame(KEY,FOOD,CAR)

Body:
gsub("\\.","",CAR)
[1] "BMW3"      "FERRARI12" "TOYOTA58"


问:
How to get bind value in vue js?
I am having difficulty to get model.title's value and display it into console when click event triggered. For example,there is total 3 records into my json file.The first model's title name is IRIS.When I click on link then I want to also display it on console. Can anyone help me please.

```<code><div id="app">

            <div v-for="model in myData">

          <h1>{{model.title}}</h1>
          <p>{{model.project}}</p>
          <p>{{model.bedrooms}}</p>
          <a href="#" @click="getTitle">View Detail</a>

        </div>

    </div>

 var vm = new Vue({

        el:'#app',
        data:{
            myData:[]

        },
        created:function(){
        this.fetchData();
        this.getTitle();
         },

        methods:{
        fetchData: function(){
        var url='data.json';
        axios.get(url)
        .then(function(res){
        vm.myData= res.data.models;
        console.log(this.myData);

        });
     },
     getTitle:function() {
        var url='j.json';
        axios.get(url)
        .then(function(res){
        //vm.myData= res.data.models.getTitle;
        console.log(res.data.models.getTitle);

        });

     }

}

    });
</code>```

The below code is from data.json file

```<code>{
    "models": [
      {
        "title": "IRIS",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 3

      },
      {
        "title": "LILAC",
        "project": "ABC",
        "category": "DOUBLE",
        "bedrooms": 4

      },
      {
        "title": "ASTER",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 4

      }
    ]
  }
</code>```

答:
You can just do:

```<code><div id="app">
  <div v-for="model in myData">
    <h1>{{model.title}}</h1>
    <p>{{model.project}}</p>
    <p>{{model.bedrooms}}</p>
    <a href="#" @click="getTitle(model)">View Detail</a>
  </div>
</div>

var vm = new Vue({
  el:'#app',
  data(){
    return {
      myData:[]
    }
  },
  created () {
    this.fetchData();
  },
  methods:{
    fetchData () {
      let vm = this;
      var url='data.json';
      axios.get(url)
       .then(function(res){
         vm.myData = res.data.models;
         console.log(vm.myData);
       });
    },
    getTitle (model) {
      console.log(model.title)
    }
  }
});
</code>```

Just change some of your code. You can take model as parameter in getTitle function. You dont have to call it in mounted hook

Title: How to get bind value in vue js?

Body:
I am having difficulty to get model.title's value and display it into console when click event triggered. For example,there is total 3 records into my json file.The first model's title name is IRIS.When I click on link then I want to also display it on console. Can anyone help me please.

{{model.title}}

{{model.project}}

{{model.bedrooms}}

          View Detail

 var vm = new Vue({

        el:'#app',
        data:{
            myData:[]

        },
        created:function(){
        this.fetchData();
        this.getTitle();
         },

        methods:{
        fetchData: function(){
        var url='data.json';
        axios.get(url)
        .then(function(res){
        vm.myData= res.data.models;
        console.log(this.myData);

        });
     },
     getTitle:function() {
        var url='j.json';
        axios.get(url)
        .then(function(res){
        //vm.myData= res.data.models.getTitle;
        console.log(res.data.models.getTitle);

        });

     }

}

    });

The below code is from data.json file

{
    "models": [
      {
        "title": "IRIS",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 3

      },
      {
        "title": "LILAC",
        "project": "ABC",
        "category": "DOUBLE",
        "bedrooms": 4

      },
      {
        "title": "ASTER",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 4

      }
    ]
  }

Body:
You can just do:

<div id="app">
  <div v-for="model in myData">
    <h1>{{model.title}}</h1>
    <p>{{model.project}}</p>
    <p>{{model.bedrooms}}</p>
    <a href="#" @click="getTitle(model)">View Detail</a>
  </div>
</div>

var vm = new Vue({
  el:'#app',
  data(){
    return {
      myData:[]
    }
  },
  created () {
    this.fetchData();
  },
  methods:{
    fetchData () {
      let vm = this;
      var url='data.json';
      axios.get(url)
       .then(function(res){
         vm.myData = res.data.models;
         console.log(vm.myData);
       });
    },
    getTitle (model) {
      console.log(model.title)
    }
  }
});

Just change some of your code. You can take model as parameter in getTitle function. You dont have to call it in mounted hook


问:
Scipy interpolate on structured 2d data, but evaluate at unstructured points?
I have the following minimum code using scipy.interpolate.interp2d to do interpolation on 2d grid data.

```<code>import numpy as np
from scipy import interpolate
x = np.arange(-5.01, 5.01, 0.25)
y = np.arange(-5.01, 5.01, 0.25)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx**2+yy**2)
f = interpolate.interp2d(x, y, z, kind='cubic')
</code>```

Now f here can be used to evaluate other points. The problem is the points I want to evaluate are totally random points not forming a regular grid.

```<code># Evaluate at point (x_new, y_new), in total 256*256 points
x_new = np.random.random(256*256)
y_new = np.random.random(256*256)
func(x_new, y_new)
</code>```

This will cause a runtime error in my PC, it seems to treat x_new and y_new as mesh grid, generate a evaluation matrix 65536x65536, which is not my purpose.

RuntimeError: Cannot produce output of size 65536x65536 (size too large)

One way to get things done is to evaluate points one by one, using code:

```<code>z_new = np.array([f(i, j) for i, j in zip(x_new, y_new)])
</code>```

However, it is slow!!!

```<code>%timeit z_new = np.array([f(i, j) for i, j in zip(x_new, y_new)])
</code>```

1.26 s ± 46.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Is there any faster way to evaluate random points?

Faster here I mean comparable with time below:

```<code>x_new = np.random.random(256)
y_new = np.random.random(256)

%timeit f(x_new, y_new)
</code>```

Same 256*256 = 65536 evaluations, time for this in my PC:

1.21 ms ± 39.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

It does not have to be in comparable speed with 1.21ms, 121 ms is totally acceptable.

答:
The function you are looking for is scipy.interpolate.RegularGridInterpolator

Given a set of points (x,y,z), where x & y are defined on a regular grid, it allows you to sample the z-value of intermediate (x,y) points. In your case, this would look as follows

```<code>import numpy as np
from scipy import interpolate
x = np.arange(-5.01, 5.01, 0.25)
y = np.arange(-5.01, 5.01, 0.25)

def f(x,y):
    return np.sin(x**2+y**2)

z = f(*np.meshgrid(x, y, indexing='ij', sparse=True))
func = interpolate.RegularGridInterpolator((x,y), z)

x_new = np.random.random(256*256)
y_new = np.random.random(256*256)
xy_new = list(zip(x_new,y_new))
z_new = func(xy_new)func(xy_new)
</code>```

For more details, see https://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.interpolate.RegularGridInterpolator.html

Body:
I have the following minimum code using scipy.interpolate.interp2d to do interpolation on 2d grid data.

import numpy as np
from scipy import interpolate
x = np.arange(-5.01, 5.01, 0.25)
y = np.arange(-5.01, 5.01, 0.25)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx**2+yy**2)
f = interpolate.interp2d(x, y, z, kind='cubic')

Now f here can be used to evaluate other points. The problem is the points I want to evaluate are totally random points not forming a regular grid.

# Evaluate at point (x_new, y_new), in total 256*256 points
x_new = np.random.random(256*256)
y_new = np.random.random(256*256)
func(x_new, y_new)

This will cause a runtime error in my PC, it seems to treat x_new and y_new as mesh grid, generate a evaluation matrix 65536x65536, which is not my purpose.

RuntimeError: Cannot produce output of size 65536x65536 (size too large)

One way to get things done is to evaluate points one by one, using code:

z_new = np.array([f(i, j) for i, j in zip(x_new, y_new)])

However, it is slow!!!

%timeit z_new = np.array([f(i, j) for i, j in zip(x_new, y_new)])

1.26 s ± 46.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Is there any faster way to evaluate random points?

Faster here I mean comparable with time below:

x_new = np.random.random(256)
y_new = np.random.random(256)

%timeit f(x_new, y_new)

Same 256*256 = 65536 evaluations, time for this in my PC:

1.21 ms ± 39.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

It does not have to be in comparable speed with 1.21ms, 121 ms is totally acceptable.

Body:
The function you are looking for is scipy.interpolate.RegularGridInterpolator

Given a set of points (x,y,z), where x & y are defined on a regular grid, it allows you to sample the z-value of intermediate (x,y) points. In your case, this would look as follows

import numpy as np
from scipy import interpolate
x = np.arange(-5.01, 5.01, 0.25)
y = np.arange(-5.01, 5.01, 0.25)

def f(x,y):
    return np.sin(x**2+y**2)

z = f(*np.meshgrid(x, y, indexing='ij', sparse=True))
func = interpolate.RegularGridInterpolator((x,y), z)

x_new = np.random.random(256*256)
y_new = np.random.random(256*256)
xy_new = list(zip(x_new,y_new))
z_new = func(xy_new)func(xy_new)

For more details, see https://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.interpolate.RegularGridInterpolator.html


问:
PostgreSQL: dump and restore
I use EMS SQL Manager for PostgreSQL and I need to dump difficult database(domains, 300+ stored procedures/functions, triggers, data, etc).
This tool cannot do it.

Please advice me good GUI tool for postgres.

答: pg_dump -U uguryilmaz modaltrans_dev > backup.sql</p>

Title: PostgreSQL: dump and restore


问:
How to position 2 text components at the end of a view in RN?
I want to achieve this result

But this is the current behaviour

As you can notice both Text components aren't aligned correctly.

This is the code

```<code><View style={{ flexDirection: 'row', marginRight: 7, borderWidth: 2 }}>
     <Text style={{ color: '#0022FF', fontWeight: 'bold', fontSize: 20, alignSelf: 'flex-end', marginRight: 5 }}>2.6</Text>
     <Text style={{ color: '#0022FF', fontSize: 9, alignSelf: 'flex-end' }}>Bar</Text>
</View>
</code>```

Can you guys help me with this ?

答:
I think it should work if you wrap both texts inside another <Text> component like so:

```<code><View style={{ flexDirection: 'row', marginRight: 7, borderWidth: 2 }}>
  <Text>
     <Text style={{ color: '#0022FF', fontWeight: 'bold', fontSize: 20, alignSelf: 'flex-end', marginRight: 5 }}>2.6</Text>
     <Text style={{ color: '#0022FF', fontSize: 9, alignSelf: 'flex-end' }}>Bar</Text>
  </Text>
</View>
</code>```

Body:
I want to achieve this result

But this is the current behaviour

As you can notice both Text components aren't aligned correctly.

This is the code

<View style={{ flexDirection: 'row', marginRight: 7, borderWidth: 2 }}>
     <Text style={{ color: '#0022FF', fontWeight: 'bold', fontSize: 20, alignSelf: 'flex-end', marginRight: 5 }}>2.6</Text>
     <Text style={{ color: '#0022FF', fontSize: 9, alignSelf: 'flex-end' }}>Bar</Text>
</View>

Can you guys help me with this ?

Body:
I think it should work if you wrap both texts inside another <Text> component like so:

<View style={{ flexDirection: 'row', marginRight: 7, borderWidth: 2 }}>
  <Text>
     <Text style={{ color: '#0022FF', fontWeight: 'bold', fontSize: 20, alignSelf: 'flex-end', marginRight: 5 }}>2.6</Text>
     <Text style={{ color: '#0022FF', fontSize: 9, alignSelf: 'flex-end' }}>Bar</Text>
  </Text>
</View>


问:
Docker is not recognizing a directory as directory in Arch Linux
Basically, I'm getting this error when I try to create my containers:

```<code>docker: Error response from daemon: OCI runtime create failed: container_linux.go:337: starting container process caused "process_linux.go:403: container init caused \"rootfs_linux.go:58: mounting \\\"/etc/timezone\\\" to rootfs \\\"/var/lib/docker/overlay2/8864cea6615c7c165fce558661bf297c43ebf90f4de534ca9c9bd38f7af8b487/merged\\\" at \\\"/var/lib/docker/overlay2/8864cea6615c7c165fce558661bf297c43ebf90f4de534ca9c9bd38f7af8b487/merged/etc/timezone\\\" caused \\\"not a directory\\\"\"": unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type.
</code>```

No Idea why this is happening. It was working perfectly on Manjaro, but not working on Arch Labs.

答:
The image used expects a directory at /etc/timezone that is not used on Arch Linux.

Expected /etc/timezone contents example:

```<code>Etc/UTC
</code>```

Simply remove that bind mount from your command or docker-compose file. You need to set the timezone at in the container differently or find a way to keep the /etc/timezone file in sync with /etc/localtime.

/etc/timezone is a Solaris and Debian thing, I guess. It expects the timezone as a pair

```<code>Europe/Zürich
</code>```

Body:
Basically, I'm getting this error when I try to create my containers:

docker: Error response from daemon: OCI runtime create failed: container_linux.go:337: starting container process caused "process_linux.go:403: container init caused \"rootfs_linux.go:58: mounting \\\"/etc/timezone\\\" to rootfs \\\"/var/lib/docker/overlay2/8864cea6615c7c165fce558661bf297c43ebf90f4de534ca9c9bd38f7af8b487/merged\\\" at \\\"/var/lib/docker/overlay2/8864cea6615c7c165fce558661bf297c43ebf90f4de534ca9c9bd38f7af8b487/merged/etc/timezone\\\" caused \\\"not a directory\\\"\"": unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type.

No Idea why this is happening. It was working perfectly on Manjaro, but not working on Arch Labs.

Body:
The image used expects a directory at /etc/timezone that is not used on Arch Linux.

Expected /etc/timezone contents example:

Etc/UTC

Simply remove that bind mount from your command or docker-compose file. You need to set the timezone at in the container differently or find a way to keep the /etc/timezone file in sync with /etc/localtime.

/etc/timezone is a Solaris and Debian thing, I guess. It expects the timezone as a pair

Europe/Zürich


问:
Angular CLI installation Failure - spawn C:\Windows\System32\cmd.exe; ENOENT
I was able to install nodejs version v10.7.0 and npm version 6.1.0 without any issues. Also installed angular 1.7.2 and typescript 2.9.2.I am getting this below error on trying to install npm install -g @angular/cli@latest.

I have tried all of the debug steps I could find online, including force clearing the cache and installing and uninstalling nodejs and adding my system32 folder to the PATH variable. Mostly followed this article I thought was very helpful - How do you install angular-cli for windows 7

```<code>7904 info lifecycle @schematics/angular@0.6.8~postinstall: @schematics/angular@0.6.8
7905 silly postinstall @schematics/update@0.6.8
7906 info lifecycle @schematics/update@0.6.8~postinstall: @schematics/update@0.6.8
7907 silly postinstall opn@5.3.0
7908 info lifecycle opn@5.3.0~postinstall: opn@5.3.0
7909 silly postinstall resolve@1.8.1
7910 info lifecycle resolve@1.8.1~postinstall: resolve@1.8.1
7911 silly postinstall silent-error@1.1.0
7912 info lifecycle silent-error@1.1.0~postinstall: silent-error@1.1.0
7913 silly postinstall symbol-observable@1.2.0
7914 info lifecycle symbol-observable@1.2.0~postinstall: symbol-observable@1.2.0
7915 silly postinstall yargs-parser@10.1.0
7916 info lifecycle yargs-parser@10.1.0~postinstall: yargs-parser@10.1.0
7917 silly postinstall @angular/cli@6.0.8
7918 info lifecycle @angular/cli@6.0.8~postinstall: @angular/cli@6.0.8
7919 verbose lifecycle @angular/cli@6.0.8~postinstall: unsafe-perm in lifecycle true
7920 verbose lifecycle @angular/cli@6.0.8~postinstall: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\Nidhin\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\.bin;C:\Users\Nidhin\AppData\Roaming\npm\node_modules\.bin;C:\Windows\System32;C:\Users\Nidhin\AppData\Local\Programs\Python\Python37\Scripts\;C:\Users\Nidhin\AppData\Local\Programs\Python\Python37\;C:\Users\Nidhin\AppData\Local\Programs\Fiddler;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\nodejs\;C:\Users\Nidhin\AppData\Roaming\npm;C:\Windows\System32;C:\Windows\System32;C:\Users\Nidhin\AppData\Local\Programs\Python\Python37\Scripts\;C:\Users\Nidhin\AppData\Local\Programs\Python\Python37\;C:\Users\Nidhin\AppData\Local\Programs\Fiddler;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\nodejs\;C:\Users\Nidhin\AppData\Roaming\npm;C:\Windows\System32;C:\WINDOWS/system32/WindowsPowerShell/v1.0
7921 verbose lifecycle @angular/cli@6.0.8~postinstall: CWD: C:\Users\Nidhin\AppData\Roaming\npm\node_modules\@angular\cli
7922 silly lifecycle @angular/cli@6.0.8~postinstall: Args: [ '/d /s /c', 'node ./bin/ng-update-message.js' ]
7923 info lifecycle @angular/cli@6.0.8~postinstall: Failed to exec postinstall script
7924 silly lifecycle @angular/cli@6.0.8~postinstall: Returned: code: -4058  signal: null
7925 info lifecycle @angular/cli@6.0.8~postinstall: Failed to exec postinstall script
7926 timing action:postinstall Completed in 679ms
7927 verbose unlock done using C:\Users\Nidhin\AppData\Roaming\npm-cache\_locks\staging-2479c5e9a87c27dd.lock for C:\Users\Nidhin\AppData\Roaming\npm\node_modules\.staging
7928 warn rollback Rolling back is-descriptor@1.0.2 failed (this is probably harmless): EPERM: operation not permitted, lstat 'C:\Users\Nidhin\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\define-property\node_modules'
7929 warn rollback Rolling back is-extendable@1.0.1 failed (this is probably harmless): EPERM: operation not permitted, lstat 'C:\Users\Nidhin\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\mixin-deep\node_modules'
7930 warn rollback Rolling back define-property@1.0.0 failed (this is probably harmless): EPERM: operation not permitted, lstat 'C:\Users\Nidhin\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\snapdragon-node\node_modules'
7931 warn rollback Rolling back kind-of@3.2.2 failed (this is probably harmless): EPERM: operation not permitted, lstat 'C:\Users\Nidhin\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\to-object-path\node_modules'
7932 timing stage:rollbackFailedOptional Completed in 3584ms
7933 timing stage:runTopLevelLifecycles Completed in 135690ms
7934 warn optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\@angular\cli\node_modules\fsevents):
7935 warn notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
7936 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Valid OS:    darwin
7936 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Valid Arch:  any
7936 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Actual OS:   win32
7936 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Actual Arch: x64
7937 verbose stack Error: @angular/cli@6.0.8 postinstall: `node ./bin/ng-update-message.js`
7937 verbose stack spawn C:\Windows\System32\cmd.exe; ENOENT
7937 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:229:19)
7937 verbose stack     at onErrorNT (internal/child_process.js:406:16)
7937 verbose stack     at process._tickCallback (internal/process/next_tick.js:63:19)
7938 verbose pkgid @angular/cli@6.0.8
7939 verbose cwd C:\WINDOWS\system32
7940 verbose Windows_NT 6.1.7601
7941 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "@angular/cli@latest"
7942 verbose node v10.7.0
7943 verbose npm  v6.1.0
7944 error file C:\Windows\System32\cmd.exe;
7945 error path C:\Windows\System32\cmd.exe;
7946 error code ELIFECYCLE
7947 error errno ENOENT
7948 error syscall spawn C:\Windows\System32\cmd.exe;
7949 error @angular/cli@6.0.8 postinstall: `node ./bin/ng-update-message.js`
7949 error spawn C:\Windows\System32\cmd.exe; ENOENT
7950 error Failed at the @angular/cli@6.0.8 postinstall script.
7950 error This is probably not a problem with npm. There is likely additional logging output above.
7951 verbose exit [ 1, true ]
</code>```

答:
Go to

```<code>My Computer -> properties -> Advance -> Environment Variables -> System Variables
</code>```

click on ComSpec and then click the edit button at the bottom
and set the path of "ComSpec" equal to C:\Windows\System32\cmd.exe.

Body:
I was able to install nodejs version v10.7.0 and npm version 6.1.0 without any issues. Also installed angular 1.7.2 and typescript 2.9.2.I am getting this below error on trying to install npm install -g @angular/cli@latest.

I have tried all of the debug steps I could find online, including force clearing the cache and installing and uninstalling nodejs and adding my system32 folder to the PATH variable. Mostly followed this article I thought was very helpful - How do you install angular-cli for windows 7

7904 info lifecycle @schematics/angular@0.6.8~postinstall: @schematics/angular@0.6.8
7905 silly postinstall @schematics/update@0.6.8
7906 info lifecycle @schematics/update@0.6.8~postinstall: @schematics/update@0.6.8
7907 silly postinstall opn@5.3.0
7908 info lifecycle opn@5.3.0~postinstall: opn@5.3.0
7909 silly postinstall resolve@1.8.1
7910 info lifecycle resolve@1.8.1~postinstall: resolve@1.8.1
7911 silly postinstall silent-error@1.1.0
7912 info lifecycle silent-error@1.1.0~postinstall: silent-error@1.1.0
7913 silly postinstall symbol-observable@1.2.0
7914 info lifecycle symbol-observable@1.2.0~postinstall: symbol-observable@1.2.0
7915 silly postinstall yargs-parser@10.1.0
7916 info lifecycle yargs-parser@10.1.0~postinstall: yargs-parser@10.1.0
7917 silly postinstall @angular/cli@6.0.8
7918 info lifecycle @angular/cli@6.0.8~postinstall: @angular/cli@6.0.8
7919 verbose lifecycle @angular/cli@6.0.8~postinstall: unsafe-perm in lifecycle true
7920 verbose lifecycle @angular/cli@6.0.8~postinstall: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\Nidhin\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\.bin;C:\Users\Nidhin\AppData\Roaming\npm\node_modules\.bin;C:\Windows\System32;C:\Users\Nidhin\AppData\Local\Programs\Python\Python37\Scripts\;C:\Users\Nidhin\AppData\Local\Programs\Python\Python37\;C:\Users\Nidhin\AppData\Local\Programs\Fiddler;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\nodejs\;C:\Users\Nidhin\AppData\Roaming\npm;C:\Windows\System32;C:\Windows\System32;C:\Users\Nidhin\AppData\Local\Programs\Python\Python37\Scripts\;C:\Users\Nidhin\AppData\Local\Programs\Python\Python37\;C:\Users\Nidhin\AppData\Local\Programs\Fiddler;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\nodejs\;C:\Users\Nidhin\AppData\Roaming\npm;C:\Windows\System32;C:\WINDOWS/system32/WindowsPowerShell/v1.0
7921 verbose lifecycle @angular/cli@6.0.8~postinstall: CWD: C:\Users\Nidhin\AppData\Roaming\npm\node_modules\@angular\cli
7922 silly lifecycle @angular/cli@6.0.8~postinstall: Args: [ '/d /s /c', 'node ./bin/ng-update-message.js' ]
7923 info lifecycle @angular/cli@6.0.8~postinstall: Failed to exec postinstall script
7924 silly lifecycle @angular/cli@6.0.8~postinstall: Returned: code: -4058  signal: null
7925 info lifecycle @angular/cli@6.0.8~postinstall: Failed to exec postinstall script
7926 timing action:postinstall Completed in 679ms
7927 verbose unlock done using C:\Users\Nidhin\AppData\Roaming\npm-cache\_locks\staging-2479c5e9a87c27dd.lock for C:\Users\Nidhin\AppData\Roaming\npm\node_modules\.staging
7928 warn rollback Rolling back is-descriptor@1.0.2 failed (this is probably harmless): EPERM: operation not permitted, lstat 'C:\Users\Nidhin\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\define-property\node_modules'
7929 warn rollback Rolling back is-extendable@1.0.1 failed (this is probably harmless): EPERM: operation not permitted, lstat 'C:\Users\Nidhin\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\mixin-deep\node_modules'
7930 warn rollback Rolling back define-property@1.0.0 failed (this is probably harmless): EPERM: operation not permitted, lstat 'C:\Users\Nidhin\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\snapdragon-node\node_modules'
7931 warn rollback Rolling back kind-of@3.2.2 failed (this is probably harmless): EPERM: operation not permitted, lstat 'C:\Users\Nidhin\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\to-object-path\node_modules'
7932 timing stage:rollbackFailedOptional Completed in 3584ms
7933 timing stage:runTopLevelLifecycles Completed in 135690ms
7934 warn optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\@angular\cli\node_modules\fsevents):
7935 warn notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
7936 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Valid OS:    darwin
7936 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Valid Arch:  any
7936 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Actual OS:   win32
7936 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Actual Arch: x64
7937 verbose stack Error: @angular/cli@6.0.8 postinstall: `node ./bin/ng-update-message.js`
7937 verbose stack spawn C:\Windows\System32\cmd.exe; ENOENT
7937 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:229:19)
7937 verbose stack     at onErrorNT (internal/child_process.js:406:16)
7937 verbose stack     at process._tickCallback (internal/process/next_tick.js:63:19)
7938 verbose pkgid @angular/cli@6.0.8
7939 verbose cwd C:\WINDOWS\system32
7940 verbose Windows_NT 6.1.7601
7941 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "@angular/cli@latest"
7942 verbose node v10.7.0
7943 verbose npm  v6.1.0
7944 error file C:\Windows\System32\cmd.exe;
7945 error path C:\Windows\System32\cmd.exe;
7946 error code ELIFECYCLE
7947 error errno ENOENT
7948 error syscall spawn C:\Windows\System32\cmd.exe;
7949 error @angular/cli@6.0.8 postinstall: `node ./bin/ng-update-message.js`
7949 error spawn C:\Windows\System32\cmd.exe; ENOENT
7950 error Failed at the @angular/cli@6.0.8 postinstall script.
7950 error This is probably not a problem with npm. There is likely additional logging output above.
7951 verbose exit [ 1, true ]

Body:
Go to

My Computer -> properties -> Advance -> Environment Variables -> System Variables

click on ComSpec and then click the edit button at the bottom
and set the path of "ComSpec" equal to C:\Windows\System32\cmd.exe.


问:
UserForm TextBox Font change (Italic back to Default)
I have a text that shows on a textbox that appears when the forms starts and disappears when the user enters the textbox to enter some... text. Well, the problem is that i have it set to Italic but when i turn it off (False), it does not change. Here is the code:</p>

```<code>Private Userform_Initialize

    'Text in italic: "Legajo"
    If TextBox5.Text = "" Then
    TextBox5.Font.Italic = True
    TextBox5.ForeColor = cDimColor
    TextBox5.Text = "Legajo"
    End If

Private Sub TextBox5_Enter()

Dim cStdColor As Long
cStdColor = &H80000008

 If TextBox5 = "Legajo" Then

 TextBox5.Font.Italic = False 'Does not Work
 TextBox5.ForeColor = cStdColor
 TextBox5 = ""

End If
End Sub
</code>```

答:
Use Keyup event.    </p>

```<code>Private Sub TextBox5_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Dim cStdColor As Long
    cStdColor = &H80000008

    If TextBox5 = "Legajo" Then

        TextBox5.Font.Italic = False 'Does not Work
    Else
        TextBox5.Font.Italic = True
    End If
     TextBox5.ForeColor = cStdColor
End Sub
</code>```

Body:
I have a text that shows on a textbox that appears when the forms starts and disappears when the user enters the textbox to enter some... text. Well, the problem is that i have it set to Italic but when i turn it off (False), it does not change. Here is the code:

Private Userform_Initialize

    'Text in italic: "Legajo"
    If TextBox5.Text = "" Then
    TextBox5.Font.Italic = True
    TextBox5.ForeColor = cDimColor
    TextBox5.Text = "Legajo"
    End If

Private Sub TextBox5_Enter()

Dim cStdColor As Long
cStdColor = &H80000008

 If TextBox5 = "Legajo" Then

 TextBox5.Font.Italic = False 'Does not Work
 TextBox5.ForeColor = cStdColor
 TextBox5 = ""

End If
End Sub

Body:
Use Keyup event.

Private Sub TextBox5_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Dim cStdColor As Long
    cStdColor = &H80000008

    If TextBox5 = "Legajo" Then

        TextBox5.Font.Italic = False 'Does not Work
    Else
        TextBox5.Font.Italic = True
    End If
     TextBox5.ForeColor = cStdColor
End Sub


问:
JSTL <fmt:formatData> time zone problem
If I'm in Europe, Germany, and I use:

```<code><fmt:formatDate value="${now}" type="BOTH" timeZone="America/Los_Angeles"/>
</code>```

the date and time are formatted always as

17-05-2011 1.32.10

and not as in English format with first month and then day.

Only the time zone is corrected.

Why?

Thanks.

答:
You need to override pattern also, overriding timezone won't change the output format

```<code><fmt:formatDate value="${now}" type="BOTH" timeZone="America/Los_Angeles" pattern="MM/dd/yyyy HH:mm"/>
</code>```

Title: JSTL <fmt:formatData> time zone problem

Body:
If I'm in Europe, Germany, and I use:

<fmt:formatDate value="${now}" type="BOTH" timeZone="America/Los_Angeles"/>

the date and time are formatted always as

17-05-2011 1.32.10

and not as in English format with first month and then day.

Only the time zone is corrected.

Why?

Thanks.

Body:
You need to override pattern also, overriding timezone won't change the output format

<fmt:formatDate value="${now}" type="BOTH" timeZone="America/Los_Angeles" pattern="MM/dd/yyyy HH:mm"/>


问:
Jenkins Pipeline Build with Docker, Google Registry, and Google Auth Plugin
I'm building a Docker image using a Jenkins pipeline (using a pipeline script that was auto-generated by JHipster). I want to push my final docker image to the Google Container Registry.

Here's what I've done:

I've installed both the CloudBees Docker Custom Build Environment Plugin and the Google Container Registry Auth Plugin.

I've set up Google auth credentials in Jenkins following instructions over here

I've configured my build step to use the Google Registry tag format, like so: docker.build('us.gcr.io/[my-project-id]/[my-artifact-id]', 'target/docker')

I've referenced the id of my Google Auth credentials in my push step:

(Hm. Needs extra text line after bullets to format properly)

```<code>docker.withRegistry('https://us.gcr.io', '[my-credential-id]') {
    dockerImage.push 'latest'
}
</code>```

But the build fails with:

```<code>ERROR: Could not find credentials matching [my-credential-id]
Finished: FAILURE
</code>```

I'm basically at the point of believing that these plugins don't work in a pipelines world, but I thought I'd ask if anyone has accomplished this and could give me some pointers.

答:
The previous answers didn't seem to work for me anymore. This is the syntax that works for me:</p>

```<code>stage('Push Image') {
        steps {
            script {
                docker.withRegistry('https://gcr.io', 'gcr:my-credential-id') {
                    dockerImage.push()
                }
            }
        }
    }
</code>```

Body:
I'm building a Docker image using a Jenkins pipeline (using a pipeline script that was auto-generated by JHipster). I want to push my final docker image to the Google Container Registry.

Here's what I've done:

I've installed both the CloudBees Docker Custom Build Environment Plugin and the Google Container Registry Auth Plugin.

I've set up Google auth credentials in Jenkins following instructions over here

I've configured my build step to use the Google Registry tag format, like so: docker.build('us.gcr.io/[my-project-id]/[my-artifact-id]', 'target/docker')

I've referenced the id of my Google Auth credentials in my push step:

(Hm. Needs extra text line after bullets to format properly)

docker.withRegistry('https://us.gcr.io', '[my-credential-id]') {
    dockerImage.push 'latest'
}

But the build fails with:

ERROR: Could not find credentials matching [my-credential-id]
Finished: FAILURE

I'm basically at the point of believing that these plugins don't work in a pipelines world, but I thought I'd ask if anyone has accomplished this and could give me some pointers.

Body:
The previous answers didn't seem to work for me anymore. This is the syntax that works for me:

stage('Push Image') {
        steps {
            script {
                docker.withRegistry('https://gcr.io', 'gcr:my-credential-id') {
                    dockerImage.push()
                }
            }
        }
    }


问:
Laravel - Form select date - Only allow users to select between two dates send from database
I have two tables - 'Trips' and 'Events'. One trip can have many events.
I have a form which allows users to add events to their trip.
When selecting the start date and end date of the event I only want to allow the users to select a date that is from the trip start date and the trip end date.

For example if a trip to New York was created from the 1st March to the 14th March, users should only be able to add an event between those dates. Is there a good way to do this?

Trips Table
Events Table

addEvent.blade.php
`

```<code><div class="form-group">
    <div class="form-group">
        {!! Form::label('trip_id', 'Your Destinations:') !!}
        <select class="form-control" name="trip_id">
          @foreach($trips as $trip)
            <option value='{{ $trip->id}}'>{{$trip->destination}}</option>
          @endforeach
        </select>
      </div>
    </div>

<div class="form-group">
  <div class="form-group">
    {!! Form::label('event_name', 'Add Event:') !!}
    <div class="">
      {!! Form::text('event_name', null, ['class' => 'form-control']) !!}
      {!! $errors->first('event_name', '<p class="alert alert-danger">:message</p>') !!}
    </div>
  </div>
</div>

<div class="form-group">
  <div class="form-group">
    {!! Form::label('start_date', 'Start Date:') !!}
    <div class="">
      {!! Form::date('start_date', \Carbon\Carbon::now(), ['class' => 'form-control']) !!}
      {!! $errors->first('start_date', '<p class="alert alert-danger">:message</p>') !!}
    </div>
  </div>
</div>

<div class="form-group">
  <div class="form-group">
    {!! Form::label('end_date', 'End Date:') !!}
    <div class="">
      {!! Form::date('end_date', null, ['class' => 'form-control']) !!}
      {!! $errors->first('end_date', '<p class="alert alert-danger">:message</p>') !!}
    </div>
  </div>
</div>

<div class="form-group"  <br/>
{!! Form::submit('Add Event', ['class' => 'btn btn-primary']) !!}
</code>```

`

Event Controller

```<code>public function addEvent(Request $request)
{
  $validator = Validator::make($request->all(),[
    'event_name' => 'required',
    'start_date' => 'required',
    'end_date' => 'required',
    'trip_id'=> 'required',
  ]);

  if($validator->fails()) {
    \Session::flash('warning', 'Please enter the valid details');
    return redirect('/events')->with('input', Input::all());
  }

  $events = new Events;
  $trips = Trip::all();
  $events->event_name = $request['event_name'];
  $events->start_date = $request['start_date'];
  $events->end_date = $request['end_date'];
  $events->trip_id = $request['trip_id'];
  $events->save();

return redirect('trips')->with('success', 'The new event has been added to your trip')->with('trips', $trips);
}
</code>```

trip.blade.php

```<code><div class="form-group">
      <input type="text" name="destination" class="form-control" value="{{$trip->destination}}" placeholder="Destination" />
    </div>
    <h7>Trip Start Date: </h7>
    <div class="form-group">
      <input type="date" name="startdate" class="form-control" value="{{$trip->startdate}}" placeholder="Start Date" />
    </div>
    <h7>Trip End Date: </h7>
    <div class="form-group">
      <input type="date" name="enddate" class="form-control" value="{{$trip->enddate}}" placeholder="End Date" />
    </div>
    <div>
</code>```

trip controller

```<code>public function submit(Request $request){
  $this->validate($request, [
    'name'          => 'required',
    'email'         => 'required',
    'destination'   => 'required',
    'startdate'     => 'required',
    'enddate'       => 'required'
  ]);

  //Create new trips
  $trip = new Trip;
  $trip->name = $request->input('name');
  $trip->email = $request->input('email');
  $trip->destination = $request->input('destination');
  $trip->startdate = $request->input('startdate');
  $trip->enddate = $request->input('enddate');
  $trip->user_id = auth()->user()->id;

  //save trips
  $trip->save();

  //Rredirect
  return redirect('/home')->with('status', 'Trip Created Sucessfully');

}
</code>```

答:
```<code>$start_date = Carbon::parse($request['start_date'])->formet('Y-m-d');
$end_date = Carbon::parse($request['end_date'])->formet('Y-m-d');

$tripCheck = Trip:where('id', $request['trip_id'])
->whereDate('start_date', '>=', $start_dat)
->whereDate('end_date', '<', $end_date)
->first();

$trips = Trip::all();
$status = failed;
$msg = 'The new event has been not added to your trip';
if($tripCheck){
    $events = new Events;
    $events->event_name = $request['event_name'];
    $events->start_date = $request['start_date'];
    $events->end_date = $request['end_date'];
    $events->trip_id = $request['trip_id'];
    $events->save();
    $status = 'success';
    $msg = 'The new event has been not added to your trip';
}

return redirect('trips')->with($status, $msg)->with('trips', $trips);
</code>```

Body:
I have two tables - 'Trips' and 'Events'. One trip can have many events.
I have a form which allows users to add events to their trip.
When selecting the start date and end date of the event I only want to allow the users to select a date that is from the trip start date and the trip end date.

For example if a trip to New York was created from the 1st March to the 14th March, users should only be able to add an event between those dates. Is there a good way to do this?

Trips Table
Events Table

addEvent.blade.php
`

        {!! Form::label('trip_id', 'Your Destinations:') !!}
        <select class="form-control" name="trip_id">
          @foreach($trips as $trip)
            <option value='{{ $trip->id}}'>{{$trip->destination}}</option>
          @endforeach
        </select>

    {!! Form::label('event_name', 'Add Event:') !!}

      {!! Form::text('event_name', null, ['class' => 'form-control']) !!}
      {!! $errors->first('event_name', '
:message
') !!}

    {!! Form::label('start_date', 'Start Date:') !!}

      {!! Form::date('start_date', \Carbon\Carbon::now(), ['class' => 'form-control']) !!}
      {!! $errors->first('start_date', '
:message
') !!}

    {!! Form::label('end_date', 'End Date:') !!}

      {!! Form::date('end_date', null, ['class' => 'form-control']) !!}
      {!! $errors->first('end_date', '
:message
') !!}

 'btn btn-primary']) !!}

`

Event Controller

public function addEvent(Request $request)
{
  $validator = Validator::make($request->all(),[
    'event_name' => 'required',
    'start_date' => 'required',
    'end_date' => 'required',
    'trip_id'=> 'required',
  ]);

  if($validator->fails()) {
    \Session::flash('warning', 'Please enter the valid details');
    return redirect('/events')->with('input', Input::all());
  }

  $events = new Events;
  $trips = Trip::all();
  $events->event_name = $request['event_name'];
  $events->start_date = $request['start_date'];
  $events->end_date = $request['end_date'];
  $events->trip_id = $request['trip_id'];
  $events->save();

return redirect('trips')->with('success', 'The new event has been added to your trip')->with('trips', $trips);
}

trip.blade.php

      <input type="text" name="destination" class="form-control" value="{{$trip->destination}}" placeholder="Destination" />

    <h7>Trip Start Date: </h7>

      <input type="date" name="startdate" class="form-control" value="{{$trip->startdate}}" placeholder="Start Date" />

    <h7>Trip End Date: </h7>

      <input type="date" name="enddate" class="form-control" value="{{$trip->enddate}}" placeholder="End Date" />

trip controller

public function submit(Request $request){
  $this->validate($request, [
    'name'          => 'required',
    'email'         => 'required',
    'destination'   => 'required',
    'startdate'     => 'required',
    'enddate'       => 'required'
  ]);

  //Create new trips
  $trip = new Trip;
  $trip->name = $request->input('name');
  $trip->email = $request->input('email');
  $trip->destination = $request->input('destination');
  $trip->startdate = $request->input('startdate');
  $trip->enddate = $request->input('enddate');
  $trip->user_id = auth()->user()->id;

  //save trips
  $trip->save();

  //Rredirect
  return redirect('/home')->with('status', 'Trip Created Sucessfully');

}