问:
Cannot access javascript variable inside symfony controller
On my symfony (v3.4) project, I need to pass some javascript variables from my view to my controller containing a form : I used Jquery and Ajax to send my variable to the right route but for some reason I cannot access it from my controller.

Here is the script part in my twig view:

$(".month").click(function() {

  var click = $(this);

  var month = click.val();
  var year = $("#years").val();

  var url = "{{ path('av_platform_saisie') }}";

  $.ajax(url, {
    type: 'POST',
    data: {
      'month': month,
      'year': year
    },
    success: function(data) {
      alert('OK');
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });

});
```

<p>And my controller: </p>

<pre class="lang-php prettyprint-override"><code>public function saisieAction(Request $request)
{

    $user = $this->getUser();
    $thisyear = date("Y");

    $em = $this->getDoctrine()->getManager();

    // Create the form
    $form = $this->get('form.factory')->createBuilder(FormType::class)
        ->add('ndf', CollectionType::class, array(
            'entry_type' => NoteDeFraisType::class,
            'label' => false,
            'allow_add' => true,
            'allow_delete' => true,
        ))
        ->getForm();

    // if the form has been submited
    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {

        if($request->isXMLHttpRequest()){

            $month = $request->get('month');
            $year = $request->get('year');
            $sub_date = $month .'/' .$year;

        }

        $notesDeFrais = $form['ndf']->getData();

        foreach ($notesDeFrais as $ndf) {
            $ndf->setUser($user);
            $ndf->setMonth($sub_date);
            $em->persist($ndf);
        }

        $em->flush();

    }

    return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
        array(
            'year' => $thisyear,  'form' => $form->createView()
        ));
}
</code>```

The weird thing is: I tried to send my js variables from a new Twig view that is not rendered by my controller and it's working just fine with exactly the same code so maybe it is a normal behavior ?

EDIT:
I did some debugging and actually and the code inside my if($request->isXMLHttpRequest()) is not executed

答:
Did you checked the source code of the form, what is the value of action attribute? I think you can't add the js url for that AJAX request as you did. Ideally, install FosJsRoutingBundle, and modify as:

```<code>url: Routing.generate('av_platform_saisie')
</code>```

Body:
On my symfony (v3.4) project, I need to pass some javascript variables from my view to my controller containing a form : I used Jquery and Ajax to send my variable to the right route but for some reason I cannot access it from my controller.

Here is the script part in my twig view:

$(".month").click(function() {

  var click = $(this);

  var month = click.val();
  var year = $("#years").val();

  var url = "{{ path('av_platform_saisie') }}";

  $.ajax(url, {
    type: 'POST',
    data: {
      'month': month,
      'year': year
    },
    success: function(data) {
      alert('OK');
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });

});

And my controller:

public function saisieAction(Request $request)
{

    $user = $this->getUser();
    $thisyear = date("Y");

    $em = $this->getDoctrine()->getManager();

    // Create the form
    $form = $this->get('form.factory')->createBuilder(FormType::class)
        ->add('ndf', CollectionType::class, array(
            'entry_type' => NoteDeFraisType::class,
            'label' => false,
            'allow_add' => true,
            'allow_delete' => true,
        ))
        ->getForm();

    // if the form has been submited
    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {

        if($request->isXMLHttpRequest()){

            $month = $request->get('month');
            $year = $request->get('year');
            $sub_date = $month .'/' .$year;

        }

        $notesDeFrais = $form['ndf']->getData();

        foreach ($notesDeFrais as $ndf) {
            $ndf->setUser($user);
            $ndf->setMonth($sub_date);
            $em->persist($ndf);
        }

        $em->flush();

    }

    return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
        array(
            'year' => $thisyear,  'form' => $form->createView()
        ));
}

The weird thing is: I tried to send my js variables from a new Twig view that is not rendered by my controller and it's working just fine with exactly the same code so maybe it is a normal behavior ?

EDIT:
I did some debugging and actually and the code inside my if($request->isXMLHttpRequest()) is not executed

Body:
Did you checked the source code of the form, what is the value of action attribute? I think you can't add the js url for that AJAX request as you did. Ideally, install FosJsRoutingBundle, and modify as:

url: Routing.generate('av_platform_saisie')


来源: stackexchange

问:
Talking to container on Kubernetes (GKE) from other container
I have an API written in Express, that connects to a Mongo container. When I spin these up locally, I can connect to the mongo instance using something like mongodb://${DB_HOST}:${DB_PORT}/${DB_NAME} and setting .env variables.

What I am struggling to understand, is once this deployed to GKE, how will my API connect to the mongo container / pod?

It won't be running on localhost I assume, so perhaps I will need to use the internal IP created?

Should it actually be connecting via a service? What would that service look like?

I am struggling to find docs on exactly where I am stuck so I am thinking I am missing something really obvious.

I'm free new to GKE so any examples would help massively.

答:
Create a mongodb deployment and a mongodb service of type ClusterIP, which basically means that your api will be able to connect to the db internally. If you want to connect your db from outside, create a service of type LoadBalancer or other service types (see here)

With a service of type ClusterIP, let's say you give it a name of mongodbservice under metadata key. Then your api can connect to it at mongodb://mongodbservice:${DB_PORT}/${DB_NAME}

ContentLicense: CC BY-SA 4.0


问:
auto-py-exe - unable to convert (.py) script - "One binary added with two internal names"
Got the following errors.
What's wrong? Why is this error "One binary added with two internal names" flashing up? Is there any conflict?</p>

```<code>17175 INFO: Looking for dynamic libraries
17971 WARNING: lib not found: python35.dll dependency of C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\sip.pyd
27100 INFO: Looking for eggs
27100 INFO: Using Python library C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python37.dll
27100 INFO: Found binding redirects:
[]
27100 INFO: Warnings written to C:\Users\Administrator\AppData\Local\Programs\Python\Python37\auto-py-to-exe-master\build\Image Processor\warn-Image Processor.txt
27196 INFO: Graph cross-reference written to C:\Users\Administrator\AppData\Local\Programs\Python\Python37\auto-py-to-exe-master\build\Image Processor\xref-Image Processor.html
27230 INFO: checking PYZ
27230 INFO: Building PYZ because PYZ-00.toc is non existent
27230 INFO: Building PYZ (ZlibArchive) C:\Users\Administrator\AppData\Local\Programs\Python\Python37\auto-py-to-exe-master\build\Image Processor\PYZ-00.pyz
28279 INFO: Building PYZ (ZlibArchive) C:\Users\Administrator\AppData\Local\Programs\Python\Python37\auto-py-to-exe-master\build\Image Processor\PYZ-00.pyz completed successfully.
28295 INFO: checking PKG
28295 INFO: Building PKG because PKG-00.toc is non existent
28295 INFO: Building PKG (CArchive) PKG-00.pkg
28720 WARNING: One binary added with two internal names.
28720 WARNING: ('libGLESv2.dll',
 'C:\\Users\\Arvind1\\AppData\\Roaming\\Python\\Python37\\site-packages\\PyQt5\\Qt\\bin\\libGLESv2.dll',
 'BINARY')
28720 WARNING: was placed previously at
28720 WARNING: ('PyQt5\\Qt\\bin\\libGLESv2.dll',
 'C:\\Users\\Arvind1\\AppData\\Roaming\\Python\\Python37\\site-packages\\PyQt5\\Qt\\bin\\libGLESv2.dll',
 'BINARY')
</code>```

答: On the PyInstaller 3.4 release, I was getting this WARNING too. (At least the part about One binary added with two internal names and libGLESv2.dll/PyQt5\\Qt\\bin\\libGLESv2.dll.) On the develop branch of the project (this is a known working commit at the time of this post), this WARNING still appears, but at least my project builds successfully now.

Body:
Got the following errors.
What's wrong? Why is this error "One binary added with two internal names" flashing up? Is there any conflict?

17175 INFO: Looking for dynamic libraries
17971 WARNING: lib not found: python35.dll dependency of C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\sip.pyd
27100 INFO: Looking for eggs
27100 INFO: Using Python library C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python37.dll
27100 INFO: Found binding redirects:
[]
27100 INFO: Warnings written to C:\Users\Administrator\AppData\Local\Programs\Python\Python37\auto-py-to-exe-master\build\Image Processor\warn-Image Processor.txt
27196 INFO: Graph cross-reference written to C:\Users\Administrator\AppData\Local\Programs\Python\Python37\auto-py-to-exe-master\build\Image Processor\xref-Image Processor.html
27230 INFO: checking PYZ
27230 INFO: Building PYZ because PYZ-00.toc is non existent
27230 INFO: Building PYZ (ZlibArchive) C:\Users\Administrator\AppData\Local\Programs\Python\Python37\auto-py-to-exe-master\build\Image Processor\PYZ-00.pyz
28279 INFO: Building PYZ (ZlibArchive) C:\Users\Administrator\AppData\Local\Programs\Python\Python37\auto-py-to-exe-master\build\Image Processor\PYZ-00.pyz completed successfully.
28295 INFO: checking PKG
28295 INFO: Building PKG because PKG-00.toc is non existent
28295 INFO: Building PKG (CArchive) PKG-00.pkg
28720 WARNING: One binary added with two internal names.
28720 WARNING: ('libGLESv2.dll',
 'C:\\Users\\Arvind1\\AppData\\Roaming\\Python\\Python37\\site-packages\\PyQt5\\Qt\\bin\\libGLESv2.dll',
 'BINARY')
28720 WARNING: was placed previously at
28720 WARNING: ('PyQt5\\Qt\\bin\\libGLESv2.dll',
 'C:\\Users\\Arvind1\\AppData\\Roaming\\Python\\Python37\\site-packages\\PyQt5\\Qt\\bin\\libGLESv2.dll',
 'BINARY')


问:
Cannot read property of undefined on react
I am setting up a client code and the error "Cannot read property '' of undefined" keeps occur.

TypeError: Cannot read property ' ' of undefined

It is interesting that if I refresh the page several times then suddenly it works! For example, the home page is random within 10 times, menu page shows me an error page at the first time, half loaded at first refresh, fully loaded at second refresh.

I think props can't get data correctly right away. So I think I can solve this problem by refreshing automatically until props get correct data.

Is there any way refreshing until I get the props?

Or any other solution about this problem?

menu error

home error

答:
Yea, you will need to confirm that the data object exists before doing a conditional. so

loading || {data || !data.me || !data.getPlaces}


问:
Trying to make an accessor funtion in qt
you should be able to see what I am tring to do by looking at the funtion called motorcontroll I am trying to make a funtion that can set the values of several spinboxes with the call of one funtion called motorcontrol If I put the function inside the:

```<code>Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
}
</code>```

I get the error that I can not declare a function there, but if I put it outside the brackets, I get the error ui was not declared in this scope. I understand why I am getting this error but I don't know a way around it. Could I make ui a global variable/object and if so how would I do that or is there another way to solve/get around this issue. here is my code:

```<code>#include "widget.h"
#include "ui_widget.h"
#include <QCamera>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QVBoxLayout>
#include <QMenu>
#include <QAction>
#include <QFileDialog>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    mCamera = new QCamera(this);
    mCameraViewfinder = new QCameraViewfinder(this);
    mCameraImageCapture = new QCameraImageCapture(mCamera,this);
    mLayout = new QVBoxLayout;
    mOptionsMenu = new QMenu("Options",this);
    mCameraAction = new QAction("Camera",this);
    mGantryAction = new QAction("Gantry", this);
    mCaptureAction = new QAction("Capture",this);
    mLazerAction = new QAction("Lazer",this);
    mOptionsMenu->addActions({mCameraAction,mGantryAction,
                               mLazerAction});
    ui->optionsPushButton->setMenu(mOptionsMenu);
    ui->lazerDistance->setLayout(mLayout);

    ui->xAxis->setLayout(mLayout);
    ui->yAxis->setLayout(mLayout);
    ui->zAxis->setLayout(mLayout);
    ui->xRotate->setLayout(mLayout);
    ui->yRotate->setLayout(mLayout);
    ui->zRotate->setLayout(mLayout);
    ui->x1Label->setLayout(mLayout);
    ui->y1Label->setLayout(mLayout);
    ui->z1Label->setLayout(mLayout);
    ui->x2Label->setLayout(mLayout);
    ui->y2Label->setLayout(mLayout);
    ui->z2Label->setLayout(mLayout);
    ui->xAxis->hide();
    ui->yAxis->hide();
    ui->zAxis->hide();
    ui->xRotate->hide();
    ui->yRotate->hide();
    ui->zRotate->hide();
    ui->x1Label->hide();
    ui->y1Label->hide();
    ui->z1Label->hide();
    ui->x2Label->hide();
    ui->y2Label->hide();
    ui->z2Label->hide();
    ui->lazerDistance->hide();
    ui->scanButton->hide();
    ui->moterL->hide();
    ui->moterLLable->hide();

    connect(mCameraAction, &QAction::triggered, [&](){
        ui->moterL->hide();
        ui->moterLLable->hide();
        ui->xAxis->hide();
        ui->yAxis->hide();
        ui->zAxis->hide();
        ui->xRotate->hide();
        ui->yRotate->hide();
        ui->zRotate->hide();
        ui->x1Label->hide();
        ui->y1Label->hide();
        ui->z1Label->hide();
        ui->x2Label->hide();
        ui->y2Label->hide();
        ui->z2Label->hide();
        ui->lazerDistance->hide();
        ui->scanButton->hide();
        mCamera->setViewfinder(mCameraViewfinder);
        mLayout->addWidget(mCameraViewfinder);
        mLayout->setMargin(0);
        ui->ScrollArea->setLayout(mLayout);
        ui->ScrollArea->show();
        ui->scrollAreaWidgetContents->show();
        mCameraViewfinder->show();
        mCamera->start();

      });

        connect(mGantryAction,&QAction::triggered, [&](){
           mCamera->stop();
         ui->ScrollArea->hide();
          ui->scrollAreaWidgetContents->hide();
          mCameraViewfinder->hide();
          ui->lazerDistance->hide();
          ui->scanButton->hide();

            ui->x1Label->show();
            ui->y1Label->show();
            ui->z1Label->show();
            ui->x2Label->show();
            ui->y2Label->show();
            ui->z2Label->show();
            ui->moterLLable->show();
            ui->xAxis->show();
            ui->yAxis->show();
            ui->zAxis->show();
            ui->xRotate->show();
            ui->yRotate->show();
            ui->zRotate->show();
            ui->moterL->show();

            ui->scanButton->show();

        });

    connect(mLazerAction, &QAction::triggered, [&](){

        mCamera->stop();
        ui->ScrollArea->hide();
        ui->scrollAreaWidgetContents->hide();
        mCameraViewfinder->hide();
        ui->scanButton->hide();
        ui->moterL->hide();
        ui->xAxis->hide();
        ui->yAxis->hide();
        ui->zAxis->hide();
        ui->xRotate->hide();
        ui->yRotate->hide();
        ui->zRotate->hide();
        ui->x1Label->hide();
        ui->y1Label->hide();
        ui->z1Label->hide();
        ui->x2Label->hide();
        ui->y2Label->hide();
        ui->z2Label->hide();
        ui->moterLLable->hide();
        ui->lazerDistance->show();

    });

    //to change the value of the lazer distance
    //have ros input a new string
    ui->lazerDistance->setText("0");
    //funtions to set the values of the moters

    }

void motorcontroll(double x1,double x2, double y1, double y2, double z1, double z2,double l1)
{
    ui->xAxis->setValue(x1);
    ui->yAxis->setValue(y1);
    ui->zAxis->setValue(z1);
    ui->xRotate->setValue(x2);
    ui->yRotate->setValue(y2);
    ui->zRotate->setValue(z2);
    ui->moterL->setValue(l1);
}
</code>```

header file:

```<code>#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}
class QCamera;
class QCameraViewfinder;
class QCameraImageCapture;
class QVBoxLayout;
class QMenu;
class QAction;

class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();
    void motorcontroll(double x1,double x2, double y1, double y2, double z1, double z2,double l1);

private:
    Ui::Widget *ui;
    QCamera * mCamera;
    QCameraViewfinder *mCameraViewfinder;
    QCameraImageCapture *mCameraImageCapture;
    QVBoxLayout *mLayout;
    QMenu *mOptionsMenu;
    QAction *mCameraAction;
    QAction *mGantryAction;
    QAction *mCaptureAction;
    QAction *mLazerAction;
};

#endif // WIDGET_H
</code>```

答:
I get the error that I can not declare a function there, but if I put it outside the brackets, I get the error ui was not declared in this scope.

Member functions can be defined within the class definition or separately using scope resolution operator, ::. Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier.

```<code>class XYZ {
public:
    void mymethod(int arg)
    {
        // Doing Something
    }
};
</code>```

You can define the same function outside the class using the scope resolution operator (::).

```<code>void Widget::motorcontroll(double x1, double x2, double y1, double y2,
                       double z1, double z2, double l1)
{
    // Do Something
}
</code>```

You can have a look at this link to know more about difference between member functions and free function in C++.

Body:
you should be able to see what I am tring to do by looking at the funtion called motorcontroll I am trying to make a funtion that can set the values of several spinboxes with the call of one funtion called motorcontrol If I put the function inside the:

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
}

I get the error that I can not declare a function there, but if I put it outside the brackets, I get the error ui was not declared in this scope. I understand why I am getting this error but I don't know a way around it. Could I make ui a global variable/object and if so how would I do that or is there another way to solve/get around this issue. here is my code:

#include "widget.h"
#include "ui_widget.h"
#include <QCamera>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QVBoxLayout>
#include <QMenu>
#include <QAction>
#include <QFileDialog>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    mCamera = new QCamera(this);
    mCameraViewfinder = new QCameraViewfinder(this);
    mCameraImageCapture = new QCameraImageCapture(mCamera,this);
    mLayout = new QVBoxLayout;
    mOptionsMenu = new QMenu("Options",this);
    mCameraAction = new QAction("Camera",this);
    mGantryAction = new QAction("Gantry", this);
    mCaptureAction = new QAction("Capture",this);
    mLazerAction = new QAction("Lazer",this);
    mOptionsMenu->addActions({mCameraAction,mGantryAction,
                               mLazerAction});
    ui->optionsPushButton->setMenu(mOptionsMenu);
    ui->lazerDistance->setLayout(mLayout);

    ui->xAxis->setLayout(mLayout);
    ui->yAxis->setLayout(mLayout);
    ui->zAxis->setLayout(mLayout);
    ui->xRotate->setLayout(mLayout);
    ui->yRotate->setLayout(mLayout);
    ui->zRotate->setLayout(mLayout);
    ui->x1Label->setLayout(mLayout);
    ui->y1Label->setLayout(mLayout);
    ui->z1Label->setLayout(mLayout);
    ui->x2Label->setLayout(mLayout);
    ui->y2Label->setLayout(mLayout);
    ui->z2Label->setLayout(mLayout);
    ui->xAxis->hide();
    ui->yAxis->hide();
    ui->zAxis->hide();
    ui->xRotate->hide();
    ui->yRotate->hide();
    ui->zRotate->hide();
    ui->x1Label->hide();
    ui->y1Label->hide();
    ui->z1Label->hide();
    ui->x2Label->hide();
    ui->y2Label->hide();
    ui->z2Label->hide();
    ui->lazerDistance->hide();
    ui->scanButton->hide();
    ui->moterL->hide();
    ui->moterLLable->hide();

    connect(mCameraAction, &QAction::triggered, [&](){
        ui->moterL->hide();
        ui->moterLLable->hide();
        ui->xAxis->hide();
        ui->yAxis->hide();
        ui->zAxis->hide();
        ui->xRotate->hide();
        ui->yRotate->hide();
        ui->zRotate->hide();
        ui->x1Label->hide();
        ui->y1Label->hide();
        ui->z1Label->hide();
        ui->x2Label->hide();
        ui->y2Label->hide();
        ui->z2Label->hide();
        ui->lazerDistance->hide();
        ui->scanButton->hide();
        mCamera->setViewfinder(mCameraViewfinder);
        mLayout->addWidget(mCameraViewfinder);
        mLayout->setMargin(0);
        ui->ScrollArea->setLayout(mLayout);
        ui->ScrollArea->show();
        ui->scrollAreaWidgetContents->show();
        mCameraViewfinder->show();
        mCamera->start();

      });

        connect(mGantryAction,&QAction::triggered, [&](){
           mCamera->stop();
         ui->ScrollArea->hide();
          ui->scrollAreaWidgetContents->hide();
          mCameraViewfinder->hide();
          ui->lazerDistance->hide();
          ui->scanButton->hide();

            ui->x1Label->show();
            ui->y1Label->show();
            ui->z1Label->show();
            ui->x2Label->show();
            ui->y2Label->show();
            ui->z2Label->show();
            ui->moterLLable->show();
            ui->xAxis->show();
            ui->yAxis->show();
            ui->zAxis->show();
            ui->xRotate->show();
            ui->yRotate->show();
            ui->zRotate->show();
            ui->moterL->show();

            ui->scanButton->show();

        });

    connect(mLazerAction, &QAction::triggered, [&](){

        mCamera->stop();
        ui->ScrollArea->hide();
        ui->scrollAreaWidgetContents->hide();
        mCameraViewfinder->hide();
        ui->scanButton->hide();
        ui->moterL->hide();
        ui->xAxis->hide();
        ui->yAxis->hide();
        ui->zAxis->hide();
        ui->xRotate->hide();
        ui->yRotate->hide();
        ui->zRotate->hide();
        ui->x1Label->hide();
        ui->y1Label->hide();
        ui->z1Label->hide();
        ui->x2Label->hide();
        ui->y2Label->hide();
        ui->z2Label->hide();
        ui->moterLLable->hide();
        ui->lazerDistance->show();

    });

    //to change the value of the lazer distance
    //have ros input a new string
    ui->lazerDistance->setText("0");
    //funtions to set the values of the moters

    }

void motorcontroll(double x1,double x2, double y1, double y2, double z1, double z2,double l1)
{
    ui->xAxis->setValue(x1);
    ui->yAxis->setValue(y1);
    ui->zAxis->setValue(z1);
    ui->xRotate->setValue(x2);
    ui->yRotate->setValue(y2);
    ui->zRotate->setValue(z2);
    ui->moterL->setValue(l1);
}

header file:

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}
class QCamera;
class QCameraViewfinder;
class QCameraImageCapture;
class QVBoxLayout;
class QMenu;
class QAction;

class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();
    void motorcontroll(double x1,double x2, double y1, double y2, double z1, double z2,double l1);

private:
    Ui::Widget *ui;
    QCamera * mCamera;
    QCameraViewfinder *mCameraViewfinder;
    QCameraImageCapture *mCameraImageCapture;
    QVBoxLayout *mLayout;
    QMenu *mOptionsMenu;
    QAction *mCameraAction;
    QAction *mGantryAction;
    QAction *mCaptureAction;
    QAction *mLazerAction;
};

#endif // WIDGET_H

Body:
I get the error that I can not declare a function there, but if I put it outside the brackets, I get the error ui was not declared in this scope.

Member functions can be defined within the class definition or separately using scope resolution operator, ::. Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier.

class XYZ {
public:
    void mymethod(int arg)
    {
        // Doing Something
    }
};

You can define the same function outside the class using the scope resolution operator (::).

void Widget::motorcontroll(double x1, double x2, double y1, double y2,
                       double z1, double z2, double l1)
{
    // Do Something
}

You can have a look at this link to know more about difference between member functions and free function in C++.


问:
RxJS iif arguments are called when shouldn't
I want to conditionally dispatch some actions using iif utility from RxJS. The problem is that second argument to iif is called even if test function returns false. This throws an error and app crashes immediately. I am new to to the power of RxJS so i probably don't know something.  And i am using connected-react-router package if that matters. </p>

```
export const roomRouteEpic: Epic = (action$, state$) =>
  action$.ofType(LOCATION_CHANGE).pipe(
    pluck('payload'),
    mergeMap(payload =>
      iif(
        () => {
          console.log('NOT LOGGED');
          return /^\/room\/\d+$/.test(payload.location.pathname); // set as '/login'
        },
        merge(
          tap(v => console.log('NOT LOGGED TOO')),
          of(
            // following state value is immediately evaluated
            state$.value.rooms.list[payload.location.pathname.split('/')[1]]
              ? actions.rooms.initRoomEnter()
              : actions.rooms.initRoomCreate(),
          ),
          of(actions.global.setIsLoading(true)),
        ),
        empty(),
      ),
    ),
  );```

答:
A little late to the party, but I found that the role of iif is not to execute one path over the other, but to subscribe to one Observable or the other. That said, it will execute any and all code paths required to get each Observable.

From this example...

import { iif, of, pipe } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

const source$ = of('Hello');
const obsOne$ = (x) => {console.log(`${x} World`); return of('One')};
const obsTwo$ = (x) => {console.log(`${x}, Goodbye`); return of('Two')};

source$.pipe(
  mergeMap(v =>
    iif(
      () => v === 'Hello',
      obsOne$(v),
      obsTwo$(v)
    ))
).subscribe(console.log);
```
<p>you'll get the following output</p>
```Hello World
Hello, Goodbye
One
```

This is because, in order to get obsOne$ it needed to print Hello World. The same is true for obsTwo$ (except that path prints Hello, Goodbye).

However you'll notice that it only prints One and not Two. This is because iif evaluated to true, thus subscribing to obsOne$.

While your ternary works - I found this article explains a more RxJS driven way of achieving your desired outcome quite nicely: https://rangle.io/blog/rxjs-where-is-the-if-else-operator/

Body:
I want to conditionally dispatch some actions using iif utility from RxJS. The problem is that second argument to iif is called even if test function returns false. This throws an error and app crashes immediately. I am new to to the power of RxJS so i probably don't know something.  And i am using connected-react-router package if that matters.

export const roomRouteEpic: Epic = (action$, state$) =>
  action$.ofType(LOCATION_CHANGE).pipe(
    pluck('payload'),
    mergeMap(payload =>
      iif(
        () => {
          console.log('NOT LOGGED');
          return /^\/room\/\d+$/.test(payload.location.pathname); // set as '/login'
        },
        merge(
          tap(v => console.log('NOT LOGGED TOO')),
          of(
            // following state value is immediately evaluated
            state$.value.rooms.list[payload.location.pathname.split('/')[1]]
              ? actions.rooms.initRoomEnter()
              : actions.rooms.initRoomCreate(),
          ),
          of(actions.global.setIsLoading(true)),
        ),
        empty(),
      ),
    ),
  );

Body:
A little late to the party, but I found that the role of iif is not to execute one path over the other, but to subscribe to one Observable or the other. That said, it will execute any and all code paths required to get each Observable.

From this example...

import { iif, of, pipe } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

const source$ = of('Hello');
const obsOne$ = (x) => {console.log(`${x} World`); return of('One')};
const obsTwo$ = (x) => {console.log(`${x}, Goodbye`); return of('Two')};

source$.pipe(
  mergeMap(v =>
    iif(
      () => v === 'Hello',
      obsOne$(v),
      obsTwo$(v)
    ))
).subscribe(console.log);

you'll get the following output

Hello World
Hello, Goodbye
One

This is because, in order to get obsOne$ it needed to print Hello World. The same is true for obsTwo$ (except that path prints Hello, Goodbye).

However you'll notice that it only prints One and not Two. This is because iif evaluated to true, thus subscribing to obsOne$.

While your ternary works - I found this article explains a more RxJS driven way of achieving your desired outcome quite nicely: https://rangle.io/blog/rxjs-where-is-the-if-else-operator/


问:
how to print a message multiple times on multiple different lines?
for starters im new to python and not really good at this kind of thing so dont crusify me ive had bad experiences on reddit.

But, Im able to get user input to repeat the string x amount of times but i cant get it to repeat on different lines.

ive tried \n multiple times (the only thing ive used) in multiple different ways but i just get invalid syntax but i havent really tried to change the base code much.

```<code>age = int(input("how old are you?: "))

agedifference = 100 - age

print ("you will be 100 in",agedifference,"years") * int(input("pick a number: "))
</code>```

so basically i need the user to pick a number for example 4 then repeat the phrase 4 times on 4 different lines.

if you can give a solution with an in depth explanation i would greatly appreciate it (no such thing as to in depth im noob)

答:
What happens with your code is that you are multiplying the return value of print(), which is None, by the number input by the user. Instead, you should repeat the string which is passed in the print() function.

When calling the print() function, here, make sure the string you print ends with a \n. Also, my example needs Python >= 3.6 because of the way the string is formatted (with the 'f' before the string), it is called literal string interpolation.

Finally, to get rid of the last line return which prints an empty line, add the argument end='' to the call to print() (because this character is already in the string your print).

```<code>age = int(input("how old are you?: "))

age_difference = 100 - age

repetitions = int(input("pick a number: "))

print(f"you will be 100 in {age_difference} years\n" * repetitions, end='')
</code>```

Body:
for starters im new to python and not really good at this kind of thing so dont crusify me ive had bad experiences on reddit.

But, Im able to get user input to repeat the string x amount of times but i cant get it to repeat on different lines.

ive tried \n multiple times (the only thing ive used) in multiple different ways but i just get invalid syntax but i havent really tried to change the base code much.

age = int(input("how old are you?: "))

agedifference = 100 - age

print ("you will be 100 in",agedifference,"years") * int(input("pick a number: "))

so basically i need the user to pick a number for example 4 then repeat the phrase 4 times on 4 different lines.

if you can give a solution with an in depth explanation i would greatly appreciate it (no such thing as to in depth im noob)

Body:
What happens with your code is that you are multiplying the return value of print(), which is None, by the number input by the user. Instead, you should repeat the string which is passed in the print() function.

When calling the print() function, here, make sure the string you print ends with a \n. Also, my example needs Python >= 3.6 because of the way the string is formatted (with the 'f' before the string), it is called literal string interpolation.

Finally, to get rid of the last line return which prints an empty line, add the argument end='' to the call to print() (because this character is already in the string your print).

age = int(input("how old are you?: "))

age_difference = 100 - age

repetitions = int(input("pick a number: "))

print(f"you will be 100 in {age_difference} years\n" * repetitions, end='')


问:
Victory Chart - x-Axis label shorten, custom range and prevent overlapping
Using Victory Chart, I have created a simple BarChart. At the X-Axis, I have big number ranging from 500,000 to 3,000,000. Because the Chart is very narrow, the numbers at the X-Axis are overlapping. My Code looks like this:

```<code>   <VictoryChart>
      theme={VictoryTheme.material}
      <VictoryGroup
        height={chartHeight}
        offset={10}>
        <VictoryBar
          horizontal
          data={chart2}
          labels={d => d.y}
          labelComponent={<VictoryLabel dy={10} />}
        />
        <VictoryBar horizontal data={chart1} />
      </VictoryGroup>
    </VictoryChart>
</code>```

I want to have the x-axis labels like that: 500,000 -> 500K.

Furthermore on the x-axis, I would like to have only 4-5 labels, which are always evenly spreed, so e.g. 0, 1000K, 2000K, 3000K, 4000K. If I have data which x-axis going to 1000K, separation would be 0, 250K, 500K, 750K, 1000K.

答:
Just add Padding to the group

https://formidable.com/open-source/victory/guides/layout

```<code>style={{
                data: { width: 3 },
                labels: { padding: -20 }
              }}
</code>```

Body:
Using Victory Chart, I have created a simple BarChart. At the X-Axis, I have big number ranging from 500,000 to 3,000,000. Because the Chart is very narrow, the numbers at the X-Axis are overlapping. My Code looks like this:

   <VictoryChart>
      theme={VictoryTheme.material}
      <VictoryGroup
        height={chartHeight}
        offset={10}>
        <VictoryBar
          horizontal
          data={chart2}
          labels={d => d.y}
          labelComponent={<VictoryLabel dy={10} />}
        />
        <VictoryBar horizontal data={chart1} />
      </VictoryGroup>
    </VictoryChart>

I want to have the x-axis labels like that: 500,000 -> 500K.

Furthermore on the x-axis, I would like to have only 4-5 labels, which are always evenly spreed, so e.g. 0, 1000K, 2000K, 3000K, 4000K. If I have data which x-axis going to 1000K, separation would be 0, 250K, 500K, 750K, 1000K.

Body:
Just add Padding to the group

https://formidable.com/open-source/victory/guides/layout

style={{
                data: { width: 3 },
                labels: { padding: -20 }
              }}


问:
Trying to load an hdf5 table with dataframe.to_hdf before I die of old age
This sounds like it should be REALLY easy to answer with Google but I'm finding it impossible to answer the majority of my nontrivial pandas/pytables questions this way. All I'm trying to do is to load about 3 billion records from about 6000 different CSV files into a single table in a single HDF5 file. It's a simple table, 26 fields, mixture of strings, floats and ints. I'm loading the CSVs with df = pandas.read_csv() and appending them to my hdf5 file with df.to_hdf(). I really don't want to use df.to_hdf(data_columns = True) because it looks like that will take about 20 days versus about 4 days for df.to_hdf(data_columns = False). But apparently when you use df.to_hdf(data_columns = False) you end up with some pile of junk that you can't even recover the table structure from (or so it appears to my uneducated eye). Only the columns that were identified in the min_itemsize list (the 4 string columns) are identifiable in the hdf5 table, the rest are being dumped by data type into values_block_0 through values_block_4:

```<code>table = h5file.get_node('/tbl_main/table')
print(table.colnames)
['index', 'values_block_0', 'values_block_1', 'values_block_2', 'values_block_3', 'values_block_4', 'str_col1', 'str_col2', 'str_col3', 'str_col4']
</code>```

And any query like df = pd.DataFrame.from_records(table.read_where(condition)) fails with error "Exception: Data must be 1-dimensional"

So my questions are: (1) Do I really have to use data_columns = True which takes 5x as long? I was expecting to do a fast load and then index just a few columns after loading the table. (2) What exactly is this pile of garbage I get using data_columns = False? Is it good for anything if I need my table back with query-able columns? Is it good for anything at all?

答:
This is how you can create an HDF5 file from CSV data using pytables. You could also use a similar process to create the HDF5 file with h5py.

Use a loop to read the CSV files with np.genfromtxt into a np array.

After reading the first CSV file, write the data with .create_table() method, referencing the np array created in Step 1.

For additional CSV files, write the data with .append() method, referencing the np array created in Step 1

End of loop

Updated on 6/2/2019 to read a date field (mm/dd/YYY) and convert to datetime object. Note changes to genfromtxt() arguments! Data used is added below the updated code.

```<code>import numpy as np
import tables as tb
from datetime import datetime
csv_list = ['SO_56387241_1.csv', 'SO_56387241_2.csv' ]

my_dtype= np.dtype([ ('a',int),('b','S20'),('c',float),('d',float),('e','S20') ])

with tb.open_file('SO_56387241.h5', mode='w') as h5f:

for  PATH_csv in csv_list:
    csv_data = np.genfromtxt(PATH_csv, names=True, dtype=my_dtype, delimiter=',', encoding=None)
    # modify date in fifth field 'e'
    for row in csv_data :
        datetime_object = datetime.strptime(row['my_date'].decode('UTF-8'), '%m/%d/%Y' )
        row['my_date'] = datetime_object

    if h5f.__contains__('/CSV_Data') :
        dset = h5f.root.CSV_Data
        dset.append(csv_data)

    else:
        dset = h5f.create_table('/','CSV_Data', obj=csv_data)

    dset.flush()

h5f.close()
</code>```

Data for testing:

```<code>SO_56387241_1.csv:
my_int,my_str,my_float,my_exp,my_date
0,zero,0.0,0.00E+00,01/01/1980
1,one,1.0,1.00E+00,02/01/1981
2,two,2.0,2.00E+00,03/01/1982
3,three,3.0,3.00E+00,04/01/1983
4,four,4.0,4.00E+00,05/01/1984
5,five,5.0,5.00E+00,06/01/1985
6,six,6.0,6.00E+00,07/01/1986
7,seven,7.0,7.00E+00,08/01/1987
8,eight,8.0,8.00E+00,09/01/1988
9,nine,9.0,9.00E+00,10/01/1989

SO_56387241_2.csv:
my_int,my_str,my_float,my_exp,my_date
10,ten,10.0,1.00E+01,01/01/1990
11,eleven,11.0,1.10E+01,02/01/1991
12,twelve,12.0,1.20E+01,03/01/1992
13,thirteen,13.0,1.30E+01,04/01/1993
14,fourteen,14.0,1.40E+01,04/01/1994
15,fifteen,15.0,1.50E+01,06/01/1995
16,sixteen,16.0,1.60E+01,07/01/1996
17,seventeen,17.0,1.70E+01,08/01/1997
18,eighteen,18.0,1.80E+01,09/01/1998
19,nineteen,19.0,1.90E+01,10/01/1999
</code>```

Body:
This sounds like it should be REALLY easy to answer with Google but I'm finding it impossible to answer the majority of my nontrivial pandas/pytables questions this way. All I'm trying to do is to load about 3 billion records from about 6000 different CSV files into a single table in a single HDF5 file. It's a simple table, 26 fields, mixture of strings, floats and ints. I'm loading the CSVs with df = pandas.read_csv() and appending them to my hdf5 file with df.to_hdf(). I really don't want to use df.to_hdf(data_columns = True) because it looks like that will take about 20 days versus about 4 days for df.to_hdf(data_columns = False). But apparently when you use df.to_hdf(data_columns = False) you end up with some pile of junk that you can't even recover the table structure from (or so it appears to my uneducated eye). Only the columns that were identified in the min_itemsize list (the 4 string columns) are identifiable in the hdf5 table, the rest are being dumped by data type into values_block_0 through values_block_4:

table = h5file.get_node('/tbl_main/table')
print(table.colnames)
['index', 'values_block_0', 'values_block_1', 'values_block_2', 'values_block_3', 'values_block_4', 'str_col1', 'str_col2', 'str_col3', 'str_col4']

And any query like df = pd.DataFrame.from_records(table.read_where(condition)) fails with error "Exception: Data must be 1-dimensional"

So my questions are: (1) Do I really have to use data_columns = True which takes 5x as long? I was expecting to do a fast load and then index just a few columns after loading the table. (2) What exactly is this pile of garbage I get using data_columns = False? Is it good for anything if I need my table back with query-able columns? Is it good for anything at all?

Body:
This is how you can create an HDF5 file from CSV data using pytables. You could also use a similar process to create the HDF5 file with h5py.

Use a loop to read the CSV files with np.genfromtxt into a np array.

After reading the first CSV file, write the data with .create_table() method, referencing the np array created in Step 1.

For additional CSV files, write the data with .append() method, referencing the np array created in Step 1

End of loop

Updated on 6/2/2019 to read a date field (mm/dd/YYY) and convert to datetime object. Note changes to genfromtxt() arguments! Data used is added below the updated code.

import numpy as np
import tables as tb
from datetime import datetime
csv_list = ['SO_56387241_1.csv', 'SO_56387241_2.csv' ]

my_dtype= np.dtype([ ('a',int),('b','S20'),('c',float),('d',float),('e','S20') ])

with tb.open_file('SO_56387241.h5', mode='w') as h5f:

for  PATH_csv in csv_list:
    csv_data = np.genfromtxt(PATH_csv, names=True, dtype=my_dtype, delimiter=',', encoding=None)
    # modify date in fifth field 'e'
    for row in csv_data :
        datetime_object = datetime.strptime(row['my_date'].decode('UTF-8'), '%m/%d/%Y' )
        row['my_date'] = datetime_object

    if h5f.__contains__('/CSV_Data') :
        dset = h5f.root.CSV_Data
        dset.append(csv_data)

    else:
        dset = h5f.create_table('/','CSV_Data', obj=csv_data)

    dset.flush()

h5f.close()

Data for testing:

SO_56387241_1.csv:
my_int,my_str,my_float,my_exp,my_date
0,zero,0.0,0.00E+00,01/01/1980
1,one,1.0,1.00E+00,02/01/1981
2,two,2.0,2.00E+00,03/01/1982
3,three,3.0,3.00E+00,04/01/1983
4,four,4.0,4.00E+00,05/01/1984
5,five,5.0,5.00E+00,06/01/1985
6,six,6.0,6.00E+00,07/01/1986
7,seven,7.0,7.00E+00,08/01/1987
8,eight,8.0,8.00E+00,09/01/1988
9,nine,9.0,9.00E+00,10/01/1989

SO_56387241_2.csv:
my_int,my_str,my_float,my_exp,my_date
10,ten,10.0,1.00E+01,01/01/1990
11,eleven,11.0,1.10E+01,02/01/1991
12,twelve,12.0,1.20E+01,03/01/1992
13,thirteen,13.0,1.30E+01,04/01/1993
14,fourteen,14.0,1.40E+01,04/01/1994
15,fifteen,15.0,1.50E+01,06/01/1995
16,sixteen,16.0,1.60E+01,07/01/1996
17,seventeen,17.0,1.70E+01,08/01/1997
18,eighteen,18.0,1.80E+01,09/01/1998
19,nineteen,19.0,1.90E+01,10/01/1999


问:
IE 11 throwing "'timeZone' is outside of valid range" when setting timezone to "Europe/London"
I have some js to get the local time displayed in uk's timezone.

```<code>var d = new Date(); // local system time (whatever timezone that is)
var dUK = new Date(d.toLocaleString('en-GB', { timeZone: 'Europe/London' })); // UK timezone (covers BST too)
</code>```

Works fine in all browsers except IE 11(sigh...) which throws the following error:

Option value 'EUROPE/LONDON' for 'timeZone' is outside of valid range. Expected: ['UTC']

Does anybody have any suggestions? See http://jsbin.com/dawaqocuvi/1/edit?html,js,console,output for an example fiddle that supports IE.

答:
Yes, as stated above, IE 11 supports most of the Intl API but does not support the use of a specific timeZone: http://kangax.github.io/compat-table/esintl/#test-DateTimeFormat_accepts_IANA_timezone_names

Here is an example of how to polyfill just the Intl.DateTimeFormat function's timeZone support using webpack's require.ensure:

```<code>const fillIntlDateTimeFormatTimezone = () => new Promise((resolve) => {
    try {
        new Intl.DateTimeFormat('en', {
            timeZone: 'America/Los_Angeles',
            timeZoneName: 'long'
        }).format();
        return resolve();
    } catch (error) {
        require.ensure(['date-time-format-timezone'], (require) => {
            require('date-time-format-timezone');
            return resolve();
        }, 'DateTimeFormatTimezone');
    }
});
</code>```

This should only load the polyfill for browsers that don't support specifying a timeZone property which should only be IE 11 at this point.

Body:
I have some js to get the local time displayed in uk's timezone.

var d = new Date(); // local system time (whatever timezone that is)
var dUK = new Date(d.toLocaleString('en-GB', { timeZone: 'Europe/London' })); // UK timezone (covers BST too)

Works fine in all browsers except IE 11(sigh...) which throws the following error:

Option value 'EUROPE/LONDON' for 'timeZone' is outside of valid range. Expected: ['UTC']

Does anybody have any suggestions? See http://jsbin.com/dawaqocuvi/1/edit?html,js,console,output for an example fiddle that supports IE.

Body:
Yes, as stated above, IE 11 supports most of the Intl API but does not support the use of a specific timeZone: http://kangax.github.io/compat-table/esintl/#test-DateTimeFormat_accepts_IANA_timezone_names

Here is an example of how to polyfill just the Intl.DateTimeFormat function's timeZone support using webpack's require.ensure:

const fillIntlDateTimeFormatTimezone = () => new Promise((resolve) => {
    try {
        new Intl.DateTimeFormat('en', {
            timeZone: 'America/Los_Angeles',
            timeZoneName: 'long'
        }).format();
        return resolve();
    } catch (error) {
        require.ensure(['date-time-format-timezone'], (require) => {
            require('date-time-format-timezone');
            return resolve();
        }, 'DateTimeFormatTimezone');
    }
});

This should only load the polyfill for browsers that don't support specifying a timeZone property which should only be IE 11 at this point.


问:
Parse error: syntax error, unexpected ';' everything looks fine
I want to insert some information into a MySQL table but in the line of code where I'm inserting the info, it keeps giving me the same error.

The problem is in the first line of code.

I checked any parentheses I maybe forgot to add or square brackets or curly brackets. I don't see any problems but maybe you will. Could you please help me?

for some reason this if statement doesn't want to be inside the box of code.

```<code>if(mysql_num_rows($sql2==1) {

        $sql = "INSERT INTO users (username, email, password) VALUES (:username, :email, :password)";

        if($stmt = $pdo->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bindParam(":username", $param_username, PDO::PARAM_STR);
            $stmt->bindParam(":email", $param_email, PDO::PARAM_STR);
            $stmt->bindParam(":password", $param_password, PDO::PARAM_STR);

            // Set parameters
            $param_username = $username;
            $param_email = $email;
            $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Redirect to login page
                header("location: login.php");
            } else{
                echo "Something went wrong. Please try again later.";
            }
        }

        // Close statement
        unset($stmt);
    }
</code>```

Parse error: syntax error, unexpected ';'

答:
You have to do it like this:

```<code>if (mysql_num_rows($sql2) == 1) {
    //ur code
}
</code>```

You forgot a ")" and are asking a qustion inside a pdo function

It also give the response of "Parse error: syntax error, unexpected ';' everything looks fine"

because the function mysql_num_rows cant handle "=="

EDIT

the function mysql_num_rows is deprecated use mysqli_num_rows() instead

read the docs here

Body:
I want to insert some information into a MySQL table but in the line of code where I'm inserting the info, it keeps giving me the same error.

The problem is in the first line of code.

I checked any parentheses I maybe forgot to add or square brackets or curly brackets. I don't see any problems but maybe you will. Could you please help me?

for some reason this if statement doesn't want to be inside the box of code.

if(mysql_num_rows($sql2==1) {

        $sql = "INSERT INTO users (username, email, password) VALUES (:username, :email, :password)";

        if($stmt = $pdo->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bindParam(":username", $param_username, PDO::PARAM_STR);
            $stmt->bindParam(":email", $param_email, PDO::PARAM_STR);
            $stmt->bindParam(":password", $param_password, PDO::PARAM_STR);

            // Set parameters
            $param_username = $username;
            $param_email = $email;
            $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Redirect to login page
                header("location: login.php");
            } else{
                echo "Something went wrong. Please try again later.";
            }
        }

        // Close statement
        unset($stmt);
    }

Parse error: syntax error, unexpected ';'

Body:
You have to do it like this:

if (mysql_num_rows($sql2) == 1) {
    //ur code
}

You forgot a ")" and are asking a qustion inside a pdo function

It also give the response of "Parse error: syntax error, unexpected ';' everything looks fine"

because the function mysql_num_rows cant handle "=="

EDIT

the function mysql_num_rows is deprecated use mysqli_num_rows() instead

read the docs here


问:
Bootstrap : Add a junction between div
I'm trying to add a junction (a line) between 2 divs in the middle.

```<code><div class="row">
<div class="col-xs-6 col-md-6">
    <div style="background-color:#f39a6f;width:100%;height:100px;">
    ....1
    </div>
</div>
<div class="col-xs-6 col-md-6">
    <div style="background-color:#ffff00;width:100%;height:100px;">
    ....2
    </div>
</div>
</code>```

Thanks for help.

答:
My idea is to have the junction (a line) always be the center of a row via absolute/relative positioning, with lower z-index than what those color blocks have so that the line is hidden behind the blocks but shown between the blocks.

The tricky part is accurately calculate the position of the junction line, due to the fact that bootstrap rows have their own paddings. That's why it's better to use SCSS so that you can read bootstrap default values for row and column settings, and calculate the junction line based on those.

But for demo purpose, I will stick with CSS and "hardcode" the pre-configured values from bootstrap.

HTML Structure

```
<h3>CSS</h3>
<pre class="lang-css prettyprint-override"><code>.junction-row {
    height: 6rem;
    position: relative;
}

.junction-row::after {
    content: '';
    position: absolute;
    background-color: var(--danger);
    height: 5%;

    // Default bootstrap row's padding is 1rem.
    // Width = 100% - left padding of the row - right padding of the row
    width: calc(100% - 2rem);

    // Top = total height 100% - the height of the line, and then divide by 2
    // to have the line stay in the center of the row.
    top: calc((100% - 5%) / 2);

    // Left = starting after the row's left padding
    left: 1rem;

    // Any value here, but it needs to be lower than what .block has
    z-index: 1;
}

.block {
    position: relative;
    height: 6rem;
    z-index: 2;
}
</code>```

Result

demo: https://jsfiddle.net/davidliang2008/vknor3cz/32/

Title: Bootstrap : Add a junction between div

Body:
I'm trying to add a junction (a line) between 2 divs in the middle.

    ....1

    ....2

Thanks for help.

Body:
My idea is to have the junction (a line) always be the center of a row via absolute/relative positioning, with lower z-index than what those color blocks have so that the line is hidden behind the blocks but shown between the blocks.

The tricky part is accurately calculate the position of the junction line, due to the fact that bootstrap rows have their own paddings. That's why it's better to use SCSS so that you can read bootstrap default values for row and column settings, and calculate the junction line based on those.

But for demo purpose, I will stick with CSS and "hardcode" the pre-configured values from bootstrap.

HTML Structure

<div class="row junction-row">
    <div class="col-6 col-sm-3">
        <div class="block bg-primary"></div>
    </div>
    </div class="col-6 col-sm-4 offset-sm-5">
        <div class="block bg-danger"></div>
    </div>
</div>

CSS

.junction-row {
    height: 6rem;
    position: relative;
}

.junction-row::after {
    content: '';
    position: absolute;
    background-color: var(--danger);
    height: 5%;

    // Default bootstrap row's padding is 1rem.
    // Width = 100% - left padding of the row - right padding of the row
    width: calc(100% - 2rem);

    // Top = total height 100% - the height of the line, and then divide by 2
    // to have the line stay in the center of the row.
    top: calc((100% - 5%) / 2);

    // Left = starting after the row's left padding
    left: 1rem;

    // Any value here, but it needs to be lower than what .block has
    z-index: 1;
}

.block {
    position: relative;
    height: 6rem;
    z-index: 2;
}

Result

demo: https://jsfiddle.net/davidliang2008/vknor3cz/32/


问:
Removing an object from list where the objects string property is not in another list<t>'s property
So I have two lists

List<ObjectA> and List<ObjectB>

each list contains a string property ItemID

I have an issue where if any ObjectA's string property within the list is not found within any of the string property of ObjectB within the list, then remove ObjectA from the list.

So far here is my code

```<code>List<string> orderedItemIds = new List<string>();
List<string> shippedItemIds = new List<string>();

for (int y = 0; y <= result.Order_Info.Order_Items.Count - 1; y++)
{
    orderedItemIds.Add(result.Order_Info.Order_Items[y].Item_Id);
}

for (int i = 0; i <= result.Order_Info.Shipments.Count-1; i++)
{
    for (int x = 0; x <= result.Order_Info.Shipments[i].Items_Info.Count - 1; x++)
    {
       shippedItemIds.Add(result.Order_Info.Shipments[i].Items_Info[x].Item_Id);
    }
}
</code>```

Now I'm stuck on even if I am able to identify which string isn't in the other list, how am I going to remove that object? Do I just loop through each object of the list I am removing from and check if that string is within the list, if it is then remove it?

Solution:
Thanks to the answer I realized I could flip the logic but I guess I was tunnel visioned.

```<code>        List<string> orderedItemIds = new List<string>();
        List<OrderShipmentModel> shippedItems = new List<OrderShipmentModel>();
        for (int y = 0; y <= result.Order_Info.Order_Items.Count - 1; y++)
        {
            orderedItemIds.Add(result.Order_Info.Order_Items[y].Item_Id);
        }

        for (int i = 0; i <= result.Order_Info.Shipments.Count-1; i++)
        {
            for (int x = 0; x <= result.Order_Info.Shipments[i].Items_Info.Count - 1; x++)
                if(orderedItemIds.Any(item => item == result.Order_Info.Shipments[i].Items_Info[x].Item_Id))
                    shippedItems.Add(result.Order_Info.Shipments[i]);
        }
</code>```

答:
You can change the logic here, instead of removing items from original list, you can create the new list that will contain only valid items.

```<code>class Program
{
    private class MyClass
    {
        public string ItemId { get; set; }
    }
    static void Main(string[] args)
    {
        var listA = new List<MyClass> {
            new MyClass { ItemId = "a"},
            new MyClass { ItemId = "b"},
            new MyClass { ItemId = "c"},
            new MyClass { ItemId = "d"}};

        var listB = new List<MyClass> {
            new MyClass { ItemId = "a"},
            new MyClass { ItemId = "b"},
            new MyClass { ItemId = "x"},
            new MyClass { ItemId = "y"}};

        var listWithValidItemsOnly = new List<MyClass>();

        foreach (var itemA in listA)
        {
            if (listB.Any(item => item.ItemId == itemA.ItemId))
                listWithValidItemsOnly.Add(itemA);
        }

    }
}
</code>```

I made this example simple to depict the logic here. Keep in mind that for bigger lists, it would be better to convert listB to Dictionary so then you will be able to get the presence of any key with O(1) complexity.

Body:
So I have two lists

List<ObjectA> and List<ObjectB>

each list contains a string property ItemID

I have an issue where if any ObjectA's string property within the list is not found within any of the string property of ObjectB within the list, then remove ObjectA from the list.

So far here is my code

List<string> orderedItemIds = new List<string>();
List<string> shippedItemIds = new List<string>();

for (int y = 0; y <= result.Order_Info.Order_Items.Count - 1; y++)
{
    orderedItemIds.Add(result.Order_Info.Order_Items[y].Item_Id);
}

for (int i = 0; i <= result.Order_Info.Shipments.Count-1; i++)
{
    for (int x = 0; x <= result.Order_Info.Shipments[i].Items_Info.Count - 1; x++)
    {
       shippedItemIds.Add(result.Order_Info.Shipments[i].Items_Info[x].Item_Id);
    }
}

Now I'm stuck on even if I am able to identify which string isn't in the other list, how am I going to remove that object? Do I just loop through each object of the list I am removing from and check if that string is within the list, if it is then remove it?

Solution:
Thanks to the answer I realized I could flip the logic but I guess I was tunnel visioned.

        List<string> orderedItemIds = new List<string>();
        List<OrderShipmentModel> shippedItems = new List<OrderShipmentModel>();
        for (int y = 0; y <= result.Order_Info.Order_Items.Count - 1; y++)
        {
            orderedItemIds.Add(result.Order_Info.Order_Items[y].Item_Id);
        }

        for (int i = 0; i <= result.Order_Info.Shipments.Count-1; i++)
        {
            for (int x = 0; x <= result.Order_Info.Shipments[i].Items_Info.Count - 1; x++)
                if(orderedItemIds.Any(item => item == result.Order_Info.Shipments[i].Items_Info[x].Item_Id))
                    shippedItems.Add(result.Order_Info.Shipments[i]);
        }

Body:
You can change the logic here, instead of removing items from original list, you can create the new list that will contain only valid items.

class Program
{
    private class MyClass
    {
        public string ItemId { get; set; }
    }
    static void Main(string[] args)
    {
        var listA = new List<MyClass> {
            new MyClass { ItemId = "a"},
            new MyClass { ItemId = "b"},
            new MyClass { ItemId = "c"},
            new MyClass { ItemId = "d"}};

        var listB = new List<MyClass> {
            new MyClass { ItemId = "a"},
            new MyClass { ItemId = "b"},
            new MyClass { ItemId = "x"},
            new MyClass { ItemId = "y"}};

        var listWithValidItemsOnly = new List<MyClass>();

        foreach (var itemA in listA)
        {
            if (listB.Any(item => item.ItemId == itemA.ItemId))
                listWithValidItemsOnly.Add(itemA);
        }

    }
}

I made this example simple to depict the logic here. Keep in mind that for bigger lists, it would be better to convert listB to Dictionary so then you will be able to get the presence of any key with O(1) complexity.


问:
AttributeError: 'str' object has no attribute 'copy' when parsing Multipart email message
Python 3.6 email module crashes with this error:

```<code>Traceback (most recent call last):
  File "empty-eml.py", line 9, in <module>
    for part in msg.iter_attachments():
  File "/usr/lib/python3.6/email/message.py", line 1055, in iter_attachments
    parts = self.get_payload().copy()
AttributeError: 'str' object has no attribute 'copy'
</code>```

The crash can be reproduced with this EML file,

```<code>From: "xxx@xxx.xx" <xxx@xxx.xx>
To: <xx@xxx.xx>
Subject: COURRIER EMIS PAR PACIFICA
MIME-Version: 1.0
Content-Type: multipart/mixed;
    boundary="----=_Part_3181_1274694650.1556805728023"
Date: Thu, 2 May 2019 16:02:08 +0200
</code>```

and this piece of minimal code:

```<code>from email import policy
from email.parser import Parser
from sys import argv

with open(argv[1]) as eml_file:
    msg = Parser(policy=policy.default).parse(eml_file)

for part in msg.iter_attachments():
    pass
</code>```

I believe it has to do something with the Content-Type being multipart/mixed together with the email content being empty, which causes get_payload to return str. However, I am not sure, if such EML is forbidden by standard (but I have many such samples), it is a bug in the email module, or me using the code wrong.

答:
If you change the policy to strict:

```<code>Parser(policy=policy.strict).parse(eml_file)
</code>```

the parser raises email.errors.StartBoundaryNotFoundDefect, described in the docs as:

StartBoundaryNotFoundDefect – The start boundary claimed in the Content-Type header was never found.

If you parse the message with policy.default and inspect it's defects afterwards it contains two defects:

```<code>[StartBoundaryNotFoundDefect(), MultipartInvariantViolationDefect()]
</code>```

MultipartInvariantViolationDefect – A message claimed to be a multipart, but no subparts were found. Note that when a message has this defect, its is_multipart() method may return false even though its content type claims to be multipart.

A consequence of the StartBoundaryNotFoundDefect is that the parser terminates parsing and sets the message payload to the body that has been captured so far - in this case, nothing, so the payload is an empty string, causing the exception that you are seeing when you run your code.

Arguably the fact that Python doesn't check whether payload is a list before calling copy() on it is a bug.

In practice, you have to handle these messages either by wrapping the iteration of attachments in a try/except, conditioning iteration on the contents of msg.defects, or parsing with policy.strict and discarding all messages that report defects.

Body:
Python 3.6 email module crashes with this error:

Traceback (most recent call last):
  File "empty-eml.py", line 9, in <module>
    for part in msg.iter_attachments():
  File "/usr/lib/python3.6/email/message.py", line 1055, in iter_attachments
    parts = self.get_payload().copy()
AttributeError: 'str' object has no attribute 'copy'

The crash can be reproduced with this EML file,

From: "xxx@xxx.xx" <xxx@xxx.xx>
To: <xx@xxx.xx>
Subject: COURRIER EMIS PAR PACIFICA
MIME-Version: 1.0
Content-Type: multipart/mixed;
    boundary="----=_Part_3181_1274694650.1556805728023"
Date: Thu, 2 May 2019 16:02:08 +0200

and this piece of minimal code:

from email import policy
from email.parser import Parser
from sys import argv

with open(argv[1]) as eml_file:
    msg = Parser(policy=policy.default).parse(eml_file)

for part in msg.iter_attachments():
    pass

I believe it has to do something with the Content-Type being multipart/mixed together with the email content being empty, which causes get_payload to return str. However, I am not sure, if such EML is forbidden by standard (but I have many such samples), it is a bug in the email module, or me using the code wrong.

Body:
If you change the policy to strict:

Parser(policy=policy.strict).parse(eml_file)

the parser raises email.errors.StartBoundaryNotFoundDefect, described in the docs as:

StartBoundaryNotFoundDefect – The start boundary claimed in the Content-Type header was never found.

If you parse the message with policy.default and inspect it's defects afterwards it contains two defects:

[StartBoundaryNotFoundDefect(), MultipartInvariantViolationDefect()]

MultipartInvariantViolationDefect – A message claimed to be a multipart, but no subparts were found. Note that when a message has this defect, its is_multipart() method may return false even though its content type claims to be multipart.

A consequence of the StartBoundaryNotFoundDefect is that the parser terminates parsing and sets the message payload to the body that has been captured so far - in this case, nothing, so the payload is an empty string, causing the exception that you are seeing when you run your code.

Arguably the fact that Python doesn't check whether payload is a list before calling copy() on it is a bug.

In practice, you have to handle these messages either by wrapping the iteration of attachments in a try/except, conditioning iteration on the contents of msg.defects, or parsing with policy.strict and discarding all messages that report defects.


问:
Lapply a function over list of data tables, that requires reference to previous row
I would like to apply an function over all rows of a data table, for all data tables in a list, however the function must refer to a previous row in the calculation (apart from row 1, which is independent)

I can do it when not needing to refer to the previous row;

```<code>require(data.table)

# dummy list data
l <- list(data.table(col1=c(2,3,4,2,1), col2=c(1,2,3,4,3), col3=c(5,4,3,4,5), col4=c(1,1,1,1,2)), data.table(col1=c(3,4,3,2,3), col2=c(1,3,4,2,2), col3=c(5,4,3,2,3), col4=c(5,5,5,5,5)))

# apply the function to the data table by row, and apply this function to all tables in the list
lapply(l, function(b) b[ , value := mapply(function(w,x,y,z) w + x + y * z, col1, col2, col3, col4)])
</code>```

but how do i make value take into account value from the previous row?

```<code># this wont work b'cos value hasn't been created yet
lapply(l, function(b) b[ , value := mapply(function(w,x,y,z) w + x + y * z, col1, col2, col3, col4)])

 Error in mapply(function(w, x, y, z, v) (w + x + y * z)/shift(v, 1), col1,  :
  object 'value' not found

# so make 'value' for row 1 only and try again
lapply(l, function(b) b[ , value := 0])
lapply(l, function(b) b[1 , value := col1 + col2 + col3 - col4])

# using shift inside mapply
lapply(l, function(b) b[ , value := mapply(function(w,x,y,z,v) (w + x + y * z) / shift(v,1), col1, col2, col3, col4, value)])
</code>```

turns the value column all into NAs

答:
updated to reflect other comments

for this case couldn't you just avoid apply functions altogether and do something like:

```<code>names(l) <- c("list1","list2")
l <- rbindlist(l,idcol=TRUE)
l[,value := col1 + col2 + col3 * col4,by=.id]
l[,value2 := value / shift(value, fill = 1),by=.id]
</code>```

which returns

```<code>      .id col1 col2 col3 col4 value     value2
 1: list1    2    1    5    1     8  8.0000000
 2: list1    3    2    4    1     9  1.1250000
 3: list1    4    3    3    1    10  1.1111111
 4: list1    2    4    4    1    10  1.0000000
 5: list1    1    3    5    2    14  1.4000000
 6: list2    3    1    5    5    29 29.0000000
 7: list2    4    3    4    5    27  0.9310345
 8: list2    3    4    3    5    22  0.8148148
 9: list2    2    2    2    5    14  0.6363636
10: list2    3    2    3    5    20  1.4285714
</code>```

the important part here is the fill argument of the shift() function, described here

Body:
I would like to apply an function over all rows of a data table, for all data tables in a list, however the function must refer to a previous row in the calculation (apart from row 1, which is independent)

I can do it when not needing to refer to the previous row;

require(data.table)

# dummy list data
l <- list(data.table(col1=c(2,3,4,2,1), col2=c(1,2,3,4,3), col3=c(5,4,3,4,5), col4=c(1,1,1,1,2)), data.table(col1=c(3,4,3,2,3), col2=c(1,3,4,2,2), col3=c(5,4,3,2,3), col4=c(5,5,5,5,5)))

# apply the function to the data table by row, and apply this function to all tables in the list
lapply(l, function(b) b[ , value := mapply(function(w,x,y,z) w + x + y * z, col1, col2, col3, col4)])

but how do i make value take into account value from the previous row?

# this wont work b'cos value hasn't been created yet
lapply(l, function(b) b[ , value := mapply(function(w,x,y,z) w + x + y * z, col1, col2, col3, col4)])

 Error in mapply(function(w, x, y, z, v) (w + x + y * z)/shift(v, 1), col1,  :
  object 'value' not found

# so make 'value' for row 1 only and try again
lapply(l, function(b) b[ , value := 0])
lapply(l, function(b) b[1 , value := col1 + col2 + col3 - col4])

# using shift inside mapply
lapply(l, function(b) b[ , value := mapply(function(w,x,y,z,v) (w + x + y * z) / shift(v,1), col1, col2, col3, col4, value)])

turns the value column all into NAs

Body:
updated to reflect other comments

for this case couldn't you just avoid apply functions altogether and do something like:

names(l) <- c("list1","list2")
l <- rbindlist(l,idcol=TRUE)
l[,value := col1 + col2 + col3 * col4,by=.id]
l[,value2 := value / shift(value, fill = 1),by=.id]

which returns

      .id col1 col2 col3 col4 value     value2
 1: list1    2    1    5    1     8  8.0000000
 2: list1    3    2    4    1     9  1.1250000
 3: list1    4    3    3    1    10  1.1111111
 4: list1    2    4    4    1    10  1.0000000
 5: list1    1    3    5    2    14  1.4000000
 6: list2    3    1    5    5    29 29.0000000
 7: list2    4    3    4    5    27  0.9310345
 8: list2    3    4    3    5    22  0.8148148
 9: list2    2    2    2    5    14  0.6363636
10: list2    3    2    3    5    20  1.4285714

the important part here is the fill argument of the shift() function, described here


问:
Object to array to generate API payload
I know that the title might be really similar to other existing questions but the actual problem is really different from the ones existing (at least I can't really find another one similar).

I have an API that I need to communicate with in order to create a customer, in the fields to create a new customer, there's the Address field, and yes, the field requires the A uppercase. But what this all mean?

I thought about creating entities with public method so I can convert them to array and generate the payload to send, something like this:

```<code>class Customer extends Entity
{
    public $name;
    public $email;
    public $phone;
    public $address;
}
</code>```

This entity would be easily converted to array by just using (array) or even using get_object_vars, the real problem here is that I want $address to be an instance of another entity called Address, like this:

```<code>class Address extends Entity
{
    public $street;
    public $number;
    public $city;
    public $state;
}
</code>```

For this I implemented one method called properties, like this:

```<code>abstract class Entity {
    public function properties(): array
    {
        $convert = function($value) use(&$convert)
        {
            return is_scalar($value) ? $value : array_map($convert, (array) $value);
        };

        return $convert($this);
    }
}
</code>```

It works, it will transform recursively.

The problem here is: instead of Address as key, it's returning address in lower case (obviously) because it's only getting the fields.

I was wondering, how can I accomplish that? How can I set the key with the first letter uppercase if the field of an entity is an object (another entity)?

The expected result would be something like:

```<code>[
    'name' => '...'
    'email' => '...'
    'phone' => '...'
    'Address' => [
        'street' => '...'
        'number' => '...'
        'city' => '...'
        'state' => '...'
    ]
]
</code>```

Thank you in advanced.

答:
You could reverse the condition, and use the class name as the key if the value of the property is an instance of Entity.

```<code>public function properties(): array
{
    $result = [];
    foreach ($this as $key => $value) {
        if ($value instanceof Entity) {
            $result[get_class($value)] = $value->properties();
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}
</code>```

I can see some potential drawbacks to the general idea of this, though. For example, if a person entity needs to have multiple addresses at some point this won't work because the second address will overwrite the first one. You could just strtoupper the property name, but if it isn't the class name, it seems like it wouldn't really matter if it was capitalized or not.

Title: Object to array to generate API payload

Body:
I know that the title might be really similar to other existing questions but the actual problem is really different from the ones existing (at least I can't really find another one similar).

I have an API that I need to communicate with in order to create a customer, in the fields to create a new customer, there's the Address field, and yes, the field requires the A uppercase. But what this all mean?

I thought about creating entities with public method so I can convert them to array and generate the payload to send, something like this:

class Customer extends Entity
{
    public $name;
    public $email;
    public $phone;
    public $address;
}

This entity would be easily converted to array by just using (array) or even using get_object_vars, the real problem here is that I want $address to be an instance of another entity called Address, like this:

class Address extends Entity
{
    public $street;
    public $number;
    public $city;
    public $state;
}

For this I implemented one method called properties, like this:

abstract class Entity {
    public function properties(): array
    {
        $convert = function($value) use(&$convert)
        {
            return is_scalar($value) ? $value : array_map($convert, (array) $value);
        };

        return $convert($this);
    }
}

It works, it will transform recursively.

The problem here is: instead of Address as key, it's returning address in lower case (obviously) because it's only getting the fields.

I was wondering, how can I accomplish that? How can I set the key with the first letter uppercase if the field of an entity is an object (another entity)?

The expected result would be something like:

[
    'name' => '...'
    'email' => '...'
    'phone' => '...'
    'Address' => [
        'street' => '...'
        'number' => '...'
        'city' => '...'
        'state' => '...'
    ]
]

Thank you in advanced.

Body:
You could reverse the condition, and use the class name as the key if the value of the property is an instance of Entity.

public function properties(): array
{
    $result = [];
    foreach ($this as $key => $value) {
        if ($value instanceof Entity) {
            $result[get_class($value)] = $value->properties();
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}

I can see some potential drawbacks to the general idea of this, though. For example, if a person entity needs to have multiple addresses at some point this won't work because the second address will overwrite the first one. You could just strtoupper the property name, but if it isn't the class name, it seems like it wouldn't really matter if it was capitalized or not.


问:
CSS trouble getting elements to center both vertically and horizontally using flex

Sorry for the beginner question but i have been stuck on this for a long time. I have am trying to use flex to center align the div.Homepage elements but i cant seem to get anything but the button to align horizontally.  I also cant get the text TEST to center.  My CSS is below:

```<code>body {
    font-family: 'Recoleta';
    color: #FFF;
    background: #111;

}

html, body {
    height: 100%;

}

.Homepage{
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
}

.logo-social-image{
    max-width: 20%;
}
</code>```

My React HTML is below

```<code>   return(
            <div className="Homepage">
                <div className="Name-social">
                    {view}
                </div>
                <div className="Pro-button">
                    <OutlinedButtons  isLoading={this.state.isLoading} isLoaded={this.isLoaded} />
                </div>
            </div>
        )
</code>```

答:
Just add justify-content: center to the class Homepage.

```<code>.Homepage {
  /*Keep your previous style*/
  justify-content: center;
}
</code>```

Body:
Sorry for the beginner question but i have been stuck on this for a long time. I have am trying to use flex to center align the div.Homepage elements but i cant seem to get anything but the button to align horizontally.  I also cant get the text TEST to center.  My CSS is below:

body {
    font-family: 'Recoleta';
    color: #FFF;
    background: #111;

}

html, body {
    height: 100%;

}

.Homepage{
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
}

.logo-social-image{
    max-width: 20%;
}

My React HTML is below

   return(

                    {view}

                    <OutlinedButtons  isLoading={this.state.isLoading} isLoaded={this.isLoaded} />

        )

Body:
Just add justify-content: center to the class Homepage.

.Homepage {
  /*Keep your previous style*/
  justify-content: center;
}


问:
How to create a new application with `ng new`?
I am using node v10.16.0 but every time I try to run "ng new" or "ng -v" I get an error saying I am running V6.11.3 and that I should use version 10.9 or greater.

I have tried to clean the cache using "npm cache clean". I have tried to uninstall and reinstall angular and node. I have check the system variables and add the path.

```<code>C:\Users\Yv-Arnel\code>node -v
v10.16.0

C:\Users\Yv-Arnel\code>ng -v
You are running version v6.11.3 of Node.js, which is not supported by Angular CLI 8.0+.
The official Node.js version that is supported is 10.9 or greater.

Please visit https://nodejs.org/en/ to find instructions on how to update Node.js.
</code>```

答:
There was a node version installed using Laragon

I was using Laragon a year ago and I installed node.js using Laragon.
I uninstall node with Control Panel But I was still able to run "node -v" because there was two versions installed.So I looked for the directory where Laragon installed it and delete it after that I installed the latest versions of node aivalaible on their website and I was able to run "ng new".

Body:
I am using node v10.16.0 but every time I try to run "ng new" or "ng -v" I get an error saying I am running V6.11.3 and that I should use version 10.9 or greater.

I have tried to clean the cache using "npm cache clean". I have tried to uninstall and reinstall angular and node. I have check the system variables and add the path.

C:\Users\Yv-Arnel\code>node -v
v10.16.0

C:\Users\Yv-Arnel\code>ng -v
You are running version v6.11.3 of Node.js, which is not supported by Angular CLI 8.0+.
The official Node.js version that is supported is 10.9 or greater.

Please visit https://nodejs.org/en/ to find instructions on how to update Node.js.


问:
AutoMapper - Retrieve a different field from a linked source table than the one that links it
I have the following table structure that mixes legacy fields with an updated schema:

```<code>Coaster
  Id (Int)
  ParkId (Int)

Park
  Id (int)
  UniqueId (Guid)
</code>```

So, the Coaster and Park tables are linked using the Park.Id field. The UniqueId field is not currently used in the old schema. We are migrating to a clean DB using AutoMapper, and this new schema looks like this:

```<code>Coaster
  Id (Int)
  ParkId (Guid)

Park
  Id (Guid)
</code>```

The problem I am having is doing this using AutoMapper. I've been experimenting with this code:

```<code>private ModelMapper()
{
    Mapper.Initialize(x =>
    {
        x.AddProfile<ConvertersMappingProfile>();
    });
}

    // This is the part that I'm trying to work out
    public ConvertersMappingProfile()
    {
            CreateMap<Park, NewSchema.Park>()
                .ForMember(dst => dst.Id, map => map.MapFrom(src => src.ParkId));
    }
</code>```

In the new schema, the Park table's Id matches the old schema's UniqueId.

My question is: Because in the old schema there is no direct link to the UniqueId value of the Park table, how to do I get that value to map to the new schema using the Coaster.ParkId field to Park.Id field mapping?

答:
I used a custom resolve to fix the problem. So I created my resolver, which pulls up a list of the items in the database (which is typically pretty small) to get all the values from the table I need, and retrieves the value. (Pre-refactored code):

```<code>public class ParkResolver : IValueResolver<Original.Park, New.Park, string> {
    public string Resolve(Original.Park source, New.Park dest, string destMember, ResolutionContext context) {

        List<Original.Park> list = new List<Original.Park>();

        using (IDbConnection con = new SQLiteConnection(@"Data Source=C:\Users\Me\Documents\Parks.sql;")) {
            con.Open();
            list = con.Query<Original.Park>($"SELECT * FROM Parks WHERE Id = {source.ParkId}").ToList();
            con.Close();
        }

        return list.FirstOrDefault().UniqueId;
    }
}
</code>```

And I call my custom resolver for the tables I am mapping:

```<code>        CreateMap<Original.Park, New.Park>()
            .ForMember(dst => dst.ParkId, map => map.MapFrom(new ParkResolver()));
</code>```

Hopefully that will help someone else.

Body:
I have the following table structure that mixes legacy fields with an updated schema:

Coaster
  Id (Int)
  ParkId (Int)

Park
  Id (int)
  UniqueId (Guid)

So, the Coaster and Park tables are linked using the Park.Id field. The UniqueId field is not currently used in the old schema. We are migrating to a clean DB using AutoMapper, and this new schema looks like this:

Coaster
  Id (Int)
  ParkId (Guid)

Park
  Id (Guid)

The problem I am having is doing this using AutoMapper. I've been experimenting with this code:

private ModelMapper()
{
    Mapper.Initialize(x =>
    {
        x.AddProfile<ConvertersMappingProfile>();
    });
}

    // This is the part that I'm trying to work out
    public ConvertersMappingProfile()
    {
            CreateMap<Park, NewSchema.Park>()
                .ForMember(dst => dst.Id, map => map.MapFrom(src => src.ParkId));
    }

In the new schema, the Park table's Id matches the old schema's UniqueId.

My question is: Because in the old schema there is no direct link to the UniqueId value of the Park table, how to do I get that value to map to the new schema using the Coaster.ParkId field to Park.Id field mapping?

Body:
I used a custom resolve to fix the problem. So I created my resolver, which pulls up a list of the items in the database (which is typically pretty small) to get all the values from the table I need, and retrieves the value. (Pre-refactored code):

public class ParkResolver : IValueResolver<Original.Park, New.Park, string> {
    public string Resolve(Original.Park source, New.Park dest, string destMember, ResolutionContext context) {

        List<Original.Park> list = new List<Original.Park>();

        using (IDbConnection con = new SQLiteConnection(@"Data Source=C:\Users\Me\Documents\Parks.sql;")) {
            con.Open();
            list = con.Query<Original.Park>($"SELECT * FROM Parks WHERE Id = {source.ParkId}").ToList();
            con.Close();
        }

        return list.FirstOrDefault().UniqueId;
    }
}

And I call my custom resolver for the tables I am mapping:

        CreateMap<Original.Park, New.Park>()
            .ForMember(dst => dst.ParkId, map => map.MapFrom(new ParkResolver()));

Hopefully that will help someone else.


问:
Converting ISO 8601-compliant String to java.util.Date
I am trying to convert an ISO 8601 formatted String to a java.util.Date.

I found the pattern yyyy-MM-dd'T'HH:mm:ssZ to be ISO8601-compliant if used with a Locale (compare sample).

However, using the java.text.SimpleDateFormat, I cannot convert the correctly formatted String 2010-01-01T12:00:00+01:00. I have to convert it first to 2010-01-01T12:00:00+0100, without the colon.

So, the current solution is

SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.GERMANY);
String date = "2010-01-01T12:00:00+01:00".replaceAll("\\+0([0-9]){1}\\:00", "+0$100");
System.out.println(ISO8601DATEFORMAT.parse(date));
```

<p>which obviously isn't that nice. Am I missing something or is there a better solution?</p>

<hr>

<p><strong>Answer</strong></p>

<p>Thanks to JuanZe's comment, I found the Joda-Time magic, it is also described here.</p>

<p>So, the solution is</p>

<pre class="lang-java prettyprint-override"><code>DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();
String jtdate = "2010-01-01T12:00:00+01:00";
System.out.println(parser2.parseDateTime(jtdate));
</code>```

Or more simply, use the default parser via the constructor:

DateTime dt = new DateTime( "2010-01-01T12:00:00+01:00" ) ;
```

To me, this is nice.

答:
I am surprised that not even one java library supports all ISO 8601 date formats as per https://en.wikipedia.org/wiki/ISO_8601. Joda DateTime was supporting most of them, but not all and hence I added custom logic to handle all of them. Here is my implementation.

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang3.time.DateUtils;
import org.joda.time.DateTime;

public class ISO8601DateUtils {

 /**
  * It parses all the date time formats from https://en.wikipedia.org/wiki/ISO_8601 and returns Joda DateTime.
  * Zoda DateTime does not support dates of format 20190531T160233Z, and hence added custom logic to handle this using SimpleDateFormat.
  * @param dateTimeString ISO 8601 date time string
  * @return
  */
 public static DateTime parse(String dateTimeString) {
  try {
   return new DateTime( dateTimeString );
  } catch(Exception e) {
   try {
    Date dateTime = DateUtils.parseDate(dateTimeString, JODA_NOT_SUPPORTED_ISO_DATES);
    return new DateTime(dateTime.getTime());
   } catch (ParseException e1) {
    throw new RuntimeException(String.format("Date %s could not be parsed to ISO date", dateTimeString));
   }
  }
 }

   private static String[] JODA_NOT_SUPPORTED_ISO_DATES = new String[] {
   // upto millis
   "yyyyMMdd'T'HHmmssSSS'Z'",
   "yyyyMMdd'T'HHmmssSSSZ",
   "yyyyMMdd'T'HHmmssSSSXXX",

   "yyyy-MM-dd'T'HHmmssSSS'Z'",
   "yyyy-MM-dd'T'HHmmssSSSZ",
   "yyyy-MM-dd'T'HHmmssSSSXXX",

   // upto seconds
   "yyyyMMdd'T'HHmmss'Z'",
   "yyyyMMdd'T'HHmmssZ",
   "yyyyMMdd'T'HHmmssXXX",

   "yyyy-MM-dd'T'HHmmss'Z'",
   "yyyy-MM-dd'T'HHmmssZ",
   "yyyy-MM-dd'T'HHmmssXXX",

   // upto minutes
   "yyyyMMdd'T'HHmm'Z'",
   "yyyyMMdd'T'HHmmZ",
   "yyyyMMdd'T'HHmmXXX",

   "yyyy-MM-dd'T'HHmm'Z'",
   "yyyy-MM-dd'T'HHmmZ",
   "yyyy-MM-dd'T'HHmmXXX",

   //upto hours is already supported by Joda DateTime
 };
}```

Body:
I am trying to convert an ISO 8601 formatted String to a java.util.Date.

I found the pattern yyyy-MM-dd'T'HH:mm:ssZ to be ISO8601-compliant if used with a Locale (compare sample).

However, using the java.text.SimpleDateFormat, I cannot convert the correctly formatted String 2010-01-01T12:00:00+01:00. I have to convert it first to 2010-01-01T12:00:00+0100, without the colon.

So, the current solution is

SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.GERMANY);
String date = "2010-01-01T12:00:00+01:00".replaceAll("\\+0([0-9]){1}\\:00", "+0$100");
System.out.println(ISO8601DATEFORMAT.parse(date));

which obviously isn't that nice. Am I missing something or is there a better solution?

Answer

Thanks to JuanZe's comment, I found the Joda-Time magic, it is also described here.

So, the solution is

DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();
String jtdate = "2010-01-01T12:00:00+01:00";
System.out.println(parser2.parseDateTime(jtdate));

Or more simply, use the default parser via the constructor:

DateTime dt = new DateTime( "2010-01-01T12:00:00+01:00" ) ;

To me, this is nice.


问:
Pentaho kettle Can't run transformation due to plugin missing
I trying to execute transformation file using java , transformation get data from database and print data to file in s3 by s3 output file step.it works fine when run by spoon ,but when trying to run in java application get the following error

```<code>Can't run transformation due to plugin missing
</code>```

java code

```<code>    KettleEnvironment.init();
    URL ktrUrl = PipelineResource.class.getClassLoader().getResource(tempFile.getAbsolutePath());
    TransMeta transMeta = new TransMeta(ktrUrl.getPath());
    Trans trans = new Trans(transMeta);
    trans.execute(new String[]{});
    trans.waitUntilFinished();
    if (trans.getErrors() > 0) {
</code>```

full stack trace

```<code>  2017/06/29 12:46:11 - S3 File Output.0 - ERROR (version 7.0.0.6-95, build
1 from 2017-05-23 03.01.13 by buildguy) : Can't run transformation due to
plugin missing2017/06/29 12:46:11 - S3 File Output.0 - ERROR (version
7.0.0.6-95, build 1 from 2017-05-23 03.01.13 by buildguy) : Error
initializing step [S3 File Output]
2017/06/29 12:46:11 - transformation1 - ERROR (version 7.0.0.6-95, build 1
from 2017-05-23 03.01.13 by buildguy) : Step [S3 File Output.0] failed to
initialize!
2017/06/29 12:46:11 - data from asset.0 - Finished reading query, closing
connection.
2017-06-29 12:46:11.048 ERROR 22396 --- [ XNIO-2 task-2]
com.innvo.aop.logging.LoggingAspect : Exception in
com.innvo.web.rest.PipelineResource.runPipeline() with cause = 'NULL' and
exception = '
We failed to initialize at least one step. Execution can not begin!'
org.pentaho.di.core.exception.KettleException:
We failed to initialize at least one step. Execution can not begin!
at org.pentaho.di.trans.Trans.prepareExecution(Trans.java:1157)
at org.pentaho.di.trans.Trans.execute(Trans.java:627)
at com.innvo.web.rest.PipelineResource.runPipeline(PipelineResource.java:201)
at com.innvo.web.rest.PipelineResource$$FastClassBySpringCGLIB$$81033db7.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
at com.innvo.aop.logging.LoggingAspect.logAround(LoggingAspect.java:85)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
</code>```

答:
It only worked when I did the following:

1) Added the following variables that points the data-integration plugin folder to the VM Arguments:

```<code>-DKETTLE_PLUGIN_BASE_FOLDERS=path_to_your_data-integration/plugin
</code>```

2) this wasn't enough because my plugin folder was missing the mongodb jar, when I added the jar pentaho-mongo-utils-8.2.0.0-342.jar(beware the jar may vary according the version you're targetting) it worked.

ContentLicense: CC BY-SA 3.0

Body:
I trying to execute transformation file using java , transformation get data from database and print data to file in s3 by s3 output file step.it works fine when run by spoon ,but when trying to run in java application get the following error

Can't run transformation due to plugin missing

java code

    KettleEnvironment.init();
    URL ktrUrl = PipelineResource.class.getClassLoader().getResource(tempFile.getAbsolutePath());
    TransMeta transMeta = new TransMeta(ktrUrl.getPath());
    Trans trans = new Trans(transMeta);
    trans.execute(new String[]{});
    trans.waitUntilFinished();
    if (trans.getErrors() > 0) {

full stack trace

  2017/06/29 12:46:11 - S3 File Output.0 - ERROR (version 7.0.0.6-95, build
1 from 2017-05-23 03.01.13 by buildguy) : Can't run transformation due to
plugin missing2017/06/29 12:46:11 - S3 File Output.0 - ERROR (version
7.0.0.6-95, build 1 from 2017-05-23 03.01.13 by buildguy) : Error
initializing step [S3 File Output]
2017/06/29 12:46:11 - transformation1 - ERROR (version 7.0.0.6-95, build 1
from 2017-05-23 03.01.13 by buildguy) : Step [S3 File Output.0] failed to
initialize!
2017/06/29 12:46:11 - data from asset.0 - Finished reading query, closing
connection.
2017-06-29 12:46:11.048 ERROR 22396 --- [ XNIO-2 task-2]
com.innvo.aop.logging.LoggingAspect : Exception in
com.innvo.web.rest.PipelineResource.runPipeline() with cause = 'NULL' and
exception = '
We failed to initialize at least one step. Execution can not begin!'
org.pentaho.di.core.exception.KettleException:
We failed to initialize at least one step. Execution can not begin!
at org.pentaho.di.trans.Trans.prepareExecution(Trans.java:1157)
at org.pentaho.di.trans.Trans.execute(Trans.java:627)
at com.innvo.web.rest.PipelineResource.runPipeline(PipelineResource.java:201)
at com.innvo.web.rest.PipelineResource$$FastClassBySpringCGLIB$$81033db7.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
at com.innvo.aop.logging.LoggingAspect.logAround(LoggingAspect.java:85)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)

Body:
It only worked when I did the following:

1) Added the following variables that points the data-integration plugin folder to the VM Arguments:

-DKETTLE_PLUGIN_BASE_FOLDERS=path_to_your_data-integration/plugin

2) this wasn't enough because my plugin folder was missing the mongodb jar, when I added the jar pentaho-mongo-utils-8.2.0.0-342.jar(beware the jar may vary according the version you're targetting) it worked.


问:
Python regex match certain floating point numbers
I'm trying to match: 0 or more numbers followed by a dot followed by ( (0 or more numbers) but not (if followed by a d,D, or _))

Some examples and what should match/not:

match:

```<code>['1.0','1.','0.1','.1','1.2345']
</code>```

not match:

```<code>['1d2','1.2d3','1._dp','1.0_dp','1.123165d0','1.132_dp','1D5','1.2356D6']
</code>```

Currently i have:

```<code>"([0-9]*\.)([0-9]*(?!(d|D|_)))"
</code>```

Which correctly matches everything in the match list. But for those in the things it should not match it incorrectly matches on:

```<code>['1.2d3','1.0_dp','1.123165d0','1.132_dp','1.2356D6']
</code>```

and correctly does not match on:

```<code>['1d2','1._dp','1D5']
</code>```

So it appears i have problem with the ([0-9]*(?!(d|D|_)) part which is trying to not match if there is a d|D|_ after the dot (with zero or more numbers in-between). Any suggestions?

答: \d*[.](?!.*[_Dd]).* is what you are looking for:

Body:
I'm trying to match: 0 or more numbers followed by a dot followed by ( (0 or more numbers) but not (if followed by a d,D, or _))

Some examples and what should match/not:

match:

['1.0','1.','0.1','.1','1.2345']

not match:

['1d2','1.2d3','1._dp','1.0_dp','1.123165d0','1.132_dp','1D5','1.2356D6']

Currently i have:

"([0-9]*\.)([0-9]*(?!(d|D|_)))"

Which correctly matches everything in the match list. But for those in the things it should not match it incorrectly matches on:

['1.2d3','1.0_dp','1.123165d0','1.132_dp','1.2356D6']

and correctly does not match on:

['1d2','1._dp','1D5']

So it appears i have problem with the ([0-9]*(?!(d|D|_)) part which is trying to not match if there is a d|D|_ after the dot (with zero or more numbers in-between). Any suggestions?


问:
How to fix for-loop output in python
I have 3 routers on my test lab environment, I'm trying to reach these routers and send some commands using for-loop and send output in the way I type/list them.

I have 3 1841 Cisco routers and running 12.4 IOS:

```<code>    multi_ip_addr = ['192.168.1.1', '192.168.2.1', '192.168.3.1']
    for ips in multi_ip_addr:
        pass
    len_ip_addr = len(multi_ip_addr)
    for len_ip in range(len_ip_addr):
        device = {'ip': ips,
        'username': 'admin',
        'password': 'password'}
        print(device)
</code>```

My expected result is:

```<code>{'ip': '192.168.1.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.2.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'}
</code>```

however I am getting this output:

```<code>{'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'}
</code>```

答:
```<code>multi_ip_addr = ['192.168.1.1', '192.168.2.1', '192.168.3.1']
for ips in multi_ip_addr:
    device = {'ip':ips, 'username':'admin', 'password':'password'}
    print(device)
</code>```

Title: How to fix for-loop output in python

Body:
I have 3 routers on my test lab environment, I'm trying to reach these routers and send some commands using for-loop and send output in the way I type/list them.

I have 3 1841 Cisco routers and running 12.4 IOS:

    multi_ip_addr = ['192.168.1.1', '192.168.2.1', '192.168.3.1']
    for ips in multi_ip_addr:
        pass
    len_ip_addr = len(multi_ip_addr)
    for len_ip in range(len_ip_addr):
        device = {'ip': ips,
        'username': 'admin',
        'password': 'password'}
        print(device)

My expected result is:

{'ip': '192.168.1.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.2.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'}

however I am getting this output:

{'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'}