问:
Encrypt AWS keys on local machine for AWS commands
On developers machines, when using aws --configure and s3cmd configure, the AWS key and secret are stored in a plain text file.

For security reasons I'd like the secret, at least, to be kept in a secure and encrypted way, using MAC keychain for example.

Env variables don't seem like a solution as they would also need to be kept securely.

Is there any way to store the keys in a secure way?

(As a side note, no need to mention that all machines have passwords and the keys have the minimum needed permissions in AWS and there are other security methods in place.)

答:
Instead of long-term credentials (AWS IAM Access Keys), you can use short-term credentials by leveraging AWS SSO & AWS Organizations. The short-term credentials are not encrypted though, but temporarily valid (can be configured).

see https://latanassov.dev/aws/2020-01-23/aws-sso-aws-cli.html


来源: stackexchange

问:
Mocking stripe class from stripe php package in laravel
I'm using this package for stripe

https://github.com/stripe/stripe-php

I have a class that I'm using that uses the stripe methods called StripeBiller

```<code>class StripeBiller
{

    public function setApiKey() {
        $stripe = new Stripe();
        $stripe->setApiKey(env('STRIPE_API_KEY'));
    }
}
</code>```

I'm trying to test that the setApiKey method is called when $stripebiller()->setApiKey() is called. To do this I'm mocking the stripe class in the test.

```<code>    public function test_api_key_is_set() {

    $this->mock(Stripe::class, function ($mock) {
        $mock->shouldReceive('setApiKey')->once();
    });
    $biller = new StripeBiller();
    $biller->setApiKey();

}
</code>```

When I execute this test I get this error.

```<code>    Mockery\Exception\InvalidCountException : Method setApiKey(<Any Arguments>) from Mockery_2_Stripe_Stripe should be called
 exactly 1 times but called 0 times.
</code>```

How do I correctly mock this stripe class?

答:
You can't mock things you are manually newing up. There are a couple ways to accomplish what you're trying to do here.

Pass a Stripe class into the constructor of your StripeBiller class

class StripeBiller
{
    private $Stripe;

    public function __construct(Stripe $Stripe)
    {
        $this->Stripe = $Stripe;
    }

    public function setApiKey()
    {
        $this->Stripe->setApiKey(env('STRIPE_API_KEY'));
    }
}
```

<pre class="lang-php prettyprint-override"><code>// StripeBillerTest.php
public function test_api_key_is_set()
{
    $StripeMock = \Mockery::mock(Stripe::class);
    $StripeMock->shouldReceive('setApiKey')->once();

    $biller = new StripeBiller($StripeMock);
    $biller->setApiKey();

}

</code>```

Create the Stripe class with the container and tell the container to use a mock in your test.

// StripeBiller.php
public function setApiKey()
{
    $stripe = app(Stripe::class);
    $stripe->setApiKey(env('STRIPE_API_KEY'));
}
```

<pre class="lang-php prettyprint-override"><code>// StripeBillerTest.php
public function test_api_key_is_set()
{
    $StripeMock = \Mockery::mock(Stripe::class);
    $StripeMock->shouldReceive('setApiKey')->once();
    $this->app->instance(Stripe::class, $StripeMock);

    $biller = new StripeBiller();
    $biller->setApiKey();

}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using this package for stripe

https://github.com/stripe/stripe-php

I have a class that I'm using that uses the stripe methods called StripeBiller

class StripeBiller
{

    public function setApiKey() {
        $stripe = new Stripe();
        $stripe->setApiKey(env('STRIPE_API_KEY'));
    }
}

I'm trying to test that the setApiKey method is called when $stripebiller()->setApiKey() is called. To do this I'm mocking the stripe class in the test.

    public function test_api_key_is_set() {

    $this->mock(Stripe::class, function ($mock) {
        $mock->shouldReceive('setApiKey')->once();
    });
    $biller = new StripeBiller();
    $biller->setApiKey();

}

When I execute this test I get this error.

    Mockery\Exception\InvalidCountException : Method setApiKey(<Any Arguments>) from Mockery_2_Stripe_Stripe should be called
 exactly 1 times but called 0 times.

How do I correctly mock this stripe class?

Body:
You can't mock things you are manually newing up. There are a couple ways to accomplish what you're trying to do here.

Pass a Stripe class into the constructor of your StripeBiller class

class StripeBiller
{
    private $Stripe;

    public function __construct(Stripe $Stripe)
    {
        $this->Stripe = $Stripe;
    }

    public function setApiKey()
    {
        $this->Stripe->setApiKey(env('STRIPE_API_KEY'));
    }
}

// StripeBillerTest.php
public function test_api_key_is_set()
{
    $StripeMock = \Mockery::mock(Stripe::class);
    $StripeMock->shouldReceive('setApiKey')->once();

    $biller = new StripeBiller($StripeMock);
    $biller->setApiKey();

}

Create the Stripe class with the container and tell the container to use a mock in your test.

// StripeBiller.php
public function setApiKey()
{
    $stripe = app(Stripe::class);
    $stripe->setApiKey(env('STRIPE_API_KEY'));
}

// StripeBillerTest.php
public function test_api_key_is_set()
{
    $StripeMock = \Mockery::mock(Stripe::class);
    $StripeMock->shouldReceive('setApiKey')->once();
    $this->app->instance(Stripe::class, $StripeMock);

    $biller = new StripeBiller();
    $biller->setApiKey();

}


问:
How to get user id and access token of instagram account after the oct 15th update?
In my Instagram developer account it is showing this:

Starting October 15, 2019, new client registration and permission review on Instagram API platform are discontinued in favor of the Instagram Basic Display API.

So I don't know how to get user id and access token now. Could someone explain what are the ways to get user id and access token of the Instagram account.

I tried to get a Client ID but the new change in Instagram is not allowing further steps. I followed this article -> https://docs.oceanwp.org/article/487-how-to-get-instagram-access-token

It showing like this for every account.
View of account

答:
You can get the access token from this link.

Try it -> https://instagram.pixelunion.net/


问:
Devise and stored_location_for: how do you store the return location?
I have a page whose path is (e.g.) /premises/92 on which I'm displaying "please [log in] or [register] for additional information" if the user is not logged in, and I want devise to return that same /premises/92 page after the user logs in.

I've read other posts and I think I understand how devise's stored_location_for is supposed to work.  In theory, I could put something like this in my ApplicationController:

```<code>def stored_location_for(resource)
  if (r = session[:return_to])
    session[:return_to] = nil
    r
  else
    super
  end
end
</code>```

My question is: how / where do I set up session[:return_to]?

I want to set session[:return_to] only if the user clicks on [log in] or [register], but what's the best way to do that?

Decorate the links with JavaScript?  That could work, but seems heavy-handed.

Set it in the Premises Controller before rendering the page?  That doesn't seem right: what if the user doesn't click on the [log in] or [register] links?  Then I have session[:return_to] set to some odd value which might trip me up if the user logs in from some other page.

Add a ?return_to=/premises/92 query string to the [log in] and [register] links, and detect that in the RegistrationsController and SessionsController and use that info to set up session[:return_to]?  That seems like it would work, but also heavy-handed.

None of these smell right.  What's the generally accepted technique for setting up state for stored_location_for?

答:
I do like this:

```<code>class ApplicationController < AC::Base
  after_filter :clear_attached_unit # UPDATED

  protected
  def clear_attached_unit
    session[:attached_unit_path] = nil unless keep_attached_unit_path?
  end

  def keep_attached_unit_path? # UPDATED
    @keep_attached_unit_path
  end
end

class UnitController < ApplicationController
  before_filter :attach_unit, :only => [:show]

  protected
  def attach_unit
    session[:attached_unit_path] = request.url if request.get? && !request.xhr?
  end
end

class SessionsController < Devise::SessionsController
  before_filter :keep_attached_unit_path! # UPDATED

  protected
  def keep_attached_unit_path! # UPDATED
    @keep_attached_unit_path = true
  end

  def after_sign_in_path_for(resource_or_scope)
    if resource_or_scope.is_a?(User) && session[:attached_unit_path].present?
      session[:attached_unit_path]
    else
      super
    end
  end
end
</code>```

And extract this to module.

ContentLicense: CC BY-SA 3.0

Body:
I have a page whose path is (e.g.) /premises/92 on which I'm displaying "please [log in] or [register] for additional information" if the user is not logged in, and I want devise to return that same /premises/92 page after the user logs in.

I've read other posts and I think I understand how devise's stored_location_for is supposed to work.  In theory, I could put something like this in my ApplicationController:

def stored_location_for(resource)
  if (r = session[:return_to])
    session[:return_to] = nil
    r
  else
    super
  end
end

My question is: how / where do I set up session[:return_to]?

I want to set session[:return_to] only if the user clicks on [log in] or [register], but what's the best way to do that?

Decorate the links with JavaScript?  That could work, but seems heavy-handed.

Set it in the Premises Controller before rendering the page?  That doesn't seem right: what if the user doesn't click on the [log in] or [register] links?  Then I have session[:return_to] set to some odd value which might trip me up if the user logs in from some other page.

Add a ?return_to=/premises/92 query string to the [log in] and [register] links, and detect that in the RegistrationsController and SessionsController and use that info to set up session[:return_to]?  That seems like it would work, but also heavy-handed.

None of these smell right.  What's the generally accepted technique for setting up state for stored_location_for?

Body:
I do like this:

class ApplicationController < AC::Base
  after_filter :clear_attached_unit # UPDATED

  protected
  def clear_attached_unit
    session[:attached_unit_path] = nil unless keep_attached_unit_path?
  end

  def keep_attached_unit_path? # UPDATED
    @keep_attached_unit_path
  end
end

class UnitController < ApplicationController
  before_filter :attach_unit, :only => [:show]

  protected
  def attach_unit
    session[:attached_unit_path] = request.url if request.get? && !request.xhr?
  end
end

class SessionsController < Devise::SessionsController
  before_filter :keep_attached_unit_path! # UPDATED

  protected
  def keep_attached_unit_path! # UPDATED
    @keep_attached_unit_path = true
  end

  def after_sign_in_path_for(resource_or_scope)
    if resource_or_scope.is_a?(User) && session[:attached_unit_path].present?
      session[:attached_unit_path]
    else
      super
    end
  end
end

And extract this to module.


问:
Speed improvements on plotting
I am working on a bigger project where i need to plot a lot of live data coming in. A very simplified version of my program is this (Kudos to https://stackoverflow.com/a/41687202/1482066):

```<code>from PyQt5 import QtCore, QtGui, QtWidgets
import pyqtgraph as pg
import random
import time

number_of_plots = 6
number_of_caps = 48
show_plots = True

print(f"Number of plots: {number_of_plots}")
print(f"Number of caps: {number_of_caps}")

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.central_widget = QtWidgets.QStackedWidget()
        self.setCentralWidget(self.central_widget)
        self.login_widget = LoginWidget(self)
        self.login_widget.button.clicked.connect(self.plotter)
        self.central_widget.addWidget(self.login_widget)
        self.data = dict()
        self.curve = dict()

        self.points_kwargs = list()

        colors = ["#000000", "#e6194B", "#f58231", "#3cb44b", "#42d4f4", "#4363d8", "#911eb4", "#f032e6", "#bfef45" ,"#000075", "#e6beff", "#9A6324"]

        self.colors = colors * 4

        for color in self.colors:
            self.points_kwargs.append({"pen": None,
                                       "symbol": 'x',
                                       "symbolSize": 8,
                                       "symbolPen": color,
                                       "symbolBrush": color})

    def plotter(self):
        for j in range(number_of_plots):
            self.data[j] = list()
            self.curve[j] = list()
            for i in range(number_of_caps):
                self.data[j].append([i])
                self.curve[j].append(self.login_widget.plots[j].getPlotItem().plot(**self.points_kwargs[i]))

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updater)
        self.timer.start(0)

    def updater(self):
        starttime = time.perf_counter()

        for key in self.data.keys():
            for i in range(number_of_caps):
                self.data[key][i].append(self.data[key][i][-1]+0.2*(0.5-random.random()))
                self.curve[key][i].setData(self.data[key][i])

        print(f"Plottime: {time.perf_counter() - starttime}")

class LoginWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(LoginWidget, self).__init__(parent)
        layout = QtWidgets.QHBoxLayout()
        self.button = QtWidgets.QPushButton('Start Plotting')
        layout.addWidget(self.button)

        self.plots = list()

        for i in range(number_of_plots):
            plot = pg.PlotWidget()
            self.plots.append(plot)
            layout.addWidget(plot)
            if not show_plots:
                plot.hide()

        self.plots[0].show()
        self.setLayout(layout)

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()
</code>```

The numbers on top show how this scales with plots and caps. 6 and 48 is why my program needs to handle.
Running the program the plotting time is about 1sec/update. On my machine at least.

To make complicated matters easy: I would need to bring this plotting time down as much as possible. factor 2 might be okay, 10 would be very nice.

Any ideas? Thanks for your time!

Best

答:
I figured out how to improve the speed in my case.
As mentioned in my comment the plotting gets a lot faster if you zoom out. The rescaling of the plots actually takes the majority of the time required for the plotting. In my case plotting one point takes ~2-4ms and rescaling takes another 20-40ms.

I solved this issue by calculating the maximum x- and y-range my plot will have in the end and setting the range before plotting begins. This does not help if you don't know how much data will show up, but in this case the autoPan function might help. I added the following to my code:

```<code>plot.setXRange(min_x,max_x, 0.05)
plot.setYRange(min_y,max_y, 0.05)
plot.hideButtons()
</code>```

.hideButtons() disables the autozoom button in the bottom left corner of the plot. This prevents the user from reenabling autozoom. The user can still zoom in and out if they like, but the automatic rescaling does no longer happen. This is not a perfect solution but works in my case.

Title: Speed improvements on plotting

Body:
I am working on a bigger project where i need to plot a lot of live data coming in. A very simplified version of my program is this (Kudos to https://stackoverflow.com/a/41687202/1482066):

from PyQt5 import QtCore, QtGui, QtWidgets
import pyqtgraph as pg
import random
import time

number_of_plots = 6
number_of_caps = 48
show_plots = True

print(f"Number of plots: {number_of_plots}")
print(f"Number of caps: {number_of_caps}")

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.central_widget = QtWidgets.QStackedWidget()
        self.setCentralWidget(self.central_widget)
        self.login_widget = LoginWidget(self)
        self.login_widget.button.clicked.connect(self.plotter)
        self.central_widget.addWidget(self.login_widget)
        self.data = dict()
        self.curve = dict()

        self.points_kwargs = list()

        colors = ["#000000", "#e6194B", "#f58231", "#3cb44b", "#42d4f4", "#4363d8", "#911eb4", "#f032e6", "#bfef45" ,"#000075", "#e6beff", "#9A6324"]

        self.colors = colors * 4

        for color in self.colors:
            self.points_kwargs.append({"pen": None,
                                       "symbol": 'x',
                                       "symbolSize": 8,
                                       "symbolPen": color,
                                       "symbolBrush": color})

    def plotter(self):
        for j in range(number_of_plots):
            self.data[j] = list()
            self.curve[j] = list()
            for i in range(number_of_caps):
                self.data[j].append([i])
                self.curve[j].append(self.login_widget.plots[j].getPlotItem().plot(**self.points_kwargs[i]))

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updater)
        self.timer.start(0)

    def updater(self):
        starttime = time.perf_counter()

        for key in self.data.keys():
            for i in range(number_of_caps):
                self.data[key][i].append(self.data[key][i][-1]+0.2*(0.5-random.random()))
                self.curve[key][i].setData(self.data[key][i])

        print(f"Plottime: {time.perf_counter() - starttime}")

class LoginWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(LoginWidget, self).__init__(parent)
        layout = QtWidgets.QHBoxLayout()
        self.button = QtWidgets.QPushButton('Start Plotting')
        layout.addWidget(self.button)

        self.plots = list()

        for i in range(number_of_plots):
            plot = pg.PlotWidget()
            self.plots.append(plot)
            layout.addWidget(plot)
            if not show_plots:
                plot.hide()

        self.plots[0].show()
        self.setLayout(layout)

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

The numbers on top show how this scales with plots and caps. 6 and 48 is why my program needs to handle.
Running the program the plotting time is about 1sec/update. On my machine at least.

To make complicated matters easy: I would need to bring this plotting time down as much as possible. factor 2 might be okay, 10 would be very nice.

Any ideas? Thanks for your time!

Best

Body:
I figured out how to improve the speed in my case.
As mentioned in my comment the plotting gets a lot faster if you zoom out. The rescaling of the plots actually takes the majority of the time required for the plotting. In my case plotting one point takes ~2-4ms and rescaling takes another 20-40ms.

I solved this issue by calculating the maximum x- and y-range my plot will have in the end and setting the range before plotting begins. This does not help if you don't know how much data will show up, but in this case the autoPan function might help. I added the following to my code:

plot.setXRange(min_x,max_x, 0.05)
plot.setYRange(min_y,max_y, 0.05)
plot.hideButtons()

.hideButtons() disables the autozoom button in the bottom left corner of the plot. This prevents the user from reenabling autozoom. The user can still zoom in and out if they like, but the automatic rescaling does no longer happen. This is not a perfect solution but works in my case.


问:
is there any way to clean all projects in gradle 6.0.1
I want to clean all project of gradle,now I using this task in root project build.gradle:

```<code>task clean {
    subprojects.each {
        it.afterEvaluate {
            def cleanTask = it.tasks.findByName('clean')
            if (cleanTask) {
                dependsOn(cleanTask)
            }
        }
    }
}
</code>```

it give me tips this clean task already exists,is there other way to do this task?I do not want to write many code like :

```<code>./gradlew clean projectA
./gradlew clean projectB
./gradlew clean projectC
</code>```

Now I have more than 30 project.

答:
There's a feature in Gradle where:

If you call a task on the root project

And the root project does not contain that task

A "proxy" task will be created in the root project

The "proxy" task will invoke any tasks with the same name in its subprojects

So usually, your subprojects will contain a "clean" task and your root project will not. So invoking "clean" on the root project will actually invoke "clean" on all the subprojects. I think this is the behavior you want?

If this is not occurring, it's likely you've created a "clean" task in your root project with different behavior (perhaps you applied the "base" plugin to the root project?). I suggest you remove the "clean" task from the root project

Body:
I want to clean all project of gradle,now I using this task in root project build.gradle:

task clean {
    subprojects.each {
        it.afterEvaluate {
            def cleanTask = it.tasks.findByName('clean')
            if (cleanTask) {
                dependsOn(cleanTask)
            }
        }
    }
}

it give me tips this clean task already exists,is there other way to do this task?I do not want to write many code like :

./gradlew clean projectA
./gradlew clean projectB
./gradlew clean projectC

Now I have more than 30 project.


问:
cocoa - How to display a NSSavePanel modal window in front of another modal view
I'm developing a macOS document-based application using cocoa. I want to make a behavior like the start-up of XCode, namely: in a window, begin a modal view whose controller is called viewController by presentViewControllerAsSheet:, and after click the 'Next' button, show NSSavePanel by running [self saveDocument:self].

My code is:

```<code>self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]
[self.contentViewController presentViewControllerAsSheet:viewController;
//...some set ups about the NSButton on the view.
//And in the method to handle the Next Button being clicked:
[self saveDocument:self];
</code>```

After I run the application, when I click the 'Next' Button, nothing happens.

答:
I was just dealing with this problem myself. I was calling back from a secondary controller to my main document class with the data to be saved, and trying to call save() was not showing the modal dialog. Turns out I had to explicitly call back to the main thread to ensure the UI is shown:

```<code>newServerWindowController?.saveNewDocument = { remote in
    DispatchQueue.main.async {
        guard let newDoc = self.document else { return }
        newDoc.remote = remote
        newDoc.save(self)
        self.windowController?.update()
    }
}
</code>```

Hope this helps!

Body:
I'm developing a macOS document-based application using cocoa. I want to make a behavior like the start-up of XCode, namely: in a window, begin a modal view whose controller is called viewController by presentViewControllerAsSheet:, and after click the 'Next' button, show NSSavePanel by running [self saveDocument:self].

My code is:

self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]
[self.contentViewController presentViewControllerAsSheet:viewController;
//...some set ups about the NSButton on the view.
//And in the method to handle the Next Button being clicked:
[self saveDocument:self];

After I run the application, when I click the 'Next' Button, nothing happens.

Body:
I was just dealing with this problem myself. I was calling back from a secondary controller to my main document class with the data to be saved, and trying to call save() was not showing the modal dialog. Turns out I had to explicitly call back to the main thread to ensure the UI is shown:

newServerWindowController?.saveNewDocument = { remote in
    DispatchQueue.main.async {
        guard let newDoc = self.document else { return }
        newDoc.remote = remote
        newDoc.save(self)
        self.windowController?.update()
    }
}

Hope this helps!


问:
Sanic web framework performance
I have a question to ask about sanic / asyncpg performance.

During a testing a weird things kept happening (Maybe it is by design).

First let me explain testing procedure. It is simple.

I use locust to push the server as much as possible by setting max user count.

The testing script is:

```<code>from locust import HttpLocust, TaskSet, task, between

class UserActions(TaskSet):
    @task(1)
    def test_point_1(self):
        self.client.get(
            '/json_1',
            headers={'Content-Type': 'application/json'}
        )

    @task(2)
    def test_point_2(self):
        self.client.get(
            '/json_2',
            headers={'Content-Type': 'application/json'}
        )

class ApplicationUser(HttpLocust):
    task_set = UserActions
    wait_time = between(0, 0)

</code>```

It is used to test the following code. Notice asyncpg is calling potgresql sleep function to simulate a load:

```<code>import asyncio
import uvloop
from asyncpg import create_pool
from sanic import Sanic, response
from sanic.log import logger
import aiotask_context as context

app = Sanic(__name__)

DATABASE = {
    'type': 'postgresql',
    'host': '127.0.0.1',
    'user': 'test_user',
    'port': '5432',
    'password': 'test_password',
    'database': 'test_database'
}

conn_uri = '{0}://{1}:{2}@{3}:{4}/{5}'.format(
            'postgres',
            DATABASE['user'], DATABASE['password'], DATABASE['host'],
            DATABASE['port'], DATABASE['database'])

@app.route("/json_1")
async def handler_json_1(request):
    async with request.app.pg.acquire() as connection:
        await connection.fetchrow('SELECT pg_sleep(0.85);')
    return response.json({"foo": "bar"})

@app.route("/json_2")
async def handler_json_2(request):
    async with request.app.pg.acquire() as connection:
        await connection.fetchrow('SELECT pg_sleep(0.2);')
    return response.json({"foo": "bar"})

@app.listener("before_server_start")
async def listener_before_server_start(*args, **kwargs):
    try:

        pg_pool = await create_pool(
            conn_uri, min_size=2, max_size=10,
            server_settings={'application_name': 'test_backend'})
        app.pg = pg_pool

    except Exception as bss_error:
        logger.error('before_server_start_test erred with :{}'.format(bss_error))
        app.pg = None

@app.listener("after_server_start")
async def listener_after_server_start(*args, **kwargs):
    # print("after_server_start")
    pass

@app.listener("before_server_stop")
async def listener_before_server_stop(*args, **kwargs):
    # print("before_server_stop")
    pass

@app.listener("after_server_stop")
async def listener_after_server_stop(*args, **kwargs):
    # print("after_server_stop")
    pass

if __name__ == '__main__':
    asyncio.set_event_loop(uvloop.new_event_loop())
    server = app.create_server(host="0.0.0.0", port=8282, return_asyncio_server=True)
    loop = asyncio.get_event_loop()
    loop.set_task_factory(context.task_factory)
    task = asyncio.ensure_future(server)
    try:
        loop.run_forever()
    except Exception as lerr:
        logger.error('Loop run error: {}'.format(lerr))
        loop.stop()

</code>```

The issue is, after a random amount of time server becomes unresponsive
(Does not return 503 or any other code) for a cca. 60 seconds.
Also process hangs (I can see it with ps aux and CTRL+C cannot kill it.)

That might be problematic because for one it is hard to detect and it is difficult to determine a rate at which we can send request to the server.

Could that be an issue with the configuration (sanic/asyncpg)?

Could setting nginx / sanic request timeout be the only option to circumvent this problem ?

答: Your aiopg pool is limited to 10 connections. So 10 requests at a time max, each takes 0.2 sec, your max possible load would be 1 sec / 0.2 sec * 10 pool size = 50 RPS. After that all incoming requests would just wait for a connection and queue of requests to serve would grow much faster than your ability to serve and your server would become irresponsive.</p>

Title: Sanic web framework performance

Body:
I have a question to ask about sanic / asyncpg performance.

During a testing a weird things kept happening (Maybe it is by design).

First let me explain testing procedure. It is simple.

I use locust to push the server as much as possible by setting max user count.

The testing script is:

from locust import HttpLocust, TaskSet, task, between

class UserActions(TaskSet):
    @task(1)
    def test_point_1(self):
        self.client.get(
            '/json_1',
            headers={'Content-Type': 'application/json'}
        )

    @task(2)
    def test_point_2(self):
        self.client.get(
            '/json_2',
            headers={'Content-Type': 'application/json'}
        )

class ApplicationUser(HttpLocust):
    task_set = UserActions
    wait_time = between(0, 0)

It is used to test the following code. Notice asyncpg is calling potgresql sleep function to simulate a load:

import asyncio
import uvloop
from asyncpg import create_pool
from sanic import Sanic, response
from sanic.log import logger
import aiotask_context as context

app = Sanic(__name__)

DATABASE = {
    'type': 'postgresql',
    'host': '127.0.0.1',
    'user': 'test_user',
    'port': '5432',
    'password': 'test_password',
    'database': 'test_database'
}

conn_uri = '{0}://{1}:{2}@{3}:{4}/{5}'.format(
            'postgres',
            DATABASE['user'], DATABASE['password'], DATABASE['host'],
            DATABASE['port'], DATABASE['database'])

@app.route("/json_1")
async def handler_json_1(request):
    async with request.app.pg.acquire() as connection:
        await connection.fetchrow('SELECT pg_sleep(0.85);')
    return response.json({"foo": "bar"})

@app.route("/json_2")
async def handler_json_2(request):
    async with request.app.pg.acquire() as connection:
        await connection.fetchrow('SELECT pg_sleep(0.2);')
    return response.json({"foo": "bar"})

@app.listener("before_server_start")
async def listener_before_server_start(*args, **kwargs):
    try:

        pg_pool = await create_pool(
            conn_uri, min_size=2, max_size=10,
            server_settings={'application_name': 'test_backend'})
        app.pg = pg_pool

    except Exception as bss_error:
        logger.error('before_server_start_test erred with :{}'.format(bss_error))
        app.pg = None

@app.listener("after_server_start")
async def listener_after_server_start(*args, **kwargs):
    # print("after_server_start")
    pass

@app.listener("before_server_stop")
async def listener_before_server_stop(*args, **kwargs):
    # print("before_server_stop")
    pass

@app.listener("after_server_stop")
async def listener_after_server_stop(*args, **kwargs):
    # print("after_server_stop")
    pass

if __name__ == '__main__':
    asyncio.set_event_loop(uvloop.new_event_loop())
    server = app.create_server(host="0.0.0.0", port=8282, return_asyncio_server=True)
    loop = asyncio.get_event_loop()
    loop.set_task_factory(context.task_factory)
    task = asyncio.ensure_future(server)
    try:
        loop.run_forever()
    except Exception as lerr:
        logger.error('Loop run error: {}'.format(lerr))
        loop.stop()

The issue is, after a random amount of time server becomes unresponsive
(Does not return 503 or any other code) for a cca. 60 seconds.
Also process hangs (I can see it with ps aux and CTRL+C cannot kill it.)

That might be problematic because for one it is hard to detect and it is difficult to determine a rate at which we can send request to the server.

Could that be an issue with the configuration (sanic/asyncpg)?

Could setting nginx / sanic request timeout be the only option to circumvent this problem ?


问:
Angular subscribe elegant
I'd like to ask about my subscribe method. I want to get my objects(employees) from firebase and do a loot of operations on my objects, like avg salaries, avg missed days... In my opinion it looks so horrible. My service void:

```<code> getEmployees(): Observable<Employee[]> {
    return this.db.list<Employee>(this.Api_url).snapshotChanges()
      .pipe(map(response => response.map(car => this.assignKey(car))));
  }
</code>```

And my ngOnInit:

```<code>  ngOnInit() {

    this.subscribtion = this.mainservice.getEmployees().subscribe((emps)=> {
      this.employees = emps;
      this.workersdatas = [];
      this.educationdatas = [];
      this.checkavaragesalaries(emps);
      this.countMonthAbsences(emps, 1);
      this.countMonthSalaries(emps, 1);
      this.departments.forEach((one)=> {
        const dep = emps.filter(on => on.department.includes(one) && this.FilterEmployees(on)).length;
        this.workersdatas.push({name: one, value: dep});
      });

      this.educations.forEach((one)=> {
        const edu = emps.filter(on => on.education.includes(one)).length;
        this.educationdatas.push({name: one, value: edu});
      });

      const mynumb =this.educationdatas.map(on => on.value);
      this.mosteducation = this.educationdatas.filter(one => one.value === Math.max(...mynumb))[0].name;
    }); }
</code>```

Should I unsubscribe() it on ngOnDestroy or that's not necessary? Is that allowed to write it like that?

答: Is that allowed to put every operations inside subscribe method like I did?</p>

Title: Angular subscribe elegant

Body:
I'd like to ask about my subscribe method. I want to get my objects(employees) from firebase and do a loot of operations on my objects, like avg salaries, avg missed days... In my opinion it looks so horrible. My service void:

 getEmployees(): Observable<Employee[]> {
    return this.db.list<Employee>(this.Api_url).snapshotChanges()
      .pipe(map(response => response.map(car => this.assignKey(car))));
  }

And my ngOnInit:

  ngOnInit() {

    this.subscribtion = this.mainservice.getEmployees().subscribe((emps)=> {
      this.employees = emps;
      this.workersdatas = [];
      this.educationdatas = [];
      this.checkavaragesalaries(emps);
      this.countMonthAbsences(emps, 1);
      this.countMonthSalaries(emps, 1);
      this.departments.forEach((one)=> {
        const dep = emps.filter(on => on.department.includes(one) && this.FilterEmployees(on)).length;
        this.workersdatas.push({name: one, value: dep});
      });

      this.educations.forEach((one)=> {
        const edu = emps.filter(on => on.education.includes(one)).length;
        this.educationdatas.push({name: one, value: edu});
      });

      const mynumb =this.educationdatas.map(on => on.value);
      this.mosteducation = this.educationdatas.filter(one => one.value === Math.max(...mynumb))[0].name;
    }); }

Should I unsubscribe() it on ngOnDestroy or that's not necessary? Is that allowed to write it like that?


问:
adding contents to tab layout
I followed the Android tutorial (as well as some other threads here at Stackoverflow..)

Now I want to incorporate twitter client into one of the tabs. The tutorial is this: Twitter Client

Thus far I have the following structure:

HelloTabWidget.java

MyTwitter.java (previously artists.java - also my first tab)

AlbumsActitivity.java  (2nd tab)

SongsActitivity.java  (3rd tab)

For each of the tabs, I have their own drawable xml (for the icons). I also have main.xml in the layout.

So now I started with the tutorial, but how do I modify main.xml when (1) no graphical display is available, and (2) this main.xml controls only the outline.

Then I thought about creating a mytwitter.xml but how do I tell the actitivty to use mytwitter.xml to display the content (while main.xml keeps the outline of the whole app's layout)?

In summary, how do I specify the content layout for each tab??? I see in HelloTabWidget.java we have setContent (refers to each tab's tab xml).

Thank you very much for any input!

Update
I am posting codes.
(1) HelloTabWidget.java
(2) main.xml
(3) MyTwitter.java

In the main.xml, I defined tabview2 (linear layout) with a button. I changed the parameter of setContentView to R.id.tabview2, but I got "force to quit"

According to CAT, I have the following errors:

05-17 10:29:14.402:
  ERROR/AndroidRuntime(796): FATAL
  EXCEPTION: main

05-17 10:29:14.402:
  ERROR/AndroidRuntime(796):
  java.lang.RuntimeException: Unable to
  start activity
  ComponentInfo{ywong02.android.HelloTabWidget/ywong02.android.HelloTabWidget.HelloTabWidget}:
  java.lang.RuntimeException: Your
  content must have a TabHost whose id
  attribute is 'android.R.id.tabhost'

What should I do?
Again, I want to display, say, a button on the first tab (namely, MyTwitter)

答: You have to use a layout, xml or not, in every activity. I mean every Activity must call setContentView to display its contents. If there's something that you need to reuse you can use the include tag, the same way you use it in JSP.</p>

Title: adding contents to tab layout


问:
How to get this into Kotlin?
I am a newbie at Kotlin and have been praticing Android for months now . I am stuck at converting this code from Java to Kotlin . The declaration syntax of args is out of my understanding.How can I convert below piece of code to Kotlin?

```<code> public static boolean validate(EditText... editTexts){
        EditText nameTxt = editTexts[0];
        EditText descriptionTxt = editTexts[1];
        EditText galaxyTxt = editTexts[2];
        return true;
}
</code>```

Thank-You in advance

答:
Java to Kotlin

```<code>fun validate(vararg editTexts: EditText): Boolean {
    val nameTxt = editTexts[0]
    val descriptionTxt = editTexts[1]
    val galaxyTxt = editTexts[2]
    return true
}
</code>```

To make it static, wrap it within companion object

```<code>companion object {
    fun validate(vararg editTexts: EditText): Boolean {
        val nameTxt = editTexts[0]
        val descriptionTxt = editTexts[1]
        val galaxyTxt = editTexts[2]
        return true
    }
}
</code>```

Title: How to get this into Kotlin?

Body:
I am a newbie at Kotlin and have been praticing Android for months now . I am stuck at converting this code from Java to Kotlin . The declaration syntax of args is out of my understanding.How can I convert below piece of code to Kotlin?

 public static boolean validate(EditText... editTexts){
        EditText nameTxt = editTexts[0];
        EditText descriptionTxt = editTexts[1];
        EditText galaxyTxt = editTexts[2];
        return true;
}

Thank-You in advance

Body:
Java to Kotlin

fun validate(vararg editTexts: EditText): Boolean {
    val nameTxt = editTexts[0]
    val descriptionTxt = editTexts[1]
    val galaxyTxt = editTexts[2]
    return true
}

To make it static, wrap it within companion object

companion object {
    fun validate(vararg editTexts: EditText): Boolean {
        val nameTxt = editTexts[0]
        val descriptionTxt = editTexts[1]
        val galaxyTxt = editTexts[2]
        return true
    }
}


问:
Is Apache NiFi a proper instrument for this use case?
Please help me to choose a right tool. I have the following task: there are N data sources (N < 20), it could be either relational DB (MySQL, PostgreSQL) or REST API. I need to load all the data from N data sources into a single relational database (only once). So the final goal seems to be a simple ETL:

extract data from data source

transform the data (map data to fit into a target DB schema)

load to DB

(Note: each source DB contain 10-15 coupled tables with 100 000 - 1 000 000 rows)

I'm currently trying to discover the proper instrument and I believe that Apache NiFi is exactly what I need: love the idea to just configure everything via friendly UI instead of coding and reinventing the wheel.

A couple of questions:

Does Apache NiFi look suitable for my task or it would be an overkill?

Will I have any benefit configuring Apache NiFi with zero knowledge of that instrument vs writing a custom script using some programming language I'm comfortable with (Python, for example)

Thanks!

答:
Apache NiFi could be the right answer for this case but can come down to the details.

Your case of having many varied data sources is a common deployment pattern for NiFi where users will perform a somewhat tiered approach of:

bringing the data in from its respective sources,

annotating/extracting key attributes/properties of a piece of data

transforming the data into a canonical representation,

routing to the appropriate downstream consumers,

passing it through a processor to persist in the targeted storage/system/service

Scripts are how many folks initially gravitate toward solving this problem but can lead to an unruly collection of such one off processes that are hard to consider as a whole and reason about their interactions with each other.  For long running data flows that will evolve and potentially bring additional sources/sinks, NiFi is a great offering to bring this path of data into a consolidated view.  The UI further empowers users to make changes for when those "specifications" inevitably change and react more readily than changing one or more scripts/apps.

Given the mention of "simple" ETL and the fact that you are using other sources beyond databases, this seems to fit well within the scope of NiFi's intended usage.  NiFi is not well suited to some of the more complex ETL operations nor does it have a UI custom built for those types of operations.


问:
How to keep a bash script running in the background
I write a simple bash script:

```<code>while :
do
sleep 2;

//my code

done
</code>```

Now I want this bash script always be running.

```<code>bash mybash.sh > /dev/null &
</code>```

When I run above command my bash works fine. but when I close my terminal I think my bash is killed. because it doesn't work as my script make some files when it running.

答:
#!/bin/bash

while true; do

// your code

sleep 5;

done;

write a bash script and put it that to cron and check once it will start comment the cron it will run in a background.

insted of sleep 5 you can use whatever second you want to put.

For checking your process use below commend to get the details
ps -ef | grep script_file_name

if you find more then one process is running leave one process and rest kill the process for script.

Hope so this will resolve your issue....!!!!

Body:
I write a simple bash script:

while :
do
sleep 2;

//my code

done

Now I want this bash script always be running.

bash mybash.sh > /dev/null &

When I run above command my bash works fine. but when I close my terminal I think my bash is killed. because it doesn't work as my script make some files when it running.


问:
How to filter rows containing a similar pattern
i have this dataframe in pandas:

```<code>               Value    Date
ISIN
TRT010213A15    10    2019-11-15
TRT010213T23    100   2019-11-15
TRT010213T23    70    2019-12-20
TRT080328T15    150   2018-10-12
TRT080420T12    175   2018-05-11
TRT150120T16    150   2019-08-29
TRT150120A05    15    2019-11-18
TRT150120T16    300   2019-10-15
TRT150120T16    275   2019-11-18
</code>```

How to get the difference (subtraction) between "Values" columns if both the first 9 characters of the indixes ("ISIN") and the values in the "Date" column are same. Subtraction will be held between indexes that have "T" on the 10th character and "A" on the 10th character.

e.g. first 9 characters of first and second indexes are "TR010213" and "Date" values are "2019-11-15". In this case new value of "Value" for second row (cause 10th char of index is "T") should be 90(100-10) and "Value" for first row (10th char of index is "A") will not be changed.

I wanna get this dataframe:

```<code>                Value   Date
ISIN
TRT010213A15    10  2019-11-15
TRT010213T23    90  2019-11-15
TRT010213T23    70  2019-12-20
TRT080328T15    150 2018-10-12
TRT080420T12    175 2018-05-11
TRT150120T16    150 2019-08-29
TRT150120A05    15  2019-11-18
TRT150120T16    300 2019-10-15
TRT150120T16    260 2019-11-18
</code>```

Body:
i have this dataframe in pandas:

               Value    Date
ISIN
TRT010213A15    10    2019-11-15
TRT010213T23    100   2019-11-15
TRT010213T23    70    2019-12-20
TRT080328T15    150   2018-10-12
TRT080420T12    175   2018-05-11
TRT150120T16    150   2019-08-29
TRT150120A05    15    2019-11-18
TRT150120T16    300   2019-10-15
TRT150120T16    275   2019-11-18

How to get the difference (subtraction) between "Values" columns if both the first 9 characters of the indixes ("ISIN") and the values in the "Date" column are same. Subtraction will be held between indexes that have "T" on the 10th character and "A" on the 10th character.

e.g. first 9 characters of first and second indexes are "TR010213" and "Date" values are "2019-11-15". In this case new value of "Value" for second row (cause 10th char of index is "T") should be 90(100-10) and "Value" for first row (10th char of index is "A") will not be changed.

I wanna get this dataframe:

                Value   Date
ISIN
TRT010213A15    10  2019-11-15
TRT010213T23    90  2019-11-15
TRT010213T23    70  2019-12-20
TRT080328T15    150 2018-10-12
TRT080420T12    175 2018-05-11
TRT150120T16    150 2019-08-29
TRT150120A05    15  2019-11-18
TRT150120T16    300 2019-10-15
TRT150120T16    260 2019-11-18

Body:
You could use this:

df.update(df.groupby([df.index.str[:9],'Date']).transform('diff'))

              Value        Date
ISIN
TRT010213A15   10.0  2019-11-15
TRT010213T23   90.0  2019-11-15
TRT010213T23   70.0  2019-12-20
TRT080328T15  150.0  2018-10-12
TRT080420T12  175.0  2018-05-11
TRT150120T16  150.0  2019-08-29
TRT150120A05   15.0  2019-11-18
TRT150120T16  300.0  2019-10-15
TRT150120T16  260.0  2019-11-18


问:
How to place an Imageview on top of anothe Layout as shown in the figure?
I would like to create a layout which could make the UI look like as shown in figure.

All comments and pointers welcome.

Adding my current Layout :

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><LinearLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="vertical"
    android:id="@+id/video_panel">

    <RelativeLayout android:layout_width="fill_parent"
        android:id="@+id/top_panel" android:gravity="top"
        android:orientation="horizontal" android:alwaysDrawnWithCache="true"
        android:layout_height="fill_parent" android:layout_gravity="top"
        android:layout_weight="14" android:background="@drawable/top_bg1">

        <TextView android:layout_width="wrap_content"
            android:layout_height="fill_parent" android:id="@+id/date"
            android:layout_alignParentLeft="true" android:layout_alignParentTop="true"
            android:text="@string/space" />

        <RelativeLayout android:layout_centerHorizontal="true"
            android:id="@+id/button_panel" android:layout_height="fill_parent"
            android:layout_width="wrap_content" android:gravity="center_horizontal"
            android:layout_centerInParent="true">
        </RelativeLayout>

        <TextView android:layout_height="fill_parent"
            android:layout_width="wrap_content" android:layout_alignParentRight="true"
            android:layout_alignParentTop="true" android:id="@+id/time"
            android:text="@string/space" />
    </RelativeLayout>

    <LinearLayout android:layout_width="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_height="fill_parent" android:layout_gravity="center_horizontal"
        android:layout_weight="4" android:id="@+id/screen">
    </LinearLayout>

    <RelativeLayout android:layout_width="fill_parent"
        android:id="@+id/bottom_panel" android:layout_height="fill_parent"
        android:layout_gravity="bottom" android:layout_weight="13"
        android:orientation="vertical" android:background="@drawable/bottom_bg1"
        android:duplicateParentState="true" android:alwaysDrawnWithCache="true">

        <LinearLayout android:foregroundGravity="center"
            android:id="@+id/album_art" android:layout_alignParentLeft="true"
            android:layout_width="256dip" android:layout_height="fill_parent">
            <ImageView android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:layout_gravity="center"
                android:id="@+id/thumbnail"></ImageView>
        </LinearLayout>

        <LinearLayout android:layout_toRightOf="@+id/album_art"
            android:layout_height="fill_parent" android:orientation="vertical"
            android:paddingTop="10dip" android:layout_width="wrap_content"
            android:layout_centerHorizontal="true" android:layout_toLeftOf="@+id/status_frame"
            android:id="@+id/info_panel">
        </LinearLayout>

        <FrameLayout android:layout_width="wrap_content"
            android:id="@+id/status_frame" android:layout_height="fill_parent"
            android:visibility="visible" android:foregroundGravity="center"
            android:layout_alignParentRight="true" android:paddingTop="50dip">
            <ImageView android:id="@+id/status" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:scaleType="fitCenter"
                android:layout_gravity="center" />
        </FrameLayout>
    </RelativeLayout>
</LinearLayout>
</code>```

How Should i change this layout to make it look like in my picture?

答:
How about changing the framelayout to a relativelayout.

Have the VideoView fill_parent, the bluelayout align_parentBottom=true, the linearlayout horizontallayout center horizontal, alignparentbottom, the blue image view align_parentleft=true, alignparentbottom true, with a large bottom margin to bump it up. the orange imageview alignparentright & bottom.

Body:
I would like to create a layout which could make the UI look like as shown in figure.

All comments and pointers welcome.

Adding my current Layout :

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="vertical"
    android:id="@+id/video_panel">

    <RelativeLayout android:layout_width="fill_parent"
        android:id="@+id/top_panel" android:gravity="top"
        android:orientation="horizontal" android:alwaysDrawnWithCache="true"
        android:layout_height="fill_parent" android:layout_gravity="top"
        android:layout_weight="14" android:background="@drawable/top_bg1">

        <TextView android:layout_width="wrap_content"
            android:layout_height="fill_parent" android:id="@+id/date"
            android:layout_alignParentLeft="true" android:layout_alignParentTop="true"
            android:text="@string/space" />

        <RelativeLayout android:layout_centerHorizontal="true"
            android:id="@+id/button_panel" android:layout_height="fill_parent"
            android:layout_width="wrap_content" android:gravity="center_horizontal"
            android:layout_centerInParent="true">
        </RelativeLayout>

        <TextView android:layout_height="fill_parent"
            android:layout_width="wrap_content" android:layout_alignParentRight="true"
            android:layout_alignParentTop="true" android:id="@+id/time"
            android:text="@string/space" />
    </RelativeLayout>

    <LinearLayout android:layout_width="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_height="fill_parent" android:layout_gravity="center_horizontal"
        android:layout_weight="4" android:id="@+id/screen">
    </LinearLayout>

    <RelativeLayout android:layout_width="fill_parent"
        android:id="@+id/bottom_panel" android:layout_height="fill_parent"
        android:layout_gravity="bottom" android:layout_weight="13"
        android:orientation="vertical" android:background="@drawable/bottom_bg1"
        android:duplicateParentState="true" android:alwaysDrawnWithCache="true">

        <LinearLayout android:foregroundGravity="center"
            android:id="@+id/album_art" android:layout_alignParentLeft="true"
            android:layout_width="256dip" android:layout_height="fill_parent">
            <ImageView android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:layout_gravity="center"
                android:id="@+id/thumbnail"></ImageView>
        </LinearLayout>

        <LinearLayout android:layout_toRightOf="@+id/album_art"
            android:layout_height="fill_parent" android:orientation="vertical"
            android:paddingTop="10dip" android:layout_width="wrap_content"
            android:layout_centerHorizontal="true" android:layout_toLeftOf="@+id/status_frame"
            android:id="@+id/info_panel">
        </LinearLayout>

        <FrameLayout android:layout_width="wrap_content"
            android:id="@+id/status_frame" android:layout_height="fill_parent"
            android:visibility="visible" android:foregroundGravity="center"
            android:layout_alignParentRight="true" android:paddingTop="50dip">
            <ImageView android:id="@+id/status" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:scaleType="fitCenter"
                android:layout_gravity="center" />
        </FrameLayout>
    </RelativeLayout>
</LinearLayout>

How Should i change this layout to make it look like in my picture?


问:
Magento 2 Observer not working on event 'checkout_onepage_controller_success_action'
I've tried a lot of suggestions here but it seems like nothing works for me. I am trying to listen to event 'checkout_onepage_controller_success_action'. I am trying to set the order status to 'complete' upon checkout (for now, I commented out that part).

As you may see below (inside the execute method), I am trying to print out the order object then exit. But when testing, nothing happens. No print out, no error message. Nothing...

I ran the following commands before testing:
bin/magento setup:upgrade, bin/magento setup:di:compile, bin/magento cache:clean

I also tried listening to event sales_order_place_after. I also got nothing...

app/code/[company]/[module]/etc/frontend/events.xml

```<code><?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_onepage_controller_success_action">
        <observer instance="[company]\[module]\Observer\CheckoutSuccessObserver" name="checkout_onepage_controller_success_action_observer"/>
    </event>
</config>

</code>```

app/code/[company]/[module]/Observer/CheckoutSuccessObserver.php

```<code><?php

namespace [company]\[module]\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;

/**
 * Class CheckoutSuccessObserver
 *
 * @package [company]\[module]\Observer
 */
class CheckoutSuccessObserver implements ObserverInterface
{

    /**
     * Execute observer
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(Observer $observer)
    {
        $order = $observer->getEvent()->getOrder();
        print_r($order); exit;

        //$order = $observer->getEvent()->getOrder();
        //$order_id = $order->getIncrementId();

        //$order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
        //$order->setData('state', "complete");
        //$order->setStatus("complete");

        //$history = $order->addStatusHistoryComment('Order was set to complete by our automation tool.', false);
        //$history->setIsCustomerNotified(null);

        //$order->save();
    }
}
</code>```

答:
Your sample code looks ok.
Did you enable your custom module? Check it using bin/magento module:status [company]_[module]
Try also to clear the project's directories: https://devdocs.magento.com/guides/v2.3/howdoi/php/php_clear-dirs.html.

Body:
I've tried a lot of suggestions here but it seems like nothing works for me. I am trying to listen to event 'checkout_onepage_controller_success_action'. I am trying to set the order status to 'complete' upon checkout (for now, I commented out that part).

As you may see below (inside the execute method), I am trying to print out the order object then exit. But when testing, nothing happens. No print out, no error message. Nothing...

I ran the following commands before testing:
bin/magento setup:upgrade, bin/magento setup:di:compile, bin/magento cache:clean

I also tried listening to event sales_order_place_after. I also got nothing...

app/code/[company]/[module]/etc/frontend/events.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_onepage_controller_success_action">
        <observer instance="[company]\[module]\Observer\CheckoutSuccessObserver" name="checkout_onepage_controller_success_action_observer"/>
    </event>
</config>

app/code/[company]/[module]/Observer/CheckoutSuccessObserver.php

<?php

namespace [company]\[module]\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;

/**
 * Class CheckoutSuccessObserver
 *
 * @package [company]\[module]\Observer
 */
class CheckoutSuccessObserver implements ObserverInterface
{

    /**
     * Execute observer
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(Observer $observer)
    {
        $order = $observer->getEvent()->getOrder();
        print_r($order); exit;

        //$order = $observer->getEvent()->getOrder();
        //$order_id = $order->getIncrementId();

        //$order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
        //$order->setData('state', "complete");
        //$order->setStatus("complete");

        //$history = $order->addStatusHistoryComment('Order was set to complete by our automation tool.', false);
        //$history->setIsCustomerNotified(null);

        //$order->save();
    }
}


问:
Reacord deleted from the database but getting an error :- Request failed with status code 404 using axios, node, mongo and Koa
The Data Is Deleted Successfully but I am getting an error with the code GET http://localhost:3000/api/deletetagbyid/5e4d896cea390804241612cd 404 (Not Found).

Can any one please help me actually I am new in react node:-
Thanx You

```<code>// Delete Discount Tag Using Axios :-
const handleDelete = async (e, id) => {

    if (confirm("Are you sure. You Want to delete this tag?")) {

        await axios.get("/api/deletetagbyid/" + id).then((result) => {
            console.log(result);
        }).catch(() => {
            console.log('Error Occured');
        });
    }
}

// This is the backend code to delete data with koa js :-
exports.deletetagbyid = (ctx) => {

    let id = ctx.params.id;
    Note.findOne({
        "_id": ObjectID(id)
    }, function (err, docs) {

        if (!docs) {
            ctx.body = 404;
        } else {
            Note.deleteOne({
                _id: id
            }, function (err, obj) {
                if (err) throw err;
                ctx.body = "Deleted SuccessFully";
                console.log(" document(s) deleted");
            });
        }
    })
};

// This is the route for delete data :-
router.get('/api/deletetagbyid/:id', discounttag.deletetagbyid);
</code>```

答:
Sorry , do not use get method for deleting the record from database use DELETE method

And for your question i think you are calling the delete api two times

Body:
The Data Is Deleted Successfully but I am getting an error with the code GET http://localhost:3000/api/deletetagbyid/5e4d896cea390804241612cd 404 (Not Found).

Can any one please help me actually I am new in react node:-
Thanx You

// Delete Discount Tag Using Axios :-
const handleDelete = async (e, id) => {

    if (confirm("Are you sure. You Want to delete this tag?")) {

        await axios.get("/api/deletetagbyid/" + id).then((result) => {
            console.log(result);
        }).catch(() => {
            console.log('Error Occured');
        });
    }
}

// This is the backend code to delete data with koa js :-
exports.deletetagbyid = (ctx) => {

    let id = ctx.params.id;
    Note.findOne({
        "_id": ObjectID(id)
    }, function (err, docs) {

        if (!docs) {
            ctx.body = 404;
        } else {
            Note.deleteOne({
                _id: id
            }, function (err, obj) {
                if (err) throw err;
                ctx.body = "Deleted SuccessFully";
                console.log(" document(s) deleted");
            });
        }
    })
};

// This is the route for delete data :-
router.get('/api/deletetagbyid/:id', discounttag.deletetagbyid);


问:
I need to sort an array of strings by popularity of the values inside the array
I have an array of strings, with some values multiple times like this.

```<code>const arr = ['banana', 'orange', 'banana', 'apple', 'apple', 'apple', 'orange', 'apple', 'banana']
</code>```

And i'd like to end up with an array of objects with the most popular value first paired with how many of those values are in the array and so on:

```<code>const newArr = [
   { fruit: 'apple', count: 4 },
   { fruit: 'banana', count: 3 },
   { fruit: 'orange', count: 2 }
]
</code>```

答:
Using temprary object:</p>

```<code>const dict = {}
const newArr = []
arr.forEach(v => {
  if (!dict[v]) {
    dict[v] = {fruit: v, count:0}
    newArr.push(dict[v])
  }
  dict[v].count++
})
newArr.sort((o1, o2) => o2.count - o1.count)
</code>```

Body:
I have an array of strings, with some values multiple times like this.

const arr = ['banana', 'orange', 'banana', 'apple', 'apple', 'apple', 'orange', 'apple', 'banana']

And i'd like to end up with an array of objects with the most popular value first paired with how many of those values are in the array and so on:

const newArr = [
   { fruit: 'apple', count: 4 },
   { fruit: 'banana', count: 3 },
   { fruit: 'orange', count: 2 }
]

Body:
Using temprary object:

const dict = {}
const newArr = []
arr.forEach(v => {
  if (!dict[v]) {
    dict[v] = {fruit: v, count:0}
    newArr.push(dict[v])
  }
  dict[v].count++
})
newArr.sort((o1, o2) => o2.count - o1.count)


问:
How to integrate bootstrap css and js with my liferay 7.2 theme?
I created a liferay 7.2 theme based on gradle with liferay developer Studio ( new Module project) , For now,I added some navigation menus and footer and contents , it looks not responsive anymore that's why I ask how to integrate bootstrap within my theme.
Can I do so by importing the cdn bootstrap link inside the portal_normal.ftl ?
I heart about clay but I didn't understand how to proceed !

How can I fix this please?

thank you

答:
Clay is an extension of Bootstrap’s open source CSS Framework

By creating a Liferay theme, you have at your disposal clay. You should import it in your _custom.scss if it is not the case :

```<code>@import "clay/base";
</code>```

Therefore, you can use all Bootstrap' css classes for responsive design.

Here is a thread about importing clay into a Lifeay theme.

Body:
Clay is an extension of Bootstrap’s open source CSS Framework

By creating a Liferay theme, you have at your disposal clay. You should import it in your _custom.scss if it is not the case :

@import "clay/base";

Therefore, you can use all Bootstrap' css classes for responsive design.

Here is a thread about importing clay into a Lifeay theme.


问:
SQL query for group by result in different column
I Have table having 2 columns

Column1 Value
   A     10
   B     20
   C     11
   A     40
   B     30
   C     22
```

<p>I Want Result like</p>

<pre class="lang-none prettyprint-override"><code>Column1 Value1 Value2
A       10      40
B       20      30
C       11      22
</code>```

Is there any query or store Procdure to get such Output

答:
If you don't know for sure how many values per Column1 there will be, you'll have to do dynamic SQL.

Adapting @LukStorms excellent answer above:

```<code>IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL
    DROP TABLE #MyTable

create table #MyTable (c nvarchar(1), v int)

insert into #MyTable
select 'A',10
union select 'B',20
union select 'C',11
union select 'A',40
union select 'B',30
union select 'C',22
union select 'A',60
union select 'C',28
union select 'C',150

declare @s varchar(max), @maxVals int, @i int = 1

select @maxVals = max(ct) from (select c,count(*) as ct from #MyTable group by c) as x

set @s = 'SELECT *
FROM
(
    SELECT c as Column1, v
    , Col = CONCAT(''Value'', ROW_NUMBER() OVER (PARTITION BY c ORDER BY v))
    FROM #MyTable
) Src
PIVOT (
    MAX(v)
    FOR Col IN ('

while @i <= @maxVals
begin

set @s = @s + 'Value' + cast(@i as varchar)

if @i < @maxVals
     set @s = @s + ', '

set @i = @i +1
end

set @s = @s + ')
) Pvt'

exec(@s)
</code>```

Note that SQL won't necessarily keep the order the values were inserted, unless you use an identity column and sort on that. Also, if a column1 has more than one value the same, it will ignore the duplicate.

Hope that helps, and thanks @LukStorms for the initial work

Body:
I Have table having 2 columns

Column1 Value
   A     10
   B     20
   C     11
   A     40
   B     30
   C     22

I Want Result like

Column1 Value1 Value2
A       10      40
B       20      30
C       11      22

Is there any query or store Procdure to get such Output

Body:
If you don't know for sure how many values per Column1 there will be, you'll have to do dynamic SQL.

Adapting @LukStorms excellent answer above:

IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL
    DROP TABLE #MyTable

create table #MyTable (c nvarchar(1), v int)

insert into #MyTable
select 'A',10
union select 'B',20
union select 'C',11
union select 'A',40
union select 'B',30
union select 'C',22
union select 'A',60
union select 'C',28
union select 'C',150

declare @s varchar(max), @maxVals int, @i int = 1

select @maxVals = max(ct) from (select c,count(*) as ct from #MyTable group by c) as x

set @s = 'SELECT *
FROM
(
    SELECT c as Column1, v
    , Col = CONCAT(''Value'', ROW_NUMBER() OVER (PARTITION BY c ORDER BY v))
    FROM #MyTable
) Src
PIVOT (
    MAX(v)
    FOR Col IN ('

while @i <= @maxVals
begin

set @s = @s + 'Value' + cast(@i as varchar)

if @i < @maxVals
     set @s = @s + ', '

set @i = @i +1
end

set @s = @s + ')
) Pvt'

exec(@s)

Note that SQL won't necessarily keep the order the values were inserted, unless you use an identity column and sort on that. Also, if a column1 has more than one value the same, it will ignore the duplicate.

Hope that helps, and thanks @LukStorms for the initial work


问:
Keeping track of mutated rows in BigQuery?
I have a large table whose rows get updated/inserted/merged periodically from a few different queries. I need a scheduled process to run (via API) to periodically check for which rows in that table were updated since the last check. So here are my issues...

When I run the merge query, I don't see a way for it to return which records were updated... otherwise, I could be copying those updated rows to a special updated_records table.

There are no triggers so I can't keep track of mutations that way.

I could add a last_updated timestamp column to keep track that way, but then repeatedly querying the entire table all day for that would be a huge amount of data billed (expensive).

I'm wondering if I'm overlooking something obvious or if maybe there's some kind of special BQ metadata that could help?

The reason I'm attempting this is that I'm wanting to extract and synchronize a smaller subset of this table into my PostgreSQL instance because the latency for querying BQ is just too much for smaller queries.

Any ideas? Thanks!

答:
An approach would be to have 3 tables:

one basetable in "append only" mode, only inserts are added, and updates as full row, in this table would be every record like a versioning system.

a table to hold deletes (or this can be incorporated as a soft delete if there is a special column kept in the first table)

a livetable where you hold the current data (in this table you would do your MERGE statements most probably from the first base table.

If you choose partitioning and clustering, you could end up leverage a lot for long time storage discounted price and scan less data by using partitioning and clustering.


问:
Programmatically build a technical drawing
I've just spent roughly a week on this task and I'm slowly giving up on this. Basically I'm trying to build a layout for a drawing that will change its size based on selected type of product. It is a really simple drawing... Axe (top container) which is a plain container with white border, fixed width and hight stretch from top of the container to bottom of the wheel. Wheel (bottom container) which is also another container filled white which changes its radiuses fixed size and shape based on selected product. That what I managed to do without any problem. The problem is to add layout for placing dimension annotation to it.

1/ Container for horizontal annotation should change its width based on wheel width

2/ Placing container for wheel height annotation which change its height based on wheel height and container for overall length annotation which will stretch its height from top of the axe container to bottom of wheel container

This is mock-up of what I'm trying to achieve

Here is my code

```<code>Column(
              children: <Widget>[
                AxeBuilder(),
                WheelBuilder(
                  wheelType: WheelType.T,
                ),
                SizedBox(height: 5),
                DimBuilder(
                  plane: Plane.Horizontal,
                  height: 30,
                ),
              ],
            ),
</code>```

And this is what I get

Any idea what should I do to make it work?

答:
I've made it and it is horrendous. It still need some polishing but it works. Message to Flutter team : could you include Grid container in flutter for this purposes? (Not a grid view which is already included)

```<code>Container(
          height: 200,
          child: Row(
            children: <Widget>[
              IntrinsicWidth(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    AxeBuilder(),
                    WheelBuilder(
                      wheelType: WheelType.T,
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    DimBuilder(
                      plane: Plane.Horizontal,
                      height: 25,
                    ),
                  ],
                ),
              ),
              Row(
                children: <Widget>[
                  SizedBox(
                    //   width: 30,
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Expanded(
                          child: SizedBox(),
                        ),
                        IntrinsicHeight(
                          child: Row(
                            children: <Widget>[
                              SizedBox(
                                width: 5,
                                child: WheelBuilder(
                                  wheelType: WheelType.T,
                                ),
                              ),
                              DimBuilder(
                                plane: Plane.Vertical,
                                height: 20,
                              )
                            ],
                          ),
                        ),
                        SizedBox(
                          height: 5,
                        ),
                        SizedBox(
                          height: 24,
                        )
                      ],
                    ),
                  ),
                ],
              ),
              Column(
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  Expanded(
                      child: DimBuilder(
                    plane: Plane.Vertical,
                    height: 20,
                  )),
                  SizedBox(
                    height: 5,
                  ),
                  SizedBox(
                    height: 24,
                  )
                ],
              )
            ],
          ),
        ),
      ],
    ),
  ),
);
</code>```

Body:
I've just spent roughly a week on this task and I'm slowly giving up on this. Basically I'm trying to build a layout for a drawing that will change its size based on selected type of product. It is a really simple drawing... Axe (top container) which is a plain container with white border, fixed width and hight stretch from top of the container to bottom of the wheel. Wheel (bottom container) which is also another container filled white which changes its radiuses fixed size and shape based on selected product. That what I managed to do without any problem. The problem is to add layout for placing dimension annotation to it.

1/ Container for horizontal annotation should change its width based on wheel width

2/ Placing container for wheel height annotation which change its height based on wheel height and container for overall length annotation which will stretch its height from top of the axe container to bottom of wheel container

This is mock-up of what I'm trying to achieve

Here is my code

Column(
              children: <Widget>[
                AxeBuilder(),
                WheelBuilder(
                  wheelType: WheelType.T,
                ),
                SizedBox(height: 5),
                DimBuilder(
                  plane: Plane.Horizontal,
                  height: 30,
                ),
              ],
            ),

And this is what I get

Any idea what should I do to make it work?

Body:
I've made it and it is horrendous. It still need some polishing but it works. Message to Flutter team : could you include Grid container in flutter for this purposes? (Not a grid view which is already included)

Container(
          height: 200,
          child: Row(
            children: <Widget>[
              IntrinsicWidth(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    AxeBuilder(),
                    WheelBuilder(
                      wheelType: WheelType.T,
                    ),
                    SizedBox(
                      height: 5,
                    ),
                    DimBuilder(
                      plane: Plane.Horizontal,
                      height: 25,
                    ),
                  ],
                ),
              ),
              Row(
                children: <Widget>[
                  SizedBox(
                    //   width: 30,
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Expanded(
                          child: SizedBox(),
                        ),
                        IntrinsicHeight(
                          child: Row(
                            children: <Widget>[
                              SizedBox(
                                width: 5,
                                child: WheelBuilder(
                                  wheelType: WheelType.T,
                                ),
                              ),
                              DimBuilder(
                                plane: Plane.Vertical,
                                height: 20,
                              )
                            ],
                          ),
                        ),
                        SizedBox(
                          height: 5,
                        ),
                        SizedBox(
                          height: 24,
                        )
                      ],
                    ),
                  ),
                ],
              ),
              Column(
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  Expanded(
                      child: DimBuilder(
                    plane: Plane.Vertical,
                    height: 20,
                  )),
                  SizedBox(
                    height: 5,
                  ),
                  SizedBox(
                    height: 24,
                  )
                ],
              )
            ],
          ),
        ),
      ],
    ),
  ),
);


问:
VScode PHPCS Extension Error: Referenced Sniff "WordPress-Core" does not exist
I want to add PHP CodeSniffer to VScode.

Within VScode I am getting the error 'phpcs: Referenced sniff "WordPress-Core" does not exist'

However when I run the following command in the terminal:

phpcs --standard="WordPress-Core" dropdowns.php

PHP CodeSniffer works as expected with the following terminal output:

```<code>--------------------------------------------------------------------------------
FOUND 34 ERRORS AND 17 WARNINGS AFFECTING 51 LINES
--------------------------------------------------------------------------------
  15 | WARNING | [x] Array double arrow not aligned correctly; expected 10
     |         |     space(s) between "'id'" and double arrow, but found 1.
  17 | WARNING | [x] Array double arrow not aligned correctly; expected 4
     |         |     space(s) between "'taxonomy'" and double arrow, but found
     |         |     1.
  18 | WARNING | [x] Array double arrow not aligned correctly; expected 5
     |         |     space(s) between "'orderby'" and double arrow, but found
     |         |     1.
  34 | WARNING | [x] Equals sign not aligned with surrounding assignments;
     |         |     expected 10 spaces but found 1 space
  35 | WARNING | [x] Equals sign not aligned with surrounding assignments;
     |         |     expected 7 spaces but found 1 space
  36 | ERROR   | [x] Short array syntax is not allowed
  44 | WARNING | [x] Equals sign not aligned with surrounding assignments;
     |         |     expected 2 spaces but found 1 space
  84 | WARNING | [x] Equals sign not aligned with surrounding assignments;
     |         |     expected 2 spaces but found 1 space
</code>```

My settings.json file looks like this:

```<code>{
    "workbench.colorTheme": "Default Light+",
    "window.zoomLevel": 0,
    "phpcs.standard": "WordPress",
    "phpcs.executablePath": "/Users/michelle/.composer/vendor/bin/phpcs",
    "phpcs.enable": true,
    "phpcs.showWarnings": true,
    "phpcs.showSources": true,
}
</code>```

My phpcs.ruleset.xml looks like this:

```<code><?xml version="1.0"?>
<ruleset name="WordPress Theme Coding Standards">
    <description>My Project's Coding Standards</description>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Docs"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Extra"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Core"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPressVIPMinimum"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-VIP-Go"/>
</ruleset>
</code>```

答:
I solved this error by updating the rule references in this file:
~/.composer/vendor/wp-coding-standards/wpcs/WordPressto also be absolute paths. Final ruleset.xml for WordPress coding standards now looks like this:

```<code><?xml version="1.0"?>
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="WordPress" namespace="WordPressCS\WordPress" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/squizlabs/PHP_CodeSniffer/master/phpcs.xsd">

    <description>WordPress Coding Standards</description>

    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Core"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Docs"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Extra">
        <!-- Prevent duplicate messages + deprecation notice from deprecated sniff. -->
        <exclude name="WordPress.WP.TimezoneChange.timezone_change_date_default_timezone_set"/>
        <exclude name="WordPress.WP.TimezoneChange.DeprecatedSniff"/>
    </rule>

</ruleset>
</code>```

Body:
I want to add PHP CodeSniffer to VScode.

Within VScode I am getting the error 'phpcs: Referenced sniff "WordPress-Core" does not exist'

However when I run the following command in the terminal:

phpcs --standard="WordPress-Core" dropdowns.php

PHP CodeSniffer works as expected with the following terminal output:

--------------------------------------------------------------------------------
FOUND 34 ERRORS AND 17 WARNINGS AFFECTING 51 LINES
--------------------------------------------------------------------------------
  15 | WARNING | [x] Array double arrow not aligned correctly; expected 10
     |         |     space(s) between "'id'" and double arrow, but found 1.
  17 | WARNING | [x] Array double arrow not aligned correctly; expected 4
     |         |     space(s) between "'taxonomy'" and double arrow, but found
     |         |     1.
  18 | WARNING | [x] Array double arrow not aligned correctly; expected 5
     |         |     space(s) between "'orderby'" and double arrow, but found
     |         |     1.
  34 | WARNING | [x] Equals sign not aligned with surrounding assignments;
     |         |     expected 10 spaces but found 1 space
  35 | WARNING | [x] Equals sign not aligned with surrounding assignments;
     |         |     expected 7 spaces but found 1 space
  36 | ERROR   | [x] Short array syntax is not allowed
  44 | WARNING | [x] Equals sign not aligned with surrounding assignments;
     |         |     expected 2 spaces but found 1 space
  84 | WARNING | [x] Equals sign not aligned with surrounding assignments;
     |         |     expected 2 spaces but found 1 space

My settings.json file looks like this:

{
    "workbench.colorTheme": "Default Light+",
    "window.zoomLevel": 0,
    "phpcs.standard": "WordPress",
    "phpcs.executablePath": "/Users/michelle/.composer/vendor/bin/phpcs",
    "phpcs.enable": true,
    "phpcs.showWarnings": true,
    "phpcs.showSources": true,
}

My phpcs.ruleset.xml looks like this:

<?xml version="1.0"?>
<ruleset name="WordPress Theme Coding Standards">
    <description>My Project's Coding Standards</description>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Docs"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Extra"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Core"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPressVIPMinimum"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-VIP-Go"/>
</ruleset>

Body:
I solved this error by updating the rule references in this file:
~/.composer/vendor/wp-coding-standards/wpcs/WordPressto also be absolute paths. Final ruleset.xml for WordPress coding standards now looks like this:

<?xml version="1.0"?>
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="WordPress" namespace="WordPressCS\WordPress" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/squizlabs/PHP_CodeSniffer/master/phpcs.xsd">

    <description>WordPress Coding Standards</description>

    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Core"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Docs"/>
    <rule ref="~/.composer/vendor/wp-coding-standards/wpcs/WordPress-Extra">
        <!-- Prevent duplicate messages + deprecation notice from deprecated sniff. -->
        <exclude name="WordPress.WP.TimezoneChange.timezone_change_date_default_timezone_set"/>
        <exclude name="WordPress.WP.TimezoneChange.DeprecatedSniff"/>
    </rule>

</ruleset>


问:
Block the "show" event when my modal is already open (the script reloads)
I use a modal to dynamically load content to the user (thanks to AJAX and the link he clicked)

On one of the Ajax pages that I load I added a date field with the bootstrap-datepicker plugin (https://bootstrap-datepicker.readthedocs.io/en/latest/)

The problem is that when I click on the input to add the date, it is as if the modal is reloading and I cannot block it

I created a simple example to show the problem (but suddenly on my site, when I click on the date field, it reloads the page at AJAX)

http://jsfiddle.net/1L32hyzt/

HTML:

```<code><!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <input type="text" name="date_from" class="form-control date-test date-from" placeholder="" value="" autocomplete="off">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

Javascript:

```<code>$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget)
  var modal = $(this)

  //......

  console.log('MODAL SHOW')
  $('.date-test').datepicker();
  $('.modal-body').prepend('<div><strong>MODAL SHOW</strong></div>')
});
</code>```

As you can see, when we click on this input, it reloads the script and adds "MODAL SHOW" again

I tried to add modal.off(); in the modal script like this:

```<code>$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget)
  var modal = $(this)

  //......

  modal.off();
  console.log('MODAL SHOW')
  $('.date-test').datepicker();
  $('.modal-body').prepend('<div><strong>MODAL SHOW</strong></div>')
});
</code>```

But the problem is that if the user closes the modal and clicks on another link, it reloads the same modal as the old one (whereas it is another link with another data)

Where does the problem come from ?

How to make sure that when I click on the input, the script does not think that I am reloading the modal

答:
Adding the following code should help with your problem.

```<code>$(".date-test").datepicker().on('show.bs.modal', function(event) {
    // prevent datepicker from firing bootstrap modal "show.bs.modal"
    event.stopPropagation();
</code>```

That's a known bug hat has to do with bootstraps datetimepicker
https://github.com/uxsolutions/bootstrap-datepicker/issues/978

Body:
I use a modal to dynamically load content to the user (thanks to AJAX and the link he clicked)

On one of the Ajax pages that I load I added a date field with the bootstrap-datepicker plugin (https://bootstrap-datepicker.readthedocs.io/en/latest/)

The problem is that when I click on the input to add the date, it is as if the modal is reloading and I cannot block it

I created a simple example to show the problem (but suddenly on my site, when I click on the date field, it reloads the page at AJAX)

http://jsfiddle.net/1L32hyzt/

HTML:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <input type="text" name="date_from" class="form-control date-test date-from" placeholder="" value="" autocomplete="off">

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Javascript:

$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget)
  var modal = $(this)

  //......

  console.log('MODAL SHOW')
  $('.date-test').datepicker();
  $('.modal-body').prepend('
MODAL SHOW
')
});

As you can see, when we click on this input, it reloads the script and adds "MODAL SHOW" again

I tried to add modal.off(); in the modal script like this:

$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget)
  var modal = $(this)

  //......

  modal.off();
  console.log('MODAL SHOW')
  $('.date-test').datepicker();
  $('.modal-body').prepend('
MODAL SHOW
')
});

But the problem is that if the user closes the modal and clicks on another link, it reloads the same modal as the old one (whereas it is another link with another data)

Where does the problem come from ?

How to make sure that when I click on the input, the script does not think that I am reloading the modal

Body:
Adding the following code should help with your problem.

$(".date-test").datepicker().on('show.bs.modal', function(event) {
    // prevent datepicker from firing bootstrap modal "show.bs.modal"
    event.stopPropagation();

That's a known bug hat has to do with bootstraps datetimepicker
https://github.com/uxsolutions/bootstrap-datepicker/issues/978


问:
Python time between x and y run code. And no code if time between xy
Im gonna try and explain to the best of my efforts.
Script im running is below.

I want to include something that will make the pir sensor not do anything between the hours of 24:00 and 05:00. But the button should work at those times regardless.

Also i want to be able to send different colors at certain times of the day.
So that if its between 8pm and 11 pm it will give this code to the lights: {"on":true,"bri":255,"sat":80,"hue":357}

There will be 4 colors in total. I have tried defining the command called with command(): and the colors but im at a standstill here.

Can anyone help me with this? I do really hope i made myself clear here, but fire away if anything is unclear.

```<code>import sys
sys.path.append("/home/pi/.local/lib/python2.7/site-packages")

from phue import Bridge
import RPi.GPIO as GPIO
import time
import datetime
print 'Waiting for network...'
time.sleep(30)
print 'The wait is over. It\'s showtime!'
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN) #Read output from PIR motion sensor
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Read output from button.
b=Bridge('192.168.1.47')
try:
    b.connect()
except ImportError:
    print "Import error occurred!"
print "Connected to Hue bridge!"

lightson=b.get_light(2, "on")
if lightson: print "Lights are already on."
print 'Entering infinite loop...'

light_on_delay = 15  # time in min for light to stay on when button pressed
button_pressed = 0

while True:
# check for button press
input_state = GPIO.input(18)
if input_state == False:
    print('Button Pressed')
    end = (light_on_delay * 1) + time.time()
    button_pressed = 1
    command =  {"on" : True, "bri" : 255, "sat" : 0, "hue" : 0}
    b.set_group(2, command)
    lightson=True
    print('Lights are on for 15 minutes')

# check if button has been pressed if it has check to see if time is up
if button_pressed == 1:
    if time.time() > end:
        button_pressed = 0

else:

    i=GPIO.input(4)
    timestamp=datetime.datetime.now().time()
    if (timestamp < offstarttime and timestamp > offendtime):
    if i==0:            #When output from motion sensor is LOW
        print ('No movement detected - Turning lights off')
        b.set_group(2, 'on', False)
        lightson=False
        print ('Lights are off')
        time.sleep(0.1)
    else:               #When output from motion sensor is HIGH
        print ('Movement detected - Turning lights on')
        command =  {"on" : True, "bri" : 255, "sat" : 0, "hue" : 0}
        b.set_group(2, command)
        lightson=True
        print ('Lights are on.')
        time.sleep(5)

# added delay to prevent program using 100% cpu time.
time.sleep(0.5)
</code>```

答:
You can add a time check using datetime module at the start of each iteration to conditionally set your command dictionary and run your PIR code if between certain hours. The button logic code should be run outside of the if blocks to make sure it always works</p>

```<code>from datetime import datetime

while True:
    now = datetime.now()
    # Check to see if it is 5am or later
    if now.hour >= 5:
        # PIR sensor code here
        print("PIR sensor should work now")

    # Check to see if between 8pm and 11pm
    if now.hour >= 20 and now.hour <= 23:
        # Configure command dictionary for specific hours
        command = {"on": True,"bri": 255,"sat": 80,"hue": 357}
    else:
        # Configure command dictionary for regular hours
        command = {"on": False}

    # Rest of your code including button logic
</code>```

Body:
Im gonna try and explain to the best of my efforts.
Script im running is below.

I want to include something that will make the pir sensor not do anything between the hours of 24:00 and 05:00. But the button should work at those times regardless.

Also i want to be able to send different colors at certain times of the day.
So that if its between 8pm and 11 pm it will give this code to the lights: {"on":true,"bri":255,"sat":80,"hue":357}

There will be 4 colors in total. I have tried defining the command called with command(): and the colors but im at a standstill here.

Can anyone help me with this? I do really hope i made myself clear here, but fire away if anything is unclear.

import sys
sys.path.append("/home/pi/.local/lib/python2.7/site-packages")

from phue import Bridge
import RPi.GPIO as GPIO
import time
import datetime
print 'Waiting for network...'
time.sleep(30)
print 'The wait is over. It\'s showtime!'
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN) #Read output from PIR motion sensor
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Read output from button.
b=Bridge('192.168.1.47')
try:
    b.connect()
except ImportError:
    print "Import error occurred!"
print "Connected to Hue bridge!"

lightson=b.get_light(2, "on")
if lightson: print "Lights are already on."
print 'Entering infinite loop...'

light_on_delay = 15  # time in min for light to stay on when button pressed
button_pressed = 0

while True:
# check for button press
input_state = GPIO.input(18)
if input_state == False:
    print('Button Pressed')
    end = (light_on_delay * 1) + time.time()
    button_pressed = 1
    command =  {"on" : True, "bri" : 255, "sat" : 0, "hue" : 0}
    b.set_group(2, command)
    lightson=True
    print('Lights are on for 15 minutes')

# check if button has been pressed if it has check to see if time is up
if button_pressed == 1:
    if time.time() > end:
        button_pressed = 0

else:

    i=GPIO.input(4)
    timestamp=datetime.datetime.now().time()
    if (timestamp < offstarttime and timestamp > offendtime):
    if i==0:            #When output from motion sensor is LOW
        print ('No movement detected - Turning lights off')
        b.set_group(2, 'on', False)
        lightson=False
        print ('Lights are off')
        time.sleep(0.1)
    else:               #When output from motion sensor is HIGH
        print ('Movement detected - Turning lights on')
        command =  {"on" : True, "bri" : 255, "sat" : 0, "hue" : 0}
        b.set_group(2, command)
        lightson=True
        print ('Lights are on.')
        time.sleep(5)

# added delay to prevent program using 100% cpu time.
time.sleep(0.5)

Body:
You can add a time check using datetime module at the start of each iteration to conditionally set your command dictionary and run your PIR code if between certain hours. The button logic code should be run outside of the if blocks to make sure it always works

from datetime import datetime

while True:
    now = datetime.now()
    # Check to see if it is 5am or later
    if now.hour >= 5:
        # PIR sensor code here
        print("PIR sensor should work now")

    # Check to see if between 8pm and 11pm
    if now.hour >= 20 and now.hour <= 23:
        # Configure command dictionary for specific hours
        command = {"on": True,"bri": 255,"sat": 80,"hue": 357}
    else:
        # Configure command dictionary for regular hours
        command = {"on": False}

    # Rest of your code including button logic